diff --git a/LТ b/LТ deleted file mode 100644 index e69de29..0000000 diff --git a/communication_system.txt b/communication_system.txt deleted file mode 100644 index a04e106..0000000 --- a/communication_system.txt +++ /dev/null @@ -1,52792 +0,0 @@ -├── .gitea -│ ├── workflows -│ │ ├── deploy.yml -├── .gitignore -├── .golangci.yml -├── LТ -├── README.md -├── build_core.sh -├── core -│ ├── .gitignore -│ ├── .golangci.yml -│ ├── config -│ │ ├── config-load-options.go -│ │ ├── config-types.go -│ │ ├── config.example.yml -│ │ ├── config.yml -│ │ ├── configcore.go -│ ├── db -│ │ ├── db.go -│ │ ├── db_migration -│ │ │ ├── .DS_Store -│ │ │ ├── 0_init.go -│ │ │ ├── common.go -│ │ │ ├── default_data -│ │ │ │ ├── .DS_Store -│ │ │ ├── default_data.go -│ │ │ ├── tables -│ │ │ │ ├── admin_action_log.go -│ │ │ │ ├── admins.go -│ │ │ │ ├── approval.go -│ │ │ │ ├── approval_additional_approver.go -│ │ │ │ ├── approval_additional_observer.go -│ │ │ │ ├── approval_comment.go -│ │ │ │ ├── approval_delegation.go -│ │ │ │ ├── approval_files.go -│ │ │ │ ├── approval_flow_node.go -│ │ │ │ ├── approval_revocation_request.go -│ │ │ │ ├── approval_steps.go -│ │ │ │ ├── approval_task.go -│ │ │ │ ├── approval_task_transfer.go -│ │ │ │ ├── approval_topic.go -│ │ │ │ ├── approval_topic_category.go -│ │ │ │ ├── approval_topic_executor.go -│ │ │ │ ├── department.go -│ │ │ │ ├── directors_category_subscription.go -│ │ │ │ ├── helpers.go -│ │ │ │ ├── notifications.go -│ │ │ │ ├── permission.go -│ │ │ │ ├── providers.go -│ │ │ │ ├── role.go -│ │ │ │ ├── sms_log.go -│ │ │ │ ├── suggestion_messages.go -│ │ │ │ ├── suggestions.go -│ │ │ │ ├── user.go -│ │ │ │ ├── user_hierarchy.go -│ │ │ │ ├── user_role.go -│ │ │ ├── tables.go -│ │ │ ├── triggers.go -│ │ ├── methods -│ │ │ ├── admin.go -│ │ │ ├── admin_action_logs.go -│ │ │ ├── approval.go -│ │ │ ├── approval_additional_approver.go -│ │ │ ├── approval_additional_observer.go -│ │ │ ├── approval_comment.go -│ │ │ ├── approval_delegation.go -│ │ │ ├── approval_file.go -│ │ │ ├── approval_flow_node.go -│ │ │ ├── approval_revocation_request.go -│ │ │ ├── approval_step.go -│ │ │ ├── approval_task.go -│ │ │ ├── approval_task_transfer.go -│ │ │ ├── approval_topic.go -│ │ │ ├── approval_topic_category.go -│ │ │ ├── approval_topic_executor.go -│ │ │ ├── department.go -│ │ │ ├── director_notification.go -│ │ │ ├── notifications.go -│ │ │ ├── permission.go -│ │ │ ├── role.go -│ │ │ ├── sms_log.go -│ │ │ ├── suggestion.go -│ │ │ ├── suggestion_message.go -│ │ │ ├── user.go -│ │ │ ├── user_hierarchy.go -│ │ │ ├── user_role.go -│ │ ├── table_names -│ │ │ ├── table_names.go -│ ├── go.mod -│ ├── go.sum -│ ├── lib -│ │ ├── external -│ │ │ ├── gorm -│ │ │ │ ├── gorm.go -│ │ │ ├── pgxpool -│ │ │ │ ├── pgxpools.go -│ │ │ ├── telegram -│ │ │ │ ├── init.go -│ │ │ │ ├── message.go -│ │ │ │ ├── req.go -│ │ │ │ ├── types.go -│ │ │ ├── tgkit -│ │ │ │ ├── client.go -│ │ │ │ ├── err.go -│ │ │ │ ├── keyboard.go -│ │ │ │ ├── media.go -│ │ │ │ ├── message.go -│ │ │ │ ├── types.go -│ │ ├── internally -│ │ │ ├── client-controllers -│ │ │ │ ├── 0_init.go -│ │ │ │ ├── db-client.go -│ │ │ │ ├── redis-client.go -│ │ │ ├── config-loader -│ │ │ │ ├── cfgldr.go -│ │ │ │ ├── loader.go -│ │ │ │ ├── tag-worker.go -│ │ │ │ ├── type.go -│ │ │ │ ├── validate.go -│ │ │ ├── init.go -│ │ │ ├── redis -│ │ │ │ ├── 0_init.go -│ │ │ │ ├── redis_check.go -│ │ │ │ ├── redis_methods.go -│ │ │ │ ├── redis_w.go -│ │ │ │ ├── request_quota.go -│ │ │ │ ├── types.go -│ ├── reportcore -│ │ ├── autoFitCol.go -│ │ ├── excel.go -│ │ ├── helpers.go -│ ├── securecore -│ │ ├── hashing.go -│ │ ├── jwt-methods.go -│ ├── typescore -│ │ ├── admin.go -│ │ ├── admin_action_log.go -│ │ ├── api.go -│ │ ├── approval.go -│ │ ├── approval_additional_approver.go -│ │ ├── approval_additional_observer.go -│ │ ├── approval_comment.go -│ │ ├── approval_delegation.go -│ │ ├── approval_file.go -│ │ ├── approval_flow_node.go -│ │ ├── approval_revocation_request.go -│ │ ├── approval_step.go -│ │ ├── approval_task.go -│ │ ├── approval_task_assigment.go -│ │ ├── approval_task_transfer.go -│ │ ├── approval_topic.go -│ │ ├── approval_topic_category.go -│ │ ├── approval_topic_executor.go -│ │ ├── balancer.go -│ │ ├── base_db.go -│ │ ├── department.go -│ │ ├── director_notification.go -│ │ ├── handler.go -│ │ ├── notifications.go -│ │ ├── permission.go -│ │ ├── report.go -│ │ ├── role.go -│ │ ├── suggestion.go -│ │ ├── telephony.go -│ │ ├── user.go -│ │ ├── user_auth.go -│ │ ├── user_hierarchy.go -│ │ ├── user_role.go -│ │ ├── user_sessions.go -│ ├── utilscore -│ │ ├── conversion.go -│ │ ├── db -│ │ │ ├── db.go -│ │ │ ├── db_operations.go -│ │ │ ├── db_rows.go -│ │ │ ├── query.go -│ │ │ ├── query_where.go -│ │ │ ├── transaction.go -│ │ │ ├── update_set.go -│ │ ├── eq.go -│ │ ├── gen.go -│ │ ├── ip.go -│ │ ├── plural.go -│ │ ├── rest.go -│ │ ├── secure.go -│ │ ├── sendBotMsg.go -│ │ ├── validation.go -│ │ ├── w-recover.go -│ ├── variables -│ │ ├── api_headers.go -│ │ ├── const.go -│ │ ├── redis-const.go -├── deploy.sh -├── go.work -├── go.work.sum -├── service -│ ├── .DS_Store -│ ├── auth_service -│ ├── notification_service -│ ├── rest_admin_service -│ │ ├── .gitignore -│ │ ├── .golangci.yml -│ │ ├── README.MD -│ │ ├── admin_api.txt -│ │ ├── cmd -│ │ │ ├── app.go -│ │ ├── docs -│ │ │ ├── docs.go -│ │ │ ├── swagger.json -│ │ │ ├── swagger.yaml -│ │ ├── go.mod -│ │ ├── go.sum -│ │ ├── handlers -│ │ │ ├── admin -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── admin_actions -│ │ │ │ ├── handlers.go -│ │ │ ├── approval_steps -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── approval_tasks -│ │ │ │ ├── handlers_tasks.go -│ │ │ │ ├── routes.go -│ │ │ ├── approvalextras -│ │ │ │ ├── handler.go -│ │ │ ├── approvals -│ │ │ │ ├── files.go -│ │ │ │ ├── handlers.go -│ │ │ │ ├── reports.go -│ │ │ │ ├── routes.go -│ │ │ ├── auth -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── dashboard -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── departments -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── flow_nodes -│ │ │ │ ├── handler.go -│ │ │ │ ├── preview.go -│ │ │ │ ├── router.go -│ │ │ │ ├── utils.go -│ │ │ ├── middleware.go -│ │ │ ├── notification -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── permission -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── profile -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── register.go -│ │ │ ├── roles -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── system_monitoring -│ │ │ │ ├── handlers.go -│ │ │ ├── topic_categories -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── topic_executors -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── topics -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── user_hierarchy -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── user_roles -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ │ ├── users -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ ├── types -│ │ │ ├── module.go -│ │ │ ├── req.go -│ │ ├── version -│ ├── rest_balancer_service -│ │ ├── .gitignore -│ │ ├── .golangci.yml -│ │ ├── Dockerfile -│ │ ├── build.sh -│ │ ├── cmd -│ │ │ ├── app.go -│ │ ├── docker_run.sh -│ │ ├── go.mod -│ │ ├── go.sum -│ │ ├── handler -│ │ │ ├── balancer -│ │ │ │ ├── handler.go -│ │ │ │ ├── routes.go -│ │ │ │ ├── utils.go -│ │ │ ├── handler.go -│ │ │ ├── middleware.go -│ │ ├── types -│ │ │ ├── handler.go -│ │ │ ├── types.go -│ ├── rest_telephony_service -│ │ ├── cmd -│ │ │ ├── app.go -│ │ ├── go.mod -│ │ ├── go.sum -│ │ ├── handlers -│ │ │ ├── register.go -│ │ │ ├── telephony -│ │ │ │ ├── bitrix.go -│ │ │ │ ├── handlers.go -│ │ │ │ ├── routes.go -│ │ ├── types -│ │ │ ├── types.go -│ ├── rest_user_service -│ │ ├── cmd -│ │ │ ├── app.go -│ ├── system_service -│ │ ├── .gitignore -│ │ ├── .golangci.yml -│ │ ├── Dockerfile -│ │ ├── Dockerfile.serv -│ │ ├── cmd -│ │ │ ├── app.go -│ │ ├── database_additionally -│ │ │ ├── tables.go -│ │ ├── go.mod -│ │ ├── go.sum -│ │ ├── jobs -│ │ │ ├── init.go -│ │ ├── start.sh -│ │ ├── types -│ │ │ ├── types.go -│ │ ├── version -│ ├── task_service -│ ├── telegram_service -│ │ ├── .DS_Store -│ │ ├── .gitignore -│ │ ├── .golangci.yml -│ │ ├── Dockerfile -│ │ ├── Dockerfile.serv -│ │ ├── approvalflow -│ │ │ ├── dynamic_topic.go -│ │ │ ├── flow.go -│ │ │ ├── topic.go -│ │ ├── cmd -│ │ │ ├── app.go -│ │ ├── common -│ │ │ ├── .DS_Store -│ │ │ ├── update -│ │ │ │ ├── 0_init.go -│ │ │ │ ├── callback.go -│ │ │ │ ├── update.go -│ │ ├── go.mod -│ │ ├── go.sum -│ │ ├── handlers -│ │ │ ├── approval -│ │ │ │ ├── absense_delegation.go -│ │ │ │ ├── approval_revocation.go -│ │ │ │ ├── approval_task_transfer.go -│ │ │ │ ├── approver_approvals.go -│ │ │ │ ├── db_watcher.go -│ │ │ │ ├── director_notification_settings.go -│ │ │ │ ├── handle_attachment.go -│ │ │ │ ├── handle_files.go -│ │ │ │ ├── handle_multiselect.go -│ │ │ │ ├── handler.go -│ │ │ │ ├── handler_add_approver.go -│ │ │ │ ├── handler_comment.go -│ │ │ │ ├── handler_decision.go -│ │ │ │ ├── handler_delegation.go -│ │ │ │ ├── handler_executor.go -│ │ │ │ ├── handler_observer.go -│ │ │ │ ├── handler_pending_comments.go -│ │ │ │ ├── handler_report.go -│ │ │ │ ├── helper.go -│ │ │ │ ├── http_fetch.go -│ │ │ │ ├── list.go -│ │ │ │ ├── navigation.go -│ │ │ │ ├── notify.go -│ │ │ │ ├── registry.go -│ │ │ │ ├── reminder.go -│ │ │ │ ├── revision.go -│ │ │ │ ├── selection_approver.go -│ │ │ │ ├── selection_first_approver.go -│ │ │ │ ├── selection_observer.go -│ │ │ │ ├── topics -│ │ │ │ │ ├── absence -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── client_changes -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── dealautoapproval -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── deliveryclients -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── free -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── goods_order -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── inventory -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── manager_expenses -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── non_budget_expenses -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── non_budget_expenses_pet_line -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── nonstandard_contract -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── otk_conditions -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── payments_cashless -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── rates_logistics -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── receipts -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── returns -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── shipments_soh -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── sick_leave -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── time_off -│ │ │ │ │ │ ├── time_off.go -│ │ │ │ │ ├── transaction_passport -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── vacation -│ │ │ │ │ │ ├── topic.go -│ │ │ │ │ ├── vshipments -│ │ │ │ │ │ ├── topic.go -│ │ │ ├── faq -│ │ │ │ ├── handler.go -│ │ │ ├── start -│ │ │ │ ├── handler.go -│ │ │ │ ├── helpers.go -│ │ │ ├── suggestion -│ │ │ │ ├── handler.go -│ │ ├── keyboard -│ │ │ ├── absense_delegation_keyboard.go -│ │ │ ├── add_approver.go -│ │ │ ├── approval.go -│ │ │ ├── builder.go -│ │ │ ├── delegation.go -│ │ │ ├── menu.go -│ │ │ ├── misc.go -│ │ │ ├── observer.go -│ │ ├── migrate -│ │ │ ├── insert.go -│ │ ├── scheduler -│ │ │ ├── daily_reminder.go -│ │ │ ├── delegation_checker.go -│ │ ├── start.sh -│ │ ├── state -│ │ │ ├── add_approver.go -│ │ │ ├── attachment.go -│ │ │ ├── comment.go -│ │ │ ├── delegation.go -│ │ │ ├── pending_state.go -│ │ │ ├── report_state.go -│ │ │ ├── revision.go -│ │ │ ├── state.go -│ │ │ ├── suggesttion.go -│ │ ├── types -│ │ │ ├── types.go -│ │ ├── version -├── update-go-and-deps.sh -File: core/config/config-load-options.go -Lines: 19 ------BEGIN core/config/config-load-options.go----- -package configcore - -// ExposedServiceOptions определяет, какие сервисы нужно загружать -type ExposedServiceOptions struct { - TelegramService bool - RESTBaseService bool - RESTAdminService bool -} - -// ConfigLoadOptions определяет, какие группы конфигурации нужно загружать -type ConfigLoadOptions struct { - Env bool - Redis bool - Database bool - Bitrix bool - Secrets SecretsOptions - Telegram bool - Server ExposedServiceOptions -} - ------END core/config/config-load-options.go----- - -File: core/config/config-types.go -Lines: 125 ------BEGIN core/config/config-types.go----- -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"` -} - -// AuthJWTOptions определяет, какие JWT секреты нужно загружать -type AuthJWTOptions struct { - Admin bool - User bool -} - -type SecretsOptions struct { - AuthJWT AuthJWTOptions - OAuthConfig bool - WebAuth bool - AdminAccessCode bool - UserAccessCode bool - TonProofConfig bool -} - -// 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"` - RESTAdminService RestServiceConfig `yaml:"rest_admin_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"` -} - -// AuthJWTConfig конфигурация JWT аутентификации -type AuthJWTConfig struct { - AdminSecret string `yaml:"admin_secret"` - UserSecret string `yaml:"user_secret"` - TempSecret string `yaml:"temp_secret"` - TemporaryPasswordLifeMinute int `yaml:"temporary_password_life_minute"` - JwtAdminSessionLengthHours int `yaml:"jwt_admin_session_length_hours"` - JwtUserSessionLengthHours int `yaml:"jwt_user_session_length_hours"` -} - -// SecretsConfig конфигурация секретов -type SecretsConfig struct { - AuthJWT AuthJWTConfig `yaml:"auth_jwt"` - ApiPublicUser string `yaml:"access_code_user"` - ApiPrivateUser string - ApiPublicAdmin string `yaml:"api_public_admin"` - ApiPrivateAdmin string `yaml:"api_private_admin"` - ApiPublicBase string `yaml:"api_public_base"` - ApiPrivateBase string `yaml:"api_private_base"` -} - -type Config struct { - Environment string `yaml:"env"` - Redis RedisConfig `yaml:"redis"` - Database DatabaseConfig `yaml:"database"` - Telegram TelegramConfig `yaml:"telegram"` - Server Server `yaml:"server"` - Secrets SecretsConfig `yaml:"secrets"` - Bitrix Bitrix `yaml:"bitrix"` -} - ------END core/config/config-types.go----- - -File: core/config/configcore.go -Lines: 88 ------BEGIN core/config/configcore.go----- -package configcore - -import ( - cfgldrlib "bitrix_balancer_api/core/lib/internally/config-loader" - _ "embed" - "errors" - "fmt" - "github.com/sirupsen/logrus" -) - -//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) { - if options == nil { - logrus.Error("config options is nil") - return - } - - if options.Env { - target.Environment = source.Environment - } - // Копируем 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 - } - - // Копируем ExposedServiceConfig - if options.Server.RESTBaseService { - target.Server.RESTBaseService = source.Server.RESTBaseService - } - if options.Server.RESTAdminService { - target.Server.RESTAdminService = source.Server.RESTAdminService - } - if options.Server.TelegramService { - target.Server.Telegram = source.Server.Telegram - } - - if options.Secrets.AuthJWT.Admin { - target.Secrets.AuthJWT.AdminSecret = source.Secrets.AuthJWT.AdminSecret - target.Secrets.AuthJWT.JwtAdminSessionLengthHours = source.Secrets.AuthJWT.JwtAdminSessionLengthHours - } - if options.Secrets.AuthJWT.User { - target.Secrets.AuthJWT.UserSecret = source.Secrets.AuthJWT.UserSecret - target.Secrets.AuthJWT.JwtUserSessionLengthHours = source.Secrets.AuthJWT.JwtUserSessionLengthHours - } - if options.Secrets.AdminAccessCode { - target.Secrets.ApiPublicAdmin = source.Secrets.ApiPublicAdmin - target.Secrets.ApiPrivateAdmin = source.Secrets.ApiPrivateAdmin - } - if options.Secrets.UserAccessCode { - target.Secrets.ApiPublicUser = source.Secrets.ApiPublicUser - } -} - ------END core/config/configcore.go----- - -File: core/db/db.go -Lines: 107 ------BEGIN core/db/db.go----- -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 - ApprovalComment *dbcore.ApprovalCommentDB - Suggestion *dbcore.SuggestionDB - SuggestionMessage *dbcore.SuggestionMessageDB - ApprovalAdditionalObserver *dbcore.ApprovalAdditionalObserverDB - ApprovalTopicExecutor *dbcore.ApprovalTopicExecutorDB - Admin *dbcore.AdminDB - Notification *dbcore.NotificationDB - DirectorNotifications *dbcore.DirectorNotificationDB - ApprovalTaskTransfer *dbcore.ApprovalTaskTransferDB - ApprovalRevocation *dbcore.ApprovalRevocationDB - ApprovalFlowNode *dbcore.ApprovalFlowNodeDB - AdminActionLogs *dbcore.AdminActionLogDB - SMSLog *dbcore.SmsLogDB -} - -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) - modules.ApprovalComment = dbcore.NewApprovalCommentDB(modules.Pool) - modules.SuggestionMessage = dbcore.NewSuggestionMessageDB(modules.Pool) - modules.Suggestion = dbcore.NewSuggestionDB(modules.Pool) - modules.ApprovalAdditionalObserver = dbcore.NewApprovalAdditionalObserverDB(modules.Pool) - modules.ApprovalTopicExecutor = dbcore.NewApprovalTopicExecutorDB(modules.Pool) - modules.Admin = dbcore.NewAdminDB(modules.Pool) - modules.Notification = dbcore.NewNotificationDB(modules.Pool) - modules.DirectorNotifications = dbcore.NewDirectorNotificationDB(modules.Pool) - modules.ApprovalTaskTransfer = dbcore.NewApprovalTaskTransferDB(modules.Pool) - modules.ApprovalRevocation = dbcore.NewApprovalRevocationDB(modules.Pool) - modules.ApprovalFlowNode = dbcore.NewApprovalFlowNodeDB(modules.Pool) - modules.AdminActionLogs = dbcore.NewAdminActionLogDB(modules.Pool) - modules.SMSLog = dbcore.NewSmsLogDB(modules.Pool) - - return modules -} - -func (m *ModuleDB) Migrate() *dbmigration.MigrationFunctions { - return dbmigration.NewMigrationFunctions(m.Pool, m.gormDB) -} - ------END core/db/db.go----- - -File: core/db/db_migration/0_init.go -Lines: 37 ------BEGIN core/db/db_migration/0_init.go----- -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 -} - ------END core/db/db_migration/0_init.go----- - -File: core/db/db_migration/common.go -Lines: 21 ------BEGIN core/db/db_migration/common.go----- -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 -} - ------END core/db/db_migration/common.go----- - -File: core/db/db_migration/default_data.go -Lines: 305 ------BEGIN core/db/db_migration/default_data.go----- -package dbmigration - -import ( - _ "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" -) - -// 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 - -// 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) - } -} - ------END core/db/db_migration/default_data.go----- - -File: core/db/db_migration/tables/admin_action_log.go -Lines: 36 ------BEGIN core/db/db_migration/tables/admin_action_log.go----- -package tablesmigration - -import ( - dbcoretablenames "bitrix_balancer_api/core/db/table_names" - "bitrix_balancer_api/core/typescore" - "gorm.io/gorm" - "time" -) - -// LocalAdminProvider - локальная структура для миграции -type LocalAdminActionProvider typescore.AdminActionLog - -func (LocalAdminActionProvider) TableName() string { - return dbcoretablenames.TableNameAdminActionLogs.ToString() -} - -// AdminsTableMigrate - миграция таблицы Admins -func AdminActionLogsTableMigrate(db *gorm.DB) error { - hasTable := db.Migrator().HasTable(&LocalAdminActionProvider{}) - - // Выполняем автосоздание таблицы - err := db.AutoMigrate(&LocalAdminActionProvider{}) - if err != nil { - return err - } - - if !hasTable { - time.Sleep(5 * time.Second) // Добавляем задержку - - // Add comments to table and columns - db.Exec(` - COMMENT ON TABLE admin_action_logs IS 'Таблица для хранения данных о действиях администратора'; - `) - } - return nil -} - ------END core/db/db_migration/tables/admin_action_log.go----- - -File: core/db/db_migration/tables/admins.go -Lines: 43 ------BEGIN core/db/db_migration/tables/admins.go----- -package tablesmigration - -import ( - dbcoretablenames "bitrix_balancer_api/core/db/table_names" - "bitrix_balancer_api/core/typescore" - "gorm.io/gorm" - "time" -) - -// LocalAdminProvider - локальная структура для миграции -type LocalAdminProvider typescore.Admin - -func (LocalAdminProvider) TableName() string { - return dbcoretablenames.TableNameAdmin.ToString() -} - -// AdminsTableMigrate - миграция таблицы Admins -func AdminsTableMigrate(db *gorm.DB) error { - hasTable := db.Migrator().HasTable(&LocalAdminProvider{}) - - // Выполняем автосоздание таблицы - err := db.AutoMigrate(&LocalAdminProvider{}) - if err != nil { - return err - } - - if !hasTable { - time.Sleep(5 * time.Second) // Добавляем задержку - - // Add comments to table and columns - db.Exec(` - COMMENT ON TABLE admins IS 'Таблица для хранения данных о администраторах'; - COMMENT ON COLUMN admins.id IS 'Уникальный идентификатор администратора'; - COMMENT ON COLUMN admins.login IS 'Логин администратора'; - COMMENT ON COLUMN admins.password_hash IS 'Хэшированный пароль администратора'; - COMMENT ON COLUMN admins.created_at IS 'Дата создания записи'; - COMMENT ON COLUMN admins.last_login IS 'Дата последнего входа'; - COMMENT ON COLUMN admins.last_ip_login IS 'Последний IP-адрес авторизации'; - COMMENT ON COLUMN admins.is_blocked IS 'Заблокирован ли администратор'; - `) - } - return nil -} - ------END core/db/db_migration/tables/admins.go----- - -File: core/db/db_migration/tables/approval.go -Lines: 55 ------BEGIN core/db/db_migration/tables/approval.go----- -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 'Дата последнего изменения заявки'; - `) - } - - // 🚀 Индексы: покрывают фильтры GetApprovalsListHandler, JOIN'ы enrichApprovalsBatch и сортировку - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_initiator_id ON approvals (initiator_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_topic_id ON approvals (topic_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_department_id ON approvals (department_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_revoked_by_id ON approvals (revoked_by_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_status ON approvals (status)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_created_at ON approvals (created_at DESC)`) - // Композитный индекс под самый частый сценарий: список заявок конкретного статуса, отсортированный по дате - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_status_created_at ON approvals (status, created_at DESC)`) - // Под фильтр report по инициатору + период - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_initiator_created_at ON approvals (initiator_id, created_at DESC)`) - // Под DeleteTopicHandler / проверку "есть ли заявки по теме" - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_topic_status ON approvals (topic_id, status)`) - - return nil -} - ------END core/db/db_migration/tables/approval.go----- - -File: core/db/db_migration/tables/approval_additional_approver.go -Lines: 44 ------BEGIN core/db/db_migration/tables/approval_additional_approver.go----- -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) - - 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`) - - 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 'Дата и время последнего изменения записи'; - `) - } - - // 🚀 approval_id — джойн при обогащении заявки; approver_id — "мои задачи на согласование"; - // композит approval_id+status — фильтр pending-согласующих конкретной заявки - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_approval_id ON approval_additional_approvers (approval_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_approver_id ON approval_additional_approvers (approver_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_added_by_id ON approval_additional_approvers (added_by_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_approval_status ON approval_additional_approvers (approval_id, status)`) - - return nil -} - ------END core/db/db_migration/tables/approval_additional_approver.go----- - -File: core/db/db_migration/tables/approval_additional_observer.go -Lines: 37 ------BEGIN core/db/db_migration/tables/approval_additional_observer.go----- -package tablesmigration - -import ( - "gorm.io/gorm" - "time" -) - -func ApprovalAdditionalObserverTableMigrate(db *gorm.DB) error { - hasTable := db.Migrator().HasTable(&ApprovalAdditionalObserver{}) - - if err := db.AutoMigrate(&ApprovalAdditionalObserver{}); err != nil { - return err - } - - if !hasTable { - time.Sleep(5 * time.Second) - - db.Exec(`ALTER TABLE approval_additional_observers 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_observers ADD CONSTRAINT fk_approval_additional_approvers_observer_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) - db.Exec(`ALTER TABLE approval_additional_observers ADD CONSTRAINT fk_approval_additional_approvers_added_by_id FOREIGN KEY (added_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) - - execComments(db, ` - COMMENT ON TABLE "approval_additional_observers" IS 'Дополнительные наблюдатели заявки: кто добавлен для согласования конкретной заявки'; - COMMENT ON COLUMN "approval_additional_observers".id IS 'Внутренний уникальный идентификатор записи'; - COMMENT ON COLUMN "approval_additional_observers".approval_id IS 'ID заявки, к которой добавлен согласующий (ссылка на approvals.id)'; - COMMENT ON COLUMN "approval_additional_observers".user_id IS 'ID сотрудника, добавленного как дополнительный наблюдатель (ссылка на users.id)'; - COMMENT ON COLUMN "approval_additional_observers".added_by_id IS 'ID сотрудника, который добавил этого согласующего (ссылка на users.id)'; - COMMENT ON COLUMN "approval_additional_observers".created_at IS 'Дата и время создания записи'; - `) - } - - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_observers_approval_id ON approval_additional_observers (approval_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_observers_user_id ON approval_additional_observers (user_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_observers_added_by_id ON approval_additional_observers (added_by_id)`) - - return nil -} - ------END core/db/db_migration/tables/approval_additional_observer.go----- - -File: core/db/db_migration/tables/approval_comment.go -Lines: 37 ------BEGIN core/db/db_migration/tables/approval_comment.go----- -package tablesmigration - -import ( - "gorm.io/gorm" - "time" -) - -func ApprovalCommentsTableMigrate(db *gorm.DB) error { - hasTable := db.Migrator().HasTable(&ApprovalCommentsProvider{}) - - if err := db.AutoMigrate(&ApprovalCommentsProvider{}); err != nil { - return err - } - - if !hasTable { - time.Sleep(5 * time.Second) - - db.Exec(`ALTER TABLE approval_comments ADD CONSTRAINT fk_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`) - db.Exec(`ALTER TABLE approval_comments ADD CONSTRAINT fk_approval_comm_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE`) - - execComments(db, ` - COMMENT ON TABLE "approval_comments" IS 'Заявки на согласование, поданные сотрудниками'; - COMMENT ON COLUMN "approval_comments".id IS 'Внутренний ID файла'; - COMMENT ON COLUMN "approval_comments".approval_id IS 'ID заявки, к которой привязаны комментарии'; - COMMENT ON COLUMN "approval_comments".user_id IS 'ID пользователя, оставившего комментарий'; - COMMENT ON COLUMN "approval_comments".comment IS 'Комментарий к согласованию'; - COMMENT ON COLUMN "approval_comments".created_at IS 'Дата создания комментария'; - COMMENT ON COLUMN "approval_comments".updated_at IS 'Дата последнего изменения комментария'; - `) - } - - // 🚀 Композит покрывает типичный запрос "комментарии заявки в хронологическом порядке" - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_comments_approval_id_created_at ON approval_comments (approval_id, created_at)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_comments_user_id ON approval_comments (user_id)`) - - return nil -} - ------END core/db/db_migration/tables/approval_comment.go----- - -File: core/db/db_migration/tables/approval_delegation.go -Lines: 45 ------BEGIN core/db/db_migration/tables/approval_delegation.go----- -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) - - 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`) - - 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 'Дата и время последнего изменения записи'; - `) - } - - // 🚀 Композит под самый вероятный запрос: "активные делегирования делегата по теме, ещё не истёкшие" - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_delegator_id ON approval_delegations (delegator_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_delegate_id ON approval_delegations (delegate_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_topic_id ON approval_delegations (topic_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_active_valid_until ON approval_delegations (is_active, valid_until) WHERE is_active = true`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_delegator_topic_active ON approval_delegations (delegator_id, topic_id) WHERE is_active = true`) - - return nil -} - ------END core/db/db_migration/tables/approval_delegation.go----- - -File: core/db/db_migration/tables/approval_files.go -Lines: 34 ------BEGIN core/db/db_migration/tables/approval_files.go----- -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 'Дата создания файла'; - `) - } - - // 🚀 Ключевой индекс под GetFilesByApprovalIDsDB (батч IN по approval_id) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_files_approval_id ON approval_files (approval_id)`) - - return nil -} - ------END core/db/db_migration/tables/approval_files.go----- - -File: core/db/db_migration/tables/approval_flow_node.go -Lines: 52 ------BEGIN core/db/db_migration/tables/approval_flow_node.go----- -package tablesmigration - -import ( - "gorm.io/gorm" - "time" -) - -// ApprovalFlowNodesTableMigrate создаёт таблицу узлов дерева навигации -func ApprovalFlowNodesTableMigrate(db *gorm.DB) error { - hasTable := db.Migrator().HasTable(&LocalApprovalFlowNodeProvider{}) - - if err := db.AutoMigrate(&LocalApprovalFlowNodeProvider{}); err != nil { - return err - } - - if !hasTable { - time.Sleep(5 * time.Second) - - // Foreign key на approval_topics - db.Exec(`ALTER TABLE approval_flow_nodes ADD CONSTRAINT fk_approval_flow_nodes_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE CASCADE ON UPDATE CASCADE`) - - // Самореференсный foreign key (parent_id -> id) - db.Exec(`ALTER TABLE approval_flow_nodes ADD CONSTRAINT fk_approval_flow_nodes_parent_id FOREIGN KEY (parent_id) REFERENCES approval_flow_nodes(id) ON DELETE CASCADE ON UPDATE CASCADE`) - - // Уникальный индекс (topic_id, key) — чтобы ключи узлов были уникальны в рамках одной темы - db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_flow_nodes_topic_key ON approval_flow_nodes(topic_id, key)`) - - // Комментарии - execComments(db, ` - COMMENT ON TABLE "approval_flow_nodes" IS 'Узлы дерева навигации темы согласования: описывают структуру кнопок, шагов ввода и мультиселекта для динамического построения флоу'; - COMMENT ON COLUMN "approval_flow_nodes".id IS 'Внутренний уникальный идентификатор узла'; - COMMENT ON COLUMN "approval_flow_nodes".topic_id IS 'ID темы согласования, к которой принадлежит узел (ссылка на approval_topics.id)'; - COMMENT ON COLUMN "approval_flow_nodes".parent_id IS 'ID родительского узла (ссылка на approval_flow_nodes.id). NULL для корневого узла'; - COMMENT ON COLUMN "approval_flow_nodes".key IS 'Уникальный ключ узла в рамках темы (используется для навигации и идентификации)'; - COMMENT ON COLUMN "approval_flow_nodes".label IS 'Отображаемое название узла (текст на кнопке)'; - COMMENT ON COLUMN "approval_flow_nodes".data_key IS 'Ключ в map collected, куда сохраняется значение при выборе этого узла'; - COMMENT ON COLUMN "approval_flow_nodes".data_value IS 'Значение, сохраняемое в collected[data_key] при выборе этого узла'; - COMMENT ON COLUMN "approval_flow_nodes".is_input IS 'Флаг: является ли узел шагом текстового ввода'; - COMMENT ON COLUMN "approval_flow_nodes".input_key IS 'Ключ в collected, куда сохраняется введённый пользователем текст'; - COMMENT ON COLUMN "approval_flow_nodes".input_hint IS 'Подсказка/шаблон для пользователя при текстовом вводе'; - COMMENT ON COLUMN "approval_flow_nodes".is_multi_select IS 'Флаг: является ли узел узлом мультиселекта (выбор нескольких значений)'; - COMMENT ON COLUMN "approval_flow_nodes".multi_select_key IS 'Ключ в collected, куда сохраняется результат мультиселекта (через запятую)'; - COMMENT ON COLUMN "approval_flow_nodes".multi_select_value IS 'Значение этого варианта в мультиселекте'; - COMMENT ON COLUMN "approval_flow_nodes".topic_code IS 'Код темы для проверки прав доступа (если задан — кнопка показывается только при наличии права create на эту тему)'; - COMMENT ON COLUMN "approval_flow_nodes".sort_order IS 'Порядок сортировки узла среди братьев (0, 1, 2, ...)'; - COMMENT ON COLUMN "approval_flow_nodes".created_at IS 'Дата и время создания узла'; - COMMENT ON COLUMN "approval_flow_nodes".updated_at IS 'Дата и время последнего изменения узла'; - `) - } - - return nil -} - ------END core/db/db_migration/tables/approval_flow_node.go----- - -File: core/db/db_migration/tables/approval_revocation_request.go -Lines: 77 ------BEGIN core/db/db_migration/tables/approval_revocation_request.go----- -package tablesmigration - -import ( - "gorm.io/gorm" - "time" -) - -type LocalApprovalRevocationRequestProvider struct { - ID uint64 `gorm:"column:id;primaryKey;autoIncrement"` - ApprovalID uint64 `gorm:"column:approval_id;not null"` - RequestedByID uint64 `gorm:"column:requested_by_id;not null"` - Reason *string `gorm:"column:reason;type:text"` - Status string `gorm:"column:status;type:text;not null;default:'pending'"` - CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"` - UpdatedAt time.Time `gorm:"column:updated_at;default:CURRENT_TIMESTAMP"` -} - -func (LocalApprovalRevocationRequestProvider) TableName() string { - return "approval_revocation_requests" -} - -type LocalApprovalRevocationApproverProvider struct { - ID uint64 `gorm:"column:id;primaryKey;autoIncrement"` - RevocationRequestID uint64 `gorm:"column:revocation_request_id;not null"` - ApproverID uint64 `gorm:"column:approver_id;not null"` - Status string `gorm:"column:status;type:text;not null;default:'pending'"` - Comment *string `gorm:"column:comment;type:text"` - ActedAt *time.Time `gorm:"column:acted_at"` - CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP"` -} - -func (LocalApprovalRevocationApproverProvider) TableName() string { - return "approval_revocation_approvers" -} - -func ApprovalRevocationTablesMigrate(db *gorm.DB) error { - hasReqTable := db.Migrator().HasTable(&LocalApprovalRevocationRequestProvider{}) - hasApprTable := db.Migrator().HasTable(&LocalApprovalRevocationApproverProvider{}) - - if err := db.AutoMigrate(&LocalApprovalRevocationRequestProvider{}); err != nil { - return err - } - if err := db.AutoMigrate(&LocalApprovalRevocationApproverProvider{}); err != nil { - return err - } - - if !hasReqTable || !hasApprTable { - time.Sleep(5 * time.Second) - - db.Exec(`ALTER TABLE approval_revocation_requests ADD CONSTRAINT fk_arr_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`) - db.Exec(`ALTER TABLE approval_revocation_requests ADD CONSTRAINT fk_arr_requested_by_id FOREIGN KEY (requested_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) - - db.Exec(`ALTER TABLE approval_revocation_approvers ADD CONSTRAINT fk_ara_request_id FOREIGN KEY (revocation_request_id) REFERENCES approval_revocation_requests(id) ON DELETE CASCADE ON UPDATE CASCADE`) - db.Exec(`ALTER TABLE approval_revocation_approvers ADD CONSTRAINT fk_ara_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) - - execComments(db, ` - COMMENT ON TABLE "approval_revocation_requests" IS 'Запрос инициатора на отзыв уже согласованной заявки, требующий согласия всех согласующих'; - COMMENT ON COLUMN "approval_revocation_requests".approval_id IS 'Заявка, которую пытаются отозвать'; - COMMENT ON COLUMN "approval_revocation_requests".requested_by_id IS 'Инициатор, запросивший отзыв'; - COMMENT ON COLUMN "approval_revocation_requests".reason IS 'Причина отзыва, указанная инициатором'; - COMMENT ON COLUMN "approval_revocation_requests".status IS 'pending | approved | rejected | cancelled'; - - COMMENT ON TABLE "approval_revocation_approvers" IS 'Согласующие, чьё согласие требуется для отзыва уже согласованной заявки'; - COMMENT ON COLUMN "approval_revocation_approvers".revocation_request_id IS 'Запрос на отзыв'; - COMMENT ON COLUMN "approval_revocation_approvers".approver_id IS 'Согласующий, участвовавший в первоначальном согласовании'; - COMMENT ON COLUMN "approval_revocation_approvers".status IS 'pending | approved | rejected'; - `) - } - - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_arr_approval_id ON approval_revocation_requests (approval_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_arr_status ON approval_revocation_requests (status)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ara_request_id ON approval_revocation_approvers (revocation_request_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ara_approver_id ON approval_revocation_approvers (approver_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ara_request_status ON approval_revocation_approvers (revocation_request_id, status)`) - - return nil -} - ------END core/db/db_migration/tables/approval_revocation_request.go----- - -File: core/db/db_migration/tables/approval_steps.go -Lines: 44 ------BEGIN core/db/db_migration/tables/approval_steps.go----- -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 'Дата последнего обновления шага'; - `) - } - - // 🚀 Композит покрывает GetApprovalStepsByApprovalIDsDB (IN approval_id + ORDER BY step_order) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_steps_approval_id_step_order ON approval_steps (approval_id, step_order)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_steps_approver_id ON approval_steps (approver_id)`) - // Под "мои pending-согласования" - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_steps_approver_status ON approval_steps (approver_id, status)`) - - return nil -} - ------END core/db/db_migration/tables/approval_steps.go----- - -File: core/db/db_migration/tables/approval_task.go -Lines: 39 ------BEGIN core/db/db_migration/tables/approval_task.go----- -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 'Дата последнего изменения задачи'; - `) - } - - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_tasks_approval_id ON approval_tasks (approval_id)`) - // Под "мои задачи исполнителя, отфильтрованные по статусу" - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_tasks_executor_status ON approval_tasks (executor_id, status)`) - - return nil -} - ------END core/db/db_migration/tables/approval_task.go----- - -File: core/db/db_migration/tables/approval_task_transfer.go -Lines: 38 ------BEGIN core/db/db_migration/tables/approval_task_transfer.go----- -package tablesmigration - -import ( - "gorm.io/gorm" - "time" -) - -func ApprovalTaskTransfersTableMigrate(db *gorm.DB) error { - hasTable := db.Migrator().HasTable(&LocalApprovalTaskTransferProvider{}) - - if err := db.AutoMigrate(&LocalApprovalTaskTransferProvider{}); err != nil { - return err - } - - if !hasTable { - time.Sleep(5 * time.Second) - - db.Exec(`ALTER TABLE approval_task_transfers ADD CONSTRAINT fk_att_task_id FOREIGN KEY (task_id) REFERENCES approval_tasks(id) ON DELETE CASCADE ON UPDATE CASCADE`) - db.Exec(`ALTER TABLE approval_task_transfers ADD CONSTRAINT fk_att_from_executor_id FOREIGN KEY (from_executor_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) - db.Exec(`ALTER TABLE approval_task_transfers ADD CONSTRAINT fk_att_to_executor_id FOREIGN KEY (to_executor_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) - - execComments(db, ` - COMMENT ON TABLE "approval_task_transfers" IS 'История запросов на передачу задач исполнения между пользователями'; - COMMENT ON COLUMN "approval_task_transfers".task_id IS 'Передаваемая задача'; - COMMENT ON COLUMN "approval_task_transfers".from_executor_id IS 'Исполнитель, инициировавший передачу'; - COMMENT ON COLUMN "approval_task_transfers".to_executor_id IS 'Пользователь, которому предлагается принять задачу'; - COMMENT ON COLUMN "approval_task_transfers".status IS 'Статус: pending | accepted | declined | cancelled'; - COMMENT ON COLUMN "approval_task_transfers".responded_at IS 'Когда получатель ответил на запрос'; - `) - } - - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_task_id ON approval_task_transfers (task_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_to_executor_id ON approval_task_transfers (to_executor_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_status ON approval_task_transfers (status)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_att_task_status ON approval_task_transfers (task_id, status)`) - - return nil -} - ------END core/db/db_migration/tables/approval_task_transfer.go----- - -File: core/db/db_migration/tables/approval_topic.go -Lines: 44 ------BEGIN core/db/db_migration/tables/approval_topic.go----- -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 'Дата последнего обновления записи'; - `) - } - - // 🚀 code — уникальность/поиск при создании темы; category_id — под GetTopicsListHandler фильтр и enrich; - // композит category_id+is_active — под список активных тем категории (частый сценарий в боте) - db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_approval_topics_code ON approval_topics (code)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topics_category_id ON approval_topics (category_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topics_category_active ON approval_topics (category_id, is_active)`) - - return nil -} - ------END core/db/db_migration/tables/approval_topic.go----- - -File: core/db/db_migration/tables/approval_topic_category.go -Lines: 37 ------BEGIN core/db/db_migration/tables/approval_topic_category.go----- -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 - } - - 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`) - - 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 'Дата последнего обновления записи'; - `) - } - - // 🚀 code используется в GetApprovalTopicCategoryByCodeDB и в JOIN'ах GetObserversForApprovalDB/GetUserPermissionsDB - db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_approval_topic_categories_code ON approval_topic_categories (code)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_categories_active ON approval_topic_categories (is_active)`) - - return nil -} - ------END core/db/db_migration/tables/approval_topic_category.go----- - -File: core/db/db_migration/tables/approval_topic_executor.go -Lines: 44 ------BEGIN core/db/db_migration/tables/approval_topic_executor.go----- -package tablesmigration - -import ( - "gorm.io/gorm" - "time" -) - -func ApprovalTopicExecutorsTableMigrate(db *gorm.DB) error { - hasTable := db.Migrator().HasTable(&LocalApprovalTopicExecutorProvider{}) - - if err := db.AutoMigrate(&LocalApprovalTopicExecutorProvider{}); err != nil { - return err - } - - if !hasTable { - time.Sleep(5 * time.Second) - - db.Exec(`ALTER TABLE approval_topic_executor ADD CONSTRAINT fk_users FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`) - db.Exec(`ALTER TABLE approval_topic_executor ADD CONSTRAINT fk_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE SET NULL ON UPDATE CASCADE`) - - execComments(db, ` - COMMENT ON TABLE "approval_topic_executor" IS 'Исполнители шагов согласования по темам'; - COMMENT ON COLUMN "approval_topic_executor".id IS 'Внутренний ID записи исполнителя'; - COMMENT ON COLUMN "approval_topic_executor".topic_id IS 'ID темы согласования, к которой относится шаг'; - COMMENT ON COLUMN "approval_topic_executor".user_id IS 'ID пользователя, назначенного исполнителем на данном шаге'; - COMMENT ON COLUMN "approval_topic_executor".step_order IS 'Порядковый номер шага согласования'; - COMMENT ON COLUMN "approval_topic_executor".require_file IS 'Требуется ли от исполнителя прикрепление файла'; - COMMENT ON COLUMN "approval_topic_executor".task_text IS 'Текст задачи или комментарий для исполнителя'; - COMMENT ON COLUMN "approval_topic_executor".is_active IS 'Активен ли данный шаг/исполнитель в маршруте согласования'; - COMMENT ON COLUMN "approval_topic_executor".created_at IS 'Дата создания записи'; - COMMENT ON COLUMN "approval_topic_executor".updated_at IS 'Дата последнего обновления записи'; - `) - } - - // 🚀 Композит покрывает GetExecutorsByTopicIDDB (topic_id + is_active + ORDER BY step_order) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_executor_topic_active_step ON approval_topic_executor (topic_id, is_active, step_order)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_executor_user_id ON approval_topic_executor (user_id)`) - // Уникальность под проверку "исполнитель уже назначен на этот шаг" в CreateTopicExecutorHandler - db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_approval_topic_executor_topic_user_step ON approval_topic_executor (topic_id, user_id, step_order)`) - // Под фильтрацию GetApprovalTopicExecutorListByCategoryDB (JOIN approval_topics ON t.category_id) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_executor_id_step ON approval_topic_executor (id, step_order)`) - - return nil -} - ------END core/db/db_migration/tables/approval_topic_executor.go----- - -File: core/db/db_migration/tables/department.go -Lines: 34 ------BEGIN core/db/db_migration/tables/department.go----- -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 'Дата последнего обновления записи'; - `) - } - - db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_departments_code ON departments (code)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_departments_active ON departments (is_active)`) - - return nil -} - ------END core/db/db_migration/tables/department.go----- - -File: core/db/db_migration/tables/directors_category_subscription.go -Lines: 33 ------BEGIN core/db/db_migration/tables/directors_category_subscription.go----- -package tablesmigration - -import ( - "gorm.io/gorm" - "time" -) - -func DirectorNotificationSubscriptionsTableMigrate(db *gorm.DB) error { - hasTable := db.Migrator().HasTable(&LocalDirectorNotificationSubscriptionProvider{}) - - if err := db.AutoMigrate(&LocalDirectorNotificationSubscriptionProvider{}); err != nil { - return err - } - - if !hasTable { - time.Sleep(5 * time.Second) - - db.Exec(`ALTER TABLE director_notification_subscriptions ADD CONSTRAINT fk_dns_director_id FOREIGN KEY (director_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) - db.Exec(`ALTER TABLE director_notification_subscriptions ADD CONSTRAINT fk_dns_category_id FOREIGN KEY (category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`) - db.Exec(`ALTER TABLE director_notification_subscriptions ADD CONSTRAINT uq_dns_director_category UNIQUE (director_id, category_id)`) - - execComments(db, ` - COMMENT ON TABLE "director_notification_subscriptions" IS 'Подписки директоров на уведомления по категориям тем согласования. Наличие строки = подписка включена, по умолчанию для всех категорий выключено'; - COMMENT ON COLUMN "director_notification_subscriptions".director_id IS 'Директор, оформивший подписку'; - COMMENT ON COLUMN "director_notification_subscriptions".category_id IS 'Категория тем, на которую подписан директор'; - `) - } - - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_dns_director_id ON director_notification_subscriptions (director_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_dns_category_id ON director_notification_subscriptions (category_id)`) - - return nil -} - ------END core/db/db_migration/tables/directors_category_subscription.go----- - -File: core/db/db_migration/tables/helpers.go -Lines: 15 ------BEGIN core/db/db_migration/tables/helpers.go----- -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) - } -} - ------END core/db/db_migration/tables/helpers.go----- - -File: core/db/db_migration/tables/notifications.go -Lines: 66 ------BEGIN core/db/db_migration/tables/notifications.go----- -package tablesmigration - -import ( - "gorm.io/gorm" - "time" -) - -func NotificationsTableMigrate(db *gorm.DB) error { - hasNotificationsTable := db.Migrator().HasTable(&LocalNotificationProvider{}) - hasRecipientsTable := db.Migrator().HasTable(&LocalNotificationRecipientProvider{}) - - if err := db.AutoMigrate(&LocalNotificationProvider{}); err != nil { - return err - } - if err := db.AutoMigrate(&LocalNotificationRecipientProvider{}); err != nil { - return err - } - - if !hasNotificationsTable || !hasRecipientsTable { - time.Sleep(5 * time.Second) - - db.Exec(`ALTER TABLE notifications ADD CONSTRAINT fk_notifications_created_by_id FOREIGN KEY (created_by_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`) - - db.Exec(`ALTER TABLE notification_recipients ADD CONSTRAINT fk_notification_recipients_notification_id FOREIGN KEY (notification_id) REFERENCES notifications(id) ON DELETE CASCADE ON UPDATE CASCADE`) - db.Exec(`ALTER TABLE notification_recipients ADD CONSTRAINT fk_notification_recipients_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) - - execComments(db, ` - COMMENT ON TABLE "notifications" IS 'Уведомления/рассылки, отправляемые администратором через Telegram-бота'; - COMMENT ON COLUMN "notifications".id IS 'Внутренний ID уведомления'; - COMMENT ON COLUMN "notifications".title IS 'Заголовок рассылки (для админки, не отправляется в Telegram)'; - COMMENT ON COLUMN "notifications".message_html IS 'Текст сообщения в HTML-разметке, совместимой с Telegram ParseMode=HTML'; - COMMENT ON COLUMN "notifications".photo_base64 IS 'Прикреплённое фото в формате base64, опционально'; - COMMENT ON COLUMN "notifications".photo_file_name IS 'Оригинальное имя прикреплённого файла фото'; - COMMENT ON COLUMN "notifications".target_filters IS 'Критерии выбора получателей (user_ids, role_ids, role_type_flags, department_ids) в формате JSON, для аудита'; - COMMENT ON COLUMN "notifications".status IS 'Статус рассылки: pending | sending | completed | failed'; - COMMENT ON COLUMN "notifications".total_count IS 'Общее число подобранных получателей'; - COMMENT ON COLUMN "notifications".sent_count IS 'Число успешно доставленных сообщений'; - COMMENT ON COLUMN "notifications".failed_count IS 'Число сообщений с ошибкой доставки'; - COMMENT ON COLUMN "notifications".created_by_id IS 'Администратор, инициировавший рассылку'; - COMMENT ON COLUMN "notifications".created_at IS 'Дата создания рассылки'; - COMMENT ON COLUMN "notifications".updated_at IS 'Дата последнего изменения статуса рассылки'; - COMMENT ON COLUMN "notifications".sent_at IS 'Дата фактической отправки рассылки получателям'; - - COMMENT ON TABLE "notification_recipients" IS 'История доставки уведомления конкретным пользователям'; - COMMENT ON COLUMN "notification_recipients".id IS 'Внутренний ID записи истории доставки'; - COMMENT ON COLUMN "notification_recipients".notification_id IS 'Уведомление, к которому относится доставка'; - COMMENT ON COLUMN "notification_recipients".user_id IS 'Получатель уведомления'; - COMMENT ON COLUMN "notification_recipients".status IS 'Статус доставки: pending | sent | failed'; - COMMENT ON COLUMN "notification_recipients".error_message IS 'Текст ошибки при неудачной отправке'; - COMMENT ON COLUMN "notification_recipients".telegram_message_id IS 'ID отправленного сообщения в Telegram, если доставка успешна'; - COMMENT ON COLUMN "notification_recipients".sent_at IS 'Дата и время фактической отправки этому получателю'; - COMMENT ON COLUMN "notification_recipients".created_at IS 'Дата создания записи (постановка в очередь на отправку)'; - `) - } - - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_status ON notifications (status)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_created_at ON notifications (created_at DESC)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notifications_created_by_id ON notifications (created_by_id)`) - - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_notification_id ON notification_recipients (notification_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_user_id ON notification_recipients (user_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_status ON notification_recipients (status)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_notification_recipients_notification_status ON notification_recipients (notification_id, status)`) - - return nil -} - ------END core/db/db_migration/tables/notifications.go----- - -File: core/db/db_migration/tables/permission.go -Lines: 46 ------BEGIN core/db/db_migration/tables/permission.go----- -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 'Дата последнего обновления записи'; - `) - } - - // 🚀 role_id — под GetUserPermissionsDB JOIN с user_roles; композит role_id+action — под UserCanCreateTopicDB; - // topic_id/topic_category_id — под enrichPermissionsBatch и JOIN'ы наблюдателей - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_role_id ON permissions (role_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_role_id_action ON permissions (role_id, action)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_topic_id ON permissions (topic_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_topic_category_id ON permissions (topic_category_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_action ON permissions (action)`) - // Под GetObserversForCategoryDB / GetObserversForApprovalDB: action='observe' + topic_category_id - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_action_category ON permissions (action, topic_category_id)`) - - return nil -} - ------END core/db/db_migration/tables/permission.go----- - -File: core/db/db_migration/tables/providers.go -Lines: 104 ------BEGIN core/db/db_migration/tables/providers.go----- -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 ApprovalAdditionalObserver typescore.ApprovalAdditionalObserver -type ApprovalTaskProvider typescore.ApprovalTask -type ApprovalCommentsProvider typescore.ApprovalComment -type LocalSuggestionProvider typescore.Suggestion -type LocalSuggestionMessagesProvider typescore.SuggestionMessage -type LocalApprovalTopicExecutorProvider typescore.ApprovalTopicExecutor -type LocalNotificationProvider typescore.Notification -type LocalNotificationRecipientProvider typescore.NotificationRecipient -type LocalDirectorNotificationSubscriptionProvider typescore.DirectorNotificationSubscription -type LocalApprovalTaskTransferProvider typescore.ApprovalTaskTransfer -type LocalApprovalFlowNodeProvider typescore.ApprovalFlowNode - -func (LocalApprovalTaskTransferProvider) TableName() string { - return dbcoretablenames.TableNameApprovalTaskTransfers.ToString() -} -func (LocalDirectorNotificationSubscriptionProvider) TableName() string { - return dbcoretablenames.TableNameDirectorNotificationSubscriptions.ToString() -} -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() -} -func (ApprovalCommentsProvider) TableName() string { - return dbcoretablenames.TableNameApprovalComments.ToString() -} -func (LocalSuggestionProvider) TableName() string { - return dbcoretablenames.TableNameSuggestions.ToString() -} -func (LocalSuggestionMessagesProvider) TableName() string { - return dbcoretablenames.TableNameSuggestionMessages.ToString() -} -func (ApprovalAdditionalObserver) TableName() string { - return dbcoretablenames.TableNameApprovalAdditionalObservers.ToString() -} -func (LocalApprovalTopicExecutorProvider) TableName() string { - return dbcoretablenames.TableNameApprovalTopicExecutor.ToString() -} -func (LocalNotificationProvider) TableName() string { - return dbcoretablenames.TableNameNotifications.ToString() -} -func (LocalNotificationRecipientProvider) TableName() string { - return dbcoretablenames.TableNameNotificationsRecipients.ToString() -} -func (LocalApprovalFlowNodeProvider) TableName() string { - return dbcoretablenames.TableNameApprovalFlowNodes.ToString() -} - ------END core/db/db_migration/tables/providers.go----- - -File: core/db/db_migration/tables/role.go -Lines: 42 ------BEGIN core/db/db_migration/tables/role.go----- -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 'Дата последнего обновления записи'; - `) - } - - // 🚀 code — под GetUsersByRoleCodeDB; флаги is_director/is_approver/is_observer используются - // как условия в JOIN'ах GetDirectorsDB/IsDirectorDB/IsApproverDB/IsObserverDB/GetObserversForCategoryDB — - // частичные индексы дают максимальную выборочность, т.к. флаг true встречается редко - db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_roles_code ON roles (code)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_director ON roles (id) WHERE is_director = true`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_approver ON roles (id) WHERE is_approver = true`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_observer ON roles (id) WHERE is_observer = true`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_default ON roles (id) WHERE is_default = true`) - - return nil -} - ------END core/db/db_migration/tables/role.go----- - -File: core/db/db_migration/tables/sms_log.go -Lines: 31 ------BEGIN core/db/db_migration/tables/sms_log.go----- -package tablesmigration - -import ( - "bitrix_balancer_api/core/typescore" - "gorm.io/gorm" - "time" -) - -type LocalSmsLogProvider typescore.SmsLog - -func (LocalSmsLogProvider) TableName() string { - return "sms_logs" -} - -func SmsLogsTableMigrate(db *gorm.DB) error { - hasTable := db.Migrator().HasTable(&LocalSmsLogProvider{}) - - err := db.AutoMigrate(&LocalSmsLogProvider{}) - if err != nil { - return err - } - - if !hasTable { - time.Sleep(5 * time.Second) - db.Exec(` - COMMENT ON TABLE sms_logs IS 'Таблица для хранения логов SMS из внешней телефонии'; - COMMENT ON COLUMN sms_logs.direction IS '0 - входящее, 1 - исходящее'; - `) - } - return nil -} - ------END core/db/db_migration/tables/sms_log.go----- - -File: core/db/db_migration/tables/suggestion_messages.go -Lines: 38 ------BEGIN core/db/db_migration/tables/suggestion_messages.go----- -package tablesmigration - -import ( - "gorm.io/gorm" - "time" -) - -func SuggestionMessagesTableMigrate(db *gorm.DB) error { - hasTable := db.Migrator().HasTable(&LocalSuggestionMessagesProvider{}) - - if err := db.AutoMigrate(&LocalSuggestionMessagesProvider{}); err != nil { - return err - } - - if !hasTable { - time.Sleep(5 * time.Second) - - db.Exec(`ALTER TABLE suggestion_messages ADD CONSTRAINT fk_suggestion_messages_suggestion_id FOREIGN KEY (suggestion_id) REFERENCES suggestions(id) ON DELETE CASCADE ON UPDATE CASCADE`) - db.Exec(`ALTER TABLE suggestion_messages ADD CONSTRAINT fk_suggestion_messages_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`) - - execComments(db, ` - COMMENT ON TABLE "suggestion_messages" IS 'Сообщения переписки в рамках обсуждения предложения'; - COMMENT ON COLUMN "suggestion_messages".id IS 'Внутренний уникальный идентификатор сообщения'; - COMMENT ON COLUMN "suggestion_messages".suggestion_id IS 'ID предложения, к которому относится сообщение (ссылка на suggestions.id)'; - COMMENT ON COLUMN "suggestion_messages".user_id IS 'ID автора сообщения (ссылка на users.id)'; - COMMENT ON COLUMN "suggestion_messages".message IS 'Текст сообщения'; - COMMENT ON COLUMN "suggestion_messages".file_data IS 'Прикреплённый файл в формате base64 (опционально)'; - COMMENT ON COLUMN "suggestion_messages".file_name IS 'Оригинальное имя прикреплённого файла (опционально)'; - COMMENT ON COLUMN "suggestion_messages".created_at IS 'Дата и время отправки сообщения'; - `) - } - - // 🚀 Композит покрывает "переписка по предложению в хронологическом порядке" - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestion_messages_suggestion_id_created_at ON suggestion_messages (suggestion_id, created_at)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestion_messages_user_id ON suggestion_messages (user_id)`) - - return nil -} - ------END core/db/db_migration/tables/suggestion_messages.go----- - -File: core/db/db_migration/tables/suggestions.go -Lines: 38 ------BEGIN core/db/db_migration/tables/suggestions.go----- -package tablesmigration - -import ( - "gorm.io/gorm" - "time" -) - -func SuggestionsTableMigrate(db *gorm.DB) error { - hasTable := db.Migrator().HasTable(&LocalSuggestionProvider{}) - - if err := db.AutoMigrate(&LocalSuggestionProvider{}); err != nil { - return err - } - - if !hasTable { - time.Sleep(5 * time.Second) - - db.Exec(`ALTER TABLE suggestions ADD CONSTRAINT fk_suggestions_initiator_id FOREIGN KEY (initiator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) - db.Exec(`ALTER TABLE suggestions ADD CONSTRAINT fk_suggestions_director_id FOREIGN KEY (director_id) REFERENCES users(id) ON DELETE SET NULL ON UPDATE CASCADE`) - - execComments(db, ` - COMMENT ON TABLE "suggestions" IS 'Предложения и обращения сотрудников к руководству'; - COMMENT ON COLUMN "suggestions".id IS 'Внутренний уникальный идентификатор предложения'; - COMMENT ON COLUMN "suggestions".initiator_id IS 'ID сотрудника, создавшего предложение (ссылка на users.id)'; - COMMENT ON COLUMN "suggestions".director_id IS 'ID руководителя, к которому обращено предложение (ссылка на users.id)'; - COMMENT ON COLUMN "suggestions".subject IS 'Тема или заголовок предложения'; - COMMENT ON COLUMN "suggestions".status IS 'Статус предложения: open (открыто) | closed (закрыто)'; - COMMENT ON COLUMN "suggestions".created_at IS 'Дата и время создания предложения'; - COMMENT ON COLUMN "suggestions".updated_at IS 'Дата и время последнего изменения предложения'; - `) - } - - // 🚀 Композиты под "мои открытые предложения" / "предложения, адресованные директору" - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestions_initiator_status ON suggestions (initiator_id, status)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestions_director_status ON suggestions (director_id, status)`) - - return nil -} - ------END core/db/db_migration/tables/suggestions.go----- - -File: core/db/db_migration/tables/user.go -Lines: 50 ------BEGIN core/db/db_migration/tables/user.go----- -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 CASCADE 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 'Дата последнего обновления записи'; - `) - } - - // 🚀 telegram_id — под GetUserByTelegramIDDB (уникальный лукап при каждом сообщении в бота); - // department_id — под фильтр users и JOIN'ы в enrichUsersBatch; - // pg_trgm-индекс под LIKE-поиск по full_name (GetUserListHandler search) - db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_users_telegram_id ON users (telegram_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_department_id ON users (department_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_is_blocked ON users (is_blocked)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_is_fired ON users (is_fired)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_created_at ON users (created_at DESC)`) - // Композит под самый частый вызов фильтра списка: не заблокирован + не уволен - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_blocked_fired ON users (is_blocked, is_fired)`) - // Требует расширения pg_trgm: CREATE EXTENSION IF NOT EXISTS pg_trgm; - db.Exec(`CREATE EXTENSION IF NOT EXISTS pg_trgm`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_full_name_trgm ON users USING gin (full_name gin_trgm_ops)`) - - return nil -} - ------END core/db/db_migration/tables/user.go----- - -File: core/db/db_migration/tables/user_hierarchy.go -Lines: 40 ------BEGIN core/db/db_migration/tables/user_hierarchy.go----- -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 'Дата последнего обновления записи'; - `) - } - - // 🚀 Композит покрывает основной сценарий: "цепочка согласующих подчинённого в отделе по приоритету" - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_hierarchy_subordinate_dept_priority ON user_hierarchy (subordinate_id, department_id, priority)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_hierarchy_approver_id ON user_hierarchy (approver_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_hierarchy_department_id ON user_hierarchy (department_id)`) - - return nil -} - ------END core/db/db_migration/tables/user_hierarchy.go----- - -File: core/db/db_migration/tables/user_role.go -Lines: 39 ------BEGIN core/db/db_migration/tables/user_role.go----- -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 'Дата последнего обновления записи'; - `) - } - - // 🚀 Индексы: user_id — под GetUserRolesByUserIDsDB/DeleteUserRolesByUserIDDB, - // role_id — под GetPermissionsByRoleIDHandler JOIN'ы, - // уникальный композит — защита от дублей роли у пользователя + быстрый lookup в AssignUserRoleHandler - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_roles_user_id ON user_roles (user_id)`) - db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_roles_role_id ON user_roles (role_id)`) - db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_user_roles_user_role ON user_roles (user_id, role_id)`) - - return nil -} - ------END core/db/db_migration/tables/user_role.go----- - -File: core/db/db_migration/tables.go -Lines: 59 ------BEGIN core/db/db_migration/tables.go----- -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, - tablesmigration.ApprovalCommentsTableMigrate, - tablesmigration.SuggestionsTableMigrate, - tablesmigration.SuggestionMessagesTableMigrate, - tablesmigration.ApprovalAdditionalObserverTableMigrate, - tablesmigration.ApprovalTopicExecutorsTableMigrate, - tablesmigration.AdminsTableMigrate, - - tablesmigration.NotificationsTableMigrate, - tablesmigration.DirectorNotificationSubscriptionsTableMigrate, - tablesmigration.ApprovalTaskTransfersTableMigrate, - tablesmigration.ApprovalRevocationTablesMigrate, - tablesmigration.ApprovalFlowNodesTableMigrate, - tablesmigration.AdminActionLogsTableMigrate, - - tablesmigration.SmsLogsTableMigrate, - } - - for _, migrate := range migrations { - if err := migrate(m.gormDB); err != nil { - return err - } - } - - return nil -} - ------END core/db/db_migration/tables.go----- - -File: core/db/db_migration/triggers.go -Lines: 157 ------BEGIN core/db/db_migration/triggers.go----- -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())) -} - ------END core/db/db_migration/triggers.go----- - -File: core/db/methods/admin.go -Lines: 248 ------BEGIN core/db/methods/admin.go----- -package dbcore - -import ( - dbcoretablenames "bitrix_balancer_api/core/db/table_names" - "bitrix_balancer_api/core/typescore" - dbutils "bitrix_balancer_api/core/utilscore/db" - "bitrix_balancer_api/core/variables" - "context" - "errors" - "fmt" - "strings" - - "github.com/Masterminds/squirrel" - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgxpool" - "github.com/sirupsen/logrus" -) - -type AdminDB struct { - pool *pgxpool.Pool -} - -func NewAdminDB(pool *pgxpool.Pool) *AdminDB { - - return &AdminDB{pool: pool} -} - -type AdminDBI interface { - GetAdminsListDB(options ...typescore.ListDbOptions) ([]*typescore.Admin, uint64, error) - CreateAdminDB(tx pgx.Tx, adminObj *typescore.Admin, returnObj ...bool) (*typescore.Admin, pgx.Tx, error) - UpdateAdminDB(tx pgx.Tx, paramsUpdate *typescore.Admin, returnObj ...bool) (*typescore.Admin, pgx.Tx, error) - DeleteAdminDB(params *typescore.Admin) error - - CheckAdminAvailabilityDB(email *string) (bool, error) -} - -func (u *AdminDB) GetAdminsListDB(opts ...typescore.ListDbOptions) ([]*typescore.Admin, uint64, error) { - ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase) - defer cancel() - - fields := dbutils.GetStructFieldsDB(&typescore.Admin{}, dbcoretablenames.TableNameAdmin.ToString()) - // Добавляем поле total_count - selectFields := append(fields, "COUNT(*) OVER() AS total_count") - - // Используем обобщённую функцию для обработки опций - options, filter, err := dbutils.GetOptionsDB[typescore.Admin](opts...) - if err != nil { - return nil, 0, errors.New(fmt.Sprintf("%s: failed to parse options for %s: %v", "error_get", dbcoretablenames.TableNameAdmin.ToString(), err)) - } - - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameAdmin.ToString(), selectFields) - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameAdmin.ToString()) - query = query.OrderBy("created_at DESC") - - sql, args, err := query.ToSql() - if err != nil { - return nil, 0, errors.New(fmt.Sprintf("%s: failed to create SELECT %s SQL: %v", "error_get", dbcoretablenames.TableNameAdmin.ToString(), err)) - } - - rows, err := u.pool.Query(ctx, sql, args...) - if err != nil { - return nil, 0, errors.New(fmt.Sprintf("%s: failed to execute query on %s SQL: %v", "error_get", dbcoretablenames.TableNameAdmin.ToString(), err)) - } - defer rows.Close() - - var admins []*typescore.Admin - var totalCount uint64 - for rows.Next() { - admin := &typescore.Admin{} - if err := dbutils.ScanRowsToStructRows(rows, admin, &totalCount); err != nil { - logrus.Errorf("🔴 error: %s: %+v", "GetAdminsListDB-ScanRowsToStructRows", err) - continue - } - admins = append(admins, admin) - } - - return admins, totalCount, nil -} - -// CreateAdminDB Создает нового пользователя -func (u *AdminDB) CreateAdminDB(tx pgx.Tx, adminObj *typescore.Admin, returnObj ...bool) (*typescore.Admin, pgx.Tx, error) { - if adminObj == nil { - return nil, nil, errors.New(fmt.Sprintf("object_is_nil: failed to create %s INSERT SQL. error: %s", dbcoretablenames.TableNameAdmin.ToString(), "adminObj is nil")) - } - - ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase) - defer cancel() - - err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameAdmin.ToString()) - - sqlV, args, err := dbutils.GenerateInsertRequest(query, adminObj) - if err != nil { - return err - } - - _, err = tx.Exec(ctx, *sqlV, args...) - if err != nil { - logrus.Errorf("🔴 error: %s: %+v", "CreateAdminDB-Exec", err) - return err - } - - return nil - }) - - if err != nil { - return nil, tx, err - } - - returnObjBool := false - if len(returnObj) > 0 { - returnObjBool = returnObj[0] - } - if returnObjBool { - admin, _, err := u.GetAdminsListDB(typescore.ListDbOptions{Filtering: adminObj}) - if err != nil { - return nil, tx, err - } - if len(admin) > 0 { - return admin[0], tx, nil - } - } - - return nil, tx, nil -} - -func (u *AdminDB) UpdateAdminDB(tx pgx.Tx, paramsUpdate *typescore.Admin, returnObj ...bool) (*typescore.Admin, pgx.Tx, error) { - if paramsUpdate.ID == nil && paramsUpdate.Login == nil { - logrus.Errorf("❌ UpdateAdminDB error: %s", errors.New("id and email is nil")) - return nil, nil, errors.New(fmt.Sprintf("error_update: failed to create UPDATE %s SQL: %v", dbcoretablenames.TableNameAdmin.ToString(), errors.New("id and email is nil"))) - } - - ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase) - defer cancel() - - err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameAdmin.ToString()) - - // Используем функцию для добавления ненулевых полей в запрос - query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) - - // Добавляем условие WHERE - if paramsUpdate.ID != nil { - query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) - } - if paramsUpdate.Login != nil { - query = query.Where(squirrel.Eq{"login": paramsUpdate.Login}) - } - - // Генерируем SQL и аргументы - sql, args, err := query.ToSql() - if err != nil { - logrus.Errorf("🔴 error: %s: %+v", "UpdateAdminDB-ToSql", err) - return err - } - - _, err = tx.Exec(ctx, sql, args...) - if err != nil { - logrus.Errorf("🔴 error: %s: %+v", "UpdateAdminDB-Exec", err) - if strings.Contains(err.Error(), "violates foreign key constraint") { - return err - } - 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.Admin{ID: paramsUpdate.ID}} - getInfoUp, _, errW := u.GetAdminsListDB(options) - if errW != nil { - logrus.Errorf("🔴 error: %s: %+v", "UpdateAdminDB-GetAdminsListDB", errW) - return nil, nil, errW - } - if len(getInfoUp) > 0 { - return getInfoUp[0], tx, nil - } - } - - return nil, tx, nil -} - -func (u *AdminDB) DeleteAdminDB(params *typescore.Admin) error { - if params != nil && params.ID != nil { - ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase) - defer cancel() - - query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Delete(dbcoretablenames.TableNameAdmin.ToString()). - Where(squirrel.Eq{"id": *params.ID}). - ToSql() - - if err != nil { - return errors.New(fmt.Sprintf("error_delete: failed to create DELETE %s SQL: %v", dbcoretablenames.TableNameAdmin.ToString(), err)) - } - - _, err = u.pool.Exec(ctx, query, args...) - if err != nil { - return err - } - - return nil - } else { - return errors.New(fmt.Sprintf("error_delete: failed to create DELETE %s SQL: %v", dbcoretablenames.TableNameAdmin.ToString(), errors.New("admin obj is nil"))) - } -} - -func (u *AdminDB) CheckAdminAvailabilityDB(email *string) (bool, error) { - ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase) - defer cancel() - - if email == nil { - return false, errors.New("error_check_admin_availability: email is nil") - } - - query := squirrel.StatementBuilder. - PlaceholderFormat(squirrel.Dollar). - Select("EXISTS(SELECT 1)"). - From(dbcoretablenames.TableNameAdmin.ToString()). - Where(squirrel.Eq{"email": *email}). - Where(squirrel.Eq{"is_blocked": false}) - - sql, args, err := query.ToSql() - if err != nil { - logrus.Errorln("🔴 error: CheckAdminAvailabilityDB-ToSql:", email, err) - return false, errors.New(fmt.Sprintf("error_check_admin_availability: %v", err)) - } - - var exists bool - err = u.pool.QueryRow(ctx, sql, args...).Scan(&exists) - if err != nil { - logrus.Errorln("🔴 error: CheckAdminAvailabilityDB-QueryRow", email, err) - return false, errors.New(fmt.Sprintf("error_check_admin_availability: %v", err)) - } - - return exists, nil -} - ------END core/db/methods/admin.go----- - -File: core/db/methods/admin_action_logs.go -Lines: 192 ------BEGIN core/db/methods/admin_action_logs.go----- -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 AdminActionLogDB struct { - pool *pgxpool.Pool -} - -func NewAdminActionLogDB(pool *pgxpool.Pool) *AdminActionLogDB { - return &AdminActionLogDB{pool: pool} -} - -type AdminActionLogDBI interface { - GetAdminActionLogsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.AdminActionLog, uint64, error) - CreateAdminActionLogDB(ctx context.Context, tx pgx.Tx, obj *typescore.AdminActionLog, returnObj ...bool) (*typescore.AdminActionLog, pgx.Tx, error) - DeleteAdminActionLogDB(ctx context.Context, params *typescore.AdminActionLog) error - GetAdminActionLogByIDDB(ctx context.Context, id uint64) (*typescore.AdminActionLog, error) - GetAdminActionLogsFilteredDB(ctx context.Context, filter typescore.AdminActionLogFilter, offset, limit *uint64) ([]*typescore.AdminActionLog, uint64, error) -} - -func (u *AdminActionLogDB) GetAdminActionLogsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.AdminActionLog, uint64, error) { - fields := dbutils.GetStructFieldsDB(&typescore.AdminActionLog{}, dbcoretablenames.TableNameAdminActionLogs.ToString()) - selectFields := append(fields, "COUNT(*) OVER() AS total_count") - - options, filter, err := dbutils.GetOptionsDB[typescore.AdminActionLog](opts...) - if err != nil { - return nil, 0, err - } - - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameAdminActionLogs.ToString(), selectFields) - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameAdminActionLogs.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 logs []*typescore.AdminActionLog - var totalCount uint64 - for rows.Next() { - entry := &typescore.AdminActionLog{} - if err := dbutils.ScanRowsToStructRows(rows, entry, &totalCount); err != nil { - logrus.Warn("GetAdminActionLogsListDB:ScanRowsToStructRows", err) - continue - } - logs = append(logs, entry) - } - - return logs, totalCount, nil -} - -func (u *AdminActionLogDB) GetAdminActionLogsFilteredDB(ctx context.Context, filter typescore.AdminActionLogFilter, offset, limit *uint64) ([]*typescore.AdminActionLog, uint64, error) { - fields := dbutils.GetStructFieldsDB(&typescore.AdminActionLog{}, dbcoretablenames.TableNameAdminActionLogs.ToString()) - selectFields := append(fields, "COUNT(*) OVER() AS total_count") - - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameAdminActionLogs.ToString(), selectFields) - - if filter.AdminID != nil { - query = query.Where(squirrel.Eq{"admin_id": *filter.AdminID}) - } - if filter.AdminLogin != nil && *filter.AdminLogin != "" { - query = query.Where(squirrel.ILike{"admin_login": "%" + *filter.AdminLogin + "%"}) - } - if filter.Action != nil { - query = query.Where(squirrel.Eq{"action": *filter.Action}) - } - if filter.EntityType != nil { - query = query.Where(squirrel.Eq{"entity_type": *filter.EntityType}) - } - if filter.EntityID != nil { - query = query.Where(squirrel.Eq{"entity_id": *filter.EntityID}) - } - if filter.DateFrom != nil { - query = query.Where(squirrel.GtOrEq{"created_at": *filter.DateFrom}) - } - if filter.DateTo != nil { - query = query.Where(squirrel.LtOrEq{"created_at": *filter.DateTo}) - } - if filter.Search != nil && *filter.Search != "" { - query = query.Where(squirrel.ILike{"description": "%" + *filter.Search + "%"}) - } - - query = dbutils.SetterLimitAndOffsetQuery(query, offset, limit) - 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 logs []*typescore.AdminActionLog - var totalCount uint64 - for rows.Next() { - entry := &typescore.AdminActionLog{} - if err := dbutils.ScanRowsToStructRows(rows, entry, &totalCount); err != nil { - logrus.Warn("GetAdminActionLogsFilteredDB:ScanRowsToStructRows", err) - continue - } - logs = append(logs, entry) - } - - return logs, totalCount, nil -} - -func (u *AdminActionLogDB) CreateAdminActionLogDB(ctx context.Context, tx pgx.Tx, obj *typescore.AdminActionLog, returnObj ...bool) (*typescore.AdminActionLog, pgx.Tx, error) { - if obj == nil { - return nil, nil, errors.New("AdminActionLog 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.TableNameAdminActionLogs.ToString()) - - sqlV, args, err := dbutils.GenerateInsertRequest(query, obj) - 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.GetAdminActionLogByIDDB(ctx, insertedID) - return created, tx, err - } - return nil, tx, nil -} - -func (u *AdminActionLogDB) DeleteAdminActionLogDB(ctx context.Context, params *typescore.AdminActionLog) error { - if params == nil || params.ID == nil { - return errors.New("AdminActionLog obj is nil") - } - - query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Delete(dbcoretablenames.TableNameAdminActionLogs.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 -} - -func (u *AdminActionLogDB) GetAdminActionLogByIDDB(ctx context.Context, id uint64) (*typescore.AdminActionLog, error) { - logs, _, err := u.GetAdminActionLogsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.AdminActionLog{ID: &id}, - }) - if err != nil { - return nil, err - } - if len(logs) == 0 { - return nil, nil - } - return logs[0], nil -} - ------END core/db/methods/admin_action_logs.go----- - -File: core/db/methods/approval.go -Lines: 740 ------BEGIN core/db/methods/approval.go----- -package dbcore - -import ( - dbcoretablenames "bitrix_balancer_api/core/db/table_names" - "bitrix_balancer_api/core/typescore" - dbutils "bitrix_balancer_api/core/utilscore/db" - "context" - "database/sql" - "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) - SearchApprovalsByContentDB(ctx context.Context, content string, opts ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error) - GetOldPendingApprovalsDB(ctx context.Context, since time.Time, limit int) ([]*typescore.Approval, error) - CountApprovalsDB(ctx context.Context, filter *typescore.Approval) (int, error) - CountApprovalsCreatedOnDB(ctx context.Context, date time.Time) (int, error) - CountApprovalsApprovedOnDB(ctx context.Context, date time.Time) (int, error) - GetTopTopicsDB(ctx context.Context, limit int) ([]map[string]interface{}, error) - GetApprovalsListFilteredDB(ctx context.Context, filter typescore.ApprovalFilter, offset, limit uint64) ([]*typescore.Approval, uint64, error) -} - -// GetApprovalsListFilteredDB — расширенный метод с JOIN'ами и поддержкой массивов -func (u *ApprovalDB) GetApprovalsListFilteredDB(ctx context.Context, filter typescore.ApprovalFilter, offset, limit uint64) ([]*typescore.Approval, uint64, error) { - q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("DISTINCT a.*, COUNT(*) OVER() AS total_count"). - From("approvals a"). - LeftJoin("approval_topics t ON t.id = a.topic_id"). - LeftJoin("approval_topic_categories c ON c.id = t.category_id"). - OrderBy("a.created_at DESC") - - if filter.ObserverUserID != nil { - subQ1 := buildApprovalIdSubquery("initiator", filter.ObserverUserID) - subQ2 := buildApprovalIdSubquery("approver", filter.ObserverUserID) - subQ3 := buildApprovalIdSubquery("observer", filter.ObserverUserID) - subQ4 := buildApprovalIdSubquery("executor", filter.ObserverUserID) - subQ5 := buildApprovalIdSubquery("additional_approver", filter.ObserverUserID) - subQ6 := buildApprovalIdSubquery("additional_observer", filter.ObserverUserID) - - 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() - s5, a5, _ := subQ5.PlaceholderFormat(squirrel.Question).ToSql() - s6, a6, _ := subQ6.PlaceholderFormat(squirrel.Question).ToSql() - - unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4, s5, s6) - allArgs := append(append(append(append(append(a1, a2...), a3...), a4...), a5...), a6...) - - q = q.Where(squirrel.Expr("a.id IN ("+unionSQL+")", allArgs...)) - } - - if filter.Status != nil && *filter.Status != "" { - q = q.Where(squirrel.Eq{"a.status": *filter.Status}) - } - if filter.InitiatorID != nil { - q = q.Where(squirrel.Eq{"a.initiator_id": *filter.InitiatorID}) - } - if filter.DepartmentID != nil { - q = q.Where(squirrel.Eq{"a.department_id": *filter.DepartmentID}) - } - if filter.ID != nil { - q = q.Where(squirrel.Eq{"a.id": *filter.ID}) - } - if filter.Content != nil && *filter.Content != "" { - q = q.Where(squirrel.Like{"a.content": "%" + *filter.Content + "%"}) - } - - 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}) - } - if len(filter.CategoryIDs) > 0 { - q = q.Where(squirrel.Eq{"t.category_id": filter.CategoryIDs}) - } - if len(filter.TopicIDs) > 0 { - q = q.Where(squirrel.Eq{"a.topic_id": filter.TopicIDs}) - } - - // Пагинация - if limit > 0 { - q = q.Limit(limit) - } - if offset > 0 { - q = q.Offset(offset) - } - - sql, args, err := q.ToSql() - if err != nil { - return nil, 0, err - } - - logrus.Infof("🔍 GetApprovalsListFilteredDB SQL: %s", sql) - logrus.Infof("🔍 GetApprovalsListFilteredDB Args: %v", args) - - 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("GetApprovalsListFilteredDB:ScanRowsToStructRows", err) - continue - } - approvals = append(approvals, approval) - } - - return approvals, totalCount, nil -} - -// SearchApprovalsByContentDB — поиск заявок по частичному совпадению в тексте -func (u *ApprovalDB) SearchApprovalsByContentDB(ctx context.Context, content string, opts ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error) { - fields := dbutils.GetStructFieldsDB(&typescore.Approval{}, "approvals") - 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("approvals", selectFields) - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - - // 🆕 Для collation "C" используем явное приведение - // Вариант 1: Через CAST с collation - query = query.Where( - squirrel.Expr( - "approvals.content::text ILIKE ? COLLATE \"ru_RU.UTF-8\"", - "%"+content+"%", - ), - ) - - // Применяем остальные фильтры - query = dbutils.ApplyFilters(query, filter, nil, "approvals") - query = query.OrderBy("approvals.created_at DESC") - - sql, args, err := query.ToSql() - if err != nil { - return nil, 0, err - } - - logrus.Infof("🔍 SearchApprovalsByContentDB SQL: %s", sql) - logrus.Infof("🔍 SearchApprovalsByContentDB Args: %v", args) - - rows, err := u.pool.Query(ctx, sql, args...) - if err != nil { - logrus.Errorf("❌ SearchApprovalsByContentDB error: %v", err) - 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("SearchApprovalsByContentDB:ScanRowsToStructRows", err) - continue - } - approvals = append(approvals, approval) - } - - logrus.Infof("✅ SearchApprovalsByContentDB found: %d approvals, total: %d", len(approvals), totalCount) - - return approvals, totalCount, nil -} - -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 — получение согласований для отчёта с учётом всех ролей пользователя. -// Пользователь видит согласования где он: инициатор, согласующий, наблюдатель или исполнитель. -// 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) - subQ5 := buildApprovalIdSubquery("additional_approver", filter.UserID) // 🆕 Доп. согласующий - subQ6 := buildApprovalIdSubquery("additional_observer", 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() - s5, a5, _ := subQ5.PlaceholderFormat(squirrel.Question).ToSql() // 🆕 - s6, a6, _ := subQ6.PlaceholderFormat(squirrel.Question).ToSql() // 🆕 - - unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4, s5, s6) - - allArgs := append(append(append(append(append(a1, a2...), a3...), a4...), a5...), a6...) - - 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 "additional_approver": - return q. - Join(dbcoretablenames.TableNameApprovalAdditionalApprovers.ToString() + " aaa ON aaa.approval_id = a.id"). - Where(squirrel.Eq{"aaa.approver_id": userID}) - - case "additional_observer": - return q. - Join(dbcoretablenames.TableNameApprovalAdditionalObservers.ToString() + " ao ON ao.approval_id = a.id"). - Where(squirrel.Eq{"ao.user_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.role_id IN (SELECT ur.role_id FROM user_roles ur WHERE ur.user_id = ?)", userID). - Where(squirrel.Eq{"p.action": "observe"}). - Where(squirrel.Or{ - squirrel.And{ - squirrel.Expr("p.topic_id IS NULL"), - squirrel.Expr("p.topic_category_id = c.id"), - }, - squirrel.Expr("p.topic_id = t.id"), - }) - - default: - return q.Where(squirrel.Expr("false")) - } -} - -// CountApprovalsDB — подсчёт заявок с фильтром -func (u *ApprovalDB) CountApprovalsDB(ctx context.Context, filter *typescore.Approval) (int, error) { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("COUNT(*)"). - From(dbcoretablenames.TableNameApprovals.ToString()) - - if filter != nil { - if filter.Status != nil { - query = query.Where(squirrel.Eq{"status": *filter.Status}) - } - } - - sql, args, err := query.ToSql() - if err != nil { - return 0, err - } - - var count int - err = u.pool.QueryRow(ctx, sql, args...).Scan(&count) - return count, err -} - -// CountApprovalsCreatedOnDB — заявки, созданные в определённый день -func (u *ApprovalDB) CountApprovalsCreatedOnDB(ctx context.Context, date time.Time) (int, error) { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("COUNT(*)"). - From(dbcoretablenames.TableNameApprovals.ToString()). - Where("DATE(created_at) = ?", date.Format("2006-01-02")) - - sql, args, err := query.ToSql() - if err != nil { - return 0, err - } - - var count int - err = u.pool.QueryRow(ctx, sql, args...).Scan(&count) - return count, err -} - -// CountApprovalsApprovedOnDB — заявки, согласованные в определённый день -func (u *ApprovalDB) CountApprovalsApprovedOnDB(ctx context.Context, date time.Time) (int, error) { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("COUNT(DISTINCT approval_id)"). - From(dbcoretablenames.TableNameApprovalSteps.ToString()). - Where("DATE(acted_at) = ? AND status = 'approved'", date.Format("2006-01-02")) - - sql, args, err := query.ToSql() - if err != nil { - return 0, err - } - - var count int - err = u.pool.QueryRow(ctx, sql, args...).Scan(&count) - return count, err -} - -// GetTopTopicsDB — топ тем по количеству заявок -func (u *ApprovalDB) GetTopTopicsDB(ctx context.Context, limit int) ([]map[string]interface{}, error) { - query := ` - SELECT - t.id, - t.name, - c.name as category_name, - COUNT(a.id) as total_count, - COUNT(CASE WHEN a.status = 'pending' THEN 1 END) as pending_count - FROM approval_topics t - LEFT JOIN approval_topic_categories c ON t.category_id = c.id - LEFT JOIN approvals a ON a.topic_id = t.id - GROUP BY t.id, t.name, c.name - ORDER BY total_count DESC - LIMIT $1 - ` - - rows, err := u.pool.Query(ctx, query, limit) - if err != nil { - return nil, err - } - defer rows.Close() - - var result []map[string]interface{} - for rows.Next() { - var id uint64 - var name, categoryName sql.NullString - var totalCount, pendingCount int - - if err := rows.Scan(&id, &name, &categoryName, &totalCount, &pendingCount); err != nil { - continue - } - - result = append(result, map[string]interface{}{ - "id": id, - "name": name.String, - "category_name": categoryName.String, - "total_count": totalCount, - "pending_count": pendingCount, - }) - } - - return result, nil -} - -// GetOldPendingApprovalsDB — заявки, которые давно висят в pending -func (u *ApprovalDB) GetOldPendingApprovalsDB(ctx context.Context, since time.Time, limit int) ([]*typescore.Approval, error) { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("*"). - From(dbcoretablenames.TableNameApprovals.ToString()). - Where(squirrel.And{ - squirrel.Eq{"status": "pending"}, - squirrel.Lt{"created_at": since}, - }). - OrderBy("created_at ASC"). - Limit(uint64(limit)) - - sql, args, err := query.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 { - continue - } - result = append(result, a) - } - - return result, nil -} - ------END core/db/methods/approval.go----- - -File: core/db/methods/approval_additional_approver.go -Lines: 186 ------BEGIN core/db/methods/approval_additional_approver.go----- -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 -} - ------END core/db/methods/approval_additional_approver.go----- - -File: core/db/methods/approval_additional_observer.go -Lines: 186 ------BEGIN core/db/methods/approval_additional_observer.go----- -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 ApprovalAdditionalObserverDB struct { - pool *pgxpool.Pool -} - -func NewApprovalAdditionalObserverDB(pool *pgxpool.Pool) *ApprovalAdditionalObserverDB { - return &ApprovalAdditionalObserverDB{ - pool: pool, - } -} - -type ApprovalAdditionalObserverDBI interface { - GetApprovalAdditionalObserversListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalAdditionalObserver, uint64, error) - CreateApprovalAdditionalObserverDB(ctx context.Context, tx pgx.Tx, ApprovalAdditionalObserverObj *typescore.ApprovalAdditionalObserver, returnObj ...bool) (*typescore.ApprovalAdditionalObserver, pgx.Tx, error) - UpdateApprovalAdditionalObserverDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalAdditionalObserver, returnObj ...bool) (*typescore.ApprovalAdditionalObserver, pgx.Tx, error) - DeleteApprovalAdditionalObserverDB(ctx context.Context, params *typescore.ApprovalAdditionalObserver) error - GetApprovalAdditionalObserverByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalAdditionalObserver, error) -} - -func (u *ApprovalAdditionalObserverDB) GetApprovalAdditionalObserversListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalAdditionalObserver, uint64, error) { - fields := dbutils.GetStructFieldsDB(&typescore.ApprovalAdditionalObserver{}, dbcoretablenames.TableNameApprovalAdditionalObservers.ToString()) - selectFields := append(fields, "COUNT(*) OVER() AS total_count") - - options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalAdditionalObserver](opts...) - if err != nil { - return nil, 0, err - } - - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalAdditionalObservers.ToString(), selectFields) - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalAdditionalObservers.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 ApprovalAdditionalObservers []*typescore.ApprovalAdditionalObserver - var totalCount uint64 - for rows.Next() { - ApprovalAdditionalObserver := &typescore.ApprovalAdditionalObserver{} - if err := dbutils.ScanRowsToStructRows(rows, ApprovalAdditionalObserver, &totalCount); err != nil { - logrus.Warn("GetApprovalAdditionalObserversListDB:ScanRowsToStructRows", err) - continue - } - ApprovalAdditionalObservers = append(ApprovalAdditionalObservers, ApprovalAdditionalObserver) - } - - return ApprovalAdditionalObservers, totalCount, nil -} - -func (u *ApprovalAdditionalObserverDB) CreateApprovalAdditionalObserverDB(ctx context.Context, tx pgx.Tx, ApprovalAdditionalObserverObj *typescore.ApprovalAdditionalObserver, returnObj ...bool) (*typescore.ApprovalAdditionalObserver, pgx.Tx, error) { - if ApprovalAdditionalObserverObj == nil { - return nil, nil, errors.New("ApprovalAdditionalObserver 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.TableNameApprovalAdditionalObservers.ToString()) - - sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalAdditionalObserverObj) - 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.GetApprovalAdditionalObserverByIDDB(ctx, insertedID) - return created, tx, err - } - - return nil, tx, nil -} - -func (u *ApprovalAdditionalObserverDB) UpdateApprovalAdditionalObserverDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalAdditionalObserver, returnObj ...bool) (*typescore.ApprovalAdditionalObserver, pgx.Tx, error) { - if paramsUpdate.ID == nil { - return nil, nil, errors.New("ApprovalAdditionalObserver obj is nil") - } - - err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalAdditionalObservers.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.ApprovalAdditionalObserver{ID: paramsUpdate.ID}} - getInfoUp, _, err := u.GetApprovalAdditionalObserversListDB(ctx, options) - if err != nil { - return nil, nil, err - } - if len(getInfoUp) > 0 { - return getInfoUp[0], tx, nil - } - } - - return nil, tx, nil -} - -func (u *ApprovalAdditionalObserverDB) DeleteApprovalAdditionalObserverDB(ctx context.Context, params *typescore.ApprovalAdditionalObserver) error { - if params != nil && params.ID != nil { - query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Delete(dbcoretablenames.TableNameApprovalAdditionalObservers.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("ApprovalAdditionalObserver obj is nil") - } -} - -func (u *ApprovalAdditionalObserverDB) GetApprovalAdditionalObserverByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalAdditionalObserver, error) { - ApprovalAdditionalObservers, _, err := u.GetApprovalAdditionalObserversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalObserver{ID: &id}, - }) - if err != nil { - return nil, err - } - if len(ApprovalAdditionalObservers) == 0 { - return nil, nil - } - return ApprovalAdditionalObservers[0], nil -} - ------END core/db/methods/approval_additional_observer.go----- - -File: core/db/methods/approval_comment.go -Lines: 222 ------BEGIN core/db/methods/approval_comment.go----- -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 ApprovalCommentDB struct { - pool *pgxpool.Pool -} - -func NewApprovalCommentDB(pool *pgxpool.Pool) *ApprovalCommentDB { - return &ApprovalCommentDB{ - pool: pool, - } -} - -type ApprovalCommentDBI interface { - GetApprovalCommentsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalComment, uint64, error) - CreateApprovalCommentDB(ctx context.Context, tx pgx.Tx, ApprovalCommentObj *typescore.ApprovalComment, returnObj ...bool) (*typescore.ApprovalComment, pgx.Tx, error) - UpdateApprovalCommentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalComment, returnObj ...bool) (*typescore.ApprovalComment, pgx.Tx, error) - DeleteApprovalCommentDB(ctx context.Context, params *typescore.ApprovalComment) error - GetCommentsByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalComment, error) - GetApprovalCommentByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalComment, error) -} - -func (u *ApprovalCommentDB) GetApprovalCommentsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalComment, uint64, error) { - fields := dbutils.GetStructFieldsDB(&typescore.ApprovalComment{}, dbcoretablenames.TableNameApprovalComments.ToString()) - selectFields := append(fields, "COUNT(*) OVER() AS total_count") - - options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalComment](opts...) - if err != nil { - return nil, 0, err - } - - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalComments.ToString(), selectFields) - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalComments.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 ApprovalComments []*typescore.ApprovalComment - var totalCount uint64 - for rows.Next() { - ApprovalComment := &typescore.ApprovalComment{} - if err := dbutils.ScanRowsToStructRows(rows, ApprovalComment, &totalCount); err != nil { - logrus.Warn("GetApprovalCommentsListDB:ScanRowsToStructRows", err) - continue - } - ApprovalComments = append(ApprovalComments, ApprovalComment) - } - - return ApprovalComments, totalCount, nil -} - -func (u *ApprovalCommentDB) CreateApprovalCommentDB(ctx context.Context, tx pgx.Tx, ApprovalCommentObj *typescore.ApprovalComment, returnObj ...bool) (*typescore.ApprovalComment, pgx.Tx, error) { - if ApprovalCommentObj == nil { - return nil, nil, errors.New("ApprovalComment 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.TableNameApprovalComments.ToString()) - - sqlV, args, err := dbutils.GenerateInsertRequest(query, ApprovalCommentObj) - if err != nil { - return err - } - - *sqlV = *sqlV + " RETURNING id" - - return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID) - }) - - if err != nil { - return nil, nil, err - } - - returnObjBool := len(returnObj) > 0 && returnObj[0] - if returnObjBool { - if insertedID == 0 { - return nil, nil, errors.New("inserted ID is 0 after insert") - } - created, err := u.GetApprovalCommentByIDDB(ctx, insertedID) - if err != nil { - return nil, nil, err - } - return created, nil, nil - } - - return nil, nil, nil -} -func (u *ApprovalCommentDB) UpdateApprovalCommentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalComment, returnObj ...bool) (*typescore.ApprovalComment, pgx.Tx, error) { - if paramsUpdate.ID == nil { - return nil, nil, errors.New("ApprovalComment obj is nil") - } - - err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameApprovalComments.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.ApprovalComment{ID: paramsUpdate.ID}} - getInfoUp, _, err := u.GetApprovalCommentsListDB(ctx, options) - if err != nil { - return nil, nil, err - } - if len(getInfoUp) > 0 { - return getInfoUp[0], tx, nil - } - } - - return nil, tx, nil -} - -func (u *ApprovalCommentDB) DeleteApprovalCommentDB(ctx context.Context, params *typescore.ApprovalComment) error { - if params != nil && params.ID != nil { - query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Delete(dbcoretablenames.TableNameApprovalComments.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("ApprovalComment obj is nil") - } -} - -func (u *ApprovalCommentDB) GetCommentsByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalComment, error) { - ApprovalComments, _, err := u.GetApprovalCommentsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalComment{ApprovalID: &id}, - }) - if err != nil { - return nil, err - } - return ApprovalComments, nil -} - -func (u *ApprovalCommentDB) GetApprovalCommentByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalComment, error) { - approvals, _, err := u.GetApprovalCommentsListDB(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 -} - -// queryApprovalComments — общий сканер строк -func (u *ApprovalCommentDB) queryApprovalComments(ctx context.Context, sql string, args []interface{}) ([]*typescore.ApprovalComment, error) { - rows, err := u.pool.Query(ctx, sql, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - var result []*typescore.ApprovalComment - for rows.Next() { - a := &typescore.ApprovalComment{} - if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil { - logrus.Warn("queryApprovalComments:ScanRowsToStruct", err) - continue - } - result = append(result, a) - } - return result, nil -} - ------END core/db/methods/approval_comment.go----- - -File: core/db/methods/approval_delegation.go -Lines: 186 ------BEGIN core/db/methods/approval_delegation.go----- -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 -} - ------END core/db/methods/approval_delegation.go----- - -File: core/db/methods/approval_file.go -Lines: 268 ------BEGIN core/db/methods/approval_file.go----- -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) - GetFilesByTaskIDDB(ctx context.Context, taskID uint64) ([]*typescore.ApprovalFile, error) - GetFilesByApprovalIDsDB(ctx context.Context, approvalIDs []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) { - files, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalFile{ID: &id}, - }) - if err != nil { - return nil, err - } - if len(files) == 0 { - return nil, nil - } - return files[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 -} - -func (u *ApprovalFileDB) GetFilesByTaskIDDB(ctx context.Context, taskID uint64) ([]*typescore.ApprovalFile, error) { - files, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalFile{TaskID: &taskID}, - }) - if err != nil { - return nil, err - } - return files, nil -} - -// GetFilesByApprovalIDsDB — пакетное получение файлов сразу для нескольких заявок (устраняет N+1) -func (a *ApprovalFileDB) GetFilesByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*typescore.ApprovalFile, error) { - if len(approvalIDs) == 0 { - return nil, nil - } - - fields := dbutils.GetStructFieldsDB(&typescore.ApprovalFile{}, dbcoretablenames.TableNameApprovalFiles.ToString()) - - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select(fields...). - From(dbcoretablenames.TableNameApprovalFiles.ToString()). - Where(squirrel.Eq{"approval_id": approvalIDs}). - ToSql() - if err != nil { - return nil, err - } - - rows, err := a.pool.Query(ctx, sql, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - var files []*typescore.ApprovalFile - for rows.Next() { - f := &typescore.ApprovalFile{} - if err := dbutils.ScanRowsToStructRows(rows, f, nil); err != nil { - logrus.Warn("GetFilesByApprovalIDsDB:ScanRowsToStructRows", err) - continue - } - files = append(files, f) - } - if err = rows.Err(); err != nil { - return nil, err - } - - return files, nil -} - ------END core/db/methods/approval_file.go----- - -File: core/db/methods/approval_flow_node.go -Lines: 175 ------BEGIN core/db/methods/approval_flow_node.go----- -package dbcore - -import ( - dbcoretablenames "bitrix_balancer_api/core/db/table_names" - "bitrix_balancer_api/core/typescore" - dbutils "bitrix_balancer_api/core/utilscore/db" - "context" - "errors" - - "github.com/Masterminds/squirrel" - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgxpool" -) - -type ApprovalFlowNodeDB struct { - pool *pgxpool.Pool -} - -func NewApprovalFlowNodeDB(pool *pgxpool.Pool) *ApprovalFlowNodeDB { - return &ApprovalFlowNodeDB{pool: pool} -} - -type ApprovalFlowNodeDBI interface { - GetApprovalFlowNodesListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalFlowNode, uint64, error) - CreateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error) - UpdateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error) - DeleteApprovalFlowNodeDB(ctx context.Context, node *typescore.ApprovalFlowNode) error - DeleteFlowNodesByCategoryIDDB(ctx context.Context, catID uint64) error - GetFlowNodeByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFlowNode, error) -} - -func (u *ApprovalFlowNodeDB) GetApprovalFlowNodesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFlowNode, uint64, error) { - fields := dbutils.GetStructFieldsDB(&typescore.ApprovalFlowNode{}, dbcoretablenames.TableNameApprovalFlowNodes.ToString()) - selectFields := append(fields, "COUNT(*) OVER() AS total_count") - - options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalFlowNode](opts...) - if err != nil { - return nil, 0, err - } - - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalFlowNodes.ToString(), selectFields) - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalFlowNodes.ToString()) - query = query.OrderBy("sort_order ASC, id ASC") - - sql, args, err := query.ToSql() - if err != nil { - return nil, 0, err - } - - rows, err := u.pool.Query(ctx, sql, args...) - if err != nil { - return nil, 0, err - } - defer rows.Close() - - var nodes []*typescore.ApprovalFlowNode - var totalCount uint64 - for rows.Next() { - node := &typescore.ApprovalFlowNode{} - if err := dbutils.ScanRowsToStructRows(rows, node, &totalCount); err != nil { - continue - } - nodes = append(nodes, node) - } - - return nodes, totalCount, nil -} - -func (u *ApprovalFlowNodeDB) CreateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error) { - if node == nil { - return nil, nil, errors.New("node is nil") - } - - err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Insert(dbcoretablenames.TableNameApprovalFlowNodes.ToString()) - - sqlV, args, err := dbutils.GenerateInsertRequest(query, node) - if err != nil { - return err - } - - _, err = tx.Exec(ctx, *sqlV, args...) - return err - }) - - if err != nil { - return nil, tx, err - } - - if len(returnObj) > 0 && returnObj[0] { - nodes, _, _ := u.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{Filtering: node}) - if len(nodes) > 0 { - return nodes[0], tx, nil - } - } - - return nil, tx, nil -} - -func (u *ApprovalFlowNodeDB) UpdateApprovalFlowNodeDB(ctx context.Context, tx pgx.Tx, node *typescore.ApprovalFlowNode, returnObj ...bool) (*typescore.ApprovalFlowNode, pgx.Tx, error) { - if node == nil || node.ID == nil { - return nil, nil, errors.New("node or node.ID is nil") - } - - err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Update(dbcoretablenames.TableNameApprovalFlowNodes.ToString()) - query = dbutils.AddNonNullFieldsToQueryUpdate(query, *node) - query = query.Where(squirrel.Eq{"id": node.ID}) - - sql, args, err := query.ToSql() - if err != nil { - return err - } - - _, err = tx.Exec(ctx, sql, args...) - return err - }) - - if err != nil { - return nil, tx, err - } - - if len(returnObj) > 0 && returnObj[0] { - updated, _ := u.GetFlowNodeByIDDB(ctx, *node.ID) - return updated, tx, nil - } - - return nil, tx, nil -} - -func (u *ApprovalFlowNodeDB) DeleteApprovalFlowNodeDB(ctx context.Context, node *typescore.ApprovalFlowNode) error { - if node == nil || node.ID == nil { - return errors.New("node or node.ID is nil") - } - - query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Delete(dbcoretablenames.TableNameApprovalFlowNodes.ToString()). - Where(squirrel.Eq{"id": *node.ID}). - ToSql() - if err != nil { - return err - } - - _, err = u.pool.Exec(ctx, query, args...) - return err -} - -func (u *ApprovalFlowNodeDB) DeleteFlowNodesByCategoryIDDB(ctx context.Context, catID uint64) error { - query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Delete(dbcoretablenames.TableNameApprovalFlowNodes.ToString()). - Where(squirrel.Eq{"category_id": catID}). - ToSql() - if err != nil { - return err - } - - _, err = u.pool.Exec(ctx, query, args...) - return err -} - -func (u *ApprovalFlowNodeDB) GetFlowNodeByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFlowNode, error) { - nodes, _, err := u.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalFlowNode{ID: &id}, - }) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, nil - } - return nodes[0], nil -} - ------END core/db/methods/approval_flow_node.go----- - -File: core/db/methods/approval_revocation_request.go -Lines: 215 ------BEGIN core/db/methods/approval_revocation_request.go----- -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/pgxpool" - "github.com/sirupsen/logrus" -) - -type ApprovalRevocationDB struct { - pool *pgxpool.Pool -} - -func NewApprovalRevocationDB(pool *pgxpool.Pool) *ApprovalRevocationDB { - return &ApprovalRevocationDB{pool: pool} -} - -type ApprovalRevocationDBI interface { - CreateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error) - UpdateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error) - GetRevocationRequestByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalRevocationRequest, error) - GetPendingRevocationRequestForApprovalDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalRevocationRequest, error) - - CreateRevocationApproversDB(ctx context.Context, approvers []*typescore.ApprovalRevocationApprover) error - UpdateRevocationApproverDB(ctx context.Context, obj *typescore.ApprovalRevocationApprover) error - GetRevocationApproversByRequestIDDB(ctx context.Context, requestID uint64) ([]*typescore.ApprovalRevocationApprover, error) - GetRevocationApproverForUserDB(ctx context.Context, requestID uint64, approverID uint64) (*typescore.ApprovalRevocationApprover, error) -} - -func (d *ApprovalRevocationDB) CreateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error) { - if obj == nil { - return nil, errors.New("revocation request obj is nil") - } - - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Insert(dbcoretablenames.TableNameApprovalRevocationRequests.ToString()) - - sqlV, args, err := dbutils.GenerateInsertRequest(query, obj) - if err != nil { - return nil, err - } - *sqlV = *sqlV + " RETURNING id" - - var insertedID uint64 - if err := d.pool.QueryRow(ctx, *sqlV, args...).Scan(&insertedID); err != nil { - return nil, err - } - - if len(returnObj) > 0 && returnObj[0] { - return d.GetRevocationRequestByIDDB(ctx, insertedID) - } - obj.ID = &insertedID - return obj, nil -} - -func (d *ApprovalRevocationDB) UpdateRevocationRequestDB(ctx context.Context, obj *typescore.ApprovalRevocationRequest, returnObj ...bool) (*typescore.ApprovalRevocationRequest, error) { - if obj.ID == nil { - return nil, errors.New("revocation request id is nil") - } - - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Update(dbcoretablenames.TableNameApprovalRevocationRequests.ToString()) - query = dbutils.AddNonNullFieldsToQueryUpdate(query, *obj) - query = query.Where(squirrel.Eq{"id": obj.ID}) - - sql, args, err := query.ToSql() - if err != nil { - return nil, err - } - if _, err := d.pool.Exec(ctx, sql, args...); err != nil { - return nil, err - } - - if len(returnObj) > 0 && returnObj[0] { - return d.GetRevocationRequestByIDDB(ctx, *obj.ID) - } - return nil, nil -} - -func (d *ApprovalRevocationDB) getRevocationRequestListDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.ApprovalRevocationRequest, error) { - fields := dbutils.GetStructFieldsDB(&typescore.ApprovalRevocationRequest{}, dbcoretablenames.TableNameApprovalRevocationRequests.ToString()) - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalRevocationRequests.ToString(), fields) - - options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalRevocationRequest](opts) - if err != nil { - return nil, err - } - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalRevocationRequests.ToString()) - query = query.OrderBy("created_at DESC") - - sql, args, err := query.ToSql() - if err != nil { - return nil, err - } - - rows, err := d.pool.Query(ctx, sql, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - var result []*typescore.ApprovalRevocationRequest - for rows.Next() { - obj := &typescore.ApprovalRevocationRequest{} - if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil { - logrus.Warn("getRevocationRequestListDB:ScanRowsToStructRows", err) - continue - } - result = append(result, obj) - } - return result, nil -} - -func (d *ApprovalRevocationDB) GetRevocationRequestByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalRevocationRequest, error) { - list, err := d.getRevocationRequestListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalRevocationRequest{ID: &id}, - }) - if err != nil || len(list) == 0 { - return nil, err - } - return list[0], nil -} - -func (d *ApprovalRevocationDB) GetPendingRevocationRequestForApprovalDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalRevocationRequest, error) { - pendingStatus := "pending" - list, err := d.getRevocationRequestListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalRevocationRequest{ApprovalID: &approvalID, Status: &pendingStatus}, - }) - if err != nil || len(list) == 0 { - return nil, err - } - return list[0], nil -} - -func (d *ApprovalRevocationDB) CreateRevocationApproversDB(ctx context.Context, approvers []*typescore.ApprovalRevocationApprover) error { - if len(approvers) == 0 { - return nil - } - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Insert(dbcoretablenames.TableNameApprovalRevocationApprovers.ToString()). - Columns("revocation_request_id", "approver_id", "status") - - for _, a := range approvers { - query = query.Values(*a.RevocationRequestID, *a.ApproverID, *a.Status) - } - - sql, args, err := query.ToSql() - if err != nil { - return err - } - _, err = d.pool.Exec(ctx, sql, args...) - return err -} - -func (d *ApprovalRevocationDB) UpdateRevocationApproverDB(ctx context.Context, obj *typescore.ApprovalRevocationApprover) error { - if obj.ID == nil { - return errors.New("revocation approver id is nil") - } - - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Update(dbcoretablenames.TableNameApprovalRevocationApprovers.ToString()) - query = dbutils.AddNonNullFieldsToQueryUpdate(query, *obj) - query = query.Where(squirrel.Eq{"id": obj.ID}) - - sql, args, err := query.ToSql() - if err != nil { - return err - } - _, err = d.pool.Exec(ctx, sql, args...) - return err -} - -func (d *ApprovalRevocationDB) GetRevocationApproversByRequestIDDB(ctx context.Context, requestID uint64) ([]*typescore.ApprovalRevocationApprover, error) { - fields := dbutils.GetStructFieldsDB(&typescore.ApprovalRevocationApprover{}, dbcoretablenames.TableNameApprovalRevocationApprovers.ToString()) - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalRevocationApprovers.ToString(), fields). - Where(squirrel.Eq{"revocation_request_id": requestID}) - - sql, args, err := query.ToSql() - if err != nil { - return nil, err - } - - rows, err := d.pool.Query(ctx, sql, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - var result []*typescore.ApprovalRevocationApprover - for rows.Next() { - obj := &typescore.ApprovalRevocationApprover{} - if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil { - continue - } - result = append(result, obj) - } - return result, nil -} - -func (d *ApprovalRevocationDB) GetRevocationApproverForUserDB(ctx context.Context, requestID uint64, approverID uint64) (*typescore.ApprovalRevocationApprover, error) { - all, err := d.GetRevocationApproversByRequestIDDB(ctx, requestID) - if err != nil { - return nil, err - } - for _, a := range all { - if a.ApproverID != nil && *a.ApproverID == approverID { - return a, nil - } - } - return nil, nil -} - ------END core/db/methods/approval_revocation_request.go----- - -File: core/db/methods/approval_step.go -Lines: 275 ------BEGIN core/db/methods/approval_step.go----- -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) - GetApprovalStepsByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*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 -} - -// GetApprovalStepsByApprovalIDsDB — пакетное получение шагов сразу для нескольких заявок (устраняет N+1) -func (a *ApprovalStepDB) GetApprovalStepsByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*typescore.ApprovalStep, error) { - if len(approvalIDs) == 0 { - return nil, nil - } - - fields := dbutils.GetStructFieldsDB(&typescore.ApprovalStep{}, dbcoretablenames.TableNameApprovalSteps.ToString()) - - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select(fields...). - From(dbcoretablenames.TableNameApprovalSteps.ToString()). - Where(squirrel.Eq{"approval_id": approvalIDs}). - OrderBy("step_order ASC"). - ToSql() - if err != nil { - return nil, err - } - - rows, err := a.pool.Query(ctx, sql, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - var steps []*typescore.ApprovalStep - for rows.Next() { - st := &typescore.ApprovalStep{} - if err := dbutils.ScanRowsToStructRows(rows, st, nil); err != nil { - logrus.Warn("GetApprovalStepsByApprovalIDsDB:ScanRowsToStructRows", err) - continue - } - steps = append(steps, st) - } - if err = rows.Err(); err != nil { - return nil, err - } - - return steps, nil -} - ------END core/db/methods/approval_step.go----- - -File: core/db/methods/approval_task.go -Lines: 284 ------BEGIN core/db/methods/approval_task.go----- -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) - GetApprovalTaskByApprovalIDDB(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()) - - if filter != nil && filter.ObserverUserID != nil { - subQ1 := buildApprovalIdSubquery("initiator", filter.ObserverUserID) - subQ2 := buildApprovalIdSubquery("approver", filter.ObserverUserID) - subQ3 := buildApprovalIdSubquery("observer", filter.ObserverUserID) - subQ4 := buildApprovalIdSubquery("executor", filter.ObserverUserID) - subQ5 := buildApprovalIdSubquery("additional_approver", filter.ObserverUserID) - subQ6 := buildApprovalIdSubquery("additional_observer", filter.ObserverUserID) - - 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() - s5, a5, _ := subQ5.PlaceholderFormat(squirrel.Question).ToSql() - s6, a6, _ := subQ6.PlaceholderFormat(squirrel.Question).ToSql() - - unionSQL := fmt.Sprintf("(%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s) UNION (%s)", s1, s2, s3, s4, s5, s6) - allArgs := append(append(append(append(append(a1, a2...), a3...), a4...), a5...), a6...) - - query = query.Where(squirrel.Expr(dbcoretablenames.TableNameApprovalTasks.ToString()+".approval_id IN ("+unionSQL+")", allArgs...)) - } - - 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 - } - - _, err = u.pool.Exec(ctx, query, args...) - if err != nil { - return err - } - - 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) GetApprovalTaskByApprovalIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTask, error) { - ApprovalTasks, _, err := u.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTask{ApprovalID: &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 -} - ------END core/db/methods/approval_task.go----- - -File: core/db/methods/approval_task_transfer.go -Lines: 151 ------BEGIN core/db/methods/approval_task_transfer.go----- -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/pgxpool" - "github.com/sirupsen/logrus" -) - -type ApprovalTaskTransferDB struct { - pool *pgxpool.Pool -} - -func NewApprovalTaskTransferDB(pool *pgxpool.Pool) *ApprovalTaskTransferDB { - return &ApprovalTaskTransferDB{pool: pool} -} - -type ApprovalTaskTransferDBI interface { - GetApprovalTaskTransferListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTaskTransfer, uint64, error) - CreateApprovalTaskTransferDB(ctx context.Context, obj *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error) - UpdateApprovalTaskTransferDB(ctx context.Context, paramsUpdate *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error) - GetApprovalTaskTransferByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTaskTransfer, error) - GetPendingTransferForTaskDB(ctx context.Context, taskID uint64) (*typescore.ApprovalTaskTransfer, error) -} - -func (u *ApprovalTaskTransferDB) GetApprovalTaskTransferListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTaskTransfer, uint64, error) { - fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTaskTransfer{}, dbcoretablenames.TableNameApprovalTaskTransfers.ToString()) - selectFields := append(fields, "COUNT(*) OVER() AS total_count") - - options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTaskTransfer](opts...) - if err != nil { - return nil, 0, err - } - - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTaskTransfers.ToString(), selectFields) - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTaskTransfers.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 result []*typescore.ApprovalTaskTransfer - var totalCount uint64 - for rows.Next() { - obj := &typescore.ApprovalTaskTransfer{} - if err := dbutils.ScanRowsToStructRows(rows, obj, &totalCount); err != nil { - logrus.Warn("GetApprovalTaskTransferListDB:ScanRowsToStructRows", err) - continue - } - result = append(result, obj) - } - - return result, totalCount, nil -} - -func (u *ApprovalTaskTransferDB) CreateApprovalTaskTransferDB(ctx context.Context, obj *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error) { - if obj == nil { - return nil, errors.New("approval task transfer obj is nil") - } - - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Insert(dbcoretablenames.TableNameApprovalTaskTransfers.ToString()) - - sqlV, args, err := dbutils.GenerateInsertRequest(query, obj) - if err != nil { - return nil, err - } - - *sqlV = *sqlV + " RETURNING id" - - var insertedID uint64 - if err := u.pool.QueryRow(ctx, *sqlV, args...).Scan(&insertedID); err != nil { - return nil, err - } - - returnObjBool := len(returnObj) > 0 && returnObj[0] - if returnObjBool && insertedID > 0 { - return u.GetApprovalTaskTransferByIDDB(ctx, insertedID) - } - - obj.ID = &insertedID - return obj, nil -} - -func (u *ApprovalTaskTransferDB) UpdateApprovalTaskTransferDB(ctx context.Context, paramsUpdate *typescore.ApprovalTaskTransfer, returnObj ...bool) (*typescore.ApprovalTaskTransfer, error) { - if paramsUpdate.ID == nil { - return nil, errors.New("approval task transfer obj is nil") - } - - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Update(dbcoretablenames.TableNameApprovalTaskTransfers.ToString()) - query = dbutils.AddNonNullFieldsToQueryUpdate(query, *paramsUpdate) - query = query.Where(squirrel.Eq{"id": paramsUpdate.ID}) - - sql, args, err := query.ToSql() - if err != nil { - return nil, err - } - - if _, err := u.pool.Exec(ctx, sql, args...); err != nil { - return nil, err - } - - returnObjBool := len(returnObj) > 0 && returnObj[0] - if returnObjBool { - return u.GetApprovalTaskTransferByIDDB(ctx, *paramsUpdate.ID) - } - - return nil, nil -} - -func (u *ApprovalTaskTransferDB) GetApprovalTaskTransferByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTaskTransfer, error) { - list, _, err := u.GetApprovalTaskTransferListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTaskTransfer{ID: &id}, - }) - if err != nil { - return nil, err - } - if len(list) == 0 { - return nil, nil - } - return list[0], nil -} - -// GetPendingTransferForTaskDB — есть ли уже незакрытый запрос по этой задаче (защита от дублей) -func (u *ApprovalTaskTransferDB) GetPendingTransferForTaskDB(ctx context.Context, taskID uint64) (*typescore.ApprovalTaskTransfer, error) { - pendingStatus := "pending" - list, _, err := u.GetApprovalTaskTransferListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTaskTransfer{TaskID: &taskID, Status: &pendingStatus}, - }) - if err != nil { - return nil, err - } - if len(list) == 0 { - return nil, nil - } - return list[0], nil -} - ------END core/db/methods/approval_task_transfer.go----- - -File: core/db/methods/approval_topic.go -Lines: 250 ------BEGIN core/db/methods/approval_topic.go----- -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) - GetApprovalTopicsByIDsDB(ctx context.Context, ids []uint64) ([]*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 -} - -// GetApprovalTopicsByIDsDB — пакетное получение тем по списку ID (устраняет N+1) -func (u *ApprovalTopicDB) GetApprovalTopicsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopic, error) { - if len(ids) == 0 { - return nil, nil - } - - fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopic{}, dbcoretablenames.TableNameApprovalTopics.ToString()) - - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select(fields...). - From(dbcoretablenames.TableNameApprovalTopics.ToString()). - Where(squirrel.Eq{"id": ids}). - 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 topics []*typescore.ApprovalTopic - for rows.Next() { - topic := &typescore.ApprovalTopic{} - if err := dbutils.ScanRowsToStructRows(rows, topic, nil); err != nil { - logrus.Warn("GetApprovalTopicsByIDsDB:ScanRowsToStructRows", err) - continue - } - topics = append(topics, topic) - } - if err = rows.Err(); err != nil { - return nil, err - } - - return topics, nil -} - ------END core/db/methods/approval_topic.go----- - -File: core/db/methods/approval_topic_category.go -Lines: 328 ------BEGIN core/db/methods/approval_topic_category.go----- -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) - GetCategoriesWithApprovalsByInitiatorDB( - ctx context.Context, - initiatorID uint64, - ) ([]*typescore.ApprovalTopicCategory, error) - GetCategoriesWithApprovalsByApproverDB(ctx context.Context, approverID uint64) ([]*typescore.ApprovalTopicCategory, error) - GetApprovalTopicCategoriesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopicCategory, error) -} - -// GetCategoriesWithApprovalsByInitiatorDB — категории тем, по которым у инициатора есть заявки -func (u *ApprovalTopicCategoryDB) GetCategoriesWithApprovalsByInitiatorDB( - ctx context.Context, - initiatorID uint64, -) ([]*typescore.ApprovalTopicCategory, error) { - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("DISTINCT c.*"). - From(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c"). - Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.category_id = c.id"). - Join(dbcoretablenames.TableNameApprovals.ToString() + " a ON a.topic_id = t.id"). - Where(squirrel.Eq{"a.initiator_id": initiatorID}). - Where(squirrel.Eq{"c.is_active": true}). - OrderBy("c.name ASC"). - 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.ApprovalTopicCategory - for rows.Next() { - obj := &typescore.ApprovalTopicCategory{} - if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil { - logrus.Warn("GetCategoriesWithApprovalsByInitiatorDB:Scan", err) - continue - } - result = append(result, obj) - } - return result, nil -} - -// GetCategoriesWithApprovalsByApproverDB — категории тем, в которых -// пользователь участвовал как согласующий (через approval_steps). -func (u *ApprovalTopicCategoryDB) GetCategoriesWithApprovalsByApproverDB( - ctx context.Context, - approverID uint64, -) ([]*typescore.ApprovalTopicCategory, error) { - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("DISTINCT c.*"). - From(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c"). - Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.category_id = c.id"). - Join(dbcoretablenames.TableNameApprovals.ToString() + " a ON a.topic_id = t.id"). - Join(dbcoretablenames.TableNameApprovalSteps.ToString() + " s ON s.approval_id = a.id"). - Where(squirrel.Eq{"s.approver_id": approverID}). - Where(squirrel.Eq{"c.is_active": true}). - OrderBy("c.name ASC"). - 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.ApprovalTopicCategory - for rows.Next() { - obj := &typescore.ApprovalTopicCategory{} - if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil { - logrus.Warn("GetCategoriesWithApprovalsByApproverDB:Scan", err) - continue - } - result = append(result, obj) - } - return result, nil -} - -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 -} - -// GetApprovalTopicCategoriesByIDsDB — пакетное получение категорий по списку ID (устраняет N+1) -func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoriesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopicCategory, error) { - if len(ids) == 0 { - return nil, nil - } - - fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopicCategory{}, dbcoretablenames.TableNameApprovalTopicCategories.ToString()) - - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select(fields...). - From(dbcoretablenames.TableNameApprovalTopicCategories.ToString()). - Where(squirrel.Eq{"id": ids}). - 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 categories []*typescore.ApprovalTopicCategory - for rows.Next() { - category := &typescore.ApprovalTopicCategory{} - if err := dbutils.ScanRowsToStructRows(rows, category, nil); err != nil { - logrus.Warn("GetApprovalTopicCategoriesByIDsDB:ScanRowsToStructRows", err) - continue - } - categories = append(categories, category) - } - if err = rows.Err(); err != nil { - return nil, err - } - - return categories, nil -} - ------END core/db/methods/approval_topic_category.go----- - -File: core/db/methods/approval_topic_executor.go -Lines: 320 ------BEGIN core/db/methods/approval_topic_executor.go----- -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 ApprovalTopicExecutorDB struct { - pool *pgxpool.Pool -} - -func NewApprovalTopicExecutorDB(pool *pgxpool.Pool) *ApprovalTopicExecutorDB { - return &ApprovalTopicExecutorDB{pool: pool} -} - -type ApprovalTopicExecutorDBI interface { - GetApprovalTopicExecutorListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicExecutor, uint64, error) - CreateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, obj *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error) - UpdateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error) - DeleteApprovalTopicExecutorDB(ctx context.Context, params *typescore.ApprovalTopicExecutor) error - GetExecutorsByTopicIDDB(ctx context.Context, topicID uint64) ([]*typescore.ApprovalTopicExecutor, error) - GetApprovalTopicExecutorListWithParamsDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.ApprovalTopicExecutor, uint64, error) - GetApprovalTopicExecutorListByCategoryDB(ctx context.Context, opts typescore.ListDbOptions, categoryID uint64) ([]*typescore.ApprovalTopicExecutor, uint64, error) -} - -func (d *ApprovalTopicExecutorDB) GetApprovalTopicExecutorListByCategoryDB(ctx context.Context, opts typescore.ListDbOptions, categoryID uint64) ([]*typescore.ApprovalTopicExecutor, uint64, error) { - options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopicExecutor](opts) - if err != nil { - return nil, 0, err - } - - countQuery := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("COUNT(DISTINCT ate.id)"). - From(dbcoretablenames.TableNameApprovalTopicExecutor.ToString() + " ate"). - Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = ate.topic_id"). - Where(squirrel.Eq{"t.category_id": categoryID}) - - countQuery = dbutils.ApplyFilters(countQuery, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) - - countSQL, countArgs, err := countQuery.ToSql() - if err != nil { - return nil, 0, err - } - - var totalCount uint64 - err = d.pool.QueryRow(ctx, countSQL, countArgs...).Scan(&totalCount) - if err != nil { - return nil, 0, err - } - - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("ate.*"). - From(dbcoretablenames.TableNameApprovalTopicExecutor.ToString() + " ate"). - Join(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = ate.topic_id"). - Where(squirrel.Eq{"t.category_id": categoryID}). - GroupBy("ate.id") - - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) - - query = query.OrderBy("ate.step_order ASC, ate.id ASC") - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - - sql, args, err := query.ToSql() - if err != nil { - return nil, 0, err - } - - rows, err := d.pool.Query(ctx, sql, args...) - if err != nil { - logrus.Errorf("GetApprovalTopicExecutorListByCategoryDB Query error: %v", err) - return nil, 0, err - } - defer rows.Close() - - var result []*typescore.ApprovalTopicExecutor - for rows.Next() { - item := &typescore.ApprovalTopicExecutor{} - if err := dbutils.ScanRowsToStructRows(rows, item, nil); err != nil { - logrus.Warn("GetApprovalTopicExecutorListByCategoryDB:ScanRowsToStructRows", err) - continue - } - result = append(result, item) - } - - if err = rows.Err(); err != nil { - return nil, 0, err - } - - return result, totalCount, nil -} - -func (d *ApprovalTopicExecutorDB) GetApprovalTopicExecutorListWithParamsDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.ApprovalTopicExecutor, uint64, error) { - options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopicExecutor](opts) - if err != nil { - return nil, 0, err - } - query := squirrel.Select( - "ate.*", - "u.id", "u.full_name", "u.username", - "t.id", "t.name", - "COUNT(*) OVER() AS total_count", - ). - From("approval_topic_executors ate"). - LeftJoin("users u ON ate.user_id = u.id"). - LeftJoin("approval_topics t ON ate.topic_id = t.id") - - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) - query = query.OrderBy("step_order ASC, id ASC") - - sql, args, err := query.PlaceholderFormat(squirrel.Dollar).ToSql() - if err != nil { - return nil, 0, err - } - - rows, err := d.pool.Query(ctx, sql, args...) - if err != nil { - return nil, 0, err - } - defer rows.Close() - - var results []*typescore.ApprovalTopicExecutor - var totalCount uint64 - - for rows.Next() { - exec := &typescore.ApprovalTopicExecutor{} - exec.User = &typescore.User{} - exec.Topic = &typescore.ApprovalTopic{} - - err := rows.Scan( - &exec.ID, &exec.TopicID, &exec.UserID, &exec.StepOrder, &exec.RequireFile, &exec.IsActive, &exec.CreatedAt, &exec.UpdatedAt, - &exec.User.ID, &exec.User.FullName, &exec.User.Username, - &exec.Topic.ID, &exec.Topic.Name, - &totalCount, - ) - if err != nil { - return nil, 0, err - } - results = append(results, exec) - } - - return results, totalCount, nil -} - -func (d *ApprovalTopicExecutorDB) GetApprovalTopicExecutorListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopicExecutor, uint64, error) { - fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopicExecutor{}, dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) - selectFields := append(fields, "COUNT(*) OVER() AS total_count") - - options, filter, err := dbutils.GetOptionsDB[typescore.ApprovalTopicExecutor](opts...) - if err != nil { - return nil, 0, err - } - - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameApprovalTopicExecutor.ToString(), selectFields) - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) - query = query.OrderBy("step_order ASC, id ASC") - - sql, args, err := query.ToSql() - if err != nil { - return nil, 0, err - } - - rows, err := d.pool.Query(ctx, sql, args...) - if err != nil { - return nil, 0, err - } - defer rows.Close() - - var result []*typescore.ApprovalTopicExecutor - var totalCount uint64 - for rows.Next() { - item := &typescore.ApprovalTopicExecutor{} - if err := dbutils.ScanRowsToStructRows(rows, item, &totalCount); err != nil { - logrus.Warn("GetApprovalTopicExecutorListDB:ScanRowsToStructRows", err) - continue - } - result = append(result, item) - } - - return result, totalCount, nil -} - -func (d *ApprovalTopicExecutorDB) CreateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, obj *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error) { - if obj == nil { - return nil, nil, errors.New("ApprovalTopicExecutor obj is nil") - } - - err := dbutils.ExecuteTx(ctx, d.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Insert(dbcoretablenames.TableNameApprovalTopicExecutor.ToString()) - - sqlV, args, err := dbutils.GenerateInsertRequest(query, obj) - if err != nil { - return err - } - - _, err = tx.Exec(ctx, *sqlV, args...) - return err - }) - - if err != nil { - return nil, tx, err - } - - returnObjBool := false - if len(returnObj) > 0 { - returnObjBool = returnObj[0] - } - if returnObjBool { - items, _, err := d.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{Filtering: obj}) - if err != nil { - return nil, tx, err - } - if len(items) > 0 { - return items[0], tx, nil - } - } - - return nil, tx, nil -} - -func (d *ApprovalTopicExecutorDB) UpdateApprovalTopicExecutorDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.ApprovalTopicExecutor, returnObj ...bool) (*typescore.ApprovalTopicExecutor, pgx.Tx, error) { - if paramsUpdate.ID == nil { - return nil, nil, errors.New("ApprovalTopicExecutor obj is nil") - } - - err := dbutils.ExecuteTx(ctx, d.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Update(dbcoretablenames.TableNameApprovalTopicExecutor.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...) - return err - }) - - if err != nil { - return nil, tx, err - } - - returnObjBool := false - if len(returnObj) > 0 { - returnObjBool = returnObj[0] - } - - if returnObjBool { - options := typescore.ListDbOptions{Filtering: &typescore.ApprovalTopicExecutor{ID: paramsUpdate.ID}} - items, _, err := d.GetApprovalTopicExecutorListDB(ctx, options) - if err != nil { - return nil, nil, err - } - if len(items) > 0 { - return items[0], tx, nil - } - } - - return nil, tx, nil -} - -func (d *ApprovalTopicExecutorDB) DeleteApprovalTopicExecutorDB(ctx context.Context, params *typescore.ApprovalTopicExecutor) error { - if params != nil && params.ID != nil { - query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Delete(dbcoretablenames.TableNameApprovalTopicExecutor.ToString()). - Where(squirrel.Eq{"id": *params.ID}). - ToSql() - - if err != nil { - return err - } - - _, err = d.pool.Exec(ctx, query, args...) - return err - } - return errors.New("ApprovalTopicExecutor obj is nil") -} - -// GetExecutorsByTopicIDDB возвращает всех исполнителей для темы, отсортированных по step_order -func (d *ApprovalTopicExecutorDB) GetExecutorsByTopicIDDB(ctx context.Context, topicID uint64) ([]*typescore.ApprovalTopicExecutor, error) { - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("ate.*"). - From(dbcoretablenames.TableNameApprovalTopicExecutor.ToString() + " ate"). - Where(squirrel.Eq{"ate.topic_id": topicID}). - Where(squirrel.Eq{"ate.is_active": true}). - OrderBy("ate.step_order ASC, ate.id ASC"). - ToSql() - if err != nil { - return nil, err - } - - rows, err := d.pool.Query(ctx, sql, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - var result []*typescore.ApprovalTopicExecutor - for rows.Next() { - item := &typescore.ApprovalTopicExecutor{} - if err := dbutils.ScanRowsToStructRows(rows, item, nil); err != nil { - logrus.Warn("GetExecutorsByTopicIDDB:ScanRowsToStructRows", err) - continue - } - result = append(result, item) - } - return result, nil -} - ------END core/db/methods/approval_topic_executor.go----- - -File: core/db/methods/department.go -Lines: 231 ------BEGIN core/db/methods/department.go----- -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) - GetDepartmentsByIDsDB(ctx context.Context, ids []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 - } - - _, err = u.pool.Exec(ctx, query, args...) - if err != nil { - return err - } - - 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 -} - -// GetDepartmentsByIDsDB — пакетное получение отделов по списку ID (устраняет N+1) -func (d *DepartmentDB) GetDepartmentsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Department, error) { - if len(ids) == 0 { - return nil, nil - } - - fields := dbutils.GetStructFieldsDB(&typescore.Department{}, dbcoretablenames.TableNameDepartments.ToString()) - - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select(fields...). - From(dbcoretablenames.TableNameDepartments.ToString()). - Where(squirrel.Eq{"id": ids}). - ToSql() - if err != nil { - return nil, err - } - - rows, err := d.pool.Query(ctx, sql, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - var departments []*typescore.Department - for rows.Next() { - dep := &typescore.Department{} - if err := dbutils.ScanRowsToStructRows(rows, dep, nil); err != nil { - logrus.Warn("GetDepartmentsByIDsDB:ScanRowsToStructRows", err) - continue - } - departments = append(departments, dep) - } - if err = rows.Err(); err != nil { - return nil, err - } - - return departments, nil -} - ------END core/db/methods/department.go----- - -File: core/db/methods/director_notification.go -Lines: 126 ------BEGIN core/db/methods/director_notification.go----- -package dbcore - -import ( - dbcoretablenames "bitrix_balancer_api/core/db/table_names" - "bitrix_balancer_api/core/typescore" - dbutils "bitrix_balancer_api/core/utilscore/db" - "context" - "github.com/Masterminds/squirrel" - "github.com/jackc/pgx/v5/pgxpool" -) - -type DirectorNotificationDB struct { - pool *pgxpool.Pool -} - -func NewDirectorNotificationDB(pool *pgxpool.Pool) *DirectorNotificationDB { - return &DirectorNotificationDB{pool: pool} -} - -type DirectorNotificationDBI interface { - GetSubscribedCategoryIDsDB(ctx context.Context, directorID uint64) ([]uint64, error) - ToggleSubscriptionDB(ctx context.Context, directorID, categoryID uint64) (enabled bool, err error) - GetDirectorsSubscribedToCategoryDB(ctx context.Context, categoryID uint64) ([]*typescore.User, error) -} - -// GetSubscribedCategoryIDsDB — список ID категорий, на которые подписан директор -func (d *DirectorNotificationDB) GetSubscribedCategoryIDsDB(ctx context.Context, directorID uint64) ([]uint64, error) { - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("category_id"). - From("director_notification_subscriptions"). - Where(squirrel.Eq{"director_id": directorID}). - ToSql() - if err != nil { - return nil, err - } - - rows, err := d.pool.Query(ctx, sql, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - var ids []uint64 - for rows.Next() { - var id uint64 - if err := rows.Scan(&id); err != nil { - continue - } - ids = append(ids, id) - } - return ids, nil -} - -// ToggleSubscriptionDB — переключает подписку директора на категорию. -// Если подписки не было — создаёт (enabled=true). Если была — удаляет (enabled=false). -func (d *DirectorNotificationDB) ToggleSubscriptionDB(ctx context.Context, directorID, categoryID uint64) (bool, error) { - checkSQL, checkArgs, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("id"). - From("director_notification_subscriptions"). - Where(squirrel.Eq{"director_id": directorID, "category_id": categoryID}). - ToSql() - if err != nil { - return false, err - } - - var existingID uint64 - err = d.pool.QueryRow(ctx, checkSQL, checkArgs...).Scan(&existingID) - - if err == nil { - // Подписка есть — удаляем (выключаем) - delSQL, delArgs, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Delete("director_notification_subscriptions"). - Where(squirrel.Eq{"id": existingID}). - ToSql() - if err != nil { - return false, err - } - _, err = d.pool.Exec(ctx, delSQL, delArgs...) - return false, err - } - - // Подписки нет — создаём (включаем) - insSQL, insArgs, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Insert("director_notification_subscriptions"). - Columns("director_id", "category_id"). - Values(directorID, categoryID). - ToSql() - if err != nil { - return false, err - } - _, err = d.pool.Exec(ctx, insSQL, insArgs...) - return true, err -} - -// GetDirectorsSubscribedToCategoryDB — все директора, подписанные на указанную категорию -func (d *DirectorNotificationDB) GetDirectorsSubscribedToCategoryDB(ctx context.Context, categoryID uint64) ([]*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("director_notification_subscriptions dns ON dns.director_id = u.id"). - Where(squirrel.Eq{"r.is_director": true}). - Where(squirrel.Eq{"u.is_blocked": false}). - Where(squirrel.Eq{"dns.category_id": categoryID}). - ToSql() - if err != nil { - return nil, err - } - - rows, err := d.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); err != nil { - continue - } - users = append(users, user) - } - return users, nil -} - ------END core/db/methods/director_notification.go----- - -File: core/db/methods/notifications.go -Lines: 169 ------BEGIN core/db/methods/notifications.go----- -package dbcore - -import ( - "bitrix_balancer_api/core/typescore" - dbutils "bitrix_balancer_api/core/utilscore/db" - "context" - "github.com/Masterminds/squirrel" - "github.com/jackc/pgx/v5/pgxpool" -) - -type NotificationDB struct { - pool *pgxpool.Pool -} - -func NewNotificationDB(pool *pgxpool.Pool) *NotificationDB { - return &NotificationDB{pool: pool} -} - -type NotificationDBI interface { - CreateNotificationDB(ctx context.Context, n *typescore.Notification) (*typescore.Notification, error) - UpdateNotificationDB(ctx context.Context, n *typescore.Notification) error - GetNotificationsListDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.Notification, uint64, error) - GetNotificationByIDDB(ctx context.Context, id uint64) (*typescore.Notification, error) - - CreateNotificationRecipientsDB(ctx context.Context, recipients []*typescore.NotificationRecipient) error - UpdateNotificationRecipientDB(ctx context.Context, r *typescore.NotificationRecipient) error - GetNotificationRecipientsDB(ctx context.Context, notificationID uint64) ([]*typescore.NotificationRecipient, error) -} - -func (n *NotificationDB) CreateNotificationDB(ctx context.Context, obj *typescore.Notification) (*typescore.Notification, error) { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Insert("notifications") - - sqlV, args, err := dbutils.GenerateInsertRequest(query, obj) - if err != nil { - return nil, err - } - - var newID uint64 - sqlStr := *sqlV + " RETURNING id" - err = n.pool.QueryRow(ctx, sqlStr, args...).Scan(&newID) - if err != nil { - return nil, err - } - - obj.ID = &newID - return obj, nil -} - -func (n *NotificationDB) UpdateNotificationDB(ctx context.Context, obj *typescore.Notification) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Update("notifications") - query = dbutils.AddNonNullFieldsToQueryUpdate(query, *obj) - query = query.Where(squirrel.Eq{"id": obj.ID}) - - sql, args, err := query.ToSql() - if err != nil { - return err - } - _, err = n.pool.Exec(ctx, sql, args...) - return err -} - -func (n *NotificationDB) GetNotificationsListDB(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.Notification, uint64, error) { - fields := dbutils.GetStructFieldsDB(&typescore.Notification{}, "notifications") - selectFields := append(fields, "COUNT(*) OVER() AS total_count") - - query := dbutils.BuildSelectQuery("notifications", selectFields) - query = dbutils.SetterLimitAndOffsetQuery(query, opts.Offset, opts.Limit) - query = query.OrderBy("created_at DESC") - - sql, args, err := query.ToSql() - if err != nil { - return nil, 0, err - } - - rows, err := n.pool.Query(ctx, sql, args...) - if err != nil { - return nil, 0, err - } - defer rows.Close() - - var result []*typescore.Notification - var total uint64 - for rows.Next() { - obj := &typescore.Notification{} - if err := dbutils.ScanRowsToStructRows(rows, obj, &total); err != nil { - continue - } - result = append(result, obj) - } - return result, total, nil -} - -func (n *NotificationDB) GetNotificationByIDDB(ctx context.Context, id uint64) (*typescore.Notification, error) { - list, _, err := n.GetNotificationsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Notification{ID: &id}, - }) - if err != nil { - return nil, err - } - if len(list) == 0 { - return nil, nil - } - return list[0], nil -} - -func (n *NotificationDB) CreateNotificationRecipientsDB(ctx context.Context, recipients []*typescore.NotificationRecipient) error { - if len(recipients) == 0 { - return nil - } - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Insert("notification_recipients"). - Columns("notification_id", "user_id", "status") - - for _, r := range recipients { - query = query.Values(*r.NotificationID, *r.UserID, *r.Status) - } - - sql, args, err := query.ToSql() - if err != nil { - return err - } - _, err = n.pool.Exec(ctx, sql, args...) - return err -} - -func (n *NotificationDB) UpdateNotificationRecipientDB(ctx context.Context, r *typescore.NotificationRecipient) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Update("notification_recipients") - query = dbutils.AddNonNullFieldsToQueryUpdate(query, *r) - query = query.Where(squirrel.Eq{"id": r.ID}) - - sql, args, err := query.ToSql() - if err != nil { - return err - } - _, err = n.pool.Exec(ctx, sql, args...) - return err -} - -func (n *NotificationDB) GetNotificationRecipientsDB(ctx context.Context, notificationID uint64) ([]*typescore.NotificationRecipient, error) { - fields := dbutils.GetStructFieldsDB(&typescore.NotificationRecipient{}, "notification_recipients") - - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select(fields...). - From("notification_recipients"). - Where(squirrel.Eq{"notification_id": notificationID}). - ToSql() - if err != nil { - return nil, err - } - - rows, err := n.pool.Query(ctx, sql, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - var result []*typescore.NotificationRecipient - for rows.Next() { - obj := &typescore.NotificationRecipient{} - if err := dbutils.ScanRowsToStructRows(rows, obj, nil); err != nil { - continue - } - result = append(result, obj) - } - return result, nil -} - ------END core/db/methods/notifications.go----- - -File: core/db/methods/permission.go -Lines: 256 ------BEGIN core/db/methods/permission.go----- -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) - UserCanCreateTopicDB(ctx context.Context, userID uint64, topicCode string) (bool, 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 - } - - _, err = u.pool.Exec(ctx, query, args...) - if err != nil { - return err - } - - 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) { - 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 -} - -func (u *PermissionDB) UserCanCreateTopicDB(ctx context.Context, userID uint64, topicCode string) (bool, error) { - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("COUNT(*)"). - From(dbcoretablenames.TableNamePermissions.ToString() + " p"). - Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = p.role_id"). - Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.role_id = r.id"). - LeftJoin(dbcoretablenames.TableNameApprovalTopics.ToString() + " t ON t.id = p.topic_id"). - LeftJoin(dbcoretablenames.TableNameApprovalTopicCategories.ToString() + " c ON c.id = p.topic_category_id"). - Where(squirrel.Eq{"ur.user_id": userID}). - Where(squirrel.Eq{"p.action": "create"}). - Where( - // Право на конкретную тему ИЛИ на всю категорию темы - squirrel.Or{ - squirrel.Eq{"t.code": topicCode}, - squirrel.And{ - squirrel.Eq{"p.topic_id": nil}, - squirrel.Expr(`c.id = ( - SELECT topic_category_id FROM `+ - dbcoretablenames.TableNameApprovalTopics.ToString()+ - ` WHERE code = ? - )`, topicCode), // ← используем ? вместо ручной подстановки $N - }, - }, - ). - 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 -} - ------END core/db/methods/permission.go----- - -File: core/db/methods/role.go -Lines: 231 ------BEGIN core/db/methods/role.go----- -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 - GetRoleByIDDB(ctx context.Context, id uint64) (*typescore.Role, error) - GetRolesByIDsDB(ctx context.Context, ids []uint64) ([]*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 - } - - _, err = u.pool.Exec(ctx, query, args...) - if err != nil { - return err - } - - return nil - } else { - return errors.New("role obj is nil") - } -} - -func (u *RoleDB) GetRoleByIDDB(ctx context.Context, id uint64) (*typescore.Role, error) { - roles, _, err := u.GetRolesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Role{ID: &id}, - }) - if err != nil || len(roles) == 0 { - return nil, err - } - return roles[0], nil -} - -// GetRolesByIDsDB — пакетное получение ролей по списку ID (устраняет N+1) -func (u *RoleDB) GetRolesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Role, error) { - if len(ids) == 0 { - return nil, nil - } - - fields := dbutils.GetStructFieldsDB(&typescore.Role{}, dbcoretablenames.TableNameRoles.ToString()) - - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select(fields...). - From(dbcoretablenames.TableNameRoles.ToString()). - Where(squirrel.Eq{"id": ids}). - 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 roles []*typescore.Role - for rows.Next() { - role := &typescore.Role{} - if err := dbutils.ScanRowsToStructRows(rows, role, nil); err != nil { - logrus.Warn("GetRolesByIDsDB:ScanRowsToStructRows", err) - continue - } - roles = append(roles, role) - } - if err = rows.Err(); err != nil { - return nil, err - } - - return roles, nil -} - ------END core/db/methods/role.go----- - -File: core/db/methods/sms_log.go -Lines: 76 ------BEGIN core/db/methods/sms_log.go----- -package dbcore - -import ( - "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" - "time" -) - -type SmsLogDB struct { - pool *pgxpool.Pool -} - -func NewSmsLogDB(pool *pgxpool.Pool) *SmsLogDB { - return &SmsLogDB{pool: pool} -} - -// CreateSmsLogDB сохраняет новую SMS в базу -func (s *SmsLogDB) CreateSmsLogDB(ctx context.Context, tx pgx.Tx, obj *typescore.SmsLog) error { - if obj == nil { - return errors.New("SmsLog obj is nil") - } - - err := dbutils.ExecuteTx(ctx, s.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Insert("sms_logs") - - sqlV, args, err := dbutils.GenerateInsertRequest(query, obj) - if err != nil { - return err - } - - _, err = tx.Exec(ctx, *sqlV, args...) - return err - }) - - return err -} - -// GetSmsLogsByDateRangeDB получает список SMS за период (для Google Script) -func (s *SmsLogDB) GetSmsLogsByDateRangeDB(ctx context.Context, startDate, endDate time.Time) ([]*typescore.SmsLog, error) { - fields := dbutils.GetStructFieldsDB(&typescore.SmsLog{}, "sms_logs") - - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select(fields...). - From("sms_logs"). - Where(squirrel.GtOrEq{"event_created": startDate}). - Where(squirrel.LtOrEq{"event_created": endDate}). - OrderBy("event_created DESC") - - sqlStr, args, err := query.ToSql() - if err != nil { - return nil, err - } - - rows, err := s.pool.Query(ctx, sqlStr, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - var logs []*typescore.SmsLog - for rows.Next() { - log := &typescore.SmsLog{} - if err := dbutils.ScanRowsToStructRows(rows, log, nil); err != nil { - continue - } - logs = append(logs, log) - } - - return logs, nil -} - ------END core/db/methods/sms_log.go----- - -File: core/db/methods/suggestion.go -Lines: 191 ------BEGIN core/db/methods/suggestion.go----- -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 SuggestionDB struct { - pool *pgxpool.Pool -} - -func NewSuggestionDB(pool *pgxpool.Pool) *SuggestionDB { - return &SuggestionDB{ - pool: pool, - } -} - -type SuggestionDBI interface { - GetSuggestionsListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.Suggestion, uint64, error) - CreateSuggestionDB(ctx context.Context, tx pgx.Tx, SuggestionObj *typescore.Suggestion, returnObj ...bool) (*typescore.Suggestion, pgx.Tx, error) - UpdateSuggestionDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Suggestion, returnObj ...bool) (*typescore.Suggestion, pgx.Tx, error) - DeleteSuggestionDB(ctx context.Context, params *typescore.Suggestion) error - GetSuggestionByIDDB(ctx context.Context, id uint64) (*typescore.Suggestion, error) -} - -func (u *SuggestionDB) GetSuggestionsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Suggestion, uint64, error) { - fields := dbutils.GetStructFieldsDB(&typescore.Suggestion{}, dbcoretablenames.TableNameSuggestions.ToString()) - selectFields := append(fields, "COUNT(*) OVER() AS total_count") - - options, filter, err := dbutils.GetOptionsDB[typescore.Suggestion](opts...) - if err != nil { - return nil, 0, err - } - - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameSuggestions.ToString(), selectFields) - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameSuggestions.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 Suggestions []*typescore.Suggestion - var totalCount uint64 - for rows.Next() { - Suggestion := &typescore.Suggestion{} - if err := dbutils.ScanRowsToStructRows(rows, Suggestion, &totalCount); err != nil { - logrus.Warn("GetSuggestionsListDB:ScanRowsToStructRows", err) - continue - } - Suggestions = append(Suggestions, Suggestion) - } - - return Suggestions, totalCount, nil -} - -func (u *SuggestionDB) CreateSuggestionDB(ctx context.Context, tx pgx.Tx, SuggestionObj *typescore.Suggestion, returnObj ...bool) (*typescore.Suggestion, pgx.Tx, error) { - if SuggestionObj == nil { - return nil, nil, errors.New("Suggestion obj is nil") - } - - err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameSuggestions.ToString()) - - sqlV, args, err := dbutils.GenerateInsertRequest(query, SuggestionObj) - 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 { - Suggestion, _, err := u.GetSuggestionsListDB(ctx, typescore.ListDbOptions{Filtering: SuggestionObj}) - if err != nil { - return nil, tx, err - } - if len(Suggestion) > 0 { - return Suggestion[0], tx, nil - } - } - - return nil, tx, nil -} - -func (u *SuggestionDB) UpdateSuggestionDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Suggestion, returnObj ...bool) (*typescore.Suggestion, pgx.Tx, error) { - if paramsUpdate.ID == nil { - return nil, nil, errors.New("Suggestion obj is nil") - } - - err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameSuggestions.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.Suggestion{ID: paramsUpdate.ID}} - getInfoUp, _, err := u.GetSuggestionsListDB(ctx, options) - if err != nil { - return nil, nil, err - } - if len(getInfoUp) > 0 { - return getInfoUp[0], tx, nil - } - } - - return nil, tx, nil -} - -func (u *SuggestionDB) DeleteSuggestionDB(ctx context.Context, params *typescore.Suggestion) error { - if params != nil && params.ID != nil { - query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Delete(dbcoretablenames.TableNameSuggestions.ToString()). - Where(squirrel.Eq{"id": *params.ID}). - ToSql() - - if err != nil { - return err - } - - _, err = u.pool.Exec(ctx, query, args...) - if err != nil { - return err - } - - return nil - } else { - return errors.New("Suggestion obj is nil") - } -} - -func (u *SuggestionDB) GetSuggestionByIDDB(ctx context.Context, id uint64) (*typescore.Suggestion, error) { - deps, _, err := u.GetSuggestionsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Suggestion{ID: &id}, - }) - if err != nil || len(deps) == 0 { - return nil, err - } - return deps[0], nil -} - ------END core/db/methods/suggestion.go----- - -File: core/db/methods/suggestion_message.go -Lines: 191 ------BEGIN core/db/methods/suggestion_message.go----- -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 SuggestionMessageDB struct { - pool *pgxpool.Pool -} - -func NewSuggestionMessageDB(pool *pgxpool.Pool) *SuggestionMessageDB { - return &SuggestionMessageDB{ - pool: pool, - } -} - -type SuggestionMessageDBI interface { - GetSuggestionMessagesListDB(ctx context.Context, options ...typescore.ListDbOptions) ([]*typescore.SuggestionMessage, uint64, error) - CreateSuggestionMessageDB(ctx context.Context, tx pgx.Tx, SuggestionMessageObj *typescore.SuggestionMessage, returnObj ...bool) (*typescore.SuggestionMessage, pgx.Tx, error) - UpdateSuggestionMessageDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.SuggestionMessage, returnObj ...bool) (*typescore.SuggestionMessage, pgx.Tx, error) - DeleteSuggestionMessageDB(ctx context.Context, params *typescore.SuggestionMessage) error - GetSuggestionMessageByIDDB(ctx context.Context, id uint64) (*typescore.SuggestionMessage, error) -} - -func (u *SuggestionMessageDB) GetSuggestionMessagesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.SuggestionMessage, uint64, error) { - fields := dbutils.GetStructFieldsDB(&typescore.SuggestionMessage{}, dbcoretablenames.TableNameSuggestionMessages.ToString()) - selectFields := append(fields, "COUNT(*) OVER() AS total_count") - - options, filter, err := dbutils.GetOptionsDB[typescore.SuggestionMessage](opts...) - if err != nil { - return nil, 0, err - } - - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameSuggestionMessages.ToString(), selectFields) - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameSuggestionMessages.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 SuggestionMessages []*typescore.SuggestionMessage - var totalCount uint64 - for rows.Next() { - SuggestionMessage := &typescore.SuggestionMessage{} - if err := dbutils.ScanRowsToStructRows(rows, SuggestionMessage, &totalCount); err != nil { - logrus.Warn("GetSuggestionMessagesListDB:ScanRowsToStructRows", err) - continue - } - SuggestionMessages = append(SuggestionMessages, SuggestionMessage) - } - - return SuggestionMessages, totalCount, nil -} - -func (u *SuggestionMessageDB) CreateSuggestionMessageDB(ctx context.Context, tx pgx.Tx, SuggestionMessageObj *typescore.SuggestionMessage, returnObj ...bool) (*typescore.SuggestionMessage, pgx.Tx, error) { - if SuggestionMessageObj == nil { - return nil, nil, errors.New("SuggestionMessage obj is nil") - } - - err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Insert(dbcoretablenames.TableNameSuggestionMessages.ToString()) - - sqlV, args, err := dbutils.GenerateInsertRequest(query, SuggestionMessageObj) - 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 { - SuggestionMessage, _, err := u.GetSuggestionMessagesListDB(ctx, typescore.ListDbOptions{Filtering: SuggestionMessageObj}) - if err != nil { - return nil, tx, err - } - if len(SuggestionMessage) > 0 { - return SuggestionMessage[0], tx, nil - } - } - - return nil, tx, nil -} - -func (u *SuggestionMessageDB) UpdateSuggestionMessageDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.SuggestionMessage, returnObj ...bool) (*typescore.SuggestionMessage, pgx.Tx, error) { - if paramsUpdate.ID == nil { - return nil, nil, errors.New("SuggestionMessage obj is nil") - } - - err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).Update(dbcoretablenames.TableNameSuggestionMessages.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.SuggestionMessage{ID: paramsUpdate.ID}} - getInfoUp, _, err := u.GetSuggestionMessagesListDB(ctx, options) - if err != nil { - return nil, nil, err - } - if len(getInfoUp) > 0 { - return getInfoUp[0], tx, nil - } - } - - return nil, tx, nil -} - -func (u *SuggestionMessageDB) DeleteSuggestionMessageDB(ctx context.Context, params *typescore.SuggestionMessage) error { - if params != nil && params.ID != nil { - query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Delete(dbcoretablenames.TableNameSuggestionMessages.ToString()). - Where(squirrel.Eq{"id": *params.ID}). - ToSql() - - if err != nil { - return err - } - - _, err = u.pool.Exec(ctx, query, args...) - if err != nil { - return err - } - - return nil - } else { - return errors.New("SuggestionMessage obj is nil") - } -} - -func (u *SuggestionMessageDB) GetSuggestionMessageByIDDB(ctx context.Context, id uint64) (*typescore.SuggestionMessage, error) { - deps, _, err := u.GetSuggestionMessagesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.SuggestionMessage{ID: &id}, - }) - if err != nil || len(deps) == 0 { - return nil, err - } - return deps[0], nil -} - ------END core/db/methods/suggestion_message.go----- - -File: core/db/methods/user.go -Lines: 787 ------BEGIN core/db/methods/user.go----- -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/jackc/pgx/v5" - "github.com/sirupsen/logrus" - - "github.com/Masterminds/squirrel" - "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) - GetUsersByRoleCodeDB(ctx context.Context, roleCode string) ([]*typescore.User, error) - GetObserversForApprovalDB(ctx context.Context, categoryCode string, topicID *uint64) ([]*typescore.User, error) - GetUsersListByRoleIDsDB(ctx context.Context, opts typescore.ListDbOptions, roleIDs []uint64) ([]*typescore.User, uint64, error) - GetUsersByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.User, error) - - IsControllerDB(ctx context.Context, userID uint64) (bool, error) - GetControllerObserversForApprovalDB(ctx context.Context, categoryCode string, topicID *uint64) ([]*typescore.User, error) - GetUsersByRoleFlagsDB(ctx context.Context, flags []string) ([]*typescore.User, error) - GetUsersByDepartmentIDsDB(ctx context.Context, departmentIDs []uint64) ([]*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 - } - - // ✅ Сохраняем значение поиска и удаляем из LikeFields - searchName := "" - if options.LikeFields != nil && options.LikeFields["full_name"] != "" { - searchName = options.LikeFields["full_name"] - delete(options.LikeFields, "full_name") - } - - // ✅ Обнуляем FullName в filter - filter.FullName = nil - - query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameUsers.ToString(), selectFields) - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - - // ✅ Сначала добавляем условие поиска - if searchName != "" { - query = query.Where("LOWER(full_name) LIKE LOWER(?)", "%"+searchName+"%") - } - - // ✅ Потом применяем остальные фильтры - 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 - } - - logrus.Debugf("GetUsersListDB SQL: %s, Args: %v", sql, args) - - 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 - } - - _, err = u.pool.Exec(ctx, query, args...) - if err != nil { - return err - } - - 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 -} - -// GetObserversForApprovalDB — возвращает наблюдателей для конкретной заявки. -// Учитывает права как на категорию темы, так и на саму тему (topic_id). -// Дубли устраняются через DISTINCT. -func (u *UserDB) GetObserversForApprovalDB( - ctx context.Context, - categoryCode string, - topicID *uint64, -) ([]*typescore.User, error) { - q := 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"). - Where(squirrel.Eq{"r.is_observer": true}). - Where(squirrel.Eq{"p.action": "observe"}). - Where(squirrel.Eq{"u.is_blocked": false}) - - if topicID != nil { - // Логика: - // 1. Наблюдатели категории: topic_id IS NULL И category_id совпадает - // 2. Наблюдатели конкретной темы: topic_id совпадает (category игнорируем) - q = q.Where(squirrel.Or{ - squirrel.And{ - squirrel.Expr("p.topic_id IS NULL"), - squirrel.Expr( - "p.topic_category_id IN (SELECT id FROM approval_topic_categories WHERE code = ?)", - categoryCode, - ), - }, - squirrel.Eq{"p.topic_id": *topicID}, - }) - } else { - // Если topicID не передан — fallback на старую логику (только по категории) - q = q.Join( - dbcoretablenames.TableNameApprovalTopicCategories.ToString() + - " c ON c.id = p.topic_category_id", - ).Where(squirrel.Eq{"c.code": categoryCode}) - } - - sql, args, err := q.ToSql() - if err != nil { - return nil, err - } - - logrus.Infof("🔍 GetObserversForApprovalDB SQL: %s", sql) - logrus.Infof("🔍 GetObserversForApprovalDB Args: %v", args) - - 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("GetObserversForApprovalDB:ScanRowsToStruct", err) - continue - } - result = append(result, usr) - } - - logrus.Infof("✅ GetObserversForApprovalDB found %d observers", len(result)) - return result, nil -} - -func (u *UserDB) GetUsersByRoleCodeDB(ctx context.Context, roleCode 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"). - Where(squirrel.Eq{"r.code": roleCode}). - Where(squirrel.Eq{"u.is_blocked": false}). - OrderBy("u.full_name ASC"). - 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); err != nil { - logrus.Warn("GetUsersByRoleCodeDB:ScanRowsToStruct", err) - continue - } - users = append(users, user) - } - return users, nil -} - -// GetUsersListByRoleIDsDB - фильтрация пользователей по массиву ID ролей -func (u *UserDB) GetUsersListByRoleIDsDB(ctx context.Context, opts typescore.ListDbOptions, roleIDs []uint64) ([]*typescore.User, uint64, error) { - if len(roleIDs) == 0 { - return u.GetUsersListDB(ctx, opts) - } - - options, filter, err := dbutils.GetOptionsDB[typescore.User](opts) - if err != nil { - return nil, 0, err - } - - searchName := "" - if options.LikeFields != nil && options.LikeFields["full_name"] != "" { - searchName = options.LikeFields["full_name"] - delete(options.LikeFields, "full_name") - } - - filter.FullName = nil - - logrus.Infof("🔍 GetUsersListByRoleIDsDB: searchName='%s', filter.FullName=%v, options.Offset=%d, options.Limit=%d", - searchName, filter.FullName, options.Offset, options.Limit) - - countQuery := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("COUNT(DISTINCT u.id)"). - From(dbcoretablenames.TableNameUsers.ToString() + " u"). - Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id"). - Where(squirrel.Eq{"ur.role_id": roleIDs}) - - if searchName != "" { - countQuery = countQuery.Where("LOWER(u.full_name) LIKE LOWER(?)", "%"+searchName+"%") - } - countQuery = dbutils.ApplyFilters(countQuery, filter, options.LikeFields, dbcoretablenames.TableNameUsers.ToString()) - - countSQL, countArgs, err := countQuery.ToSql() - if err != nil { - return nil, 0, err - } - - var totalCount uint64 - err = u.pool.QueryRow(ctx, countSQL, countArgs...).Scan(&totalCount) - if err != nil { - logrus.Errorf("🔍 GetUsersListByRoleIDsDB Count error: %v", err) - return nil, 0, err - } - - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select("u.*"). - From(dbcoretablenames.TableNameUsers.ToString() + " u"). - Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id"). - Where(squirrel.Eq{"ur.role_id": roleIDs}). - GroupBy("u.id") - - if searchName != "" { - query = query.Where("LOWER(u.full_name) LIKE LOWER(?)", "%"+searchName+"%") - } - - query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameUsers.ToString()) - - query = query.OrderBy("u.created_at DESC") - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - - sql, args, err := query.ToSql() - if err != nil { - return nil, 0, err - } - - rows, err := u.pool.Query(ctx, sql, args...) - if err != nil { - logrus.Errorf("🔍 GetUsersListByRoleIDsDB Query error: %v", err) - return nil, 0, err - } - defer rows.Close() - - var users []*typescore.User - for rows.Next() { - user := &typescore.User{} - if err := dbutils.ScanRowsToStructRows(rows, user, nil); err != nil { - logrus.Warn("GetUsersListByRoleIDsDB:ScanRowsToStructRows", err) - continue - } - users = append(users, user) - } - - if err = rows.Err(); err != nil { - return nil, 0, err - } - - return users, totalCount, nil -} - -// GetUsersByIDsDB — пакетное получение пользователей по списку ID (устраняет N+1) -func (u *UserDB) GetUsersByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.User, error) { - if len(ids) == 0 { - return nil, nil - } - - fields := dbutils.GetStructFieldsDB(&typescore.User{}, dbcoretablenames.TableNameUsers.ToString()) - - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select(fields...). - From(dbcoretablenames.TableNameUsers.ToString()). - Where(squirrel.Eq{"id": ids}). - 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); err != nil { - logrus.Warn("GetUsersByIDsDB:ScanRowsToStructRows", err) - continue - } - users = append(users, user) - } - if err = rows.Err(); err != nil { - return nil, err - } - - return users, nil -} - -// IsControllerDB проверяет, есть ли у пользователя роль наблюдателя с флагом is_controller = true. -func (u *UserDB) IsControllerDB(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}). - Where(squirrel.Eq{"r.is_controller": 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 -} - -// GetControllerObserversForApprovalDB — то же самое, что GetObserversForApprovalDB, -// но только пользователи, у которых роль имеет флаг is_controller = true. -func (u *UserDB) GetControllerObserversForApprovalDB( - ctx context.Context, - categoryCode string, - topicID *uint64, -) ([]*typescore.User, error) { - q := 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"). - Where(squirrel.Eq{"r.is_observer": true}). - Where(squirrel.Eq{"r.is_controller": true}). - Where(squirrel.Eq{"p.action": "observe"}). - Where(squirrel.Eq{"u.is_blocked": false}) - - if topicID != nil { - q = q.Where(squirrel.Or{ - squirrel.And{ - squirrel.Expr("p.topic_id IS NULL"), - squirrel.Expr( - "p.topic_category_id IN (SELECT id FROM approval_topic_categories WHERE code = ?)", - categoryCode, - ), - }, - squirrel.Eq{"p.topic_id": *topicID}, - }) - } else { - q = q.Join( - dbcoretablenames.TableNameApprovalTopicCategories.ToString() + - " c ON c.id = p.topic_category_id", - ).Where(squirrel.Eq{"c.code": categoryCode}) - } - - 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 result []*typescore.User - for rows.Next() { - usr := &typescore.User{} - if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil { - logrus.Warn("GetControllerObserversForApprovalDB:ScanRowsToStruct", err) - continue - } - result = append(result, usr) - } - return result, nil -} - -// GetUsersByRoleFlagsDB — пользователи, у которых есть роль с любым из указанных флагов -// (is_director, is_approver, is_observer, is_executor, is_controller) -func (u *UserDB) GetUsersByRoleFlagsDB(ctx context.Context, flags []string) ([]*typescore.User, error) { - if len(flags) == 0 { - return nil, nil - } - - allowedFlags := map[string]string{ - "director": "r.is_director", - "approver": "r.is_approver", - "observer": "r.is_observer", - "executor": "r.is_executor", - "controller": "r.is_controller", - } - - var orConds squirrel.Or - for _, f := range flags { - if col, ok := allowedFlags[f]; ok { - orConds = append(orConds, squirrel.Expr(col+" = true")) - } - } - if len(orConds) == 0 { - return nil, nil - } - - 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(orConds). - 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); err != nil { - logrus.Warn("GetUsersByRoleFlagsDB:ScanRowsToStructRows", err) - continue - } - users = append(users, user) - } - return users, nil -} - -// GetUsersByDepartmentIDsDB — пользователи из списка отделов -func (u *UserDB) GetUsersByDepartmentIDsDB(ctx context.Context, departmentIDs []uint64) ([]*typescore.User, error) { - if len(departmentIDs) == 0 { - return nil, nil - } - - fields := dbutils.GetStructFieldsDB(&typescore.User{}, dbcoretablenames.TableNameUsers.ToString()) - - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select(fields...). - From(dbcoretablenames.TableNameUsers.ToString()). - Where(squirrel.Eq{"department_id": departmentIDs}). - Where(squirrel.Eq{"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); err != nil { - logrus.Warn("GetUsersByDepartmentIDsDB:ScanRowsToStructRows", err) - continue - } - users = append(users, user) - } - return users, nil -} - ------END core/db/methods/user.go----- - -File: core/db/methods/user_hierarchy.go -Lines: 371 ------BEGIN core/db/methods/user_hierarchy.go----- -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" - - "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 - - // ИСПРАВЛЕНО: сигнатура интерфейса не совпадала с реализацией — не хватало - // topicID, categoryID. Из-за этого *UserHierarchyDB формально не реализовывал - // этот интерфейс. - GetApproversDB(ctx context.Context, subordinateID, departmentID, topicID, categoryID uint64, systems []string) ([]*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.GetHierarchiesWithRelations(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.GetHierarchiesWithRelations(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 { - return errors.New("userHierarchy obj or id is 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 - } - - _, err = u.pool.Exec(ctx, query, args...) - if err != nil { - return err - } - - return nil -} - -// GetApproversDB возвращает список согласующих для (subordinateID, departmentID, -// topicID, categoryID), с учётом целевой системы (systems[0], если задана). -func (u *UserHierarchyDB) GetApproversDB( - ctx context.Context, - subordinateID, departmentID, topicID, categoryID uint64, - systems []string, -) ([]*typescore.User, error) { - system := "" - if len(systems) > 0 { - system = systems[0] - } - - rawSQL := ` - WITH ranked AS ( - SELECT - uh.approver_id, - uh.priority, - uh.target_system, - 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 - ), - candidates AS ( - -- берём только самый специфичный уровень (topic > category > global), - -- как и раньше - SELECT r.approver_id, r.priority, r.target_system - FROM ranked r - JOIN best b ON r.specificity = b.min_spec - ), - system_choice AS ( - -- override применяется, только если среди кандидатов есть хотя бы - -- одна запись, нацеленная именно на выбранную систему - SELECT EXISTS ( - SELECT 1 FROM candidates c WHERE c.target_system = $5 - ) AS has_override - ) - SELECT u.* - FROM candidates c - CROSS JOIN system_choice sc - JOIN users u ON u.id = c.approver_id - WHERE - (sc.has_override AND c.target_system = $5) - OR (NOT sc.has_override AND (c.target_system IS NULL OR c.target_system = 'all')) - ORDER BY c.priority ASC - ` - - rows, err := u.pool.Query(ctx, rawSQL, - subordinateID, - departmentID, - topicID, - categoryID, - system, - ) - if err != nil { - return nil, err - } - defer rows.Close() - - var approvers []*typescore.User - seen := make(map[uint64]bool) - for rows.Next() { - usr := &typescore.User{} - if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil { - logrus.Warn("GetApproversDB:ScanRowsToStructRows", err) - continue - } - if usr.ID == nil || seen[*usr.ID] { - continue - } - seen[*usr.ID] = true - approvers = append(approvers, usr) - } - - return approvers, nil -} - -func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error) { - options, filter, err := dbutils.GetOptionsDB[typescore.UserHierarchy](opts) - if err != nil { - return nil, 0, err - } - - query := squirrel.Select( - "uh.id", - "uh.subordinate_id", - "uh.approver_id", - "uh.department_id", - "uh.topic_category_id", - "uh.topic_id", - "uh.priority", - "uh.target_system", - "uh.created_at", - "uh.updated_at", - "sub.id", "sub.full_name", "sub.username", - "app.id", "app.full_name", "app.username", - "dep.id", "dep.name", - "cat.id", "cat.name", - "top.id", "top.name", - "COUNT(*) OVER() AS total_count", - ). - From("user_hierarchy uh"). - LeftJoin("users sub ON uh.subordinate_id = sub.id"). - LeftJoin("users app ON uh.approver_id = app.id"). - LeftJoin("departments dep ON uh.department_id = dep.id"). - LeftJoin("approval_topic_categories cat ON uh.topic_category_id = cat.id"). - LeftJoin("approval_topics top ON uh.topic_id = top.id") - - query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit) - - // Явная обработка фильтров - if filter.SubordinateID != nil { - query = query.Where(squirrel.Eq{"uh.subordinate_id": *filter.SubordinateID}) - } - if filter.ApproverID != nil { - query = query.Where(squirrel.Eq{"uh.approver_id": *filter.ApproverID}) - } - if filter.DepartmentID != nil { - query = query.Where(squirrel.Eq{"uh.department_id": *filter.DepartmentID}) - } - if filter.TopicCategoryID != nil { - query = query.Where(squirrel.Eq{"uh.topic_category_id": *filter.TopicCategoryID}) - } - if filter.TopicID != nil { - query = query.Where(squirrel.Eq{"uh.topic_id": *filter.TopicID}) - } - - query = query.OrderBy("uh.created_at DESC") - - sql, args, err := query.PlaceholderFormat(squirrel.Dollar).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 results []*typescore.UserHierarchy - var totalCount uint64 - - for rows.Next() { - h := &typescore.UserHierarchy{} - h.Subordinate = &typescore.User{} - h.Approver = &typescore.User{} - h.Department = &typescore.Department{} - h.TopicCategory = &typescore.ApprovalTopicCategory{} - h.Topic = &typescore.ApprovalTopic{} - - err := rows.Scan( - &h.ID, &h.SubordinateID, &h.ApproverID, &h.DepartmentID, - &h.TopicCategoryID, &h.TopicID, &h.Priority, - &h.TargetSystem, - &h.CreatedAt, &h.UpdatedAt, - &h.Subordinate.ID, &h.Subordinate.FullName, &h.Subordinate.Username, - &h.Approver.ID, &h.Approver.FullName, &h.Approver.Username, - &h.Department.ID, &h.Department.Name, - &h.TopicCategory.ID, &h.TopicCategory.Name, - &h.Topic.ID, &h.Topic.Name, - &totalCount, - ) - if err != nil { - return nil, 0, fmt.Errorf("scan error: %w", err) - } - results = append(results, h) - } - - return results, totalCount, nil -} - ------END core/db/methods/user_hierarchy.go----- - -File: core/db/methods/user_role.go -Lines: 264 ------BEGIN core/db/methods/user_role.go----- -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 - CreateUserRolesBulkDB(ctx context.Context, tx pgx.Tx, userID uint64, roleIDs []uint64) ([]*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 - } - - _, err = u.pool.Exec(ctx, query, args...) - if err != nil { - return err - } - - return nil - } else { - return errors.New("userRole obj is nil") - } -} - -// GetUserRolesByUserIDsDB — пакетное получение ролей сразу для нескольких пользователей (устраняет N+1) -func (ur *UserRoleDB) GetUserRolesByUserIDsDB(ctx context.Context, userIDs []uint64) ([]*typescore.UserRole, error) { - if len(userIDs) == 0 { - return nil, nil - } - - fields := dbutils.GetStructFieldsDB(&typescore.UserRole{}, dbcoretablenames.TableNameUserRoles.ToString()) - - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Select(fields...). - From(dbcoretablenames.TableNameUserRoles.ToString()). - Where(squirrel.Eq{"user_id": userIDs}). - ToSql() - if err != nil { - return nil, err - } - - rows, err := ur.pool.Query(ctx, sql, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - var result []*typescore.UserRole - for rows.Next() { - item := &typescore.UserRole{} - if err := dbutils.ScanRowsToStructRows(rows, item, nil); err != nil { - logrus.Warn("GetUserRolesByUserIDsDB:ScanRowsToStructRows", err) - continue - } - result = append(result, item) - } - if err = rows.Err(); err != nil { - return nil, err - } - - return result, nil -} - -// DeleteUserRolesByUserIDDB — удаляет все роли пользователя одним запросом вместо цикла DELETE -func (ur *UserRoleDB) DeleteUserRolesByUserIDDB(ctx context.Context, userID uint64) error { - sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Delete(dbcoretablenames.TableNameUserRoles.ToString()). - Where(squirrel.Eq{"user_id": userID}). - ToSql() - if err != nil { - return err - } - - _, err = ur.pool.Exec(ctx, sql, args...) - return err -} - -// CreateUserRolesBulkDB — вставляет сразу несколько ролей одним multi-row INSERT вместо цикла -func (ur *UserRoleDB) CreateUserRolesBulkDB(ctx context.Context, tx pgx.Tx, userID uint64, roleIDs []uint64) ([]*typescore.UserRole, error) { - if len(roleIDs) == 0 { - return nil, nil - } - - err := dbutils.ExecuteTx(ctx, ur.pool, tx, func(tx pgx.Tx) error { - query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). - Insert(dbcoretablenames.TableNameUserRoles.ToString()). - Columns("user_id", "role_id") - - for _, roleID := range roleIDs { - query = query.Values(userID, roleID) - } - - sql, args, err := query.ToSql() - if err != nil { - return err - } - - _, err = tx.Exec(ctx, sql, args...) - return err - }) - if err != nil { - return nil, err - } - - return ur.GetUserRolesByUserIDsDB(ctx, []uint64{userID}) -} - ------END core/db/methods/user_role.go----- - -File: core/db/table_names/table_names.go -Lines: 38 ------BEGIN core/db/table_names/table_names.go----- -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" - TableNameApprovalAdditionalObservers TableName = "approval_additional_observers" - TableNameApprovalTasks TableName = "approval_tasks" - TableNameApprovalComments TableName = "approval_comments" - TableNameSuggestions TableName = "suggestions" - TableNameSuggestionMessages TableName = "suggestion_messages" - TableNameApprovalTopicExecutor TableName = "approval_topic_executor" - TableNameAdmin TableName = "admin" - TableNameNotifications TableName = "notifications" - TableNameNotificationsRecipients TableName = "notification_recipients" - TableNameDirectorNotificationSubscriptions TableName = "director_notification_subscriptions" - TableNameApprovalTaskTransfers TableName = "approval_task_transfers" - TableNameApprovalRevocationRequests TableName = "approval_revocation_requests" - TableNameApprovalRevocationApprovers TableName = "approval_revocation_approvers" - TableNameApprovalFlowNodes TableName = "approval_flow_nodes" - TableNameAdminActionLogs TableName = "admin_action_logs" -) - -func (t TableName) ToString() string { - return string(t) -} - ------END core/db/table_names/table_names.go----- - -File: core/lib/external/gorm/gorm.go -Lines: 139 ------BEGIN core/lib/external/gorm/gorm.go----- -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 -} - ------END core/lib/external/gorm/gorm.go----- - -File: core/lib/external/pgxpool/pgxpools.go -Lines: 86 ------BEGIN core/lib/external/pgxpool/pgxpools.go----- -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 -} - ------END core/lib/external/pgxpool/pgxpools.go----- - -File: core/lib/external/telegram/init.go -Lines: 51 ------BEGIN core/lib/external/telegram/init.go----- -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 -} - ------END core/lib/external/telegram/init.go----- - -File: core/lib/external/telegram/message.go -Lines: 56 ------BEGIN core/lib/external/telegram/message.go----- -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 -} - ------END core/lib/external/telegram/message.go----- - -File: core/lib/external/telegram/req.go -Lines: 60 ------BEGIN core/lib/external/telegram/req.go----- -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 -} - ------END core/lib/external/telegram/req.go----- - -File: core/lib/external/telegram/types.go -Lines: 25 ------BEGIN core/lib/external/telegram/types.go----- -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. -} - ------END core/lib/external/telegram/types.go----- - -File: core/lib/external/tgkit/client.go -Lines: 359 ------BEGIN core/lib/external/tgkit/client.go----- -package tgkit - -import ( - "bitrix_balancer_api/core/variables" - "bytes" - "crypto/tls" - "encoding/json" - "fmt" - "io" - "mime" - "mime/multipart" - "net/http" - "net/url" - "sync" - "time" - - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" -) - -// APIProxyRequest описывает структуру тела запроса к твоему прокси-сервису -type APIProxyRequest struct { - URL string `json:"url"` - Method string `json:"method"` - Body interface{} `json:"body,omitempty"` -} -type CustomAPIProxyTransport struct { - wrapped http.RoundTripper -} - -// Бот -> прокси-сервис. Отдельный, короткий retry-бюджет: это про -// доступность самого proxyservice.ddns.net (DNS/подключение), а не про -// доступность Telegram — за это отвечает retry внутри самого прокси -// (см. main.go прокси-сервиса, doWithRetry). -const ( - maxProxyConnectAttempts = 2 - proxyConnectRetryDelay = 500 * time.Millisecond -) - -func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response, error) { - targetURL := req.URL.String() - method := req.Method - - var proxyReq *http.Request - var bodyBytesForRetry []byte - - contentType := req.Header.Get("Content-Type") - mediaType, params, _ := mime.ParseMediaType(contentType) - - if mediaType == "multipart/form-data" && req.Body != nil { - bodyBytes, err := io.ReadAll(req.Body) - if err != nil { - return nil, fmt.Errorf("proxy transport: failed to read multipart body: %w", err) - } - _ = req.Body.Close() - - var buf bytes.Buffer - writer := multipart.NewWriter(&buf) - - _ = writer.WriteField("url", targetURL) - _ = writer.WriteField("method", method) - - boundary := params["boundary"] - mr := multipart.NewReader(bytes.NewReader(bodyBytes), boundary) - for { - part, err := mr.NextPart() - if err == io.EOF { - break - } - if err != nil { - return nil, fmt.Errorf("proxy transport: parse incoming multipart: %w", err) - } - - partBytes, _ := io.ReadAll(part) - - if part.FileName() != "" { - // Если это файл, создаем файловую часть с сохранением имени и заголовков - filePart, err := writer.CreateFormFile(part.FormName(), part.FileName()) - if err != nil { - return nil, fmt.Errorf("proxy transport: create form file: %w", err) - } - _, _ = filePart.Write(partBytes) - } else { - // Если обычное поле - fieldPart, err := writer.CreateFormField(part.FormName()) - if err != nil { - return nil, fmt.Errorf("proxy transport: create form field: %w", err) - } - _, _ = fieldPart.Write(partBytes) - } - } - _ = writer.Close() - bodyBytesForRetry = buf.Bytes() - - proxyReq, err = http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(bodyBytesForRetry)) - if err != nil { - return nil, fmt.Errorf("proxy transport: failed to create multipart request: %w", err) - } - proxyReq.Header.Set("Content-Type", writer.FormDataContentType()) - } else { - var originalBody interface{} = map[string]interface{}{} - - if req.Body != nil { - bodyBytes, err := io.ReadAll(req.Body) - if err != nil { - return nil, fmt.Errorf("proxy transport: failed to read body: %w", err) - } - _ = req.Body.Close() - - if len(bodyBytes) > 0 { - // Проверяем, JSON ли это - var raw json.RawMessage - if err := json.Unmarshal(bodyBytes, &raw); err == nil { - originalBody = raw - } else { - // Если это url-encoded строка, превращаем в map - values, err := url.ParseQuery(string(bodyBytes)) - if err == nil && len(values) > 0 { - bodyMap := make(map[string]interface{}) - for key, val := range values { - if len(val) == 1 { - bodyMap[key] = val[0] - } else if len(val) > 1 { - bodyMap[key] = val - } - } - originalBody = bodyMap - } else { - originalBody = string(bodyBytes) - } - } - } - } - - // Собираем JSON-payload для handleJSON на шлюзе - proxyReqPayload := APIProxyRequest{ - URL: targetURL, - Method: method, - Body: originalBody, - } - - proxyJsonBytes, err := json.Marshal(proxyReqPayload) - if err != nil { - return nil, fmt.Errorf("proxy transport: failed to marshal proxy payload: %w", err) - } - bodyBytesForRetry = proxyJsonBytes - - proxyReq, err = http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(bodyBytesForRetry)) - if err != nil { - return nil, fmt.Errorf("proxy transport: failed to create json request: %w", err) - } - proxyReq.Header.Set("Content-Type", "application/json") - } - - // Общие заголовки авторизации шлюза - proxyReq.Header.Set(variables.ProxySecretHeader, variables.ProxySecretKey) - - return t.roundTripWithRetry(proxyReq, bodyBytesForRetry) -} - -// roundTripWithRetry повторяет попытку достучаться до самого прокси-сервиса -// при сбое подключения (DNS, connection refused/reset и т.п.). Это отдельный -// уровень отказоустойчивости от retry внутри самого прокси: там речь про -// "прокси -> Telegram", здесь — про "бот -> прокси". -func (t *CustomAPIProxyTransport) roundTripWithRetry(req *http.Request, bodyBytes []byte) (*http.Response, error) { - var lastErr error - for attempt := 1; attempt <= maxProxyConnectAttempts; attempt++ { - req.Body = io.NopCloser(bytes.NewReader(bodyBytes)) - req.ContentLength = int64(len(bodyBytes)) - - resp, err := t.wrapped.RoundTrip(req) - if err != nil { - lastErr = err - logrus.Warnf("tgkit: proxy connect attempt %d/%d failed: %v", attempt, maxProxyConnectAttempts, err) - if attempt < maxProxyConnectAttempts { - time.Sleep(proxyConnectRetryDelay) - } - continue - } - - if resp.StatusCode != http.StatusOK { - defer resp.Body.Close() - errorBody, _ := io.ReadAll(resp.Body) - // Не ретраим: это осмысленный ответ от прокси (например, он сам - // уже исчерпал свои попытки достучаться до Telegram) — новая - // попытка прямо сейчас с тем же результатом ничего не изменит, - // а таймаут внешнего http.Client общий на весь RoundTrip. - return nil, fmt.Errorf("proxy returned status %d (%s): %s", resp.StatusCode, resp.Status, string(errorBody)) - } - - return resp, nil - } - return nil, lastErr -} - -// Client — основной клиент библиотеки -type Client struct { - bot *tgbotapi.BotAPI - timeout time.Duration -} - -// ClientConfig — конфигурация клиента -type ClientConfig struct { - Token string - Proxy *ProxyConfig // Теперь этот параметр можно оставить пустым или использовать как флаг включения прокси - Timeout time.Duration // по умолчанию defaultTimeout - Debug bool -} - -// defaultTimeout — общий таймаут http.Client на весь round trip (бот -> прокси -// -> Telegram, включая ретраи на обоих уровнях). Должен быть заметно больше -// худшего сценария retry внутри прокси (см. main.go: до 3 попыток по 15с -// каждая + паузы ≈ до ~40с) — иначе бот отваливается раньше, чем прокси -// успевает довести дело до конца, и весь смысл ретраев на прокси теряется. -const defaultTimeout = 120 * time.Second - -// Сколько раз пробовать поднять бота при старте процесса, прежде чем сдаться. -// Единичный сетевой сбой в момент старта не должен ронять весь сервис. -const ( - maxStartupAttempts = 3 - startupRetryDelay = 3 * time.Second -) - -var ( - mu sync.Mutex - instance *Client -) - -func GetClient(cfg ClientConfig) (*Client, error) { - if instance != nil { - return instance, nil - } - - mu.Lock() - defer mu.Unlock() - - if instance != nil { - return instance, nil - } - - client, err := newClient(cfg) - if err != nil { - return nil, err - } - - instance = client - return instance, nil -} - -// New создаёт нового клиента -func newClient(cfg ClientConfig) (*Client, error) { - if cfg.Token == "" { - return nil, fmt.Errorf("tgkit: token is required") - } - if cfg.Timeout == 0 { - cfg.Timeout = defaultTimeout - } - - if cfg.Proxy != nil { - logrus.Debugf("tgkit: custom API proxy is enabled") - } - - httpClient, err := buildHTTPClient(cfg.Proxy, cfg.Timeout) - if err != nil { - return nil, fmt.Errorf("tgkit: build http client: %w", err) - } - - var bot *tgbotapi.BotAPI - for attempt := 1; attempt <= maxStartupAttempts; attempt++ { - bot, err = tgbotapi.NewBotAPIWithClient(cfg.Token, tgbotapi.APIEndpoint, httpClient) - if err == nil { - break - } - logrus.Warnf("tgkit: init bot attempt %d/%d failed: %v", attempt, maxStartupAttempts, err) - if attempt < maxStartupAttempts { - time.Sleep(time.Duration(attempt) * startupRetryDelay) - } - } - if err != nil { - return nil, fmt.Errorf("tgkit: init bot after %d attempts: %w", maxStartupAttempts, err) - } - - bot.Debug = cfg.Debug - - return &Client{ - bot: bot, - timeout: cfg.Timeout, - }, nil -} - -// NewFromExisting оборачивает существующий *tgbotapi.BotAPI -func NewFromExisting(bot *tgbotapi.BotAPI) *Client { - return &Client{bot: bot, timeout: defaultTimeout} -} - -// Bot возвращает сырой *tgbotapi.BotAPI -func (c *Client) Bot() *tgbotapi.BotAPI { - return c.bot -} - -// Self возвращает информацию о боте -func (c *Client) Self() tgbotapi.User { - return c.bot.Self -} - -// GetUpdates возвращает канал обновлений -func (c *Client) GetUpdates(timeout int) tgbotapi.UpdatesChannel { - u := tgbotapi.NewUpdate(0) - u.Timeout = timeout - return c.bot.GetUpdatesChan(u) -} - -// AnswerCallback отвечает на callback query -func (c *Client) AnswerCallback(callbackID string, text string) error { - cb := tgbotapi.NewCallback(callbackID, text) - _, err := c.bot.Request(cb) - return err -} - -// DeleteMessage удаляет сообщение -func (c *Client) DeleteMessage(chatID int64, messageID int) error { - _, err := c.bot.Request(tgbotapi.NewDeleteMessage(chatID, messageID)) - return err -} - -// GetFileDirectURL возвращает прямую ссылку на файл -func (c *Client) GetFileDirectURL(fileID string) (string, error) { - return c.bot.GetFileDirectURL(fileID) -} - -// Request выполняет произвольный запрос к API -func (c *Client) Request(cfg tgbotapi.Chattable) (*tgbotapi.APIResponse, error) { - return c.bot.Request(cfg) -} - -// buildHTTPClient создаёт http.Client с поддержкой кастомного API прокси. -// -// ⚠️ ГЛАВНЫЙ ФИКС: раньше proxyCfg принимался, но никогда не использовался — -// finalTransport всегда оставался обычным прямым http.Transport, и весь -// трафик бота шёл напрямую в api.telegram.org, минуя прокси. Теперь при -// заданном proxyCfg реально оборачиваем транспорт в CustomAPIProxyTransport. -func buildHTTPClient(proxyCfg *ProxyConfig, timeout time.Duration) (*http.Client, error) { - baseTransport := &http.Transport{ - MaxIdleConns: 100, // Увеличиваем общий пул - MaxIdleConnsPerHost: 100, // Увеличиваем пул для api.telegram.org / прокси - TLSClientConfig: &tls.Config{InsecureSkipVerify: false}, - } - - var finalTransport http.RoundTripper = baseTransport - - if proxyCfg != nil { - finalTransport = &CustomAPIProxyTransport{wrapped: baseTransport} - } - - return &http.Client{ - Transport: finalTransport, - Timeout: timeout, - }, nil -} - ------END core/lib/external/tgkit/client.go----- - -File: core/lib/external/tgkit/err.go -Lines: 25 ------BEGIN core/lib/external/tgkit/err.go----- -package tgkit - -import "fmt" - -type ErrSend struct { - ChatID int64 - Reason string -} - -func (e *ErrSend) Error() string { - return fmt.Sprintf("tgkit: send to chat %d failed: %s", e.ChatID, e.Reason) -} - -type ErrNilBot struct{} - -func (e *ErrNilBot) Error() string { - return "tgkit: bot client is nil" -} - -func wrapSendErr(chatID int64, err error) error { - if err == nil { - return nil - } - return &ErrSend{ChatID: chatID, Reason: err.Error()} -} - ------END core/lib/external/tgkit/err.go----- - -File: core/lib/external/tgkit/keyboard.go -Lines: 163 ------BEGIN core/lib/external/tgkit/keyboard.go----- -package tgkit - -import ( - "fmt" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" -) - -// ───────────────────────────────────────────── -// Inline-клавиатура -// ───────────────────────────────────────────── - -// InlineKeyboard — построитель inline-клавиатуры -type InlineKeyboard struct { - Rows [][]tgbotapi.InlineKeyboardButton -} - -// NewInlineKeyboard создаёт пустой построитель -func NewInlineKeyboard() *InlineKeyboard { - return &InlineKeyboard{} -} - -// Row добавляет ряд кнопок -func (kb *InlineKeyboard) Row(buttons ...InlineButton) *InlineKeyboard { - var row []tgbotapi.InlineKeyboardButton - for _, btn := range buttons { - row = append(row, btn.Build()) - } - kb.Rows = append(kb.Rows, row) - return kb -} - -// Build возвращает готовую клавиатуру -func (kb *InlineKeyboard) Build() tgbotapi.InlineKeyboardMarkup { - return tgbotapi.NewInlineKeyboardMarkup(kb.Rows...) -} - -// InlineButton — кнопка inline-клавиатуры -type InlineButton struct { - label string - style ButtonStyle - callback string - url string -} - -// Btn создаёт кнопку с callback -func Btn(label, callback string) InlineButton { - return InlineButton{label: label, callback: callback} -} - -// BtnStyled создаёт кнопку с визуальным стилем (эмодзи) и callback -func BtnStyled(style ButtonStyle, label, callback string) InlineButton { - return InlineButton{label: label, style: style, callback: callback} -} - -// BtnURL создаёт кнопку-ссылку -func BtnURL(label, url string) InlineButton { - return InlineButton{label: label, url: url} -} - -// WithStyle задаёт стиль кнопке -func (b InlineButton) WithStyle(style ButtonStyle) InlineButton { - b.style = style - return b -} - -func (b InlineButton) Build() tgbotapi.InlineKeyboardButton { - text := string(b.style) + b.label - if b.url != "" { - return tgbotapi.NewInlineKeyboardButtonURL(text, b.url) - } - return tgbotapi.NewInlineKeyboardButtonData(text, b.callback) -} - -// ───────────────────────────────────────────── -// Reply-клавиатура (постоянные кнопки) -// ───────────────────────────────────────────── - -// ReplyKeyboard — построитель reply-клавиатуры -type ReplyKeyboard struct { - rows [][]tgbotapi.KeyboardButton - resize bool - oneTime bool -} - -// NewReplyKeyboard создаёт пустой построитель -func NewReplyKeyboard() *ReplyKeyboard { - return &ReplyKeyboard{resize: true} -} - -// Row добавляет ряд текстовых кнопок -func (kb *ReplyKeyboard) Row(labels ...string) *ReplyKeyboard { - var row []tgbotapi.KeyboardButton - for _, label := range labels { - row = append(row, tgbotapi.NewKeyboardButton(label)) - } - kb.rows = append(kb.rows, row) - return kb -} - -// OneTime скрывает клавиатуру после нажатия -func (kb *ReplyKeyboard) OneTime() *ReplyKeyboard { - kb.oneTime = true - return kb -} - -// NoResize отключает авторесайз -func (kb *ReplyKeyboard) NoResize() *ReplyKeyboard { - kb.resize = false - return kb -} - -// Build возвращает готовую клавиатуру -func (kb *ReplyKeyboard) Build() tgbotapi.ReplyKeyboardMarkup { - markup := tgbotapi.NewReplyKeyboard(kb.rows...) - markup.ResizeKeyboard = kb.resize - markup.OneTimeKeyboard = kb.oneTime - return markup -} - -// RemoveKeyboard убирает reply-клавиатуру -func RemoveKeyboard() tgbotapi.ReplyKeyboardRemove { - return tgbotapi.NewRemoveKeyboard(false) -} - -// ───────────────────────────────────────────── -// Готовые шаблоны клавиатур -// ───────────────────────────────────────────── - -// ConfirmKeyboard — клавиатура Да/Нет -func ConfirmKeyboard(yesCallback, noCallback string) tgbotapi.InlineKeyboardMarkup { - return NewInlineKeyboard(). - Row( - BtnStyled(ButtonStyleSuccess, "Да", yesCallback), - BtnStyled(ButtonStyleDanger, "Нет", noCallback), - ). - Build() -} - -// BackKeyboard — одна кнопка "← Назад" -func BackKeyboard(callback string) tgbotapi.InlineKeyboardMarkup { - return NewInlineKeyboard(). - Row(BtnStyled(ButtonStyleBack, "Назад", callback)). - Build() -} - -// PaginationRow — ряд кнопок пагинации -func PaginationRow(page, totalPages int, prevCallback, nextCallback, noopCallback string) []tgbotapi.InlineKeyboardButton { - var row []tgbotapi.InlineKeyboardButton - - if page > 0 { - row = append(row, Btn("←", prevCallback).Build()) - } - - row = append(row, tgbotapi.NewInlineKeyboardButtonData( - fmt.Sprintf("%d / %d", page+1, totalPages), noopCallback, - )) - - if page < totalPages-1 { - row = append(row, Btn("→", nextCallback).Build()) - } - - return row -} - ------END core/lib/external/tgkit/keyboard.go----- - -File: core/lib/external/tgkit/media.go -Lines: 197 ------BEGIN core/lib/external/tgkit/media.go----- -package tgkit - -import ( - "encoding/base64" - "fmt" - "io" - "net/http" - "os" - - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" -) - -func detectImageExtension(data []byte) string { - contentType := http.DetectContentType(data) - switch contentType { - case "image/png": - return "photo.png" - case "image/jpeg": - return "photo.jpg" - case "image/webp": - return "photo.webp" - case "image/gif": - return "photo.gif" - default: - return "photo.jpg" - } -} - -// SendPhoto отправляет фото по URL, пути к файлу или base64 -func (c *Client) SendPhoto(chatID int64, source string, caption string, opts ...MessageOptions) (*SentMessage, error) { - var photo tgbotapi.RequestFileData - - switch { - case isURL(source): - photo = tgbotapi.FileURL(source) - case isBase64(source): - data, err := base64.StdEncoding.DecodeString(source) - if err != nil { - return nil, fmt.Errorf("tgkit: decode base64: %w", err) - } - fileName := detectImageExtension(data) - photo = tgbotapi.FileBytes{Name: fileName, Bytes: data} - default: - photo = tgbotapi.FilePath(source) - } - - msg := tgbotapi.NewPhoto(chatID, photo) - msg.Caption = caption - msg.ParseMode = "HTML" - - if len(opts) > 0 && opts[0].ReplyMarkup != nil { - msg.ReplyMarkup = opts[0].ReplyMarkup - } - - sent, err := c.bot.Send(msg) - if err != nil { - return nil, wrapSendErr(chatID, err) - } - - return &SentMessage{MessageID: sent.MessageID, ChatID: sent.Chat.ID}, nil -} - -// SendDocument отправляет документ -func (c *Client) SendDocument(chatID int64, data []byte, fileName string, caption string, opts ...MessageOptions) (*SentMessage, error) { - doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{ - Name: fileName, - Bytes: data, - }) - doc.Caption = caption - doc.ParseMode = "HTML" - - if len(opts) > 0 && opts[0].ReplyMarkup != nil { - doc.ReplyMarkup = opts[0].ReplyMarkup - } - - sent, err := c.bot.Send(doc) - if err != nil { - return nil, wrapSendErr(chatID, err) - } - - return &SentMessage{MessageID: sent.MessageID, ChatID: sent.Chat.ID}, nil -} - -// SendDocumentFromBase64 отправляет документ из base64-строки -func (c *Client) SendDocumentFromBase64(chatID int64, base64Data string, fileName string, caption string, opts ...MessageOptions) (*SentMessage, error) { - data, err := base64.StdEncoding.DecodeString(base64Data) - if err != nil { - return nil, fmt.Errorf("tgkit: decode base64: %w", err) - } - return c.SendDocument(chatID, data, fileName, caption, opts...) -} - -// SendSticker отправляет стикер по fileID -func (c *Client) SendSticker(chatID int64, fileID string) (*SentMessage, error) { - sticker := tgbotapi.NewSticker(chatID, tgbotapi.FileID(fileID)) - sent, err := c.bot.Send(sticker) - if err != nil { - return nil, wrapSendErr(chatID, err) - } - return &SentMessage{MessageID: sent.MessageID, ChatID: sent.Chat.ID}, nil -} - -// SendMediaGroup отправляет группу медиафайлов (альбом) -func (c *Client) SendMediaGroup(chatID int64, files []MediaFile) error { - if len(files) == 0 { - return nil - } - - var media []interface{} - for i, f := range files { - photo := tgbotapi.NewInputMediaPhoto(tgbotapi.FileBytes{ - Name: f.FileName, - Bytes: f.Data, - }) - if i == 0 && f.Caption != "" { - photo.Caption = f.Caption - photo.ParseMode = "HTML" - } - media = append(media, photo) - } - - mediaGroup := tgbotapi.NewMediaGroup(chatID, media) - _, err := c.bot.Request(mediaGroup) - return err -} - -// DownloadFile скачивает файл из Telegram по fileID, возвращает байты -func (c *Client) DownloadFile(fileID string) ([]byte, string, error) { - fileURL, err := c.bot.GetFileDirectURL(fileID) - if err != nil { - return nil, "", fmt.Errorf("tgkit: get file url: %w", err) - } - - resp, err := http.Get(fileURL) //nolint:gosec - if err != nil { - return nil, "", fmt.Errorf("tgkit: download file: %w", err) - } - defer resp.Body.Close() - - data, err := io.ReadAll(resp.Body) - if err != nil { - return nil, "", fmt.Errorf("tgkit: read file: %w", err) - } - - // Извлекаем имя файла из URL - fileName := extractFileName(fileURL) - return data, fileName, nil -} - -// DownloadFileAsBase64 скачивает файл и возвращает base64 -func (c *Client) DownloadFileAsBase64(fileID string) (string, string, error) { - data, fileName, err := c.DownloadFile(fileID) - if err != nil { - return "", "", err - } - return base64.StdEncoding.EncodeToString(data), fileName, nil -} - -// MustSendDocument отправляет документ, логирует ошибку -func (c *Client) MustSendDocument(chatID int64, data []byte, fileName, caption string, opts ...MessageOptions) { - if _, err := c.SendDocument(chatID, data, fileName, caption, opts...); err != nil { - logrus.Warnf("tgkit.MustSendDocument: chatID=%d file=%s err=%v", chatID, fileName, err) - } -} - -// MediaFile — структура для SendMediaGroup -type MediaFile struct { - Data []byte - FileName string - Caption string -} - -func isURL(s string) bool { - return len(s) > 4 && (s[:4] == "http" || s[:5] == "https") -} - -func isBase64(s string) bool { - if len(s) < 4 { - return false - } - _, err := base64.StdEncoding.DecodeString(s[:4]) - return err == nil && len(s)%4 == 0 -} - -func extractFileName(fileURL string) string { - for i := len(fileURL) - 1; i >= 0; i-- { - if fileURL[i] == '/' { - return fileURL[i+1:] - } - } - return "file" -} - -func readFile(path string) ([]byte, error) { - return os.ReadFile(path) //nolint:gosec -} - ------END core/lib/external/tgkit/media.go----- - -File: core/lib/external/tgkit/message.go -Lines: 87 ------BEGIN core/lib/external/tgkit/message.go----- -package tgkit - -import ( - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" -) - -// Send отправляет текстовое сообщение -func (c *Client) Send(chatID int64, text string, opts ...MessageOptions) (*SentMessage, error) { - if c.bot == nil { - return nil, &ErrNilBot{} - } - - msg := tgbotapi.NewMessage(chatID, text) - msg.ParseMode = "HTML" // дефолт - - if len(opts) > 0 { - opt := opts[0] - if opt.ParseMode != "" { - msg.ParseMode = string(opt.ParseMode) - } - if opt.ReplyMarkup != nil { - msg.ReplyMarkup = opt.ReplyMarkup - } - msg.DisableWebPagePreview = opt.DisablePreview - msg.DisableNotification = opt.Silent - } - - sent, err := c.bot.Send(msg) - if err != nil { - return nil, wrapSendErr(chatID, err) - } - - return &SentMessage{ - MessageID: sent.MessageID, - ChatID: sent.Chat.ID, - Date: sent.Time(), - }, nil -} - -// MustSend отправляет сообщение, логирует ошибку но не возвращает её. -// Используется когда ошибка некритична (уведомление). -func (c *Client) MustSend(chatID int64, text string, opts ...MessageOptions) { - if _, err := c.Send(chatID, text, opts...); err != nil { - logrus.Warnf("tgkit.MustSend: chatID=%d err=%v", chatID, err) - } -} - -// EditText редактирует текст существующего сообщения -func (c *Client) EditText(chatID int64, messageID int, text string, opts ...MessageOptions) error { - edit := tgbotapi.NewEditMessageText(chatID, messageID, text) - edit.ParseMode = "HTML" - - if len(opts) > 0 && opts[0].ParseMode != "" { - edit.ParseMode = string(opts[0].ParseMode) - } - - _, err := c.bot.Request(edit) - return err -} - -// EditKeyboard заменяет клавиатуру у существующего сообщения -func (c *Client) EditKeyboard(chatID int64, messageID int, keyboard tgbotapi.InlineKeyboardMarkup) error { - edit := tgbotapi.NewEditMessageReplyMarkup(chatID, messageID, keyboard) - _, err := c.bot.Request(edit) - return err -} - -// WithKeyboard — хелпер для построения MessageOptions с клавиатурой -func WithKeyboard(markup interface{}) MessageOptions { - return MessageOptions{ReplyMarkup: markup} -} - -// WithInline — хелпер для inline-клавиатуры -func WithInline(kb *InlineKeyboard) MessageOptions { - return MessageOptions{ReplyMarkup: kb.Build()} -} - -// WithReply — хелпер для reply-клавиатуры -func WithReply(kb *ReplyKeyboard) MessageOptions { - return MessageOptions{ReplyMarkup: kb.Build()} -} - -// WithSilent — хелпер для тихой отправки -func WithSilent() MessageOptions { - return MessageOptions{Silent: true} -} - ------END core/lib/external/tgkit/message.go----- - -File: core/lib/external/tgkit/types.go -Lines: 58 ------BEGIN core/lib/external/tgkit/types.go----- -package tgkit - -import "time" - -// ParseMode — режим форматирования текста -type ParseMode string - -const ( - ParseModeHTML ParseMode = "HTML" - ParseModeMarkdown ParseMode = "MarkdownV2" - ParseModePlain ParseMode = "" -) - -// ButtonColorStyle — стили цветов кнопок -type ButtonColorStyle string - -const ( - ButtonColorStyleDanger ButtonColorStyle = "danger" // красная - ButtonColorStyleSuccess ButtonColorStyle = "success" // зеленая - ButtonColorStylePrimary ButtonColorStyle = "primary" // синяя -) - -// ButtonStyle — визуальный стиль кнопки (через эмодзи) -type ButtonStyle string - -const ( - ButtonStyleDefault ButtonStyle = "" - ButtonStyleSuccess ButtonStyle = "✅ " - ButtonStyleDanger ButtonStyle = "❌ " - ButtonStyleWarning ButtonStyle = "⚠️ " - ButtonStyleInfo ButtonStyle = "ℹ️ " - ButtonStylePrimary ButtonStyle = "🔵 " - ButtonStyleBack ButtonStyle = "← " - ButtonStyleForward ButtonStyle = "→ " - ButtonStyleRevision ButtonStyle = "↩️ " -) - -// MessageOptions — опции отправки сообщения -type MessageOptions struct { - ParseMode ParseMode - ReplyMarkup interface{} - DisablePreview bool - Silent bool -} - -// ProxyConfig — настройки прокси -type ProxyConfig struct { - URL string // socks5://user:pass@host:port или http://host:port - Username string - Password string -} - -// SentMessage — результат отправки -type SentMessage struct { - MessageID int - ChatID int64 - Date time.Time -} - ------END core/lib/external/tgkit/types.go----- - -File: core/lib/internally/client-controllers/0_init.go -Lines: 60 ------BEGIN core/lib/internally/client-controllers/0_init.go----- -package clientcontrollers - -import ( - configcore "bitrix_balancer_api/core/config" - database "bitrix_balancer_api/core/db" - "bitrix_balancer_api/core/lib/external/tgkit" - redismodule "bitrix_balancer_api/core/lib/internally/redis" - "errors" - "fmt" -) - -type ClientsExternal struct { - Config *configcore.Config - Redis *redismodule.ModuleRedis - DB *database.ModuleDB - Telegram *tgkit.Client -} - -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 - } - - if cfgOptions.Telegram { - tgKitClient, err := tgkit.GetClient(tgkit.ClientConfig{ - Token: cfg.Telegram.BotToken, - Proxy: &tgkit.ProxyConfig{}, - }) - if err != nil { - return clientsExternal, errors.New(fmt.Sprintf("failed to get tg client: %v", err)) - } - clientsExternal.Telegram = tgKitClient - } - - return clientsExternal, nil -} - ------END core/lib/internally/client-controllers/0_init.go----- - -File: core/lib/internally/client-controllers/db-client.go -Lines: 49 ------BEGIN core/lib/internally/client-controllers/db-client.go----- -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 -} - ------END core/lib/internally/client-controllers/db-client.go----- - -File: core/lib/internally/client-controllers/redis-client.go -Lines: 34 ------BEGIN core/lib/internally/client-controllers/redis-client.go----- -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 -} - ------END core/lib/internally/client-controllers/redis-client.go----- - -File: core/lib/internally/config-loader/cfgldr.go -Lines: 22 ------BEGIN core/lib/internally/config-loader/cfgldr.go----- -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") -} - ------END core/lib/internally/config-loader/cfgldr.go----- - -File: core/lib/internally/config-loader/loader.go -Lines: 28 ------BEGIN core/lib/internally/config-loader/loader.go----- -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 -} - ------END core/lib/internally/config-loader/loader.go----- - -File: core/lib/internally/config-loader/tag-worker.go -Lines: 290 ------BEGIN core/lib/internally/config-loader/tag-worker.go----- -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) -} - ------END core/lib/internally/config-loader/tag-worker.go----- - -File: core/lib/internally/config-loader/type.go -Lines: 26 ------BEGIN core/lib/internally/config-loader/type.go----- -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 -} - ------END core/lib/internally/config-loader/type.go----- - -File: core/lib/internally/config-loader/validate.go -Lines: 40 ------BEGIN core/lib/internally/config-loader/validate.go----- -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") -} - ------END core/lib/internally/config-loader/validate.go----- - -File: core/lib/internally/init.go -Lines: 7 ------BEGIN core/lib/internally/init.go----- -package internalservices - -import redismodule "bitrix_balancer_api/core/lib/internally/redis" - -func InitRedisModule(redisConfigObj *redismodule.RedisConfig) *redismodule.ModuleRedis { - return redismodule.GetRedisModuleInstance(redisConfigObj) -} - ------END core/lib/internally/init.go----- - -File: core/lib/internally/redis/0_init.go -Lines: 82 ------BEGIN core/lib/internally/redis/0_init.go----- -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 -} - ------END core/lib/internally/redis/0_init.go----- - -File: core/lib/internally/redis/redis_check.go -Lines: 39 ------BEGIN core/lib/internally/redis/redis_check.go----- -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 -} - ------END core/lib/internally/redis/redis_check.go----- - -File: core/lib/internally/redis/redis_methods.go -Lines: 26 ------BEGIN core/lib/internally/redis/redis_methods.go----- -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() -} - ------END core/lib/internally/redis/redis_methods.go----- - -File: core/lib/internally/redis/redis_w.go -Lines: 42 ------BEGIN core/lib/internally/redis/redis_w.go----- -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 -} - ------END core/lib/internally/redis/redis_w.go----- - -File: core/lib/internally/redis/request_quota.go -Lines: 109 ------BEGIN core/lib/internally/redis/request_quota.go----- -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() - } -} - ------END core/lib/internally/redis/request_quota.go----- - -File: core/lib/internally/redis/types.go -Lines: 36 ------BEGIN core/lib/internally/redis/types.go----- -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) -} - ------END core/lib/internally/redis/types.go----- - -File: core/reportcore/autoFitCol.go -Lines: 90 ------BEGIN core/reportcore/autoFitCol.go----- -package reportcore - -import ( - "github.com/xuri/excelize/v2" - "strings" - "unicode/utf8" -) - -// autoFitColumns автоматически подгоняет ширину колонок под содержимое. -// Учитывает длину заголовка и всех ячеек, добавляет небольшой отступ. -func autoFitColumns(f *excelize.File, sheetName string, headers []string, dataRowCount int) { - for colIdx, header := range headers { - colLetter, _ := excelize.ColumnNumberToName(colIdx + 1) - - // Начинаем с длины заголовка - maxWidth := stringWidth(header) - - // Проверяем все строки данных в этой колонке - for row := 2; row <= dataRowCount+1; row++ { - cellName, _ := excelize.CoordinatesToCellName(colIdx+1, row) - cellValue, _ := f.GetCellValue(sheetName, cellName) - w := stringWidth(cellValue) - if w > maxWidth { - maxWidth = w - } - } - - // Добавляем небольшой отступ для красоты - finalWidth := float64(maxWidth) + 2 - - // Ограничиваем минимальную и максимальную ширину - if finalWidth < 10 { - finalWidth = 10 - } - if finalWidth > 60 { - finalWidth = 60 - } - - _ = f.SetColWidth(sheetName, colLetter, colLetter, finalWidth) - } -} - -// stringWidth вычисляет "визуальную" ширину строки. -// Кириллица и другие широкие символы занимают больше места, чем латиница. -func stringWidth(s string) int { - width := 0 - for _, r := range s { - if isWideRune(r) { - width += 2 // широкие символы (кириллица, CJK) - } else { - width += 1 - } - } - // Учитываем переносы строк — берём самую длинную строку - lines := strings.Split(s, "\n") - maxLine := 0 - for _, line := range lines { - lw := 0 - for _, r := range line { - if isWideRune(r) { - lw += 2 - } else { - lw += 1 - } - } - if lw > maxLine { - maxLine = lw - } - } - if maxLine > width { - width = maxLine - } - return width -} - -// isWideRune определяет, является ли символ "широким" -func isWideRune(r rune) bool { - // Кириллица - if r >= 0x0400 && r <= 0x04FF { - return true - } - // CJK (китайские, японские, корейские) - if r >= 0x4E00 && r <= 0x9FFF { - return true - } - return false -} - -// _ используется, чтобы убрать предупреждение о неиспользуемом импорте -var _ = utf8.RuneCountInString - ------END core/reportcore/autoFitCol.go----- - -File: core/reportcore/excel.go -Lines: 502 ------BEGIN core/reportcore/excel.go----- -package reportcore - -import ( - database "bitrix_balancer_api/core/db" - "bitrix_balancer_api/core/typescore" - "bytes" - "context" - "fmt" - "sort" - "strings" - - "github.com/sirupsen/logrus" - "github.com/xuri/excelize/v2" -) - -// BuildExcelApprovalsReport — строит xlsx-файл отчёта по согласованиям и возвращает байты. -func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, approvals []*typescore.Approval) ([]byte, error) { - f := excelize.NewFile() - sheet := "Согласования" - if err := f.SetSheetName("Sheet1", sheet); err != nil { - return nil, fmt.Errorf("set sheet name: %w", err) - } - - // 1. Обновленные заголовки (добавлены Доп. согласующие и Доп. наблюдатели) - headers := []string{ - "ID", // A - "ФИО инициатора", // B - "Тема согласования", // C - "Дата создания", // D - "Согласующие", // E - "Наблюдатели", // F - "Доп. согласующие", // G 🆕 - "Доп. наблюдатели", // H 🆕 - "Статус", // I - "Текст согласования", // J - "Отдел сотрудника", // K - "Комментарии", // L - "Дата согласования", // M - "Текст задачи", // N - "Исполнитель", // O - "Статус задачи", // P - "Дата исполнения", // Q - } - - cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q"} - - colWidths := map[string]float64{ - "A": 10, "B": 25, "C": 40, "D": 18, "E": 30, - "F": 30, "G": 30, "H": 30, "I": 16, "J": 40, - "K": 25, "L": 30, "M": 18, "N": 40, "O": 25, - "P": 18, "Q": 18, - } - - headerStyle, err := 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}, - }) - if err != nil { - return nil, fmt.Errorf("create header style: %w", err) - } - - dataStyle, err := 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}, - }) - if err != nil { - return nil, fmt.Errorf("create data style: %w", err) - } - - rejectedStyle, err := 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}, - }) - if err != nil { - return nil, fmt.Errorf("create rejected style: %w", err) - } - - errorStyle, err := f.NewStyle(&excelize.Style{ - Fill: excelize.Fill{Type: "pattern", Color: []string{"FFCCCC"}, 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}, - }) - if err != nil { - return nil, fmt.Errorf("create error style: %w", err) - } - - for col, width := range colWidths { - if err := f.SetColWidth(sheet, col, col, width); err != nil { - return nil, fmt.Errorf("set col width %s: %w", col, err) - } - } - - for i, header := range headers { - cell := fmt.Sprintf("%s1", cols[i]) - if err := f.SetCellValue(sheet, cell, header); err != nil { - return nil, fmt.Errorf("set cell value %s: %w", cell, err) - } - if err := f.SetCellStyle(sheet, cell, cell, headerStyle); err != nil { - return nil, fmt.Errorf("set cell style %s: %w", cell, err) - } - } - if err := f.SetRowHeight(sheet, 1, 36); err != nil { - return nil, fmt.Errorf("set row height: %w", err) - } - - for rowIdx, a := range approvals { - row := rowIdx + 2 - - approvalID := uint64(0) - if a.ID != nil { - approvalID = *a.ID - } - - // === ФИО инициатора === - initiatorName := "" - if a.Initiator != nil && a.Initiator.FullName != nil { - initiatorName = *a.Initiator.FullName - } else if a.InitiatorID != nil { - if u, err := db.User.GetUserByIDDB(ctx, *a.InitiatorID); err == nil && u != nil && u.FullName != nil { - initiatorName = *u.FullName - } - } - - // === Тема согласования === - topicName := "" - if a.Topic != nil { - if a.Topic.Category != nil && a.Topic.Category.Name != nil { - topicName = *a.Topic.Category.Name + ": " - } else if a.Topic.CategoryID != nil { - if c, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *a.Topic.CategoryID); err == nil && c != nil && c.Name != nil { - topicName = *c.Name + ": " - } - } - if a.Topic.Name != nil { - topicName += *a.Topic.Name - } - } else if a.TopicID != nil { - if t, err := db.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); err == nil && t != nil { - if t.CategoryID != nil { - if c, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *t.CategoryID); err == nil && c != nil && c.Name != nil { - topicName = *c.Name + ": " - } - } - if 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 - lastApprovedAt := "" - - steps, _, _ := db.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: a.ID}, - }) - 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 := "" - if s.ApproverNameSnapshot != nil && *s.ApproverNameSnapshot != "" { - name = *s.ApproverNameSnapshot - } else if s.ApproverID != nil { - if u, err := db.User.GetUserByIDDB(ctx, *s.ApproverID); err == nil && 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 - } - if s.Status != nil && *s.Status == "approved" && s.ActedAt != nil { - lastApprovedAt = s.ActedAt.Format("02.01.2006 15:04") - } - } - approversCell := strings.Join(approverParts, "\n") - - // === Наблюдатели (Базовые) === - var observerParts []string - categoryCode := GetTopicCategoryCodeByApproval(ctx, db, a) - if categoryCode != "" { - observers, _ := db.User.GetObserversForApprovalDB(ctx, categoryCode, a.TopicID) - for _, obs := range observers { - if obs.FullName != nil { - observerParts = append(observerParts, *obs.FullName) - } - } - } - observersCell := strings.Join(observerParts, "\n") - - var addApproverParts []string - - addApprovers, _, _ := db.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: a.ID}, - }) - - for _, aa := range addApprovers { - name := "Неизвестный пользователь" - - // Получаем имя (используем ApproverID согласно вашей структуре) - if aa.ApproverID != nil { - if u, err := db.User.GetUserByIDDB(ctx, *aa.ApproverID); err == nil && u != nil && u.FullName != nil { - name = *u.FullName - } - } - - // Переводим статус на русский язык - aaStatus := "Ожидает" - if aa.Status != nil { - switch *aa.Status { - case "approved": - aaStatus = "Согласовано" - case "rejected": - aaStatus = "Отклонено" - case "pending": - aaStatus = "Ожидает" - } - } - - // Формируем основную строку: "Иванов И.И. (Статус: Согласовано)" - info := fmt.Sprintf("%s (Статус: %s)", name, aaStatus) - - // Добавляем дату действия, если она есть - if aa.ActedAt != nil { - info += fmt.Sprintf(" от %s", aa.ActedAt.Format("02.01.2006 15:04")) - } - - // Добавляем комментарий с новой строки, если он был оставлен - if aa.Comment != nil && *aa.Comment != "" { - info += fmt.Sprintf("\nКомментарий: %s", *aa.Comment) - } - - addApproverParts = append(addApproverParts, info) - } - - // Если доп. согласующих несколько, разделяем их пустой строкой (\n\n) для читаемости в ячейке - addApproversCell := strings.Join(addApproverParts, "\n\n") - - var addObserverParts []string - // Запрашиваем из базы доп. наблюдателей для данной заявки. - addObservers, _, _ := db.ApprovalAdditionalObserver.GetApprovalAdditionalObserversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalObserver{ApprovalID: a.ID}, - }) - for _, ao := range addObservers { - if ao.UserID != nil { - if u, err := db.User.GetUserByIDDB(ctx, *ao.UserID); err == nil && u != nil && u.FullName != nil { - addObserverParts = append(addObserverParts, *u.FullName) - } - } - } - addObserversCell := strings.Join(addObserverParts, "\n") - - // === Статус === - status := "—" - if a.Status != nil { - switch *a.Status { - case "pending": - status = "На согласовании" - case "approved": - status = "Согласовано" - case "rejected": - status = "Отклонено" - case "revoked": - status = "Отозвано" - case "revision": - status = "На доработке" - case "draft": - status = "Черновик" - } - } - - // === Текст заявки === - content := "" - if a.Content != nil { - content = *a.Content - } - - // === Отдел === - deptName := "" - if a.Department != nil && a.Department.Name != nil { - deptName = *a.Department.Name - } else if a.DepartmentID != nil { - if d, err := db.Department.GetDepartmentByIDDB(ctx, *a.DepartmentID); err == nil && d != nil && d.Name != nil { - deptName = *d.Name - } - } - - // === Комментарий === - comment := "" - if a.Status != nil && *a.Status == "rejected" { - comment = commentFromStep - } - - // === Задачи и исполнители === - taskText := "Не предусмотрено" - executorName := "Не предусмотрено" - taskStatus := "Не предусмотрено" - taskCompletedAt := "" - hasTaskError := false - - if a.TopicID != nil { - topicExecutors, _ := db.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, *a.TopicID) - - if len(topicExecutors) == 0 { - taskText = "Не предусмотрено" - executorName = "Не предусмотрено" - taskStatus = "Не предусмотрено" - } else { - tasks, _, _ := db.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTask{ApprovalID: a.ID}, - }) - - if len(tasks) == 0 { - if a.Status == nil { - taskText = "Не предусмотрено" - executorName = "Не предусмотрено" - taskStatus = "Не предусмотрено" - } else { - switch *a.Status { - case "approved": - taskText = "Ошибка: задачи не созданы" - executorName = "Ошибка" - taskStatus = "Ошибка" - hasTaskError = true - case "pending": - taskText = "Ожидает согласования" - executorName = "Ожидает согласования" - taskStatus = "Ожидает согласования" - case "rejected": - taskText = "Не выполнено (заявка отклонена)" - executorName = "Не выполнено (заявка отклонена)" - taskStatus = "Не выполнено (заявка отклонена)" - case "revoked": - taskText = "Не выполнено (заявка отозвана)" - executorName = "Не выполнено (заявка отозвана)" - taskStatus = "Не выполнено (заявка отозвана)" - default: - taskText = "Не предусмотрено" - executorName = "Не предусмотрено" - taskStatus = "Не предусмотрено" - } - } - } else { - var taskTexts []string - var executorNames []string - var taskStatuses []string - - sort.Slice(tasks, func(i, j int) bool { - if tasks[i].StepOrder == nil || tasks[j].StepOrder == nil { - return false - } - return *tasks[i].StepOrder < *tasks[j].StepOrder - }) - - for _, task := range tasks { - if task.TaskText != nil { - taskTexts = append(taskTexts, *task.TaskText) - } else { - taskTexts = append(taskTexts, "—") - } - - eName := "" - if task.ExecutorID != nil { - if u, err := db.User.GetUserByIDDB(ctx, *task.ExecutorID); err == nil && u != nil && u.FullName != nil { - eName = *u.FullName - } - } - executorNames = append(executorNames, eName) - - ts := "—" - if task.Status != nil { - switch *task.Status { - case "pending": - ts = "В работе" - case "waiting": - ts = "Ожидает" - case "completed": - ts = "Выполнено" - case "cancelled": - ts = "Отменено" - } - } - taskStatuses = append(taskStatuses, ts) - - if taskCompletedAt == "" && task.CompletedAt != nil { - taskCompletedAt = task.CompletedAt.Format("02.01.2006 15:04") - } - } - - taskText = strings.Join(taskTexts, "\n") - executorName = strings.Join(executorNames, "\n") - taskStatus = strings.Join(taskStatuses, "\n") - } - } - } - - // 🆕 Добавлены две новые переменные в массив - values := []interface{}{ - approvalID, - initiatorName, topicName, createdAt, - approversCell, observersCell, - addApproversCell, addObserversCell, - status, content, deptName, comment, - lastApprovedAt, - taskText, executorName, taskStatus, - taskCompletedAt, - } - - style := dataStyle - if a.Status != nil && *a.Status == "rejected" { - style = rejectedStyle - } - - for colIdx, val := range values { - cell := fmt.Sprintf("%s%d", cols[colIdx], row) - if err := f.SetCellValue(sheet, cell, val); err != nil { - logrus.Warnf("reportcore: set cell value %s: %v", cell, err) - continue - } - - cellStyle := style - // 🆕 Индексы колонок задач сместились из-за двух новых колонок (было 11-13, стало 13-15) - if hasTaskError && colIdx >= 13 && colIdx <= 15 { - cellStyle = errorStyle - } - if err := f.SetCellStyle(sheet, cell, cell, cellStyle); err != nil { - logrus.Warnf("reportcore: set cell style %s: %v", cell, err) - } - } - - rowHeight := 20.0 - maxLines := len(approverParts) - if len(strings.Split(taskText, "\n")) > maxLines { - maxLines = len(strings.Split(taskText, "\n")) - } - if maxLines > 1 { - rowHeight = float64(maxLines) * 18 - } - if err := f.SetRowHeight(sheet, row, rowHeight); err != nil { - logrus.Warnf("reportcore: set row height %d: %v", row, err) - } - } - - lastCol := cols[len(headers)-1] - lastRow := len(approvals) + 1 - if err := f.AutoFilter(sheet, fmt.Sprintf("A1:%s%d", lastCol, lastRow), []excelize.AutoFilterOptions{}); err != nil { - logrus.Warnf("reportcore: auto filter: %v", err) - } - - if err := f.SetPanes(sheet, &excelize.Panes{ - Freeze: true, - YSplit: 1, - TopLeftCell: "A2", - ActivePane: "bottomLeft", - }); err != nil { - logrus.Warnf("reportcore: set panes: %v", err) - } - - autoFitColumns(f, sheet, headers, len(approvals)) - - var buf bytes.Buffer - if err := f.Write(&buf); err != nil { - return nil, fmt.Errorf("write excel: %w", err) - } - return buf.Bytes(), nil -} - ------END core/reportcore/excel.go----- - -File: core/reportcore/helpers.go -Lines: 74 ------BEGIN core/reportcore/helpers.go----- -package reportcore - -import ( - database "bitrix_balancer_api/core/db" - "bitrix_balancer_api/core/typescore" - "context" -) - -// GetTopicCategoryCodeByApproval возвращает код категории темы для заявки. -func GetTopicCategoryCodeByApproval(ctx context.Context, db *database.ModuleDB, a *typescore.Approval) string { - if a == nil || a.TopicID == nil { - return "" - } - - // Если тема уже загружена - if a.Topic != nil && a.Topic.CategoryID != nil { - if a.Topic.Category != nil && a.Topic.Category.Code != nil { - return *a.Topic.Category.Code - } - if cat, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *a.Topic.CategoryID); err == nil && cat != nil && cat.Code != nil { - return *cat.Code - } - return "" - } - - // Загружаем тему - topic, err := db.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID) - if err != nil || topic == nil || topic.CategoryID == nil { - return "" - } - - cat, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID) - if err != nil || cat == nil || cat.Code == nil { - return "" - } - - return *cat.Code -} - -// GetReportCategoryCodes — объединяет категории согласующего и наблюдателя. -// Используется для определения, какие категории доступны пользователю для отчёта. -func GetReportCategoryCodes(ctx context.Context, db *database.ModuleDB, user *typescore.User) []string { - if user == nil || user.ID == nil { - return nil - } - - seen := map[string]bool{} - var codes []string - - addCodes := func(action string) { - perms, err := db.Permission.GetUserPermissionsDB(ctx, *user.ID, action) - if err != nil { - return - } - for _, p := range perms { - if p.TopicCategoryID == nil { - continue - } - cat, err := db.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 -} - ------END core/reportcore/helpers.go----- - -File: core/securecore/hashing.go -Lines: 50 ------BEGIN core/securecore/hashing.go----- -package securecore - -import ( - "encoding/hex" - "errors" - "golang.org/x/crypto/bcrypt" - "golang.org/x/crypto/sha3" -) - -// HashStringSHA3_256 вычисляет SHA‑3 (256 бит) хэш от входной строки. -func HashStringSHA3_256(input string) string { - sum := sha3.Sum256([]byte(input)) - res := hex.EncodeToString(sum[:]) - return res - // return input -} - -// HexEncode - кодирует строку в hex -func HexEncode(data []byte) string { - return hex.EncodeToString(data) - // return string(data) -} - -// HexDecode - декодирует строку из hex -func HexDecode(content string) ([]byte, error) { - return hex.DecodeString(content) - // return []byte(content), nil -} - -// Функция для проверки пароля -func CheckPasswordHash(password, hash *string) bool { - if password == nil || hash == nil { - println("CheckPasswordHash(): password or hash is nil") - return false - } - - err := bcrypt.CompareHashAndPassword([]byte(*hash), []byte(*password)) - return err == nil -} - -// Функция для хэширования пароля -func HashPassword(password *string) (*string, error) { - if password == nil { - return nil, errors.New("missed password") - } - - bytes, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost) - hashedPass := string(bytes) - return &hashedPass, err -} - ------END core/securecore/hashing.go----- - -File: core/securecore/jwt-methods.go -Lines: 95 ------BEGIN core/securecore/jwt-methods.go----- -package securecore - -import ( - "bitrix_balancer_api/core/typescore" - "errors" - "github.com/golang-jwt/jwt/v5" - - "time" -) - -// Определить пользовательский тип для контекстных ключей -type contextKey string - -func (c contextKey) String() string { - return string(c) -} - -const AddressContextKey contextKey = "raw_user_address" -const IDContextKey contextKey = "user_id" -const AccessContextKey contextKey = "access_code" -const IpContextKey contextKey = "user_ip" -const expContextKey contextKey = "exp" - -func GenerateTokenJWT( - userAddr string, - userID uint64, - userIP string, - secretJWT string, - sessionTime int, -) (string, error) { - duration := time.Duration(72) - if sessionTime > 0 { - duration = time.Duration(sessionTime) - } - // Создаем новый токен - token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ - AddressContextKey.String(): userAddr, - IDContextKey.String(): float64(userID), - IpContextKey.String(): userIP, - expContextKey.String(): time.Now().Add(time.Hour * duration).Unix(), // срок действия токена 72 часа - }) - - t, err := token.SignedString([]byte(secretJWT)) - if err != nil { - return "", err - } - - return t, nil -} - -// VerifyToken верифицирует JWT токен и возвращает данные по токену или ошибку -func VerifyToken(tokenString string, jwtSecret string) (*jwt.Token, jwt.MapClaims, error) { - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { - if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, errors.New("unexpected signing method") - } - return []byte(jwtSecret), nil - }) - - if err != nil || !token.Valid { - return nil, nil, errors.New("invalid token") - } - - claims, ok := token.Claims.(jwt.MapClaims) - if !ok { - return nil, nil, errors.New("invalid token claims") - } - - if exp, ok := claims[expContextKey.String()].(float64); ok { - if time.Unix(int64(exp), 0).Before(time.Now()) { - return nil, nil, errors.New("token expired") - } - } - - return token, claims, nil -} - -func IsSameIP(ip1, ip2 string) bool { - // Простое сравнение для начала - return ip1 == ip2 -} - -func FindDeviceID(deviceList []typescore.DeviceList, deviceID string) bool { - if len(deviceList) == 0 { - return false - } - - for _, device := range deviceList { - if device.DeviceID == deviceID { - return true - } - } - - return false -} - ------END core/securecore/jwt-methods.go----- - -File: core/typescore/admin.go -Lines: 32 ------BEGIN core/typescore/admin.go----- -package typescore - -import ( - "time" -) - -// Admin - структура для хранения данных о администраторах. -type Admin struct { - ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` - Login *string `gorm:"type:text;not null;unique;column:login" json:"login" db:"login" mapstructure:"login"` - Name *string `gorm:"type:text;column:name" json:"name,omitempty" db:"name" mapstructure:"name"` - PasswordHash *string `gorm:"type:text;not null;column:password_hash" json:"-" db:"password_hash" mapstructure:"password_hash"` - IsRoot *bool `gorm:"type:boolean;not null;default:false;column:is_root" json:"is_root" db:"is_root" mapstructure:"is_root"` - IsObserver *bool `gorm:"type:boolean;not null;default:false;column:is_observer" json:"is_observer" db:"is_observer" mapstructure:"is_observer"` - TelegramID *int64 `gorm:"type:bigint;column:telegram_id" json:"telegram_id,omitempty" db:"telegram_id" mapstructure:"telegram_id"` - CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` - LastLogin *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:last_login" json:"last_login" db:"last_login"` - LastIPLogin *string `gorm:"type:text;column:last_ip_login" json:"last_ip_login" db:"last_ip_login" mapstructure:"last_ip_login"` - IsBlocked *bool `gorm:"type:boolean;not null;index;default:false;column:is_blocked" json:"is_blocked" db:"is_blocked" mapstructure:"is_blocked"` - - Password *string `gorm:"-" json:"password,omitempty"` - TelegramUser *User `gorm:"-" json:"telegram_user,omitempty"` -} - -type AdminReq struct { - Login *string `json:"login"` - Name *string `json:"name"` - Password *string `json:"password"` - IsRoot *bool `json:"is_root"` - IsObserver *bool `json:"is_observer"` - TelegramID *int64 `json:"telegram_id"` -} - ------END core/typescore/admin.go----- - -File: core/typescore/admin_action_log.go -Lines: 28 ------BEGIN core/typescore/admin_action_log.go----- -package typescore - -import "time" - -type AdminActionLog struct { - ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"` - AdminID *uint64 `gorm:"type:bigint;not null;index;column:admin_id" json:"admin_id" db:"admin_id"` - AdminLogin *string `gorm:"type:text;not null;column:admin_login" json:"admin_login" db:"admin_login"` - Action *string `gorm:"type:text;not null;column:action" json:"action" db:"action"` - EntityType *string `gorm:"type:text;not null;column:entity_type" json:"entity_type" db:"entity_type"` - EntityID *uint64 `gorm:"type:bigint;column:entity_id" json:"entity_id,omitempty" db:"entity_id"` - Description *string `gorm:"type:text;not null;column:description" json:"description" db:"description"` - Metadata *string `gorm:"type:jsonb;column:metadata" json:"metadata,omitempty" db:"metadata"` - CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` - - Admin *Admin `gorm:"-" json:"admin,omitempty"` -} - -type AdminActionLogFilter struct { - AdminID *uint64 - AdminLogin *string // ILIKE-подстрока - Action *string - EntityType *string - EntityID *uint64 - DateFrom *time.Time - DateTo *time.Time - Search *string // ILIKE-подстрока по Description -} - ------END core/typescore/admin_action_log.go----- - -File: core/typescore/api.go -Lines: 21 ------BEGIN core/typescore/api.go----- -package typescore - -type ApiResponseBase struct { - Data interface{} `json:"data"` // данные полученные от api - TotalCount uint64 `json:"total_count,omitempty"` - TotalAmount float64 `json:"total_amount,omitempty"` -} - -type AuthHandlerResponse struct { - TempSession *string `json:"temp_session,omitempty"` // Временный токен для 2FA - Token *string `json:"token"` // токен аутентификации -} - -type AuthReqAccount struct { - Login *string `json:"login,omitempty"` - Password *string `json:"password,omitempty"` - AccessCode *string `json:"access_code,omitempty"` - Token *string `json:"token,omitempty"` - - RedirectURI *string `json:"redirect_uri,omitempty"` -} - ------END core/typescore/api.go----- - -File: core/typescore/approval.go -Lines: 95 ------BEGIN core/typescore/approval.go----- -package typescore - -import ( - "encoding/json" - "time" -) - -type ApprovalStatus string - -const ( - ApprovalStatusApproved ApprovalStatus = "approved" - ApprovalStatusRejected ApprovalStatus = "rejected" - ApprovalStatusDraft ApprovalStatus = "draft" - ApprovalStatusRevoked ApprovalStatus = "revoked" - ApprovalStatusRevision ApprovalStatus = "revision" - ApprovalStatusPending ApprovalStatus = "pending" -) - -func (status ApprovalStatus) String() string { - return string(status) -} - -// ApprovalFilter — расширенный фильтр для списка заявок -type ApprovalFilter struct { - ID *uint64 `json:"id"` - Status *string `json:"status,omitempty"` - InitiatorID *uint64 `json:"initiator_id,omitempty"` - DepartmentID *uint64 `json:"department_id,omitempty"` - Content *string `json:"content,omitempty"` - DateFrom *time.Time `json:"date_from,omitempty"` - DateTo *time.Time `json:"date_to,omitempty"` - CategoryIDs []uint64 `json:"category_ids,omitempty"` // множественный выбор категорий - TopicIDs []uint64 `json:"topic_ids,omitempty"` // множественный выбор тем - ObserverUserID *uint64 `json:"observer_user_id"` -} - -// 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" 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"` - Metadata *string `gorm:"type:jsonb;column:metadata" json:"metadata,omitempty" db:"metadata"` - RevisionComment *string `gorm:"type:text;column:revision_comment" json:"revision_comment,omitempty" db:"revision_comment"` - RevisionByID *uint64 `gorm:"type:bigint;column:revision_by_id" json:"revision_by_id,omitempty" db:"revision_by_id"` - RevisionAt *time.Time `gorm:"type:timestamp;column:revision_at" json:"revision_at,omitempty" db:"revision_at"` - RevisionCount *int `gorm:"type:int;not null;default:0;column:revision_count" json:"revision_count" db:"revision_count"` - - 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"` -} - -type ApprovalMetadata struct { - // Выбранные системы при мультиселекте, например ["okb","bitrix"] - SelectedSystems []string `json:"selected_systems,omitempty"` - // Регион - Region string `json:"region,omitempty"` - // Тип изменения - ChangeType string `json:"change_type,omitempty"` - // Любые другие поля из collected которые нужно сохранить - Extra map[string]string `json:"extra,omitempty"` -} - -func (m *ApprovalMetadata) ToJSON() (*string, error) { - b, err := json.Marshal(m) - if err != nil { - return nil, err - } - s := string(b) - return &s, nil -} - -func ParseApprovalMetadata(raw *string) (*ApprovalMetadata, error) { - if raw == nil || *raw == "" { - return &ApprovalMetadata{}, nil - } - var m ApprovalMetadata - if err := json.Unmarshal([]byte(*raw), &m); err != nil { - return nil, err - } - return &m, nil -} - ------END core/typescore/approval.go----- - -File: core/typescore/approval_additional_approver.go -Lines: 19 ------BEGIN core/typescore/approval_additional_approver.go----- -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"` -} - ------END core/typescore/approval_additional_approver.go----- - -File: core/typescore/approval_additional_observer.go -Lines: 15 ------BEGIN core/typescore/approval_additional_observer.go----- -package typescore - -import "time" - -type ApprovalAdditionalObserver 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"` - UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id"` - AddedByID *uint64 `gorm:"type:bigint;not null;index;column:added_by_id" json:"added_by_id" db:"added_by_id"` - CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` - - User *User `gorm:"-" json:"user,omitempty"` - AddedBy *User `gorm:"-" json:"added_by,omitempty"` - Approval *Approval `gorm:"-" json:"approval,omitempty"` -} - ------END core/typescore/approval_additional_observer.go----- - -File: core/typescore/approval_comment.go -Lines: 15 ------BEGIN core/typescore/approval_comment.go----- -package typescore - -import "time" - -type ApprovalComment 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"` - UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id"` - Comment *string `gorm:"type:text;not null;column:comment" json:"comment" db:"comment"` - 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"` - User *User `gorm:"-" json:"user,omitempty"` -} - ------END core/typescore/approval_comment.go----- - -File: core/typescore/approval_delegation.go -Lines: 23 ------BEGIN core/typescore/approval_delegation.go----- -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"` - ApprovalID *uint64 `gorm:"type:bigint;index;column:approval_id" json:"approval_id,omitempty" db:"approval_id" mapstructure:"approval_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"` - - Delegator *User `gorm:"-" json:"delegator,omitempty"` - Delegate *User `gorm:"-" json:"delegate,omitempty"` - Category *ApprovalTopicCategory `gorm:"-" json:"category,omitempty"` - Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"` -} - ------END core/typescore/approval_delegation.go----- - -File: core/typescore/approval_file.go -Lines: 13 ------BEGIN core/typescore/approval_file.go----- -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"` - AttachedByID *uint64 `gorm:"type:bigint;index;column:attached_by_id" json:"attached_by_id" db:"attached_by_id"` - TaskID *uint64 `gorm:"type:bigint;index;column:task_id" json:"task_id,omitempty" db:"task_id"` - CreatedAt *time.Time `gorm:"default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` -} - ------END core/typescore/approval_file.go----- - -File: core/typescore/approval_flow_node.go -Lines: 37 ------BEGIN core/typescore/approval_flow_node.go----- -package typescore - -import "time" - -// ApprovalFlowNode — узел дерева навигации темы согласования -type ApprovalFlowNode struct { - ID *uint64 `gorm:"column:id;type:bigserial;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` - TopicID *uint64 `gorm:"type:bigint;index;column:topic_id" json:"topic_id,omitempty" db:"topic_id" mapstructure:"topic_id"` - ParentID *uint64 `gorm:"type:bigint;index;column:parent_id" json:"parent_id,omitempty" db:"parent_id" mapstructure:"parent_id"` - CategoryID *uint64 `gorm:"type:bigint;not null;index;column:category_id" json:"category_id" db:"category_id" mapstructure:"category_id"` - - Key *string `gorm:"type:text;not null;column:key" json:"key" db:"key" mapstructure:"key"` - Label *string `gorm:"type:text;not null;column:label" json:"label" db:"label" mapstructure:"label"` - - DataKey *string `gorm:"type:text;column:data_key" json:"data_key,omitempty" db:"data_key" mapstructure:"data_key"` - DataValue *string `gorm:"type:text;column:data_value" json:"data_value,omitempty" db:"data_value" mapstructure:"data_value"` - - IsInput *bool `gorm:"type:boolean;default:false;column:is_input" json:"is_input" db:"is_input" mapstructure:"is_input"` - InputKey *string `gorm:"type:text;column:input_key" json:"input_key,omitempty" db:"input_key" mapstructure:"input_key"` - InputHint *string `gorm:"type:text;column:input_hint" json:"input_hint,omitempty" db:"input_hint" mapstructure:"input_hint"` - - IsMultiSelect *bool `gorm:"type:boolean;default:false;column:is_multi_select" json:"is_multi_select" db:"is_multi_select" mapstructure:"is_multi_select"` - MultiSelectKey *string `gorm:"type:text;column:multi_select_key" json:"multi_select_key,omitempty" db:"multi_select_key" mapstructure:"multi_select_key"` - MultiSelectValue *string `gorm:"type:text;column:multi_select_value" json:"multi_select_value,omitempty" db:"multi_select_value" mapstructure:"multi_select_value"` - - TopicCode *string `gorm:"type:text;column:topic_code" json:"topic_code,omitempty" db:"topic_code" mapstructure:"topic_code"` - - SortOrder *int `gorm:"type:integer;default:0;column:sort_order" json:"sort_order" db:"sort_order" mapstructure:"sort_order"` - - CodeTemplate *string `gorm:"type:text;column:code_template" json:"code_template,omitempty" db:"code_template" mapstructure:"code_template"` - MessageTemplate *string `gorm:"type:text;column:message_template" json:"message_template,omitempty" db:"message_template" mapstructure:"message_template"` - - CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at" mapstructure:"created_at"` - UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at" mapstructure:"updated_at"` - - Children []*ApprovalFlowNode `gorm:"-" json:"children,omitempty"` -} - ------END core/typescore/approval_flow_node.go----- - -File: core/typescore/approval_revocation_request.go -Lines: 23 ------BEGIN core/typescore/approval_revocation_request.go----- -package typescore - -import "time" - -type ApprovalRevocationRequest struct { - ID *uint64 `gorm:"column:id" json:"id" db:"id"` - ApprovalID *uint64 `gorm:"column:approval_id" json:"approval_id" db:"approval_id"` - RequestedByID *uint64 `gorm:"column:requested_by_id" json:"requested_by_id" db:"requested_by_id"` - Reason *string `gorm:"column:reason" json:"reason,omitempty" db:"reason"` - Status *string `gorm:"column:status" json:"status" db:"status"` - CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"` - UpdatedAt *time.Time `gorm:"column:updated_at" json:"updated_at" db:"updated_at"` -} - -type ApprovalRevocationApprover struct { - ID *uint64 `gorm:"column:id" json:"id" db:"id"` - RevocationRequestID *uint64 `gorm:"column:revocation_request_id" json:"revocation_request_id" db:"revocation_request_id"` - ApproverID *uint64 `gorm:"column:approver_id" json:"approver_id" db:"approver_id"` - Status *string `gorm:"column:status" json:"status" db:"status"` - Comment *string `gorm:"column:comment" json:"comment,omitempty" db:"comment"` - ActedAt *time.Time `gorm:"column:acted_at" json:"acted_at,omitempty" db:"acted_at"` - CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"` -} - ------END core/typescore/approval_revocation_request.go----- - -File: core/typescore/approval_step.go -Lines: 27 ------BEGIN core/typescore/approval_step.go----- -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"` - ReturnedAt *time.Time `gorm:"type:timestamp;column:returned_at" json:"returned_at,omitempty" db:"returned_at"` - - Approval *Approval `gorm:"-" json:"approval,omitempty"` - Approver *User `gorm:"-" json:"approver,omitempty"` -} - ------END core/typescore/approval_step.go----- - -File: core/typescore/approval_task.go -Lines: 22 ------BEGIN core/typescore/approval_task.go----- -package typescore - -import "time" - -type ApprovalTask struct { - ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" 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"` - ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id" json:"executor_id" db:"executor_id" mapstructure:"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';index;column:status" json:"status" db:"status" mapstructure:"status"` - StepOrder *int `gorm:"type:int;default:0;column:step_order" json:"step_order" db:"step_order"` - RequireFile *bool `gorm:"type:boolean;default:false;column:require_file" json:"require_file" db:"require_file" mapstructure:"require_file"` - TopicExecutorID *uint64 `gorm:"type:bigint;column:topic_executor_id" json:"topic_executor_id,omitempty" db:"topic_executor_id" mapstructure:"topic_executor_id"` - 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"` - - ObserverUserID *uint64 `json:"observer_user_id,omitempty" db:"-" ignore_db:"true"` - Approval *Approval `gorm:"-" json:"approval,omitempty"` - Executor *User `gorm:"-" json:"executor,omitempty"` - Files []*ApprovalFile `gorm:"-" json:"files,omitempty"` -} - ------END core/typescore/approval_task.go----- - -File: core/typescore/approval_task_assigment.go -Lines: 14 ------BEGIN core/typescore/approval_task_assigment.go----- -package typescore - -import "time" - -type ApprovalTaskAssignment struct { - ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique"` - ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id"` - ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id"` - TaskText *string `gorm:"type:text;not null;column:task_text"` - Status *string `gorm:"type:text;not null;default:'pending';column:status"` // pending|completed|cancelled - CompletedAt *time.Time `gorm:"type:timestamp;column:completed_at"` - CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at"` - UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at"` -} - ------END core/typescore/approval_task_assigment.go----- - -File: core/typescore/approval_task_transfer.go -Lines: 13 ------BEGIN core/typescore/approval_task_transfer.go----- -package typescore - -import "time" - -type ApprovalTaskTransfer struct { - ID *uint64 `gorm:"column:id;primaryKey;autoIncrement" json:"id" db:"id"` - TaskID *uint64 `gorm:"column:task_id;not null" json:"task_id" db:"task_id"` - FromExecutorID *uint64 `gorm:"column:from_executor_id;not null" json:"from_executor_id" db:"from_executor_id"` - ToExecutorID *uint64 `gorm:"column:to_executor_id;not null" json:"to_executor_id" db:"to_executor_id"` - Status *string `gorm:"column:status;type:text;not null;default:'pending'" json:"status" db:"status"` - CreatedAt *time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP" json:"created_at" db:"created_at"` - RespondedAt *time.Time `gorm:"column:responded_at" json:"responded_at,omitempty" db:"responded_at"` -} - ------END core/typescore/approval_task_transfer.go----- - -File: core/typescore/approval_topic.go -Lines: 39 ------BEGIN core/typescore/approval_topic.go----- -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"` - ApprovalMode *string `gorm:"type:text;default:'sequential';column:approval_mode" db:"approval_mode"` - // sequential — последовательно (текущее поведение) - // any_of — любой из согласующих (задача 10) - - 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;column:template" json:"template" db:"template" mapstructure:"template"` - FirstApproverRoleCode *string `gorm:"type:text;column:first_approver_role_code" json:"first_approver_role_code,omitempty" db:"first_approver_role_code" mapstructure:"first_approver_role_code"` // если задан — первый согласующий выбирается из этой роли - - AllowsFile *bool `gorm:"type:boolean;not null;default:false;column:allows_file" json:"allows_file,omitempty" db:"allows_file" mapstructure:"allows_file"` - AllowApproverSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_approver_selection" json:"allow_approver_selection,omitempty" db:"allow_approver_selection" mapstructure:"allow_approver_selection"` - AllowObserverSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_observer_selection" json:"allow_observer_selection,omitempty" db:"allow_observer_selection" mapstructure:"allow_observer_selection"` - - RequireApproverComment *bool `gorm:"type:boolean;default:false;column:require_approver_comment" json:"require_approver_comment" db:"require_approver_comment"` - RequiresFile *bool `gorm:"type:boolean;not null;default:false;column:requires_file" json:"requires_file" db:"requires_file"` - RequireObserverSelection *bool `gorm:"type:boolean;not null;default:false;column:require_observer_selection" json:"require_observer_selection" db:"require_observer_selection"` - AllowDelegationSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_delegation_selection" json:"allow_delegation_selection,omitempty" db:"allow_delegation_selection" mapstructure:"allow_delegation_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"` - Instructions *string `gorm:"type:text;column:instructions" json:"instructions,omitempty" db:"instructions"` - Category *ApprovalTopicCategory `gorm:"-" json:"category,omitempty"` -} - ------END core/typescore/approval_topic.go----- - -File: core/typescore/approval_topic_category.go -Lines: 15 ------BEGIN core/typescore/approval_topic_category.go----- -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"` -} - ------END core/typescore/approval_topic_category.go----- - -File: core/typescore/approval_topic_executor.go -Lines: 19 ------BEGIN core/typescore/approval_topic_executor.go----- -package typescore - -import "time" - -type ApprovalTopicExecutor struct { - ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` - TopicID *uint64 `gorm:"type:bigint;not null;index;column:topic_id" json:"topic_id" db:"topic_id" mapstructure:"topic_id"` - UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id" mapstructure:"user_id"` - StepOrder *int `gorm:"type:int;not null;default:0;column:step_order" json:"step_order" db:"step_order" mapstructure:"step_order"` - RequireFile *bool `gorm:"type:boolean;default:false;column:require_file" json:"require_file" db:"require_file" mapstructure:"require_file"` - TargetSystem *string `gorm:"type:text;column:target_system" json:"target_system,omitempty" db:"target_system" mapstructure:"target_system"` - TaskText *string `gorm:"type:text;column:task_text" json:"task_text,omitempty" db:"task_text" mapstructure:"task_text"` - IsActive *bool `gorm:"type:boolean;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"` - - Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"` - User *User `gorm:"-" json:"user,omitempty"` -} - ------END core/typescore/approval_topic_executor.go----- - -File: core/typescore/balancer.go -Lines: 36 ------BEGIN core/typescore/balancer.go----- -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) -} - ------END core/typescore/balancer.go----- - -File: core/typescore/base_db.go -Lines: 22 ------BEGIN core/typescore/base_db.go----- -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 // Флаг игнорирования конфликтов -} - ------END core/typescore/base_db.go----- - -File: core/typescore/department.go -Lines: 13 ------BEGIN core/typescore/department.go----- -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"` -} - ------END core/typescore/department.go----- - -File: core/typescore/director_notification.go -Lines: 10 ------BEGIN core/typescore/director_notification.go----- -package typescore - -import "time" - -type DirectorNotificationSubscription struct { - ID *uint64 `gorm:"column:id" json:"id" db:"id"` - DirectorID *uint64 `gorm:"column:director_id" json:"director_id" db:"director_id"` - CategoryID *uint64 `gorm:"column:category_id" json:"category_id" db:"category_id"` - CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"` -} - ------END core/typescore/director_notification.go----- - -File: core/typescore/handler.go -Lines: 9 ------BEGIN core/typescore/handler.go----- -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"` -} - ------END core/typescore/handler.go----- - -File: core/typescore/notifications.go -Lines: 54 ------BEGIN core/typescore/notifications.go----- -package typescore - -import "time" - -// Notification — рассылка/уведомление -type Notification struct { - ID *uint64 `gorm:"column:id" json:"id" db:"id"` - Title *string `gorm:"column:title" json:"title" db:"title"` - MessageHTML *string `gorm:"column:message_html" json:"message_html" db:"message_html"` - PhotoBase64 *string `gorm:"column:photo_base64" json:"photo_base64,omitempty" db:"photo_base64"` - PhotoFileName *string `gorm:"column:photo_file_name" json:"photo_file_name,omitempty" db:"photo_file_name"` - TargetFilters *string `gorm:"column:target_filters" json:"target_filters" db:"target_filters"` // JSON-строка - Status *string `gorm:"column:status" json:"status" db:"status"` - TotalCount *int `gorm:"column:total_count" json:"total_count" db:"total_count"` - SentCount *int `gorm:"column:sent_count" json:"sent_count" db:"sent_count"` - FailedCount *int `gorm:"column:failed_count" json:"failed_count" db:"failed_count"` - CreatedByID *uint64 `gorm:"column:created_by_id" json:"created_by_id,omitempty" db:"created_by_id"` - CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"` - UpdatedAt *time.Time `gorm:"column:updated_at" json:"updated_at" db:"updated_at"` - SentAt *time.Time `gorm:"column:sent_at" json:"sent_at,omitempty" db:"sent_at"` - - Recipients []*NotificationRecipient `gorm:"-" json:"recipients,omitempty"` -} - -// NotificationRecipient — история доставки конкретному пользователю -type NotificationRecipient struct { - ID *uint64 `gorm:"column:id" json:"id" db:"id"` - NotificationID *uint64 `gorm:"column:notification_id" json:"notification_id" db:"notification_id"` - UserID *uint64 `gorm:"column:user_id" json:"user_id" db:"user_id"` - Status *string `gorm:"column:status" json:"status" db:"status"` - ErrorMessage *string `gorm:"column:error_message" json:"error_message,omitempty" db:"error_message"` - TelegramMessageID *int `gorm:"column:telegram_message_id" json:"telegram_message_id,omitempty" db:"telegram_message_id"` - SentAt *time.Time `gorm:"column:sent_at" json:"sent_at,omitempty" db:"sent_at"` - CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"` - - User *User `gorm:"-" json:"user,omitempty"` -} - -// TargetFilters — критерии выбора получателей, приходят из админки и сохраняются как есть в JSONB -type TargetFilters struct { - UserIDs []uint64 `json:"user_ids,omitempty"` // 1. конкретные пользователи - RoleIDs []uint64 `json:"role_ids,omitempty"` // 2. конкретные роли (по id) - RoleTypeFlags []string `json:"role_type_flags,omitempty"` // 3. типы ролей: director|approver|observer|executor|controller - DepartmentIDs []uint64 `json:"department_ids,omitempty"` // 4. отделы -} - -// CreateNotificationReq — тело запроса на создание+отправку рассылки -type CreateNotificationReq struct { - Title string `json:"title"` - MessageHTML string `json:"message_html"` - PhotoBase64 *string `json:"photo_base64,omitempty"` - PhotoFileName *string `json:"photo_file_name,omitempty"` - Targets TargetFilters `json:"targets"` -} - ------END core/typescore/notifications.go----- - -File: core/typescore/permission.go -Lines: 21 ------BEGIN core/typescore/permission.go----- -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"` -} - ------END core/typescore/permission.go----- - -File: core/typescore/report.go -Lines: 20 ------BEGIN core/typescore/report.go----- -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 // конец периода -} - ------END core/typescore/report.go----- - -File: core/typescore/role.go -Lines: 20 ------BEGIN core/typescore/role.go----- -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"` - IsController *bool `gorm:"type:boolean;not null;default:false;column:is_controller" json:"is_controller" db:"is_controller" mapstructure:"is_controller"` - 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"` -} - ------END core/typescore/role.go----- - -File: core/typescore/suggestion.go -Lines: 30 ------BEGIN core/typescore/suggestion.go----- -package typescore - -import "time" - -type Suggestion struct { - ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"` - InitiatorID *uint64 `gorm:"type:bigint;not null;index;column:initiator_id" json:"initiator_id" db:"initiator_id"` - DirectorID *uint64 `gorm:"type:bigint;not null;index;column:director_id" json:"director_id" db:"director_id"` - Subject *string `gorm:"type:text;not null;column:subject" json:"subject" db:"subject"` - Status *string `gorm:"type:text;not null;default:'open';column:status" json:"status" db:"status"` // open, closed - 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"` - - Initiator *User `gorm:"-" json:"initiator,omitempty"` - Director *User `gorm:"-" json:"director,omitempty"` - Messages []*SuggestionMessage `gorm:"-" json:"messages,omitempty"` -} - -type SuggestionMessage struct { - ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"` - SuggestionID *uint64 `gorm:"type:bigint;not null;index;column:suggestion_id" json:"suggestion_id" db:"suggestion_id"` - UserID *uint64 `gorm:"type:bigint;not null;index;column:user_id" json:"user_id" db:"user_id"` - Message *string `gorm:"type:text;not null;column:message" json:"message" db:"message"` - FileData *string `gorm:"type:text;column:file_data" json:"file_data,omitempty" db:"file_data"` // base64 - FileName *string `gorm:"type:text;column:file_name" json:"file_name,omitempty" db:"file_name"` - CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` - - Suggestion *Suggestion `gorm:"-" json:"suggestion,omitempty"` - User *User `gorm:"-" json:"user,omitempty"` -} - ------END core/typescore/suggestion.go----- - -File: core/typescore/telephony.go -Lines: 55 ------BEGIN core/typescore/telephony.go----- -package typescore - -import "time" - -// SmsLog - модель для хранения истории SMS -type SmsLog struct { - ID *uint64 `json:"id" db:"id" gorm:"column:id;primaryKey;autoIncrement"` - AccountID *string `json:"account_id" db:"account_id" gorm:"column:account_id"` - UserID *string `json:"user_id" db:"user_id" gorm:"column:user_id"` - ClientNumber *string `json:"client_number" db:"client_number" gorm:"column:client_number;index"` - Direction *int `json:"direction" db:"direction" gorm:"column:direction"` - Text *string `json:"text" db:"text" gorm:"column:text"` - EventCreated *time.Time `json:"event_created" db:"event_created" gorm:"column:event_created;index"` - CreatedAt *time.Time `json:"created_at" db:"created_at" gorm:"column:created_at;default:CURRENT_TIMESTAMP"` -} - -// TelephonyWebhookReq описывает корневой объект POST-запроса от Webhook API -type TelephonyWebhookReq struct { - Webhook WebhookMeta `json:"webhook"` - Event CallEvent `json:"event"` -} - -// WebhookMeta содержит метаданные о том, кто и где сгенерировал событие -type WebhookMeta struct { - Action string `json:"action"` - AccountID string `json:"account_id"` - AccountName string `json:"account_name"` - UserID string `json:"user_id"` - UserLogin string `json:"user_login"` -} - -// CallEvent описывает полезную нагрузку события (звонок или SMS) -type CallEvent struct { - EventType int `json:"event_type"` // 1 - начало; 2 - ответ; 4 - окончание; 32 - SMS - EventCreated int64 `json:"event_created"` - Direction int `json:"direction"` // 0 - входящий, 1 - исходящий - ClientNumber string `json:"client_number"` - ClientName string `json:"client_name"` - EventPbxCallID string `json:"event_pbx_call_id"` - SrcNumber string `json:"src_number"` - SrcID string `json:"src_id"` - SrcSlot int `json:"src_slot"` - - // Поля, которые приходят только в событии окончания звонка (event_type == 4) - StartTime int64 `json:"start_time,omitempty"` - AnswerTime int64 `json:"answer_time,omitempty"` - EndTime int64 `json:"end_time,omitempty"` - Duration int `json:"duration,omitempty"` - Answered int `json:"answered,omitempty"` // 0 - не отвечен, 1 - отвечен - Recording string `json:"recording,omitempty"` // Ссылка на запись разговора - DBCallID string `json:"db_call_id,omitempty"` - - // Поле, которое приходит только для SMS (event_type == 32) - Text string `json:"text,omitempty"` -} - ------END core/typescore/telephony.go----- - -File: core/typescore/user.go -Lines: 31 ------BEGIN core/typescore/user.go----- -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"` -} - -type UpdateUserReqAdmin struct { - ID *uint64 `json:"id"` - DepartmentID *uint64 `json:"department_id"` // Логин пользователя - IsBlocked *bool `json:"is_blocked"` // Заблокирован ли пользователь - IsFired *bool `json:"is_fired"` // Заблокирован ли пользователь -} - ------END core/typescore/user.go----- - -File: core/typescore/user_auth.go -Lines: 12 ------BEGIN core/typescore/user_auth.go----- -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"` -} - ------END core/typescore/user_auth.go----- - -File: core/typescore/user_hierarchy.go -Lines: 25 ------BEGIN core/typescore/user_hierarchy.go----- -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"` - 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"` - TargetSystem *string `gorm:"type:text;column:target_system" json:"target_system,omitempty" db:"target_system" mapstructure:"target_system"` - - Subordinate *User `gorm:"-" json:"subordinate,omitempty"` - Approver *User `gorm:"-" json:"approver,omitempty"` - Department *Department `gorm:"-" json:"department,omitempty"` - TopicCategory *ApprovalTopicCategory `gorm:"-" json:"topic_category,omitempty"` - Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"` -} - ------END core/typescore/user_hierarchy.go----- - -File: core/typescore/user_role.go -Lines: 16 ------BEGIN core/typescore/user_role.go----- -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:"-" -} - ------END core/typescore/user_role.go----- - -File: core/typescore/user_sessions.go -Lines: 14 ------BEGIN core/typescore/user_sessions.go----- -package typescore - -import "time" - -type DeviceList struct { - DeviceID string `json:"device_id"` - CreatedAt *time.Time `json:"created_at"` -} - -type UsersSessions struct { - UserID *uint64 `json:"user_id,omitempty"` - AuthorizedDevices []DeviceList `json:"authorized_devices"` - LastIP string `json:"last_ip"` -} - ------END core/typescore/user_sessions.go----- - -File: core/utilscore/conversion.go -Lines: 58 ------BEGIN core/utilscore/conversion.go----- -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 -} - ------END core/utilscore/conversion.go----- - -File: core/utilscore/db/db.go -Lines: 174 ------BEGIN core/utilscore/db/db.go----- -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 -} - ------END core/utilscore/db/db.go----- - -File: core/utilscore/db/db_operations.go -Lines: 16 ------BEGIN core/utilscore/db/db_operations.go----- -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 -} - ------END core/utilscore/db/db_operations.go----- - -File: core/utilscore/db/db_rows.go -Lines: 139 ------BEGIN core/utilscore/db/db_rows.go----- -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 -} - ------END core/utilscore/db/db_rows.go----- - -File: core/utilscore/db/query.go -Lines: 22 ------BEGIN core/utilscore/db/query.go----- -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) -} - ------END core/utilscore/db/query.go----- - -File: core/utilscore/db/query_where.go -Lines: 170 ------BEGIN core/utilscore/db/query_where.go----- -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()} - } -} - ------END core/utilscore/db/query_where.go----- - -File: core/utilscore/db/transaction.go -Lines: 70 ------BEGIN core/utilscore/db/transaction.go----- -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 -} - ------END core/utilscore/db/transaction.go----- - -File: core/utilscore/db/update_set.go -Lines: 59 ------BEGIN core/utilscore/db/update_set.go----- -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 -} - ------END core/utilscore/db/update_set.go----- - -File: core/utilscore/eq.go -Lines: 62 ------BEGIN core/utilscore/eq.go----- -package utilscore - -func DerefStr(s *string) string { - if s == nil { - return "" - } - return *s -} - -func DerefBool(b *bool) bool { - if b == nil { - return false - } - return *b -} - -func StrEq(a, b *string) bool { - if a == nil && b == nil { - return true - } - if a == nil || b == nil { - return false - } - return *a == *b -} - -func BoolEq(a, b *bool) bool { - if a == nil && b == nil { - return true - } - if a == nil || b == nil { - return false - } - return *a == *b -} - -func Uint64Eq(a, b *uint64) bool { - if a == nil && b == nil { - return true - } - if a == nil || b == nil { - return false - } - return *a == *b -} - -func IntEq(a, b *int) bool { - if a == nil && b == nil { - return true - } - if a == nil || b == nil { - return false - } - return *a == *b -} - -func DerefInt(i *int) int { - if i == nil { - return 0 - } - return *i -} - ------END core/utilscore/eq.go----- - -File: core/utilscore/gen.go -Lines: 18 ------BEGIN core/utilscore/gen.go----- -package utilscore - -import ( - "crypto/rand" - "encoding/base64" -) - -// GenerateRandomString генерирует случайную строку заданной длины -func GenerateRandomString(length int) (string, error) { - // Создаем срез байтов нужной длины - bytes := make([]byte, length) - // Заполняем срез случайными байтами - if _, err := rand.Read(bytes); err != nil { - return "", err - } - // Кодируем байты в строку в формате base64 - return base64.URLEncoding.EncodeToString(bytes), nil -} - ------END core/utilscore/gen.go----- - -File: core/utilscore/ip.go -Lines: 37 ------BEGIN core/utilscore/ip.go----- -package utilscore - -import ( - "net" - "net/http" - "strings" -) - -func GetClientIP(r *http.Request) string { - - httpXRealIP := r.Header.Get("HTTP_X_REAL_IP") - if httpXRealIP != "" { - return httpXRealIP - } - - xForwardedFor := r.Header.Get("X-Forwarded-For") - if xForwardedFor != "" { - parts := strings.Split(xForwardedFor, ",") - for i, ip := range parts { - parts[i] = strings.TrimSpace(ip) - } - return parts[0] - } - - xRealIP := r.Header.Get("X-Real-IP") - if xRealIP != "" { - return xRealIP - } - - ip, _, err := net.SplitHostPort(r.RemoteAddr) - if err != nil { - // В случае ошибки возвращаем RemoteAddr как есть - // Это может быть не IP адрес пользователя, если за вашим приложением стоит прокси - return r.RemoteAddr - } - return ip -} - ------END core/utilscore/ip.go----- - -File: core/utilscore/plural.go -Lines: 14 ------BEGIN core/utilscore/plural.go----- -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) - } -} - ------END core/utilscore/plural.go----- - -File: core/utilscore/rest.go -Lines: 165 ------BEGIN core/utilscore/rest.go----- -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 -} - ------END core/utilscore/rest.go----- - -File: core/utilscore/secure.go -Lines: 26 ------BEGIN core/utilscore/secure.go----- -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) -} - ------END core/utilscore/secure.go----- - -File: core/utilscore/sendBotMsg.go -Lines: 9 ------BEGIN core/utilscore/sendBotMsg.go----- -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 -} - ------END core/utilscore/sendBotMsg.go----- - -File: core/utilscore/validation.go -Lines: 34 ------BEGIN core/utilscore/validation.go----- -package utilscore - -import ( - "errors" - "regexp" -) - -func ValidatePassword(password string) error { - // Проверка длины - if len(password) < 8 { - return errors.New("password must be at least 8 characters") - } - - // Проверка наличия хотя бы одной цифры - hasDigit := regexp.MustCompile(`\d`).MatchString(password) - if !hasDigit { - return errors.New("password must contain at least one digit") - } - - // Проверка наличия хотя бы одной латинской буквы (верхний или нижний регистр) - hasLetter := regexp.MustCompile(`[a-zA-Z]`).MatchString(password) - if !hasLetter { - return errors.New("password must contain at least one letter") - } - - // Проверка, что пароль содержит только разрешённые символы: латинские буквы, цифры, спецсимволы - validChars := regexp.MustCompile(`^[a-zA-Z0-9!@#$%^&*()_+{}[\]:;'"|,.<>/?~` + "`" + `-]*$`).MatchString(password) - if !validChars { - return errors.New("password contain invalid characters") - } - - // Все проверки пройдены - return nil -} - ------END core/utilscore/validation.go----- - -File: core/utilscore/w-recover.go -Lines: 36 ------BEGIN core/utilscore/w-recover.go----- -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())) - } -} - ------END core/utilscore/w-recover.go----- - -File: core/variables/api_headers.go -Lines: 9 ------BEGIN core/variables/api_headers.go----- -package variables - -type contextKey string - -func (c contextKey) String() string { - return string(c) -} - -const AccessContextKey contextKey = "accessCode" - ------END core/variables/api_headers.go----- - -File: core/variables/const.go -Lines: 17 ------BEGIN core/variables/const.go----- -package variables - -import "time" - -// context timeout -const ( - ContextTimeoutShort = 10 * time.Second - ContextTimeoutBase = 15 * time.Second - ContextTimeoutLong = 30 * time.Second -) - -// Константы для нового API-прокси -const ( - ProxyForwardURL = "https://proxyservice.ddns.net/forward" - ProxySecretHeader = "X-Proxy-Secret" - ProxySecretKey = "9cb0a2655bde593de45b2f3fd17f39e5" -) - ------END core/variables/const.go----- - -File: core/variables/redis-const.go -Lines: 5 ------BEGIN core/variables/redis-const.go----- -package variables - -var ( - RedisPathUserAuthSessions = "auth_sessions" -) - ------END core/variables/redis-const.go----- - -File: service/rest_admin_service/cmd/app.go -Lines: 256 ------BEGIN service/rest_admin_service/cmd/app.go----- -package main - -import ( - configcore "bitrix_balancer_api/core/config" - clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers" - _ "bitrix_balancer_api/rest_admin_service/docs" - adminhandler "bitrix_balancer_api/rest_admin_service/handlers/admin" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - approvalstepshandler "bitrix_balancer_api/rest_admin_service/handlers/approval_steps" - approvaltaskshandler "bitrix_balancer_api/rest_admin_service/handlers/approval_tasks" - approvalextrashandler "bitrix_balancer_api/rest_admin_service/handlers/approvalextras" - approvalshandler "bitrix_balancer_api/rest_admin_service/handlers/approvals" - authhandler "bitrix_balancer_api/rest_admin_service/handlers/auth" - dashboardhandler "bitrix_balancer_api/rest_admin_service/handlers/dashboard" - departmentshandler "bitrix_balancer_api/rest_admin_service/handlers/departments" - nodeshandler "bitrix_balancer_api/rest_admin_service/handlers/flow_nodes" - notificationshandler "bitrix_balancer_api/rest_admin_service/handlers/notification" - permissionshandler "bitrix_balancer_api/rest_admin_service/handlers/permission" - profilehandler "bitrix_balancer_api/rest_admin_service/handlers/profile" - roleshandler "bitrix_balancer_api/rest_admin_service/handlers/roles" - categorieshandler "bitrix_balancer_api/rest_admin_service/handlers/topic_categories" - topicexecutorshandler "bitrix_balancer_api/rest_admin_service/handlers/topic_executors" - topicshandler "bitrix_balancer_api/rest_admin_service/handlers/topics" - hierarchieshandler "bitrix_balancer_api/rest_admin_service/handlers/user_hierarchy" - userroleshandler "bitrix_balancer_api/rest_admin_service/handlers/user_roles" - usershandler "bitrix_balancer_api/rest_admin_service/handlers/users" - typesm "bitrix_balancer_api/rest_admin_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" - httpSwagger "github.com/swaggo/http-swagger" - "log" - "net/http" - "time" -) - -const ( - readTimeout = 15 * time.Minute // Таймаут чтения - writeTimeout = 15 * time.Minute // Таймаут записи - idleTimeout = 15 * time.Minute // Таймаут бездействия - rateLimit = 15 // Лимит запросов - rateWindow = 1 * time.Second // Окно времени для лимита запросов -) - -// @title RusPet Admin API -// @version 0.1 -// @description API админ-панели для системы согласований -// @description -// @description ## Возможности -// @description - Управление отделами, ролями и пользователями -// @description - Настройка тем и категорий согласований -// @description - Управление иерархией согласований -// @description - Назначение исполнителей и прав -// @description - Просмотр заявок и шагов согласования -// @description -// @description ## Аутентификация -// @description Все защищённые эндпоинты требуют: -// @description - `Authorization: Bearer ` — JWT токен администратора -// @description - `ApiKey: ` — HMAC подпись для верификации клиента -// @description - `X-Timestamp: ` — Unix timestamp (не старше 3 минут) -// @description - `x-device-id: ` — ID устройства -// -// @host localhost:8080 -// @BasePath / -// -// @securityDefinitions.apikey BearerAuth -// @in header -// @name Authorization -// -// @securityDefinitions.apikey ApiKeyAuth -// @in header -// @name ApiKey -// -// @securityDefinitions.apikey DeviceID -// @in header -// @name x-device-id -// -// @securityDefinitions.apikey Timestamp -// @in header -// @name X-Timestamp -// -// @contact.name Roman -// @contact.email romanzabolotskij0@gmail.com -func main() { - err := initService() - if err != nil { - logrus.Errorln("🔴 failed to init common: ", err) - } - select {} -} - -func initService() error { - clientsExternal, err := getClientsExternal() - if err != nil { - logrus.Errorln("🔴 failed to load config: ", err) - return err - } - - ipc, err := initInternalProvider(clientsExternal) - if err != nil { - logrus.Errorln("🔴 failed to init internal provider: ", err) - return err - } - - router, err := initBaseApiRouter(ipc) - if err != nil { - logrus.Errorln("🔴 failed to init base api router: ", err) - return err - } - - if err := startRestApiServer(ipc, router); err != nil { - logrus.Errorln("🔴 failed to start server: ", err) - return err - } - - return nil -} - -func getClientsExternal() (clientcontrollers.ClientsExternal, error) { - options := &configcore.ConfigLoadOptions{ - Redis: true, - Database: true, - Telegram: true, - Secrets: configcore.SecretsOptions{ - AuthJWT: configcore.AuthJWTOptions{ - Admin: true, - }, - AdminAccessCode: true, - }, - Server: configcore.ExposedServiceOptions{ - RESTAdminService: true, - }, - } - - return clientcontrollers.ReturnClientsExternal(options) -} - -func initInternalProvider(clientsExternal clientcontrollers.ClientsExternal) (*typesm.InternalProviderControl, error) { - return &typesm.InternalProviderControl{ - Config: clientsExternal.Config, - RedisClient: clientsExternal.Redis, - Database: clientsExternal.DB, - TGBotClient: clientsExternal.Telegram, - }, nil -} - -func startRestApiServer(ipc *typesm.InternalProviderControl, router *chi.Mux) error { - serverPort := fmt.Sprintf("%d", ipc.Config.Server.RESTAdminService.PortRest) - - serverAddr := ":" + serverPort - httpServer := &http.Server{ - Addr: serverAddr, - Handler: router, - ReadTimeout: readTimeout, - WriteTimeout: writeTimeout, - IdleTimeout: idleTimeout, - } - - log.Printf("✅ Starting server on %s", serverAddr) - return httpServer.ListenAndServe() -} - -func initBaseApiRouter(ipc *typesm.InternalProviderControl) (*chi.Mux, error) { - router := chi.NewRouter() - corsOptions := cors.New(cors.Options{ - AllowedOrigins: ipc.Config.Server.RESTAdminService.Cors.AllowedOrigins, // Список разрешенных origin - AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch, http.MethodOptions}, - AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "ApiKey", "x-device-id"}, - ExposedHeaders: []string{"Link", "Cache-Control"}, - AllowCredentials: false, - MaxAge: 300, // Максимальное время жизни предварительных запросов в секундах - }) - - router.Use(corsOptions.Handler) - router.Use(middleware.RealIP) - router.Use(middleware.Recoverer) - // Добавляем ограничение по IP - router.Use(httprate.LimitByIP(rateLimit, rateWindow)) - - if ipc.Database == nil { - return nil, errors.New("failed_to_connect_db") - } - - err := registerRoutes(router, ipc) - if err != nil { - return nil, err - } - - return router, nil -} - -// регистрирует маршруты -func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) error { - router.Get("/swagger/*", httpSwagger.Handler( - httpSwagger.URL("/swagger/doc.json"), // URL к сгенерированному JSON - httpSwagger.DeepLinking(true), - httpSwagger.DocExpansion("none"), - httpSwagger.DomID("swagger-ui"), - )) - - // Слайс обработчиков маршрутов - routeHandlers := []struct { - name string - handler func(chi.Router, *typesm.InternalProviderControl) error - }{ - {"admin", adminhandler.RegisterAdminRoutes}, - {"auth", authhandler.RegisterAuthRoutes}, - {"profile", profilehandler.RegisterProfileRoutes}, - {"users", usershandler.RegisterUserRoutes}, - {"departments", departmentshandler.RegisterDepartmentRoutes}, - {"roles", roleshandler.RegisterRoleRoutes}, - {"categories", categorieshandler.RegisterCategoryRoutes}, - {"topics", topicshandler.RegisterTopicRoutes}, - {"user-roles", userroleshandler.RegisterUserRoleRoutes}, - {"hierarchies", hierarchieshandler.RegisterHierarchyRoutes}, - {"topic-executors", topicexecutorshandler.RegisterTopicExecutorRoutes}, - {"approvals", approvalshandler.RegisterApprovalRoutes}, - {"approval-steps", approvalstepshandler.RegisterApprovalStepRoutes}, - {"permissions", permissionshandler.RegisterPermissionRoutes}, - {"approval-tasks", approvaltaskshandler.RegisterApprovalTasksRoutes}, - {"dashboard", dashboardhandler.RegisterDashboardRoutes}, - {"notifications", notificationshandler.RegisterNotificationRoutes}, - {"flownodes", nodeshandler.RegisterFlowNodesRoutes}, - {"approvalextras", approvalextrashandler.RegisterApprovalExtrasRoutes}, - {"adminlog", adminloghandler.RegisterAdminLogRoutes}, - } - - // Регистрация всех маршрутов - for _, rh := range routeHandlers { - if errObj := rh.handler(router, ipc); errObj != nil { - return errors.New(fmt.Sprintf("🔴 failed to register %s routes", rh.name)) - } - } - - // Вывод зарегистрированных маршрутов - if err := printRoutes(router, ipc); err != nil { - return errors.New(fmt.Sprintf("🔴 failed to print routes: %v", err)) - } - - return nil -} - -func printRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error { - err := chi.Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error { - logrus.Info(fmt.Sprintf("🩵 [ %s ] %s\n", method, route)) - return nil - }) - if err != nil { - return err - } - return nil -} - ------END service/rest_admin_service/cmd/app.go----- - -File: service/rest_admin_service/docs/docs.go -Lines: 3990 ------BEGIN service/rest_admin_service/docs/docs.go----- -// Package docs Code generated by swaggo/swag. DO NOT EDIT -package docs - -import "github.com/swaggo/swag" - -const docTemplate = `{ - "schemes": {{ marshal .Schemes }}, - "swagger": "2.0", - "info": { - "description": "{{escape .Description}}", - "title": "{{.Title}}", - "contact": {}, - "version": "{{.Version}}" - }, - "host": "{{.Host}}", - "basePath": "{{.BasePath}}", - "paths": { - "/api/admin": { - "get": { - "description": "Получение списка администраторов", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "admin" - ], - "summary": "Получение списка администраторов", - "parameters": [ - { - "type": "integer", - "description": "Смещение для пагинации", - "name": "offset", - "in": "query" - }, - { - "type": "integer", - "description": "Количество записей на странице", - "name": "limit", - "in": "query" - }, - { - "type": "boolean", - "description": "Фильтр по активности", - "name": "is_active", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.Admin" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "post": { - "description": "Создание администратора", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "admin" - ], - "summary": "Создание администратора", - "parameters": [ - { - "description": "Запрос", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.AdminReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/typescore.Admin" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "delete": { - "description": "Удаление администратора", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "admin" - ], - "summary": "Удаление администратора", - "parameters": [ - { - "description": "Запрос", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.AdminReq" - } - } - ], - "responses": { - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/admin/profile": { - "get": { - "description": "Получение профиля пользователя", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "profile" - ], - "summary": "Получение профиля пользователя", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/typescore.Admin" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "put": { - "description": "Обновление профиля пользователя", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "profile" - ], - "summary": "Обновление профиля пользователя", - "parameters": [ - { - "description": "Запрос", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.AdminReq" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/typescore.Admin" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/approval-steps": { - "get": { - "description": "Получение списка шагов согласования с пагинацией и фильтрацией", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "approval-steps" - ], - "summary": "Получение списка шагов", - "parameters": [ - { - "type": "integer", - "description": "Смещение для пагинации", - "name": "offset", - "in": "query" - }, - { - "type": "integer", - "description": "Количество записей на странице", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по заявке", - "name": "approval_id", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по согласующему", - "name": "approver_id", - "in": "query" - }, - { - "type": "string", - "description": "Фильтр по статусу (pending, waiting, approved, rejected, cancelled_any_of)", - "name": "status", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "put": { - "description": "Обновление данных шага согласования (статус, комментарий)", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "approval-steps" - ], - "summary": "Обновление шага", - "parameters": [ - { - "description": "Данные шага", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.ApprovalStep" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApprovalStep" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Шаг не найден", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "post": { - "description": "Создание нового шага согласования для заявки", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "approval-steps" - ], - "summary": "Создание шага", - "parameters": [ - { - "description": "Данные шага", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.ApprovalStep" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApprovalStep" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Заявка или согласующий не найдены", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "delete": { - "description": "Удаление шага согласования (только для заявок в статусе pending)", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "approval-steps" - ], - "summary": "Удаление шага", - "parameters": [ - { - "description": "ID шага для удаления", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.ApprovalStep" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "type": "boolean" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "403": { - "description": "Нельзя удалить шаг завершённой заявки", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Шаг не найден", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/approval-steps/by-approval/{approval_id}": { - "get": { - "description": "Получение списка всех шагов согласования для указанной заявки, отсортированных по step_order", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "approval-steps" - ], - "summary": "Получение шагов по заявке", - "parameters": [ - { - "type": "integer", - "description": "ID заявки", - "name": "approval_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Заявка не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/approval-steps/{id}": { - "get": { - "description": "Получение детальной информации о шаге согласования по его ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "approval-steps" - ], - "summary": "Получение шага по ID", - "parameters": [ - { - "type": "integer", - "description": "ID шага", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApprovalStep" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Шаг не найден", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/approvals": { - "get": { - "description": "Получение списка заявок с пагинацией и фильтрацией", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "approvals" - ], - "summary": "Получение списка заявок", - "parameters": [ - { - "type": "integer", - "description": "Смещение для пагинации", - "name": "offset", - "in": "query" - }, - { - "type": "integer", - "description": "Количество записей на странице", - "name": "limit", - "in": "query" - }, - { - "type": "string", - "description": "Фильтр по статусу (pending, approved, rejected, revoked, revision)", - "name": "status", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по инициатору", - "name": "initiator_id", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по теме", - "name": "topic_id", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по отделу", - "name": "department_id", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "put": { - "description": "Обновление данных заявки (статус, комментарии и т.д.)", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "approvals" - ], - "summary": "Обновление заявки", - "parameters": [ - { - "description": "Данные заявки", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.Approval" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.Approval" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Заявка не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "delete": { - "description": "Удаление заявки (только для черновиков)", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "approvals" - ], - "summary": "Удаление заявки", - "parameters": [ - { - "description": "ID заявки для удаления", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.Approval" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "type": "boolean" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "403": { - "description": "Нельзя удалить не-черновую заявку", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Заявка не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/approvals/report": { - "get": { - "description": "Получение списка заявок для отчёта с учётом периода и доступа пользователя", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "approvals" - ], - "summary": "Получение заявок для отчёта", - "parameters": [ - { - "type": "integer", - "description": "ID пользователя (если не указан - все заявки)", - "name": "user_id", - "in": "query" - }, - { - "type": "string", - "description": "Начальная дата (YYYY-MM-DD)", - "name": "date_from", - "in": "query" - }, - { - "type": "string", - "description": "Конечная дата (YYYY-MM-DD)", - "name": "date_to", - "in": "query" - }, - { - "type": "boolean", - "description": "Полный доступ (игнорировать фильтрацию по пользователю)", - "name": "all_access", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/approvals/{id}": { - "get": { - "description": "Получение детальной информации о заявке по её ID со всеми связанными данными", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "approvals" - ], - "summary": "Получение заявки по ID", - "parameters": [ - { - "type": "integer", - "description": "ID заявки", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.Approval" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Заявка не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/auth/login": { - "post": { - "description": "авторизация с помощью связки логин-пароль", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "auth" - ], - "summary": "авторизация с помощью связки логин-пароль", - "parameters": [ - { - "description": "Запрос", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.AuthReqAccount" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/typescore.AuthHandlerResponse" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/auth/token": { - "post": { - "description": "Авторизация при помощи JWT-токена", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "auth" - ], - "summary": "Авторизация при помощи JWT-токена", - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/typescore.AuthHandlerResponse" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/categories": { - "get": { - "description": "Получение списка категорий тем с пагинацией и фильтрацией", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "categories" - ], - "summary": "Получение списка категорий тем", - "parameters": [ - { - "type": "integer", - "description": "Смещение для пагинации", - "name": "offset", - "in": "query" - }, - { - "type": "integer", - "description": "Количество записей на странице", - "name": "limit", - "in": "query" - }, - { - "type": "boolean", - "description": "Фильтр по активности", - "name": "is_active", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "put": { - "description": "Обновление данных существующей категории", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "categories" - ], - "summary": "Обновление категории", - "parameters": [ - { - "description": "Данные категории", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopicCategory" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopicCategory" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Категория не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "post": { - "description": "Создание новой категории тем", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "categories" - ], - "summary": "Создание категории тем", - "parameters": [ - { - "description": "Данные категории", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopicCategory" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopicCategory" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "delete": { - "description": "Удаление категории по ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "categories" - ], - "summary": "Удаление категории", - "parameters": [ - { - "description": "ID категории для удаления", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopicCategory" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "type": "boolean" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Категория не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "409": { - "description": "Категория содержит темы", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/categories/{id}": { - "get": { - "description": "Получение детальной информации о категории по её ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "categories" - ], - "summary": "Получение категории по ID", - "parameters": [ - { - "type": "integer", - "description": "ID категории", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopicCategory" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Категория не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/departments": { - "get": { - "description": "Получение списка отделов с пагинацией и фильтрацией", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "departments" - ], - "summary": "Получение списка отделов", - "parameters": [ - { - "type": "integer", - "description": "Смещение для пагинации", - "name": "offset", - "in": "query" - }, - { - "type": "integer", - "description": "Количество записей на странице", - "name": "limit", - "in": "query" - }, - { - "type": "boolean", - "description": "Фильтр по активности", - "name": "is_active", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "put": { - "description": "Обновление данных существующего отдела", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "departments" - ], - "summary": "Обновление отдела", - "parameters": [ - { - "description": "Данные отдела", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.Department" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.Department" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Отдел не найден", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "post": { - "description": "Создание нового отдела", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "departments" - ], - "summary": "Создание отдела", - "parameters": [ - { - "description": "Данные отдела", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.Department" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.Department" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "delete": { - "description": "Удаление отдела по ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "departments" - ], - "summary": "Удаление отдела", - "parameters": [ - { - "description": "ID отдела для удаления", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.Department" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "type": "boolean" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Отдел не найден", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/departments/{id}": { - "get": { - "description": "Получение детальной информации об отделе по его ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "departments" - ], - "summary": "Получение отдела по ID", - "parameters": [ - { - "type": "integer", - "description": "ID отдела", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.Department" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Отдел не найден", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/hierarchies": { - "get": { - "description": "Получение списка связей подчинённый-согласующий с пагинацией и фильтрацией", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "hierarchies" - ], - "summary": "Получение списка записей иерархии", - "parameters": [ - { - "type": "integer", - "description": "Смещение для пагинации", - "name": "offset", - "in": "query" - }, - { - "type": "integer", - "description": "Количество записей на странице", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по подчинённому", - "name": "subordinate_id", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по согласующему", - "name": "approver_id", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по отделу", - "name": "department_id", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "put": { - "description": "Обновление данных существующей записи иерархии", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "hierarchies" - ], - "summary": "Обновление записи иерархии", - "parameters": [ - { - "description": "Данные иерархии", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.UserHierarchy" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.UserHierarchy" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Запись не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "post": { - "description": "Создание новой связи подчинённый-согласующий", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "hierarchies" - ], - "summary": "Создание записи иерархии", - "parameters": [ - { - "description": "Данные иерархии", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.UserHierarchy" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.UserHierarchy" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "409": { - "description": "Такая связь уже существует", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "delete": { - "description": "Удаление связи подчинённый-согласующий по ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "hierarchies" - ], - "summary": "Удаление записи иерархии", - "parameters": [ - { - "description": "ID записи для удаления", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.UserHierarchy" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "type": "boolean" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Запись не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/hierarchies/{id}": { - "get": { - "description": "Получение детальной информации о записи иерархии по её ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "hierarchies" - ], - "summary": "Получение записи иерархии по ID", - "parameters": [ - { - "type": "integer", - "description": "ID записи", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.UserHierarchy" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Запись не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/permissions": { - "get": { - "description": "Получение списка прав ролей с пагинацией и фильтрацией", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "permissions" - ], - "summary": "Получение списка прав", - "parameters": [ - { - "type": "integer", - "description": "Смещение для пагинации", - "name": "offset", - "in": "query" - }, - { - "type": "integer", - "description": "Количество записей на странице", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по роли", - "name": "role_id", - "in": "query" - }, - { - "type": "string", - "description": "Фильтр по действию (create, read, update, delete, approve, revoke)", - "name": "action", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по категории тем", - "name": "topic_category_id", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по теме", - "name": "topic_id", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "put": { - "description": "Обновление данных существующего права", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "permissions" - ], - "summary": "Обновление права", - "parameters": [ - { - "description": "Данные права", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.Permission" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.Permission" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Право не найдено", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "post": { - "description": "Назначение права на действие для роли", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "permissions" - ], - "summary": "Создание права", - "parameters": [ - { - "description": "Данные права", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.Permission" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.Permission" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Роль, категория или тема не найдены", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "409": { - "description": "Такое право уже существует", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "delete": { - "description": "Удаление права по ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "permissions" - ], - "summary": "Удаление права", - "parameters": [ - { - "description": "ID права для удаления", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.Permission" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "type": "boolean" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Право не найдено", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/permissions/by-role/{role_id}": { - "get": { - "description": "Получение списка всех прав для указанной роли", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "permissions" - ], - "summary": "Получение прав по роли", - "parameters": [ - { - "type": "integer", - "description": "ID роли", - "name": "role_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Роль не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/permissions/{id}": { - "get": { - "description": "Получение детальной информации о праве по его ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "permissions" - ], - "summary": "Получение права по ID", - "parameters": [ - { - "type": "integer", - "description": "ID права", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.Permission" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Право не найдено", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/roles": { - "get": { - "description": "Получение списка ролей с пагинацией и фильтрацией", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "roles" - ], - "summary": "Получение списка ролей", - "parameters": [ - { - "type": "integer", - "description": "Смещение для пагинации", - "name": "offset", - "in": "query" - }, - { - "type": "integer", - "description": "Количество записей на странице", - "name": "limit", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "put": { - "description": "Обновление данных существующей роли", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "roles" - ], - "summary": "Обновление роли", - "parameters": [ - { - "description": "Данные роли", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.Role" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.Role" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Роль не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "post": { - "description": "Создание новой роли", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "roles" - ], - "summary": "Создание роли", - "parameters": [ - { - "description": "Данные роли", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.Role" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.Role" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "delete": { - "description": "Удаление роли по ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "roles" - ], - "summary": "Удаление роли", - "parameters": [ - { - "description": "ID роли для удаления", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.Role" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "type": "boolean" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Роль не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/roles/{id}": { - "get": { - "description": "Получение детальной информации о роли по её ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "roles" - ], - "summary": "Получение роли по ID", - "parameters": [ - { - "type": "integer", - "description": "ID роли", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.Role" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Роль не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/topic-executors": { - "get": { - "description": "Получение списка исполнителей с пагинацией и фильтрацией", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "topic-executors" - ], - "summary": "Получение списка исполнителей тем", - "parameters": [ - { - "type": "integer", - "description": "Смещение для пагинации", - "name": "offset", - "in": "query" - }, - { - "type": "integer", - "description": "Количество записей на странице", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по теме", - "name": "topic_id", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по пользователю", - "name": "user_id", - "in": "query" - }, - { - "type": "boolean", - "description": "Фильтр по активности", - "name": "is_active", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "put": { - "description": "Обновление данных исполнителя для темы", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "topic-executors" - ], - "summary": "Обновление исполнителя", - "parameters": [ - { - "description": "Данные исполнителя", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopicExecutor" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopicExecutor" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Исполнитель не найден", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "post": { - "description": "Назначение исполнителя для конкретной темы согласования", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "topic-executors" - ], - "summary": "Создание исполнителя", - "parameters": [ - { - "description": "Данные исполнителя", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopicExecutor" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopicExecutor" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Тема или пользователь не найдены", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "409": { - "description": "Такой исполнитель уже назначен на этот шаг", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "delete": { - "description": "Удаление исполнителя из темы по ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "topic-executors" - ], - "summary": "Удаление исполнителя", - "parameters": [ - { - "description": "ID записи для удаления", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopicExecutor" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "type": "boolean" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Запись не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/topic-executors/by-topic/{topic_id}": { - "get": { - "description": "Получение списка всех активных исполнителей для указанной темы, отсортированных по step_order", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "topic-executors" - ], - "summary": "Получение исполнителей по теме", - "parameters": [ - { - "type": "integer", - "description": "ID темы", - "name": "topic_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Тема не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/topic-executors/{id}": { - "get": { - "description": "Получение детальной информации об исполнителе по его ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "topic-executors" - ], - "summary": "Получение исполнителя по ID", - "parameters": [ - { - "type": "integer", - "description": "ID исполнителя", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopicExecutor" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Исполнитель не найден", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/topics": { - "get": { - "description": "Получение списка тем с пагинацией и фильтрацией", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "topics" - ], - "summary": "Получение списка тем", - "parameters": [ - { - "type": "integer", - "description": "Смещение для пагинации", - "name": "offset", - "in": "query" - }, - { - "type": "integer", - "description": "Количество записей на странице", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по категории", - "name": "category_id", - "in": "query" - }, - { - "type": "boolean", - "description": "Фильтр по активности", - "name": "is_active", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "put": { - "description": "Обновление данных существующей темы", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "topics" - ], - "summary": "Обновление темы", - "parameters": [ - { - "description": "Данные темы", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopic" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopic" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Тема не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "post": { - "description": "Создание новой темы согласования", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "topics" - ], - "summary": "Создание темы", - "parameters": [ - { - "description": "Данные темы", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopic" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopic" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "delete": { - "description": "Удаление темы по ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "topics" - ], - "summary": "Удаление темы", - "parameters": [ - { - "description": "ID темы для удаления", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopic" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "type": "boolean" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Тема не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "409": { - "description": "Тема содержит заявки", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/topics/{id}": { - "get": { - "description": "Получение детальной информации о теме по её ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "topics" - ], - "summary": "Получение темы по ID", - "parameters": [ - { - "type": "integer", - "description": "ID темы", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApprovalTopic" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Тема не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/user-roles": { - "get": { - "description": "Получение списка ролей, назначенных конкретному пользователю", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user-roles" - ], - "summary": "Получение списка ролей пользователя", - "parameters": [ - { - "type": "integer", - "description": "ID пользователя", - "name": "user_id", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "post": { - "description": "Назначение роли пользователю (создание связи user_id + role_id)", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user-roles" - ], - "summary": "Назначение роли пользователю", - "parameters": [ - { - "description": "user_id и role_id", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/handlers_user_roles.AssignUserRoleRequest" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.UserRole" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Пользователь или роль не найдены", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "409": { - "description": "Роль уже назначена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "delete": { - "description": "Удаление связи user_id + role_id по ID записи", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user-roles" - ], - "summary": "Удаление роли у пользователя", - "parameters": [ - { - "description": "ID записи для удаления", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.UserRole" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "type": "boolean" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Запись не найдена", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/user-roles/bulk": { - "post": { - "description": "Полная замена ролей пользователя: удаляет все текущие роли и назначает новые", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user-roles" - ], - "summary": "Массовое назначение ролей", - "parameters": [ - { - "description": "user_id и список role_ids", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/handlers_user_roles.BulkAssignRolesRequest" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Пользователь не найден", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/users": { - "get": { - "description": "Получение списка пользователей с пагинацией, фильтрацией и подгрузкой связанных данных", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "users" - ], - "summary": "Получение списка пользователей", - "parameters": [ - { - "type": "integer", - "description": "Смещение для пагинации", - "name": "offset", - "in": "query" - }, - { - "type": "integer", - "description": "Количество записей на странице", - "name": "limit", - "in": "query" - }, - { - "type": "boolean", - "description": "Фильтр по блокировке", - "name": "is_blocked", - "in": "query" - }, - { - "type": "boolean", - "description": "Фильтр по увольнению", - "name": "is_fired", - "in": "query" - }, - { - "type": "integer", - "description": "Фильтр по отделу", - "name": "department_id", - "in": "query" - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - }, - "put": { - "description": "Обновление данных существующего пользователя", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "users" - ], - "summary": "Обновление пользователя", - "parameters": [ - { - "description": "Данные пользователя", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/typescore.UpdateUserReqAdmin" - } - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.User" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Пользователь не найден", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/users/{id}": { - "get": { - "description": "Получение детальной информации о пользователе по его ID с подгрузкой связанных данных", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "users" - ], - "summary": "Получение пользователя по ID", - "parameters": [ - { - "type": "integer", - "description": "ID пользователя", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.User" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Пользователь не найден", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - }, - "/api/users/{user_id}/roles": { - "get": { - "description": "Получение списка ролей, назначенных пользователю с указанным ID", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "user-roles" - ], - "summary": "Получение списка ролей пользователя по ID", - "parameters": [ - { - "type": "integer", - "description": "ID пользователя", - "name": "user_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Успех", - "schema": { - "$ref": "#/definitions/typescore.ApiResponseBase" - } - }, - "400": { - "description": "Некорректный запрос", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "404": { - "description": "Пользователь не найден", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - }, - "500": { - "description": "Ошибка сервера", - "schema": { - "$ref": "#/definitions/handlers.ErrorResponse" - } - } - } - } - } - }, - "definitions": { - "handlers.ErrorResponse": { - "type": "object", - "properties": { - "error_code": { - "description": "Код ошибки", - "type": "integer" - }, - "error_description": { - "description": "Описание ошибки", - "type": "string" - } - } - }, - "handlers_user_roles.AssignUserRoleRequest": { - "type": "object", - "properties": { - "role_id": { - "type": "integer" - }, - "user_id": { - "type": "integer" - } - } - }, - "handlers_user_roles.BulkAssignRolesRequest": { - "type": "object", - "properties": { - "role_ids": { - "type": "array", - "items": { - "type": "integer" - } - }, - "user_id": { - "type": "integer" - } - } - }, - "typescore.Admin": { - "type": "object", - "properties": { - "created_at": { - "description": "Дата создания записи", - "type": "string" - }, - "id": { - "description": "Автоматически заполняемое уникальное поле для большого числа записей", - "type": "integer" - }, - "is_blocked": { - "description": "Заблокирован ли администратор", - "type": "boolean" - }, - "last_ip_login": { - "description": "Последний IP входа", - "type": "string" - }, - "last_login": { - "description": "Дата входа", - "type": "string" - }, - "login": { - "description": "Логин администратора", - "type": "string" - } - } - }, - "typescore.AdminReq": { - "type": "object", - "properties": { - "login": { - "type": "string" - }, - "password": { - "description": "Пароль пользователя", - "type": "string" - } - } - }, - "typescore.ApiResponseBase": { - "type": "object", - "properties": { - "data": { - "description": "данные полученные от api" - }, - "total_amount": { - "type": "number" - }, - "total_count": { - "type": "integer" - } - } - }, - "typescore.Approval": { - "type": "object", - "properties": { - "content": { - "description": "введённые пользователем данные по шаблону", - "type": "string" - }, - "created_at": { - "type": "string" - }, - "department": { - "$ref": "#/definitions/typescore.Department" - }, - "department_id": { - "description": "снимок отдела на момент создания", - "type": "integer" - }, - "files": { - "type": "array", - "items": { - "$ref": "#/definitions/typescore.ApprovalFile" - } - }, - "id": { - "type": "integer" - }, - "initiator": { - "$ref": "#/definitions/typescore.User" - }, - "initiator_id": { - "type": "integer" - }, - "metadata": { - "type": "string" - }, - "revision_at": { - "type": "string" - }, - "revision_by_id": { - "type": "integer" - }, - "revision_comment": { - "type": "string" - }, - "revision_count": { - "type": "integer" - }, - "revoked_at": { - "type": "string" - }, - "revoked_by": { - "$ref": "#/definitions/typescore.User" - }, - "revoked_by_id": { - "type": "integer" - }, - "status": { - "type": "string" - }, - "steps": { - "type": "array", - "items": { - "$ref": "#/definitions/typescore.ApprovalStep" - } - }, - "topic": { - "$ref": "#/definitions/typescore.ApprovalTopic" - }, - "topic_id": { - "type": "integer" - }, - "updated_at": { - "type": "string" - } - } - }, - "typescore.ApprovalFile": { - "type": "object", - "properties": { - "approval_id": { - "type": "integer" - }, - "attached_by_id": { - "type": "integer" - }, - "created_at": { - "type": "string" - }, - "file_base64": { - "type": "string" - }, - "file_name": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "task_id": { - "type": "integer" - } - } - }, - "typescore.ApprovalStep": { - "type": "object", - "properties": { - "acted_at": { - "type": "string" - }, - "approval": { - "$ref": "#/definitions/typescore.Approval" - }, - "approval_id": { - "type": "integer" - }, - "approver": { - "$ref": "#/definitions/typescore.User" - }, - "approver_department_snapshot": { - "type": "string" - }, - "approver_id": { - "type": "integer" - }, - "approver_name_snapshot": { - "type": "string" - }, - "comment": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "returned_at": { - "type": "string" - }, - "status": { - "type": "string" - }, - "step_order": { - "type": "integer" - }, - "updated_at": { - "type": "string" - } - } - }, - "typescore.ApprovalTopic": { - "type": "object", - "properties": { - "allow_approver_selection": { - "type": "boolean" - }, - "allow_observer_selection": { - "type": "boolean" - }, - "allows_file": { - "type": "boolean" - }, - "approvalMode": { - "type": "string" - }, - "category": { - "$ref": "#/definitions/typescore.ApprovalTopicCategory" - }, - "category_id": { - "type": "integer" - }, - "code": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "duration_type": { - "type": "string" - }, - "first_approver_role_code": { - "description": "если задан — первый согласующий выбирается из этой роли", - "type": "string" - }, - "id": { - "type": "integer" - }, - "instructions": { - "type": "string" - }, - "is_active": { - "type": "boolean" - }, - "name": { - "type": "string" - }, - "payment_type": { - "type": "string" - }, - "require_approver_comment": { - "type": "boolean" - }, - "require_observer_selection": { - "type": "boolean" - }, - "requires_file": { - "type": "boolean" - }, - "template": { - "type": "string" - }, - "time_type": { - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - }, - "typescore.ApprovalTopicCategory": { - "type": "object", - "properties": { - "code": { - "description": "otgul, vacation, sick_leave", - "type": "string" - }, - "created_at": { - "type": "string" - }, - "description": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "is_active": { - "type": "boolean" - }, - "name": { - "type": "string" - }, - "topics": { - "type": "array", - "items": { - "$ref": "#/definitions/typescore.ApprovalTopic" - } - }, - "updated_at": { - "type": "string" - } - } - }, - "typescore.ApprovalTopicExecutor": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "is_active": { - "type": "boolean" - }, - "require_file": { - "type": "boolean" - }, - "step_order": { - "type": "integer" - }, - "target_system": { - "type": "string" - }, - "task_text": { - "type": "string" - }, - "topic": { - "$ref": "#/definitions/typescore.ApprovalTopic" - }, - "topic_id": { - "type": "integer" - }, - "updated_at": { - "type": "string" - }, - "user": { - "$ref": "#/definitions/typescore.User" - }, - "user_id": { - "type": "integer" - } - } - }, - "typescore.AuthHandlerResponse": { - "type": "object", - "properties": { - "temp_session": { - "description": "Временный токен для 2FA", - "type": "string" - }, - "token": { - "description": "токен аутентификации", - "type": "string" - } - } - }, - "typescore.AuthReqAccount": { - "type": "object", - "properties": { - "access_code": { - "type": "string" - }, - "login": { - "type": "string" - }, - "password": { - "type": "string" - }, - "redirect_uri": { - "type": "string" - }, - "token": { - "type": "string" - } - } - }, - "typescore.Department": { - "type": "object", - "properties": { - "code": { - "description": "finance, hr, it", - "type": "string" - }, - "created_at": { - "type": "string" - }, - "description": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "is_active": { - "type": "boolean" - }, - "name": { - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - }, - "typescore.Permission": { - "type": "object", - "properties": { - "action": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "role": { - "$ref": "#/definitions/typescore.Role" - }, - "role_id": { - "type": "integer" - }, - "topic": { - "$ref": "#/definitions/typescore.ApprovalTopic" - }, - "topic_category": { - "$ref": "#/definitions/typescore.ApprovalTopicCategory" - }, - "topic_category_id": { - "type": "integer" - }, - "topic_id": { - "type": "integer" - }, - "updated_at": { - "type": "string" - } - } - }, - "typescore.Role": { - "type": "object", - "properties": { - "code": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "description": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "is_approver": { - "type": "boolean" - }, - "is_default": { - "type": "boolean" - }, - "is_director": { - "type": "boolean" - }, - "is_executor": { - "type": "boolean" - }, - "is_observer": { - "type": "boolean" - }, - "name": { - "type": "string" - }, - "permissions": { - "type": "array", - "items": { - "$ref": "#/definitions/typescore.Permission" - } - }, - "updated_at": { - "type": "string" - } - } - }, - "typescore.UpdateUserReqAdmin": { - "type": "object", - "properties": { - "department_id": { - "description": "Логин пользователя", - "type": "integer" - }, - "id": { - "type": "integer" - }, - "is_blocked": { - "description": "Заблокирован ли пользователь", - "type": "boolean" - }, - "is_fired": { - "description": "Заблокирован ли пользователь", - "type": "boolean" - } - } - }, - "typescore.User": { - "type": "object", - "properties": { - "blocked_at": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "department": { - "$ref": "#/definitions/typescore.Department" - }, - "department_id": { - "type": "integer" - }, - "full_name": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "is_blocked": { - "type": "boolean" - }, - "is_fired": { - "type": "boolean" - }, - "language_code": { - "description": "FirstName *string ` + "`" + `gorm:\"type:text;not null;column:first_name\" json:\"first_name\" db:\"first_name\" mapstructure:\"first_name\"` + "`" + `\nLastName *string ` + "`" + `gorm:\"type:text;not null;column:last_name\" json:\"last_name\" db:\"last_name\" mapstructure:\"last_name\"` + "`" + `\nPatronymic *string ` + "`" + `gorm:\"type:text;column:patronymic\" json:\"patronymic,omitempty\" db:\"patronymic\" mapstructure:\"patronymic\"` + "`" + `", - "type": "string" - }, - "last_login": { - "type": "string" - }, - "telegram_id": { - "type": "integer" - }, - "updated_at": { - "type": "string" - }, - "user_roles": { - "type": "array", - "items": { - "$ref": "#/definitions/typescore.UserRole" - } - }, - "username": { - "type": "string" - } - } - }, - "typescore.UserHierarchy": { - "type": "object", - "properties": { - "approver": { - "$ref": "#/definitions/typescore.User" - }, - "approver_id": { - "type": "integer" - }, - "created_at": { - "type": "string" - }, - "department": { - "$ref": "#/definitions/typescore.Department" - }, - "department_id": { - "type": "integer" - }, - "id": { - "type": "integer" - }, - "priority": { - "type": "integer" - }, - "subordinate": { - "$ref": "#/definitions/typescore.User" - }, - "subordinate_id": { - "type": "integer" - }, - "topic_category_id": { - "type": "integer" - }, - "topic_id": { - "type": "integer" - }, - "updated_at": { - "type": "string" - } - } - }, - "typescore.UserRole": { - "type": "object", - "properties": { - "created_at": { - "type": "string" - }, - "id": { - "description": "Автоматически заполняемое уникальное поле для большого числа записей", - "type": "integer" - }, - "role": { - "description": "← добавить gorm:\"-\"", - "allOf": [ - { - "$ref": "#/definitions/typescore.Role" - } - ] - }, - "role_id": { - "type": "integer" - }, - "updated_at": { - "type": "string" - }, - "user": { - "description": "← добавить gorm:\"-\"", - "allOf": [ - { - "$ref": "#/definitions/typescore.User" - } - ] - }, - "user_id": { - "type": "integer" - } - } - } - }, - "securityDefinitions": { - "ApiKeyAuth": { - "type": "apiKey", - "name": "ApiKey", - "in": "header" - }, - "BearerAuth": { - "type": "apiKey", - "name": "Authorization", - "in": "header" - }, - "DeviceID": { - "type": "apiKey", - "name": "x-device-id", - "in": "header" - }, - "Timestamp": { - "type": "apiKey", - "name": "X-Timestamp", - "in": "header" - } - } -}` - -// SwaggerInfo holds exported Swagger Info so clients can modify it -var SwaggerInfo = &swag.Spec{ - Version: "0.1", - Host: "localhost:8080", - BasePath: "/", - Schemes: []string{}, - Title: "RusPet Admin API", - Description: "API админ-панели для системы согласований\n\n## Возможности\n- Управление отделами, ролями и пользователями\n- Настройка тем и категорий согласований\n- Управление иерархией согласований\n- Назначение исполнителей и прав\n- Просмотр заявок и шагов согласования\n\n## Аутентификация\nВсе защищённые эндпоинты требуют:\n- `Authorization: Bearer ` — JWT токен администратора\n- `ApiKey: ` — HMAC подпись для верификации клиента\n- `X-Timestamp: ` — Unix timestamp (не старше 3 минут)\n- `x-device-id: ` — ID устройства", - InfoInstanceName: "swagger", - SwaggerTemplate: docTemplate, - LeftDelim: "{{", - RightDelim: "}}", -} - -func init() { - swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) -} - ------END service/rest_admin_service/docs/docs.go----- - -File: service/rest_admin_service/handlers/admin/handlers.go -Lines: 502 ------BEGIN service/rest_admin_service/handlers/admin/handlers.go----- -package adminhandler - -import ( - "bitrix_balancer_api/core/securecore" - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - "encoding/json" - "errors" - "fmt" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strings" -) - -// GetAdminsListHandler Получение списка администраторов -// @Summary Получение списка администраторов -// @Description Получение списка администраторов -// @Tags admin -// @Accept json -// @Produce json -// @Param offset query integer false "Смещение для пагинации" -// @Param limit query integer false "Количество записей на странице" -// @Param is_active query boolean false "Фильтр по активности" -// @Success 200 {object} typescore.Admin "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/admin [get] -func (s *AdminsReg) GetAdminsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - AdminsParams := &typescore.Admin{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, AdminsParams) - if errW != nil { - return nil, errW - } - - options := typescore.ListDbOptions{ - Filtering: AdminsParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - adminsDbLst, total, errW := s.ipc.Database.Admin.GetAdminsListDB(options) - if errW != nil { - return nil, errW - } - - ctx := r.Context() - for _, admin := range adminsDbLst { - if admin.TelegramID != nil { - telegramUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, *admin.TelegramID) - if err == nil && telegramUser != nil { - admin.TelegramUser = telegramUser - } - } - } - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: adminsDbLst, - }, nil -} - -// CreateAdminHandler Создание администратора -func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - // Проверка, что текущий админ — root - currentUserID, err := handlers.GetIDFromContext(r.Context()) - if err != nil { - return nil, errors.New("user not authenticated") - } - - currentAdmins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(currentAdmins) == 0 { - return nil, errors.New("current admin not found") - } - - if currentAdmins[0].IsRoot == nil || !*currentAdmins[0].IsRoot { - return nil, errors.New("only_root_can_create_admins") - } - - body, err := io.ReadAll(r.Body) - if err != nil { - return nil, err - } - - var req typescore.AdminReq - if err := json.Unmarshal(body, &req); err != nil { - return nil, err - } - - if req.Login == nil || *req.Login == "" { - return nil, errors.New("login is required") - } - - if req.IsObserver != nil && *req.IsObserver { - if req.TelegramID == nil { - return nil, errors.New("telegram_id_required_for_observer") - } - telegramUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(r.Context(), *req.TelegramID) - if err != nil || telegramUser == nil { - return nil, errors.New("telegram_user_not_found") - } - } - - // Проверка уникальности логина - usersList, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{Login: req.Login}, - }) - if err != nil { - return nil, err - } - if len(usersList) > 0 { - return nil, errors.New("admin_is_not_available") - } - - tempPassword, err := utilscore.GenerateRandomString(12) - if err != nil { - return nil, err - } - - tempPasswordHash, err := securecore.HashPassword(&tempPassword) - if err != nil { - return nil, err - } - - newAdminObj := &typescore.Admin{ - Login: req.Login, - Name: req.Name, - PasswordHash: tempPasswordHash, - IsRoot: req.IsRoot, - IsObserver: req.IsObserver, - TelegramID: req.TelegramID, - } - - newAdmin, _, err := s.ipc.Database.Admin.CreateAdminDB(nil, newAdminObj, true) - if err != nil { - return nil, err - } - - newAdmin.Password = &tempPassword - - userID, err := handlers.GetIDFromContext(r.Context()) - if err != nil { - logrus.Errorf("Failed to get user id: %v", err) - } else { - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ - ID: &userID, - }, - }) - if err != nil { - logrus.Errorf("get admin list error: %v", err) - } - if len(admins) > 0 && admins[0] != nil { - snapshot := map[string]interface{}{ - "login": derefStr(newAdmin.Login), - "name": derefStr(newAdmin.Name), - "is_root": derefBool(newAdmin.IsRoot), - "is_observer": derefBool(newAdmin.IsObserver), - } - if newAdmin.TelegramID != nil { - snapshot["telegram_id"] = *newAdmin.TelegramID - } - - adminloghandler.LogAdminActionWithMetadata( - r.Context(), s.ipc, - *admins[0].ID, *admins[0].Login, - "create", "admin", newAdmin.ID, - fmt.Sprintf("Создан администратор «%s»", *newAdmin.Login), - map[string]interface{}{"snapshot": snapshot}, - ) - } - } - - return newAdmin, nil -} - -// UpdateAdminHandler Обновление администратора -func (s *AdminsReg) UpdateAdminHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - return nil, err - } - - var req typescore.Admin - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("admin id is required") - } - - // Получаем существующего админа - existingAdmins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: req.ID}, - }) - if err != nil || len(existingAdmins) == 0 { - return nil, errors.New("admin not found") - } - existing := existingAdmins[0] - - // Получаем текущего админа - currentUserID, err := handlers.GetIDFromContext(r.Context()) - if err != nil { - return nil, errors.New("user not authenticated") - } - currentAdmins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(currentAdmins) == 0 { - return nil, errors.New("current admin not found") - } - currentIsRoot := currentAdmins[0].IsRoot != nil && *currentAdmins[0].IsRoot - - // Проверки root-прав (как было) - if req.IsRoot != nil { - if !currentIsRoot { - return nil, errors.New("only_root_can_manage_root_rights") - } - if *req.ID == currentUserID && !*req.IsRoot { - return nil, errors.New("cannot_remove_root_from_self") - } - if !*req.IsRoot && existing.IsRoot != nil && *existing.IsRoot { - allAdmins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{}, - }) - if err == nil { - rootCount := 0 - for _, a := range allAdmins { - if a.IsRoot != nil && *a.IsRoot { - rootCount++ - } - } - if rootCount <= 1 { - return nil, errors.New("cannot_remove_last_root") - } - } - } - } - - if req.IsBlocked != nil && *req.IsBlocked { - if existing.IsRoot != nil && *existing.IsRoot && !currentIsRoot { - return nil, errors.New("cannot_block_root") - } - } - - if *req.ID == currentUserID && req.IsBlocked != nil && *req.IsBlocked { - return nil, errors.New("cannot_block_self") - } - - isObserver := existing.IsObserver - telegramID := existing.TelegramID - - if req.IsObserver != nil { - isObserver = req.IsObserver - } - if req.TelegramID != nil { - telegramID = req.TelegramID - } - - if isObserver != nil && *isObserver { - if telegramID == nil { - return nil, errors.New("telegram_id_required_for_observer") - } - telegramUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(r.Context(), *telegramID) - if err != nil || telegramUser == nil { - return nil, errors.New("telegram_user_not_found") - } - } - - type fieldChange struct { - Field string `json:"field"` - Old interface{} `json:"old"` - New interface{} `json:"new"` - } - var changes []fieldChange - var summary []string - - if req.Name != nil && !strEq(existing.Name, req.Name) { - changes = append(changes, fieldChange{"name", derefStr(existing.Name), *req.Name}) - summary = append(summary, fmt.Sprintf("имя: «%s» → «%s»", derefStr(existing.Name), *req.Name)) - } - if req.IsBlocked != nil && !boolEq(existing.IsBlocked, req.IsBlocked) { - changes = append(changes, fieldChange{"is_blocked", derefBool(existing.IsBlocked), *req.IsBlocked}) - if *req.IsBlocked { - summary = append(summary, "заблокирован") - } else { - summary = append(summary, "разблокирован") - } - } - if req.IsRoot != nil && !boolEq(existing.IsRoot, req.IsRoot) { - changes = append(changes, fieldChange{"is_root", derefBool(existing.IsRoot), *req.IsRoot}) - if *req.IsRoot { - summary = append(summary, "выдана роль root") - } else { - summary = append(summary, "роль root снята") - } - } - if req.IsObserver != nil && !boolEq(existing.IsObserver, req.IsObserver) { - changes = append(changes, fieldChange{"is_observer", derefBool(existing.IsObserver), *req.IsObserver}) - if *req.IsObserver { - summary = append(summary, "включён режим наблюдателя") - } else { - summary = append(summary, "режим наблюдателя выключен") - } - } - if req.TelegramID != nil && !int64Eq(existing.TelegramID, req.TelegramID) { - var oldVal interface{} - if existing.TelegramID != nil { - oldVal = *existing.TelegramID - } - changes = append(changes, fieldChange{"telegram_id", oldVal, *req.TelegramID}) - summary = append(summary, fmt.Sprintf("telegram_id: %v → %d", oldVal, *req.TelegramID)) - } - - // Создаём объект для обновления - updateObj := &typescore.Admin{ - ID: req.ID, - } - if req.Name != nil { - updateObj.Name = req.Name - } - if req.IsBlocked != nil { - updateObj.IsBlocked = req.IsBlocked - } - if req.IsRoot != nil { - updateObj.IsRoot = req.IsRoot - } - if req.IsObserver != nil { - updateObj.IsObserver = req.IsObserver - } - if req.TelegramID != nil { - updateObj.TelegramID = req.TelegramID - } - - updated, _, err := s.ipc.Database.Admin.UpdateAdminDB(nil, updateObj, true) - if err != nil { - return nil, err - } - - // 🆕 Логируем ПОСЛЕ успешного обновления, и только если реально что-то - // изменилось (пустой запрос на обновление без факта изменений в - // журнал не пишем — иначе он будет засоряться). - if len(changes) > 0 { - description := fmt.Sprintf("Изменён администратор «%s»: %s", derefStr(existing.Login), strings.Join(summary, "; ")) - adminloghandler.LogAdminActionWithMetadata( - r.Context(), s.ipc, - *currentAdmins[0].ID, *currentAdmins[0].Login, - "update", "admin", req.ID, - description, - map[string]interface{}{"changes": changes}, - ) - } - - return updated, nil -} - -// DeleteAdminHandler Удаление администратора -func (s *AdminsReg) DeleteAdminHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - return nil, err - } - - var req typescore.Admin - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("admin id is required") - } - - // Нельзя удалить себя - currentUserID, err := handlers.GetIDFromContext(r.Context()) - if err != nil { - return nil, errors.New("user not authenticated") - } - if *req.ID == currentUserID { - return nil, errors.New("cannot_delete_self") - } - - // Получаем удаляемого админа - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: req.ID}, - }) - if err != nil || len(admins) == 0 { - return nil, errors.New("admin not found") - } - - // 🆕 Нельзя удалить root (если текущий не root) - currentAdmins, _, _ := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - currentIsRoot := len(currentAdmins) > 0 && currentAdmins[0].IsRoot != nil && *currentAdmins[0].IsRoot - - targetIsRoot := admins[0].IsRoot != nil && *admins[0].IsRoot - if targetIsRoot && !currentIsRoot { - return nil, errors.New("cannot_delete_root") - } - - // 🆕 Снапшот удаляемого администратора — берём ДО удаления (после - // DeleteAdminDB запись из БД уже не достать). - deletedSnapshot := map[string]interface{}{ - "login": derefStr(admins[0].Login), - "name": derefStr(admins[0].Name), - "is_root": derefBool(admins[0].IsRoot), - "is_observer": derefBool(admins[0].IsObserver), - } - if admins[0].TelegramID != nil { - deletedSnapshot["telegram_id"] = *admins[0].TelegramID - } - - err = s.ipc.Database.Admin.DeleteAdminDB(&req) - if err != nil { - return nil, err - } - - if len(currentAdmins) > 0 && currentAdmins[0] != nil { - adminloghandler.LogAdminActionWithMetadata( - r.Context(), s.ipc, - *currentAdmins[0].ID, *currentAdmins[0].Login, - "delete", "admin", req.ID, - fmt.Sprintf("Удалён администратор «%s»", derefStr(admins[0].Login)), - map[string]interface{}{"snapshot": deletedSnapshot}, - ) - } - - return true, nil -} - -// ============================================================ -// Небольшие помощники сравнения/разыменования — чтобы не плодить -// одинаковые проверки "оба nil или оба равны" по всему файлу. -// ============================================================ - -func derefStr(s *string) string { - if s == nil { - return "" - } - return *s -} - -func derefBool(b *bool) bool { - if b == nil { - return false - } - return *b -} - -func strEq(a, b *string) bool { - if a == nil && b == nil { - return true - } - if a == nil || b == nil { - return false - } - return *a == *b -} - -func boolEq(a, b *bool) bool { - if a == nil && b == nil { - return true - } - if a == nil || b == nil { - return false - } - return *a == *b -} - -func uint64Eq(a, b *uint64) bool { - if a == nil && b == nil { - return true - } - if a == nil || b == nil { - return false - } - return *a == *b -} - -func int64Eq(a, b *int64) bool { - if a == nil && b == nil { - return true - } - if a == nil || b == nil { - return false - } - return *a == *b -} - ------END service/rest_admin_service/handlers/admin/handlers.go----- - -File: service/rest_admin_service/handlers/admin/routes.go -Lines: 38 ------BEGIN service/rest_admin_service/handlers/admin/routes.go----- -package adminhandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "github.com/go-chi/chi/v5" - "net/http" -) - -const ( - adminURL = "/" -) - -type AdminsReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterAdminRoutes регистрирует маршруты для группы admin -func RegisterAdminRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &AdminsReg{ - ipc: ipc, - } - - r.Route("/api/admin", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, adminURL, s.GetAdminsListHandler) - handlers.RegisterRoute(r, http.MethodPost, adminURL, s.CreateAdminHandler) - handlers.RegisterRoute(r, http.MethodDelete, adminURL, s.DeleteAdminHandler) - handlers.RegisterRoute(r, http.MethodPut, adminURL, s.UpdateAdminHandler) - }) - - return nil -} - ------END service/rest_admin_service/handlers/admin/routes.go----- - -File: service/rest_admin_service/handlers/admin_actions/handlers.go -Lines: 210 ------BEGIN service/rest_admin_service/handlers/admin_actions/handlers.go----- -package adminloghandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "context" - "encoding/json" - "net/http" - "strconv" - "time" - - "github.com/go-chi/chi/v5" - "github.com/sirupsen/logrus" -) - -type AdminLogReg struct { - ipc *typesm.InternalProviderControl -} - -func RegisterAdminLogRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error { - s := &AdminLogReg{ipc: ipc} - - r.Route("/api/admin-logs", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - handlers.RegisterRoute(r, http.MethodGet, "/", s.ListLogsHandler) - handlers.RegisterRoute(r, http.MethodDelete, "/{id}", s.DeleteLogEntryHandler) - }) - - return nil -} - -// ListLogsHandler — теперь поддерживает: -// -// admin_id, admin_login (ILIKE), action, entity_type, entity_id, -// date_from, date_to (YYYY-MM-DD, включительно на весь день), -// search (ILIKE по description) -func (s *AdminLogReg) ListLogsHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - ctx := r.Context() - q := r.URL.Query() - - filter := typescore.AdminActionLogFilter{} - - if v := q.Get("admin_id"); v != "" { - if id, err := strconv.ParseUint(v, 10, 64); err == nil { - filter.AdminID = &id - } - } - if v := q.Get("admin_login"); v != "" { - filter.AdminLogin = &v - } - if v := q.Get("action"); v != "" { - filter.Action = &v - } - if v := q.Get("entity_type"); v != "" { - filter.EntityType = &v - } - if v := q.Get("entity_id"); v != "" { - if id, err := strconv.ParseUint(v, 10, 64); err == nil { - filter.EntityID = &id - } - } - if v := q.Get("date_from"); v != "" { - if t, err := time.Parse("2006-01-02", v); err == nil { - filter.DateFrom = &t - } - } - if v := q.Get("date_to"); v != "" { - if t, err := time.Parse("2006-01-02", v); err == nil { - endOfDay := t.Add(24*time.Hour - time.Second) - filter.DateTo = &endOfDay - } - } - if v := q.Get("search"); v != "" { - filter.Search = &v - } - - limit := parseUintPtr(q.Get("limit"), 50) - offset := parseUintPtr(q.Get("offset"), 0) - - logs, totalCount, err := s.ipc.Database.AdminActionLogs.GetAdminActionLogsFilteredDB(ctx, filter, offset, limit) - if err != nil { - return nil, err - } - - return map[string]interface{}{ - "data": logs, - "total_count": totalCount, - }, nil -} - -// DeleteLogEntryHandler — 🩹 восстановлена проверка is_root, потерянная -// в промежуточной версии. Удалять записи журнала может только -// root-администратор — без этой проверки endpoint открыт любому админу, -// что сводит на нет саму цель журнала (неизменяемость для всех, кроме root). -func (s *AdminLogReg) DeleteLogEntryHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - ctx := r.Context() - - currentAdmin, ok := GetCurrentAdmin(ctx, s.ipc) - if !ok { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return nil, nil - } - if currentAdmin.IsRoot == nil || !*currentAdmin.IsRoot { - http.Error(w, "только root-администратор может удалять записи журнала", http.StatusForbidden) - return nil, nil - } - - id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 64) - if err != nil { - return nil, err - } - - if err := s.ipc.Database.AdminActionLogs.DeleteAdminActionLogDB(ctx, &typescore.AdminActionLog{ID: &id}); err != nil { - return nil, err - } - - return map[string]interface{}{"success": true}, nil -} - -func LogAdminAction( - ctx context.Context, - ipc *typesm.InternalProviderControl, - adminID uint64, - adminLogin string, - action string, - entityType string, - entityID *uint64, - description string, -) { - LogAdminActionWithMetadata(ctx, ipc, adminID, adminLogin, action, entityType, entityID, description, nil) -} - -func LogAdminActionWithMetadata( - ctx context.Context, - ipc *typesm.InternalProviderControl, - adminID uint64, - adminLogin string, - action string, - entityType string, - entityID *uint64, - description string, - metadata map[string]interface{}, -) { - var metadataJSON *string - if metadata != nil { - if b, err := json.Marshal(metadata); err == nil { - s := string(b) - metadataJSON = &s - } else { - logrus.Warnf("LogAdminActionWithMetadata: не удалось сериализовать metadata: %v", err) - } - } - - now := time.Now() - entry := &typescore.AdminActionLog{ - AdminID: &adminID, - AdminLogin: &adminLogin, - Action: &action, - EntityType: &entityType, - EntityID: entityID, - Description: &description, - Metadata: metadataJSON, - CreatedAt: &now, - } - - if _, _, err := ipc.Database.AdminActionLogs.CreateAdminActionLogDB(ctx, nil, entry); err != nil { - logrus.Errorf("LogAdminActionWithMetadata: не удалось записать в журнал (admin=%s, action=%s, entity=%s:%v): %v", - adminLogin, action, entityType, entityID, err) - } -} - -// GetCurrentAdmin — 🆕 вынесено сюда из 13 хендлеров, где было -// продублировано один в один под именем getCurrentAdmin (локальная, -// неэкспортируемая версия в каждом пакете отдельно). Экспортируемая -// версия здесь, в "родном" пакете журнала — логичное место, раз уже -// каждый из этих 13 хендлеров и так импортирует adminloghandler ради -// LogAdminActionWithMetadata. -// -// Миграция существующих хендлеров не обязательна прямо сейчас (все они -// рабочие как есть, с локальными копиями) — но при следующей правке -// любого из них имеет смысл заменить его локальный getCurrentAdmin на -// вызов adminloghandler.GetCurrentAdmin(ctx, s.ipc) и удалить дубликат. -func GetCurrentAdmin(ctx context.Context, ipc *typesm.InternalProviderControl) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, false - } - - admins, _, err := ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - return nil, false - } - - return admins[0], true -} - -func parseUintPtr(v string, fallback uint64) *uint64 { - if v == "" { - return &fallback - } - n, err := strconv.ParseUint(v, 10, 64) - if err != nil { - return &fallback - } - return &n -} - ------END service/rest_admin_service/handlers/admin_actions/handlers.go----- - -File: service/rest_admin_service/handlers/approval_steps/handlers.go -Lines: 442 ------BEGIN service/rest_admin_service/handlers/approval_steps/handlers.go----- -package approvalstepshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "context" - "encoding/json" - "errors" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strconv" - - "github.com/go-chi/chi/v5" -) - -// GetApprovalStepsListHandler Получение списка шагов согласования -// @Summary Получение списка шагов -// @Description Получение списка шагов согласования с пагинацией и фильтрацией -// @Tags approval-steps -// @Accept json -// @Produce json -// @Param offset query integer false "Смещение для пагинации" -// @Param limit query integer false "Количество записей на странице" -// @Param approval_id query integer false "Фильтр по заявке" -// @Param approver_id query integer false "Фильтр по согласующему" -// @Param status query string false "Фильтр по статусу (pending, waiting, approved, rejected, cancelled_any_of)" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approval-steps [get] -func (s *ApprovalStepsReg) GetApprovalStepsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - stepParams := &typescore.ApprovalStep{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, stepParams) - if errW != nil { - return nil, errW - } - - options := typescore.ListDbOptions{ - Filtering: stepParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - stepsDbLst, total, errW := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(r.Context(), options) - if errW != nil { - return nil, errW - } - - // 🚀 Подгружаем связанные данные - for _, step := range stepsDbLst { - s.enrichStep(r.Context(), step, false) - } - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: stepsDbLst, - }, nil -} - -// GetApprovalStepByIDHandler Получение шага по ID -// @Summary Получение шага по ID -// @Description Получение детальной информации о шаге согласования по его ID -// @Tags approval-steps -// @Accept json -// @Produce json -// @Param id path integer true "ID шага" -// @Success 200 {object} typescore.ApprovalStep "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Шаг не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approval-steps/{id} [get] -func (s *ApprovalStepsReg) GetApprovalStepByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("step id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid step id") - } - - steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(r.Context(), typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ID: &id}, - }) - if err != nil { - return nil, err - } - if len(steps) == 0 { - return nil, errors.New("approval step not found") - } - - step := steps[0] - s.enrichStep(r.Context(), step, true) - - return step, nil -} - -// GetStepsByApprovalIDHandler Получение всех шагов для заявки -// @Summary Получение шагов по заявке -// @Description Получение списка всех шагов согласования для указанной заявки, отсортированных по step_order -// @Tags approval-steps -// @Accept json -// @Produce json -// @Param approval_id path integer true "ID заявки" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Заявка не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approval-steps/by-approval/{approval_id} [get] -func (s *ApprovalStepsReg) GetStepsByApprovalIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - approvalIDStr := chi.URLParam(r, "approval_id") - if approvalIDStr == "" { - return nil, errors.New("approval_id is required") - } - - approvalID, err := strconv.ParseUint(approvalIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid approval_id") - } - - // Проверяем, что заявка существует - approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(r.Context(), approvalID) - if err != nil { - return nil, err - } - if approval == nil { - return nil, errors.New("approval not found") - } - - steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(r.Context(), typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, - }) - if err != nil { - return nil, err - } - - // Сортируем по step_order - sortStepsByOrder(steps) - - // Подгружаем связанные данные - for _, step := range steps { - s.enrichStep(r.Context(), step, false) - } - - return &typescore.ApiResponseBase{ - TotalCount: uint64(len(steps)), - Data: steps, - }, nil -} - -// CreateApprovalStepHandler Создание шага согласования -// @Summary Создание шага -// @Description Создание нового шага согласования для заявки -// @Tags approval-steps -// @Accept json -// @Produce json -// @Param request body typescore.ApprovalStep true "Данные шага" -// @Success 200 {object} typescore.ApprovalStep "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Заявка или согласующий не найдены" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approval-steps [post] -func (s *ApprovalStepsReg) CreateApprovalStepHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 CreateApprovalStepHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalStep - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - // Валидация обязательных полей - if req.ApprovalID == nil { - return nil, errors.New("approval_id is required") - } - if req.ApproverID == nil { - return nil, errors.New("approver_id is required") - } - if req.StepOrder == nil { - return nil, errors.New("step_order is required") - } - - ctx := r.Context() - - // Проверяем существование заявки - approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *req.ApprovalID) - if err != nil { - return nil, err - } - if approval == nil { - return nil, errors.New("approval not found") - } - - // 🛡 Можно добавлять шаги только к заявкам в статусе pending - if approval.Status == nil || *approval.Status != "pending" { - return nil, errors.New("can only add steps to pending approvals") - } - - // Проверяем существование согласующего - approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ApproverID) - if err != nil { - return nil, err - } - if approver == nil { - return nil, errors.New("approver user not found") - } - - // Проверяем, что пользователь не заблокирован и не уволен - if approver.IsBlocked != nil && *approver.IsBlocked { - return nil, errors.New("approver user is blocked") - } - if approver.IsFired != nil && *approver.IsFired { - return nil, errors.New("approver user is fired") - } - - // Устанавливаем значения по умолчанию - if req.Status == nil { - defaultStatus := "waiting" - req.Status = &defaultStatus - } - - // Создаём снимок имени согласующего - if approver.FullName != nil && req.ApproverNameSnapshot == nil { - req.ApproverNameSnapshot = approver.FullName - } - - createdStep, _, err := s.ipc.Database.ApprovalStep.CreateApprovalStepDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - s.enrichStep(ctx, createdStep, false) - - return createdStep, nil -} - -// UpdateApprovalStepHandler Обновление шага -// @Summary Обновление шага -// @Description Обновление данных шага согласования (статус, комментарий) -// @Tags approval-steps -// @Accept json -// @Produce json -// @Param request body typescore.ApprovalStep true "Данные шага" -// @Success 200 {object} typescore.ApprovalStep "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Шаг не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approval-steps [put] -func (s *ApprovalStepsReg) UpdateApprovalStepHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 UpdateApprovalStepHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalStep - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("step id is required") - } - - ctx := r.Context() - - // Проверяем, что шаг существует - existingSteps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ID: req.ID}, - }) - if err != nil { - return nil, err - } - if len(existingSteps) == 0 { - return nil, errors.New("approval step not found") - } - existing := existingSteps[0] - - // 🛡 Если обновляется статус — проверяем валидность перехода - if req.Status != nil && existing.Status != nil { - if !isValidStepStatusTransition(*existing.Status, *req.Status) { - return nil, errors.New("invalid status transition from " + *existing.Status + " to " + *req.Status) - } - } - - updatedStep, _, err := s.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - s.enrichStep(ctx, updatedStep, false) - - return updatedStep, nil -} - -// DeleteApprovalStepHandler Удаление шага -// @Summary Удаление шага -// @Description Удаление шага согласования (только для заявок в статусе pending) -// @Tags approval-steps -// @Accept json -// @Produce json -// @Param request body typescore.ApprovalStep true "ID шага для удаления" -// @Success 200 {object} bool "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 403 {object} handlers.ErrorResponse "Нельзя удалить шаг завершённой заявки" -// @Failure 404 {object} handlers.ErrorResponse "Шаг не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approval-steps [delete] -func (s *ApprovalStepsReg) DeleteApprovalStepHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 DeleteApprovalStepHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalStep - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("step id is required") - } - - ctx := r.Context() - - // Проверяем, что шаг существует - existingSteps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ID: req.ID}, - }) - if err != nil { - return nil, err - } - if len(existingSteps) == 0 { - return nil, errors.New("approval step not found") - } - existing := existingSteps[0] - - // Проверяем заявку - if existing.ApprovalID != nil { - approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *existing.ApprovalID) - if err != nil { - return nil, err - } - if approval == nil { - return nil, errors.New("approval not found") - } - - // 🛡 Можно удалять шаги только у заявок в статусе pending - if approval.Status == nil || *approval.Status != "pending" { - return nil, errors.New("can only delete steps from pending approvals") - } - } - - // 🛡 Нельзя удалять уже обработанные шаги - if existing.Status != nil { - if *existing.Status == "approved" || *existing.Status == "rejected" { - return nil, errors.New("cannot delete completed steps") - } - } - - err = s.ipc.Database.ApprovalStep.DeleteApprovalStepDB(ctx, &req) - if err != nil { - return nil, err - } - - return true, nil -} - -// enrichStep подгружает связанные данные для шага -func (s *ApprovalStepsReg) enrichStep(ctx context.Context, step *typescore.ApprovalStep, loadApproval bool) { - if step == nil { - return - } - - // Подгружаем согласующего - if step.ApproverID != nil { - approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID) - if err == nil && approver != nil { - step.Approver = approver - } - } - - // Подгружаем заявку (только для детального просмотра) - if loadApproval && step.ApprovalID != nil { - approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID) - if err == nil && approval != nil { - step.Approval = approval - } - } -} - -// sortStepsByOrder сортирует шаги по step_order -func sortStepsByOrder(steps []*typescore.ApprovalStep) { - for i := 0; i < len(steps); i++ { - for j := i + 1; j < len(steps); j++ { - if steps[i].StepOrder != nil && steps[j].StepOrder != nil { - if *steps[i].StepOrder > *steps[j].StepOrder { - steps[i], steps[j] = steps[j], steps[i] - } - } - } - } -} - -// isValidStepStatusTransition проверяет валидность перехода между статусами шага -func isValidStepStatusTransition(from, to string) bool { - validTransitions := map[string][]string{ - "pending": {"approved", "rejected", "cancelled_any_of"}, - "waiting": {"pending", "cancelled_any_of"}, - "approved": {}, // финальный статус - "rejected": {}, // финальный статус - "cancelled_any_of": {}, // финальный статус - } - - allowed, exists := validTransitions[from] - if !exists { - return false - } - - for _, status := range allowed { - if status == to { - return true - } - } - - return false -} - ------END service/rest_admin_service/handlers/approval_steps/handlers.go----- - -File: service/rest_admin_service/handlers/approval_steps/routes.go -Lines: 43 ------BEGIN service/rest_admin_service/handlers/approval_steps/routes.go----- -package approvalstepshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type ApprovalStepsReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterApprovalStepRoutes регистрирует маршруты для группы approval-steps -func RegisterApprovalStepRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &ApprovalStepsReg{ - ipc: ipc, - } - - r.Route("/api/approval-steps", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetApprovalStepsListHandler) - handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateApprovalStepHandler) - handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateApprovalStepHandler) - handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteApprovalStepHandler) - - r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetApprovalStepByIDHandler, - })) - - r.Get("/by-approval/{approval_id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetStepsByApprovalIDHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/approval_steps/routes.go----- - -File: service/rest_admin_service/handlers/approval_tasks/handlers_tasks.go -Lines: 531 ------BEGIN service/rest_admin_service/handlers/approval_tasks/handlers_tasks.go----- -package approvaltaskshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "path/filepath" - "strconv" - "strings" - - "github.com/go-chi/chi/v5" - "github.com/sirupsen/logrus" -) - -// GetApprovalTasksListHandler Получение списка задач -func (s *ApprovalTasksReg) GetApprovalTasksListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - taskParams := &typescore.ApprovalTask{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, taskParams) - if errW != nil { - return nil, errW - } - - ctx := r.Context() - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok && currentAdmin.IsObserver != nil && *currentAdmin.IsObserver { - if currentAdmin.TelegramID != nil && *currentAdmin.TelegramID > 0 { - if tgUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, *currentAdmin.TelegramID); err == nil && tgUser != nil && tgUser.ID != nil { - taskParams.ObserverUserID = tgUser.ID - } else { - return &typescore.ApiResponseBase{TotalCount: 0, Data: []*typescore.ApprovalTask{}}, nil - } - } else { - return &typescore.ApiResponseBase{TotalCount: 0, Data: []*typescore.ApprovalTask{}}, nil - } - } - - options := typescore.ListDbOptions{ - Filtering: taskParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - tasks, total, errW := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, options) - if errW != nil { - return nil, errW - } - - for _, task := range tasks { - s.enrichTask(ctx, task) - } - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: tasks, - }, nil -} - -// GetApprovalTaskByIDHandler Получение задачи по ID -func (s *ApprovalTasksReg) GetApprovalTaskByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("task id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid task id") - } - - ctx := r.Context() - task, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, id) - if err != nil { - return nil, err - } - if task == nil { - return nil, errors.New("task not found") - } - - s.enrichTask(ctx, task) - - return task, nil -} - -// UpdateApprovalTaskHandler Обновление задачи -func (s *ApprovalTasksReg) UpdateApprovalTaskHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 UpdateApprovalTaskHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalTask - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("task id is required") - } - - ctx := r.Context() - - // Проверяем существование - existingTask, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, *req.ID) - if err != nil || existingTask == nil { - return nil, errors.New("task not found") - } - - if req.Status != nil { - validStatuses := map[string]bool{ - "pending": true, - "waiting": true, - "completed": true, - "cancelled": true, - } - if !validStatuses[*req.Status] { - return nil, errors.New("invalid status") - } - } - - type fieldChange struct { - Field string `json:"field"` - Old interface{} `json:"old"` - New interface{} `json:"new"` - } - var changes []fieldChange - var summary []string - - if req.Status != nil && !utilscore.StrEq(existingTask.Status, req.Status) { - changes = append(changes, fieldChange{"status", utilscore.DerefStr(existingTask.Status), *req.Status}) - summary = append(summary, fmt.Sprintf("статус: «%s» → «%s»", utilscore.DerefStr(existingTask.Status), *req.Status)) - } - if req.TaskText != nil && !utilscore.StrEq(existingTask.TaskText, req.TaskText) { - changes = append(changes, fieldChange{"task_text", utilscore.DerefStr(existingTask.TaskText), *req.TaskText}) - summary = append(summary, "изменён текст задачи") - } - if req.ExecutorID != nil && !utilscore.Uint64Eq(existingTask.ExecutorID, req.ExecutorID) { - var oldVal interface{} - if existingTask.ExecutorID != nil { - oldVal = *existingTask.ExecutorID - } - changes = append(changes, fieldChange{"executor_id", oldVal, *req.ExecutorID}) - summary = append(summary, fmt.Sprintf("исполнитель: %v → %d", oldVal, *req.ExecutorID)) - } - if req.RequireFile != nil && !utilscore.BoolEq(existingTask.RequireFile, req.RequireFile) { - changes = append(changes, fieldChange{"require_file", utilscore.DerefBool(existingTask.RequireFile), *req.RequireFile}) - if *req.RequireFile { - summary = append(summary, "включено обязательное вложение файла") - } else { - summary = append(summary, "отключено обязательное вложение файла") - } - } - if req.StepOrder != nil && !utilscore.IntEq(existingTask.StepOrder, req.StepOrder) { - var oldVal interface{} - if existingTask.StepOrder != nil { - oldVal = *existingTask.StepOrder - } - changes = append(changes, fieldChange{"step_order", oldVal, *req.StepOrder}) - summary = append(summary, fmt.Sprintf("порядок шага: %v → %d", oldVal, *req.StepOrder)) - } - - updated, _, err := s.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - s.enrichTask(ctx, updated) - - if len(changes) > 0 { - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - approvalRef := "" - if existingTask.ApprovalID != nil { - approvalRef = fmt.Sprintf(" (заявка #%d)", *existingTask.ApprovalID) - } - description := fmt.Sprintf("Изменена задача #%d%s: %s", *req.ID, approvalRef, strings.Join(summary, "; ")) - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "approval_task", req.ID, - description, - map[string]interface{}{"changes": changes}, - ) - } - } - - return updated, nil -} - -// DeleteApprovalTaskHandler Удаление задачи -func (s *ApprovalTasksReg) DeleteApprovalTaskHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - return nil, err - } - - var req typescore.ApprovalTask - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("task id is required") - } - - ctx := r.Context() - - existingTask, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, *req.ID) - if err != nil || existingTask == nil { - return nil, errors.New("task not found") - } - snapshot := map[string]interface{}{ - "task_text": utilscore.DerefStr(existingTask.TaskText), - "status": utilscore.DerefStr(existingTask.Status), - "require_file": utilscore.DerefBool(existingTask.RequireFile), - } - if existingTask.ApprovalID != nil { - snapshot["approval_id"] = *existingTask.ApprovalID - } - if existingTask.ExecutorID != nil { - snapshot["executor_id"] = *existingTask.ExecutorID - } - if existingTask.StepOrder != nil { - snapshot["step_order"] = *existingTask.StepOrder - } - - err = s.ipc.Database.ApprovalTasks.DeleteApprovalTaskDB(ctx, &req) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - approvalRef := "" - if existingTask.ApprovalID != nil { - approvalRef = fmt.Sprintf(" (заявка #%d)", *existingTask.ApprovalID) - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "delete", "approval_task", req.ID, - fmt.Sprintf("Удалена задача #%d%s", *req.ID, approvalRef), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return true, nil -} - -func (s *ApprovalTasksReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - logrus.Warnf("getCurrentAdmin: GetIDFromContext err=%v", err) - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - logrus.Warnf("getCurrentAdmin: admin not found for userID=%d err=%v", currentUserID, err) - return nil, false - } - - return admins[0], true -} - -// enrichTask подгружает связанные данные для задачи -func (s *ApprovalTasksReg) enrichTask(ctx context.Context, task *typescore.ApprovalTask) { - if task == nil { - return - } - - // Подгружаем заявку - if task.ApprovalID != nil { - approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID) - if err == nil && approval != nil { - task.Approval = approval - s.enrichApproval(ctx, approval) - } - } - - // Подгружаем исполнителя - if task.ExecutorID != nil { - executor, err := s.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID) - if err == nil && executor != nil { - task.Executor = executor - if executor.DepartmentID != nil { - department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *executor.DepartmentID) - if err == nil && department != nil { - executor.Department = department - } - } - } - } - - if task.ID != nil { - files, err := s.ipc.Database.ApprovalFile.GetFilesByTaskIDDB(ctx, *task.ID) - if err == nil { - task.Files = files - } - } -} - -func (s *ApprovalTasksReg) enrichApproval(ctx context.Context, approval *typescore.Approval) { - if approval == nil { - return - } - - // Подгружаем инициатора - if approval.InitiatorID != nil { - initiator, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) - if err == nil && initiator != nil { - approval.Initiator = initiator - - // Подгружаем отдел инициатора - if initiator.DepartmentID != nil { - department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *initiator.DepartmentID) - if err == nil && department != nil { - initiator.Department = department - } - } - } - } - - // Подгружаем тему - if approval.TopicID != nil { - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if err == nil && topic != nil { - approval.Topic = topic - - // Подгружаем категорию темы - if topic.CategoryID != nil { - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID) - if err == nil && category != nil { - topic.Category = category - } - } - } - } - - // Подгружаем отдел - if approval.DepartmentID != nil { - department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID) - if err == nil && department != nil { - approval.Department = department - } - } -} - -// GetApprovalTaskFileHandler Получение файла задачи (для предпросмотра) -// -// 🆕 Не логирую просмотр/скачивание файлов — журнал задуман под -// create/update/delete-действия, а не под чтение. Если захотите отслеживать -// ещё и скачивания (например, для файлов с чувствительными данными) — это -// отдельное решение, скажите, добавлю action="download" по тому же паттерну. -func (s *ApprovalTasksReg) GetApprovalTaskFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - ctx := r.Context() - - taskIDStr := chi.URLParam(r, "task_id") - fileIDStr := chi.URLParam(r, "file_id") - - if taskIDStr == "" || fileIDStr == "" { - return nil, errors.New("task_id and file_id are required") - } - - taskID, err := strconv.ParseUint(taskIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid task_id") - } - - fileID, err := strconv.ParseUint(fileIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid file_id") - } - - // Проверяем, что задача существует - task, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID) - if err != nil || task == nil { - return nil, errors.New("task not found") - } - - // Получаем файл - file, err := s.ipc.Database.ApprovalFile.GetApprovalFileByIDDB(ctx, fileID) - if err != nil || file == nil { - return nil, errors.New("file not found") - } - - // Проверяем, что файл принадлежит задаче - if file.TaskID == nil || *file.TaskID != taskID { - return nil, errors.New("file does not belong to this task") - } - - if file.FileBase64 == nil || *file.FileBase64 == "" { - return nil, errors.New("file content is empty") - } - - fileData, err := base64.StdEncoding.DecodeString(*file.FileBase64) - if err != nil { - return nil, errors.New("failed to decode file") - } - - fileName := "" - if file.FileName != nil { - fileName = *file.FileName - } - mimeType := getMimeType(fileName) - - w.Header().Set("Content-Type", mimeType) - w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, fileName)) - w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileData))) - w.Header().Set("Cache-Control", "public, max-age=31536000") - - w.WriteHeader(http.StatusOK) - _, err = w.Write(fileData) - if err != nil { - return nil, errors.New("failed to send file") - } - - return nil, nil -} - -// DownloadApprovalTaskFileHandler Скачивание файла задачи -func (s *ApprovalTasksReg) DownloadApprovalTaskFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - ctx := r.Context() - - taskIDStr := chi.URLParam(r, "task_id") - fileIDStr := chi.URLParam(r, "file_id") - - if taskIDStr == "" || fileIDStr == "" { - return nil, errors.New("task_id and file_id are required") - } - - taskID, err := strconv.ParseUint(taskIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid task_id") - } - - fileID, err := strconv.ParseUint(fileIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid file_id") - } - - task, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID) - if err != nil || task == nil { - return nil, errors.New("task not found") - } - - file, err := s.ipc.Database.ApprovalFile.GetApprovalFileByIDDB(ctx, fileID) - if err != nil || file == nil { - return nil, errors.New("file not found") - } - - if file.TaskID == nil || *file.TaskID != taskID { - return nil, errors.New("file does not belong to this task") - } - - if file.FileBase64 == nil || *file.FileBase64 == "" { - return nil, errors.New("file content is empty") - } - - fileData, err := base64.StdEncoding.DecodeString(*file.FileBase64) - if err != nil { - return nil, errors.New("failed to decode file") - } - - fileName := "" - if file.FileName != nil { - fileName = *file.FileName - } - mimeType := getMimeType(fileName) - - w.Header().Set("Content-Type", mimeType) - w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName)) - w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileData))) - - w.WriteHeader(http.StatusOK) - _, err = w.Write(fileData) - if err != nil { - return nil, errors.New("failed to send file") - } - - return nil, nil -} - -// 🆕 getMimeType определяет MIME тип по расширению файла -func getMimeType(fileName string) string { - ext := strings.ToLower(filepath.Ext(fileName)) - - mimeTypes := map[string]string{ - ".jpg": "image/jpeg", - ".jpeg": "image/jpeg", - ".png": "image/png", - ".gif": "image/gif", - ".webp": "image/webp", - ".svg": "image/svg+xml", - ".bmp": "image/bmp", - ".pdf": "application/pdf", - ".txt": "text/plain", - ".doc": "application/msword", - ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - ".xls": "application/vnd.ms-excel", - ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - ".csv": "text/csv", - ".zip": "application/zip", - ".json": "application/json", - ".xml": "application/xml", - ".html": "text/html", - ".mp3": "audio/mpeg", - ".mp4": "video/mp4", - } - - if mimeType, ok := mimeTypes[ext]; ok { - return mimeType - } - - return "application/octet-stream" -} - ------END service/rest_admin_service/handlers/approval_tasks/handlers_tasks.go----- - -File: service/rest_admin_service/handlers/approval_tasks/routes.go -Lines: 44 ------BEGIN service/rest_admin_service/handlers/approval_tasks/routes.go----- -package approvaltaskshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type ApprovalTasksReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterApprovalTasksRoutes регистрирует маршруты для группы approvals -func RegisterApprovalTasksRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &ApprovalTasksReg{ - ipc: ipc, - } - - r.Route("/api/approval-tasks", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetApprovalTasksListHandler) - handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateApprovalTaskHandler) - handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteApprovalTaskHandler) - - r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetApprovalTaskByIDHandler, - })) - r.Get("/{task_id}/files/{file_id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetApprovalTaskFileHandler, - })) - r.Get("/{task_id}/files/{file_id}/download", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.DownloadApprovalTaskFileHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/approval_tasks/routes.go----- - -File: service/rest_admin_service/handlers/approvalextras/handler.go -Lines: 422 ------BEGIN service/rest_admin_service/handlers/approvalextras/handler.go----- -package approvalextrashandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "errors" - "net/http" - "strconv" - "time" - - "github.com/go-chi/chi/v5" -) - -type ApprovalExtrasReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterApprovalExtrasRoutes регистрирует данные о заявке, которые НЕ -// хранятся прямо на самой Approval (или пока не отдаются в основном ответе -// GET /api/approvals/{id}) — доп. согласующие, комментарии, наблюдатели -// (вычисляются динамически по категории/теме, не хранимая связь) и активный -// запрос на отзыв. -// -// ⚠️ ВАЖНО: регистрируем через r.Get() с полными путями, а НЕ через -// r.Route("/api/approvals/{id}", ...). r.Route создаёт отдельный вложенный -// роутер, который занимает узел {id} целиком — из-за этого существующий -// GET /api/approvals/{id} (без суффикса) становится недостижим и отдаёт 404, -// хотя вложенные пути (/additional-approvers и т.п.) продолжают работать. -// Проверено эмпирически на реальном chi.Router — с r.Route ломается, с -// r.Get(полный путь) — нет. -func RegisterApprovalExtrasRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &ApprovalExtrasReg{ipc: ipc} - - r.Group(func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/additional-approvers", s.GetAdditionalApproversHandler) - handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/comments", s.GetCommentsHandler) - handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/observers", s.GetObserversHandler) - handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/revocation-request", s.GetRevocationRequestHandler) - handlers.RegisterRoute(r, http.MethodGet, "/api/approvals/{id}/tasks", s.GetTasksHandler) - }) - - return nil -} - -func parseApprovalID(r *http.Request) (uint64, error) { - idStr := chi.URLParam(r, "id") - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return 0, errors.New("invalid approval id") - } - return id, nil -} - -func userName(u *typescore.User) string { - if u != nil && u.FullName != nil { - return *u.FullName - } - return "—" -} - -// ============================================================ -// GET /api/approvals/{id}/additional-approvers -// ============================================================ - -type additionalApproverDTO struct { - ID uint64 `json:"id"` - ApproverID uint64 `json:"approver_id"` - ApproverName string `json:"approver_name"` - Status string `json:"status"` - Comment string `json:"comment,omitempty"` - ActedAt *time.Time `json:"acted_at,omitempty"` -} - -func (s *ApprovalExtrasReg) GetAdditionalApproversHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - approvalID, err := parseApprovalID(r) - if err != nil { - return nil, err - } - ctx := r.Context() - - records, _, err := s.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID}, - }) - if err != nil { - return nil, err - } - - result := make([]additionalApproverDTO, 0, len(records)) - for _, rec := range records { - if rec.ApproverID == nil { - continue - } - approver, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *rec.ApproverID) - - dto := additionalApproverDTO{ - ApproverID: *rec.ApproverID, - ApproverName: userName(approver), - Status: "pending", - ActedAt: rec.ActedAt, - } - if rec.ID != nil { - dto.ID = *rec.ID - } - if rec.Status != nil { - dto.Status = *rec.Status - } - if rec.Comment != nil { - dto.Comment = *rec.Comment - } - result = append(result, dto) - } - - return &typescore.ApiResponseBase{ - TotalCount: uint64(len(result)), - Data: result, - }, nil -} - -// ============================================================ -// GET /api/approvals/{id}/comments -// ============================================================ - -type commentDTO struct { - ID uint64 `json:"id"` - UserID uint64 `json:"user_id"` - UserName string `json:"user_name"` - Comment string `json:"comment"` - CreatedAt *time.Time `json:"created_at,omitempty"` -} - -func (s *ApprovalExtrasReg) GetCommentsHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - approvalID, err := parseApprovalID(r) - if err != nil { - return nil, err - } - ctx := r.Context() - - records, _, err := s.ipc.Database.ApprovalComment.GetApprovalCommentsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalComment{ApprovalID: &approvalID}, - }) - if err != nil { - return nil, err - } - - result := make([]commentDTO, 0, len(records)) - for _, rec := range records { - dto := commentDTO{CreatedAt: rec.CreatedAt} - if rec.ID != nil { - dto.ID = *rec.ID - } - if rec.UserID != nil { - dto.UserID = *rec.UserID - user, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *rec.UserID) - dto.UserName = userName(user) - } - if rec.Comment != nil { - dto.Comment = *rec.Comment - } - result = append(result, dto) - } - - return &typescore.ApiResponseBase{ - TotalCount: uint64(len(result)), - Data: result, - }, nil -} - -// ============================================================ -// GET /api/approvals/{id}/observers -// -// Наблюдатели НЕ хранятся как связь на самой заявке — они вычисляются по -// категории/теме через права (см. GetObserversForApprovalDB в -// telegram_service). Здесь та же логика: сначала получаем код категории -// темы этой заявки, затем спрашиваем БД. -// ============================================================ - -type observerDTO struct { - ID uint64 `json:"id"` - FullName string `json:"full_name"` -} - -func (s *ApprovalExtrasReg) GetObserversHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - approvalID, err := parseApprovalID(r) - if err != nil { - return nil, err - } - ctx := r.Context() - - approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if err != nil { - return nil, err - } - if approval == nil { - return nil, errors.New("approval not found") - } - - categoryCode := "" - if approval.TopicID != nil { - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if err == nil && topic != nil && topic.CategoryID != nil { - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID) - if err == nil && category != nil && category.Code != nil { - categoryCode = *category.Code - } - } - } - - observers, err := s.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID) - if err != nil { - return nil, err - } - - result := make([]observerDTO, 0, len(observers)) - for _, obs := range observers { - if obs.ID == nil { - continue - } - result = append(result, observerDTO{ - ID: *obs.ID, - FullName: userName(obs), - }) - } - - return &typescore.ApiResponseBase{ - TotalCount: uint64(len(result)), - Data: result, - }, nil -} - -// ============================================================ -// GET /api/approvals/{id}/revocation-request -// -// Возвращает {"data": null}, если активного (pending) запроса на отзыв нет — -// это нормальный случай для большинства заявок, не ошибка. -// ============================================================ - -type revocationApproverDTO struct { - ApproverID uint64 `json:"approver_id"` - ApproverName string `json:"approver_name"` - Status string `json:"status"` -} - -type revocationRequestDTO struct { - ID uint64 `json:"id"` - Status string `json:"status"` - Reason string `json:"reason,omitempty"` - RequestedByID uint64 `json:"requested_by_id"` - RequestedByName string `json:"requested_by_name"` - Approvers []revocationApproverDTO `json:"approvers"` -} - -func (s *ApprovalExtrasReg) GetRevocationRequestHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - approvalID, err := parseApprovalID(r) - if err != nil { - return nil, err - } - ctx := r.Context() - - request, err := s.ipc.Database.ApprovalRevocation.GetPendingRevocationRequestForApprovalDB(ctx, approvalID) - if err != nil { - return nil, err - } - if request == nil { - return &typescore.ApiResponseBase{Data: nil}, nil - } - - dto := revocationRequestDTO{Status: "pending"} - if request.ID != nil { - dto.ID = *request.ID - } - if request.Status != nil { - dto.Status = *request.Status - } - if request.Reason != nil { - dto.Reason = *request.Reason - } - if request.RequestedByID != nil { - dto.RequestedByID = *request.RequestedByID - requestedBy, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *request.RequestedByID) - dto.RequestedByName = userName(requestedBy) - } - - if request.ID != nil { - approvers, err := s.ipc.Database.ApprovalRevocation.GetRevocationApproversByRequestIDDB(ctx, *request.ID) - if err == nil { - for _, a := range approvers { - if a.ApproverID == nil { - continue - } - approverUser, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *a.ApproverID) - status := "pending" - if a.Status != nil { - status = *a.Status - } - dto.Approvers = append(dto.Approvers, revocationApproverDTO{ - ApproverID: *a.ApproverID, - ApproverName: userName(approverUser), - Status: status, - }) - } - } - } - - return &typescore.ApiResponseBase{Data: dto}, nil -} - -// ============================================================ -// GET /api/approvals/{id}/tasks -// -// Две вещи в одном ответе: -// - topic_executors — что НАСТРОЕНО для темы этой заявки (ApprovalTopicExecutor), -// нужно для превью "какие задачи будут поставлены после согласования" -// на pending-заявках, ещё до их фактического создания. -// - tasks — что РЕАЛЬНО создано (ApprovalTask), уже после согласования. -// - has_task_error — та же логика, что в отчёте (reportcore.BuildExcelApprovalsReport): -// если для темы настроены исполнители, заявка уже approved, а задач -// по факту нет — это ошибка на этапе создания задач, а не "не предусмотрено". -// ============================================================ - -type plannedTaskDTO struct { - ID uint64 `json:"id"` - TaskText string `json:"task_text"` - ExecutorName string `json:"executor_name,omitempty"` - StepOrder int `json:"step_order"` -} - -type taskDTO struct { - ID uint64 `json:"id"` - TaskText string `json:"task_text"` - ExecutorName string `json:"executor_name"` - Status string `json:"status"` - CompletedAt *time.Time `json:"completed_at,omitempty"` -} - -type approvalTasksResponse struct { - TopicExecutors []plannedTaskDTO `json:"topic_executors"` - Tasks []taskDTO `json:"tasks"` - HasTaskError bool `json:"has_task_error"` -} - -func (s *ApprovalExtrasReg) GetTasksHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - approvalID, err := parseApprovalID(r) - if err != nil { - return nil, err - } - ctx := r.Context() - - approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if err != nil { - return nil, err - } - if approval == nil { - return nil, errors.New("approval not found") - } - - resp := &approvalTasksResponse{} - - if approval.TopicID == nil { - return &typescore.ApiResponseBase{Data: resp}, nil - } - - topicExecutors, err := s.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, *approval.TopicID) - if err != nil { - return nil, err - } - - for _, te := range topicExecutors { - if te.ID == nil { - continue - } - dto := plannedTaskDTO{ID: *te.ID} - if te.TaskText != nil { - dto.TaskText = *te.TaskText - } - if te.StepOrder != nil { - dto.StepOrder = *te.StepOrder - } - if te.UserID != nil { - executor, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *te.UserID) - dto.ExecutorName = userName(executor) - } - resp.TopicExecutors = append(resp.TopicExecutors, dto) - } - - tasks, _, err := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTask{ApprovalID: &approvalID}, - }) - if err != nil { - return nil, err - } - - for _, t := range tasks { - if t.ID == nil { - continue - } - dto := taskDTO{ID: *t.ID, Status: "—", CompletedAt: t.CompletedAt} - if t.TaskText != nil { - dto.TaskText = *t.TaskText - } - if t.Status != nil { - dto.Status = *t.Status - } - if t.ExecutorID != nil { - executor, _ := s.ipc.Database.User.GetUserByIDDB(ctx, *t.ExecutorID) - dto.ExecutorName = userName(executor) - } - resp.Tasks = append(resp.Tasks, dto) - } - - if len(topicExecutors) > 0 && len(tasks) == 0 && approval.Status != nil && *approval.Status == "approved" { - resp.HasTaskError = true - } - - return &typescore.ApiResponseBase{Data: resp}, nil -} - ------END service/rest_admin_service/handlers/approvalextras/handler.go----- - -File: service/rest_admin_service/handlers/approvals/files.go -Lines: 278 ------BEGIN service/rest_admin_service/handlers/approvals/files.go----- -package approvalshandler - -import ( - "bitrix_balancer_api/core/typescore" - "encoding/base64" - "fmt" - "net/http" - "path/filepath" - "strings" - - "github.com/go-chi/chi/v5" -) - -// GetApprovalFileHandler Получение файла заявки -// @Summary Получение файла заявки -// @Description Возвращает файл по ID заявки и ID файла -// @Tags approvals -// @Produce application/octet-stream -// @Param approval_id path integer true "ID заявки" -// @Param file_id path integer true "ID файла" -// @Success 200 {file} binary "Файл" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Файл не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approvals/{approval_id}/files/{file_id} [get] -func (s *ApprovalsReg) GetApprovalFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - ctx := r.Context() - - // Получаем ID из URL - approvalIDStr := chi.URLParam(r, "approval_id") - fileIDStr := chi.URLParam(r, "file_id") - - if approvalIDStr == "" || fileIDStr == "" { - return nil, fmt.Errorf("approval_id and file_id are required") - } - - approvalID, err := parseUint64(approvalIDStr) - if err != nil { - return nil, fmt.Errorf("invalid approval_id: %w", err) - } - - fileID, err := parseUint64(fileIDStr) - if err != nil { - return nil, fmt.Errorf("invalid file_id: %w", err) - } - - // Получаем заявку - approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if err != nil { - return nil, fmt.Errorf("failed to get approval: %w", err) - } - if approval == nil { - return nil, fmt.Errorf("approval not found") - } - - // Ищем файл в заявке - var targetFile *typescore.ApprovalFile - if approval.Files != nil { - for i := range approval.Files { - if approval.Files[i].ID != nil && *approval.Files[i].ID == fileID { - targetFile = approval.Files[i] - break - } - } - } - - // Если файл не найден в кэше, загружаем все файлы заявки - if targetFile == nil { - files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) - if err != nil { - return nil, fmt.Errorf("failed to get files: %w", err) - } - - for i := range files { - if files[i].ID != nil && *files[i].ID == fileID { - targetFile = files[i] - break - } - } - } - - if targetFile == nil { - return nil, fmt.Errorf("file not found") - } - - // Проверяем, что файл существует - if targetFile.FileBase64 == nil || *targetFile.FileBase64 == "" { - return nil, fmt.Errorf("file content is empty") - } - - // Декодируем base64 - fileData, err := base64.StdEncoding.DecodeString(*targetFile.FileBase64) - if err != nil { - return nil, fmt.Errorf("failed to decode file: %w", err) - } - - // Определяем MIME тип - fileName := "" - if targetFile.FileName != nil { - fileName = *targetFile.FileName - } - mimeType := getMimeType(fileName) - - // Устанавливаем заголовки - w.Header().Set("Content-Type", mimeType) - w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, fileName)) - w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileData))) - w.Header().Set("Cache-Control", "public, max-age=31536000") - - // Отправляем файл - w.WriteHeader(http.StatusOK) - _, err = w.Write(fileData) - if err != nil { - return nil, fmt.Errorf("failed to send file: %w", err) - } - - return nil, nil // nil означает, что мы уже отправили ответ -} - -// DownloadApprovalFileHandler Скачивание файла заявки -// @Summary Скачивание файла заявки -// @Description Скачивает файл по ID заявки и ID файла -// @Tags approvals -// @Produce application/octet-stream -// @Param approval_id path integer true "ID заявки" -// @Param file_id path integer true "ID файла" -// @Success 200 {file} binary "Файл" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Файл не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approvals/{approval_id}/files/{file_id}/download [get] -func (s *ApprovalsReg) DownloadApprovalFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - ctx := r.Context() - - approvalIDStr := chi.URLParam(r, "approval_id") - fileIDStr := chi.URLParam(r, "file_id") - - if approvalIDStr == "" || fileIDStr == "" { - return nil, fmt.Errorf("approval_id and file_id are required") - } - - approvalID, err := parseUint64(approvalIDStr) - if err != nil { - return nil, fmt.Errorf("invalid approval_id: %w", err) - } - - fileID, err := parseUint64(fileIDStr) - if err != nil { - return nil, fmt.Errorf("invalid file_id: %w", err) - } - - approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if err != nil { - return nil, fmt.Errorf("failed to get approval: %w", err) - } - if approval == nil { - return nil, fmt.Errorf("approval not found") - } - - var targetFile *typescore.ApprovalFile - if approval.Files != nil { - for i := range approval.Files { - if approval.Files[i].ID != nil && *approval.Files[i].ID == fileID { - targetFile = approval.Files[i] - break - } - } - } - - if targetFile == nil { - files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) - if err != nil { - return nil, fmt.Errorf("failed to get files: %w", err) - } - - for i := range files { - if files[i].ID != nil && *files[i].ID == fileID { - targetFile = files[i] - break - } - } - } - - if targetFile == nil { - return nil, fmt.Errorf("file not found") - } - - if targetFile.FileBase64 == nil || *targetFile.FileBase64 == "" { - return nil, fmt.Errorf("file content is empty") - } - - fileData, err := base64.StdEncoding.DecodeString(*targetFile.FileBase64) - if err != nil { - return nil, fmt.Errorf("failed to decode file: %w", err) - } - - fileName := "" - if targetFile.FileName != nil { - fileName = *targetFile.FileName - } - mimeType := getMimeType(fileName) - - w.Header().Set("Content-Type", mimeType) - w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName)) - w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileData))) - - w.WriteHeader(http.StatusOK) - _, err = w.Write(fileData) - if err != nil { - return nil, fmt.Errorf("failed to send file: %w", err) - } - - return nil, nil -} - -// getMimeType определяет MIME тип по расширению файла -func getMimeType(fileName string) string { - ext := strings.ToLower(filepath.Ext(fileName)) - - mimeTypes := map[string]string{ - // Images - ".jpg": "image/jpeg", - ".jpeg": "image/jpeg", - ".png": "image/png", - ".gif": "image/gif", - ".webp": "image/webp", - ".svg": "image/svg+xml", - ".bmp": "image/bmp", - ".ico": "image/x-icon", - - // PDF - ".pdf": "application/pdf", - - // Documents - ".txt": "text/plain", - ".doc": "application/msword", - ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - ".xls": "application/vnd.ms-excel", - ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - ".csv": "text/csv", - - // Archives - ".zip": "application/zip", - ".rar": "application/vnd.rar", - ".7z": "application/x-7z-compressed", - ".tar": "application/x-tar", - ".gz": "application/gzip", - - // Code - ".json": "application/json", - ".xml": "application/xml", - ".html": "text/html", - ".css": "text/css", - ".js": "application/javascript", - - // Audio/Video - ".mp3": "audio/mpeg", - ".mp4": "video/mp4", - ".avi": "video/x-msvideo", - ".mov": "video/quicktime", - ".wmv": "video/x-ms-wmv", - ".flv": "video/x-flv", - ".webm": "video/webm", - } - - if mimeType, ok := mimeTypes[ext]; ok { - return mimeType - } - - return "application/octet-stream" -} - -// parseUint64 парсит строку в uint64 -func parseUint64(s string) (uint64, error) { - var result uint64 - _, err := fmt.Sscanf(s, "%d", &result) - return result, err -} - ------END service/rest_admin_service/handlers/approvals/files.go----- - -File: service/rest_admin_service/handlers/approvals/handlers.go -Lines: 718 ------BEGIN service/rest_admin_service/handlers/approvals/handlers.go----- -package approvalshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/rest_admin_service/handlers" - "context" - "encoding/json" - "errors" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strconv" - "strings" - "sync" - "time" - - "github.com/go-chi/chi/v5" -) - -// GetApprovalsListHandler Получение списка заявок с расширенной фильтрацией -// @Summary Получение списка заявок -// @Description Получение списка заявок с пагинацией и расширенной фильтрацией -// @Tags approvals -// @Accept json -// @Produce json -// @Param offset query integer false "Смещение для пагинации" -// @Param limit query integer false "Количество записей на странице" -// @Param status query string false "Фильтр по статусу" -// @Param initiator_id query integer false "Фильтр по инициатору" -// @Param topic_id query integer false "Фильтр по теме (одна)" -// @Param topic_ids query string false "Фильтр по темам (через запятую)" -// @Param category_ids query string false "Фильтр по категориям (через запятую)" -// @Param department_id query integer false "Фильтр по отделу" -// @Param date_from query string false "Начальная дата (YYYY-MM-DD)" -// @Param date_to query string false "Конечная дата (YYYY-MM-DD)" -// @Param content query string false "Поиск по тексту заявки" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approvals [get] -func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - filter := typescore.ApprovalFilter{} - - if status := queryParams.Get("status"); status != "" { - filter.Status = &status - } - if initiatorIDStr := queryParams.Get("initiator_id"); initiatorIDStr != "" { - id, err := strconv.ParseUint(initiatorIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid initiator_id") - } - filter.InitiatorID = &id - } - if departmentIDStr := queryParams.Get("department_id"); departmentIDStr != "" { - id, err := strconv.ParseUint(departmentIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid department_id") - } - filter.DepartmentID = &id - } - if idStr := queryParams.Get("id"); idStr != "" { - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid id") - } - filter.ID = &id - } - - contentSearch := queryParams.Get("content") - if contentSearch != "" { - if len(contentSearch) < 2 { - return nil, errors.New("search query must be at least 2 characters") - } - filter.Content = &contentSearch - } - - if topicIDsStr := queryParams.Get("topic_ids"); topicIDsStr != "" { - ids, err := parseUint64Array(topicIDsStr) - if err != nil { - return nil, errors.New("invalid topic_ids") - } - filter.TopicIDs = ids - } else if topicIDStr := queryParams.Get("topic_id"); topicIDStr != "" { - id, err := strconv.ParseUint(topicIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid topic_id") - } - filter.TopicIDs = []uint64{id} - } - - if categoryIDsStr := queryParams.Get("category_ids"); categoryIDsStr != "" { - ids, err := parseUint64Array(categoryIDsStr) - if err != nil { - return nil, errors.New("invalid category_ids") - } - filter.CategoryIDs = ids - } - - if dateFromStr := queryParams.Get("date_from"); dateFromStr != "" { - dateFrom, err := time.Parse("2006-01-02", dateFromStr) - if err != nil { - return nil, errors.New("invalid date_from format, use YYYY-MM-DD") - } - filter.DateFrom = &dateFrom - } - if dateToStr := queryParams.Get("date_to"); dateToStr != "" { - dateTo, err := time.Parse("2006-01-02", dateToStr) - if err != nil { - return nil, errors.New("invalid date_to format, use YYYY-MM-DD") - } - filter.DateTo = &dateTo - } - - offset := uint64(0) - limit := uint64(100) - if offsetStr := queryParams.Get("offset"); offsetStr != "" { - if v, err := strconv.ParseUint(offsetStr, 10, 64); err == nil { - offset = v - } - } - if limitStr := queryParams.Get("limit"); limitStr != "" { - if v, err := strconv.ParseUint(limitStr, 10, 64); err == nil { - limit = v - } - } - - ctx := r.Context() - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok && currentAdmin.IsObserver != nil && *currentAdmin.IsObserver { - if currentAdmin.TelegramID != nil && *currentAdmin.TelegramID > 0 { - if tgUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, *currentAdmin.TelegramID); err == nil && tgUser != nil && tgUser.ID != nil { - filter.ObserverUserID = tgUser.ID - } else { - return &typescore.ApiResponseBase{TotalCount: 0, Data: []*typescore.Approval{}}, nil - } - } else { - return &typescore.ApiResponseBase{TotalCount: 0, Data: []*typescore.Approval{}}, nil - } - } - - approvalsDbLst, total, errW := s.ipc.Database.Approval.GetApprovalsListFilteredDB(ctx, filter, offset, limit) - if errW != nil { - logrus.Errorf("❌ GetApprovalsListHandler error: %v", errW) - return nil, errW - } - - if approvalsDbLst == nil { - approvalsDbLst = []*typescore.Approval{} - } - - s.enrichApprovalsBatch(ctx, approvalsDbLst, false) - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: approvalsDbLst, - }, nil -} - -// parseUint64Array — парсит строку "1,2,3" в []uint64 -func parseUint64Array(s string) ([]uint64, error) { - parts := strings.Split(s, ",") - result := make([]uint64, 0, len(parts)) - for _, p := range parts { - p = strings.TrimSpace(p) - if p == "" { - continue - } - v, err := strconv.ParseUint(p, 10, 64) - if err != nil { - return nil, err - } - result = append(result, v) - } - return result, nil -} - -// GetApprovalByIDHandler Получение заявки по ID -// @Summary Получение заявки по ID -// @Description Получение детальной информации о заявке по её ID со всеми связанными данными -// @Tags approvals -// @Accept json -// @Produce json -// @Param id path integer true "ID заявки" -// @Success 200 {object} typescore.Approval "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Заявка не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approvals/{id} [get] -func (s *ApprovalsReg) GetApprovalByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("approval id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid approval id") - } - - ctx := r.Context() - approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, id) - if err != nil { - return nil, err - } - if approval == nil { - return nil, errors.New("approval not found") - } - - // 🚀 Подгружаем все связанные данные - s.enrichApproval(ctx, approval, true) - - return approval, nil -} - -// UpdateApprovalHandler Обновление заявки -// @Summary Обновление заявки -// @Description Обновление данных заявки (статус, комментарии и т.д.) -// @Tags approvals -// @Accept json -// @Produce json -// @Param request body typescore.Approval true "Данные заявки" -// @Success 200 {object} typescore.Approval "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Заявка не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approvals [put] -func (s *ApprovalsReg) UpdateApprovalHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 UpdateApprovalHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.Approval - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("approval id is required") - } - - ctx := r.Context() - - // Проверяем, что заявка существует - existingApproval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existingApproval == nil { - return nil, errors.New("approval not found") - } - - // 🛡 Если обновляется статус — проверяем валидность перехода - if req.Status != nil && existingApproval.Status != nil { - if !isValidStatusTransition(*existingApproval.Status, *req.Status) { - return nil, errors.New("invalid status transition from " + *existingApproval.Status + " to " + *req.Status) - } - } - - updatedApproval, _, err := s.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - s.enrichApproval(ctx, updatedApproval, true) - - return updatedApproval, nil -} - -// DeleteApprovalHandler Удаление заявки -// @Summary Удаление заявки -// @Description Удаление заявки (только для черновиков) -// @Tags approvals -// @Accept json -// @Produce json -// @Param request body typescore.Approval true "ID заявки для удаления" -// @Success 200 {object} bool "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 403 {object} handlers.ErrorResponse "Нельзя удалить не-черновую заявку" -// @Failure 404 {object} handlers.ErrorResponse "Заявка не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approvals [delete] -func (s *ApprovalsReg) DeleteApprovalHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 DeleteApprovalHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.Approval - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("approval id is required") - } - - ctx := r.Context() - - // Проверяем, что заявка существует - existingApproval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existingApproval == nil { - return nil, errors.New("approval not found") - } - - // 🛡 Можно удалять только черновики - if existingApproval.Status == nil || *existingApproval.Status != "draft" { - return nil, errors.New("only draft approvals can be deleted") - } - - err = s.ipc.Database.Approval.DeleteApprovalDB(ctx, &req) - if err != nil { - return nil, err - } - - return true, nil -} - -// GetApprovalsForReportHandler Получение заявок для отчёта -// @Summary Получение заявок для отчёта -// @Description Получение списка заявок для отчёта с учётом периода и доступа пользователя -// @Tags approvals -// @Accept json -// @Produce json -// @Param user_id query integer false "ID пользователя (если не указан - все заявки)" -// @Param date_from query string false "Начальная дата (YYYY-MM-DD)" -// @Param date_to query string false "Конечная дата (YYYY-MM-DD)" -// @Param all_access query boolean false "Полный доступ (игнорировать фильтрацию по пользователю)" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approvals/report [get] -func (s *ApprovalsReg) GetApprovalsForReportHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - filter := typescore.ReportFilter{} - - if userIDStr := queryParams.Get("user_id"); userIDStr != "" { - userID, err := strconv.ParseUint(userIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid user_id") - } - filter.UserID = &userID - } - - if dateFromStr := queryParams.Get("date_from"); dateFromStr != "" { - dateFrom, err := time.Parse("2006-01-02", dateFromStr) - if err != nil { - return nil, errors.New("invalid date_from format, use YYYY-MM-DD") - } - filter.DateFrom = &dateFrom - } - - if dateToStr := queryParams.Get("date_to"); dateToStr != "" { - dateTo, err := time.Parse("2006-01-02", dateToStr) - if err != nil { - return nil, errors.New("invalid date_to format, use YYYY-MM-DD") - } - filter.DateTo = &dateTo - } - - if allAccessStr := queryParams.Get("all_access"); allAccessStr == "true" { - filter.AllAccess = true - } - - ctx := r.Context() - approvals, err := s.ipc.Database.Approval.GetApprovalsForReportDB(ctx, filter) - if err != nil { - return nil, err - } - - s.enrichApprovalsBatch(ctx, approvals, false) - - return &typescore.ApiResponseBase{ - TotalCount: uint64(len(approvals)), - Data: approvals, - }, nil -} - -// enrichApproval подгружает связанные данные для заявки -// enrichApproval подгружает связанные данные для ОДНОЙ заявки. -// Независимые запросы выполняются параллельно, чтобы сократить суммарную задержку. -func (s *ApprovalsReg) enrichApproval(ctx context.Context, approval *typescore.Approval, loadSteps bool) { - if approval == nil { - return - } - - var wg sync.WaitGroup - - if approval.InitiatorID != nil { - wg.Add(1) - go func() { - defer wg.Done() - if initiator, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); err == nil && initiator != nil { - approval.Initiator = initiator - } - }() - } - - if approval.TopicID != nil { - wg.Add(1) - go func() { - defer wg.Done() - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if err == nil && topic != nil { - approval.Topic = topic - if topic.CategoryID != nil { - if category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID); err == nil && category != nil { - topic.Category = category - } - } - } - }() - } - - if approval.DepartmentID != nil { - wg.Add(1) - go func() { - defer wg.Done() - if department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID); err == nil && department != nil { - approval.Department = department - } - }() - } - - if approval.RevokedByID != nil { - wg.Add(1) - go func() { - defer wg.Done() - if revokedBy, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.RevokedByID); err == nil && revokedBy != nil { - approval.RevokedBy = revokedBy - } - }() - } - - if approval.ID != nil { - wg.Add(1) - go func() { - defer wg.Done() - if files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID); err == nil { - approval.Files = files - } - }() - } - - if loadSteps && approval.ID != nil { - wg.Add(1) - go func() { - defer wg.Done() - steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID}, - }) - if err != nil { - return - } - - // Согласующие подгружаются одним батч-запросом, а не по одному на шаг - approverIDsSet := make(map[uint64]struct{}) - for _, step := range steps { - if step.ApproverID != nil { - approverIDsSet[*step.ApproverID] = struct{}{} - } - } - approverIDs := make([]uint64, 0, len(approverIDsSet)) - for id := range approverIDsSet { - approverIDs = append(approverIDs, id) - } - - if approvers, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, approverIDs); err == nil { - approversMap := make(map[uint64]*typescore.User, len(approvers)) - for _, u := range approvers { - if u.ID != nil { - approversMap[*u.ID] = u - } - } - for _, step := range steps { - if step.ApproverID != nil { - if approver, ok := approversMap[*step.ApproverID]; ok { - step.Approver = approver - } - } - } - } - - approval.Steps = steps - }() - } - - wg.Wait() -} - -// isValidStatusTransition проверяет валидность перехода между статусами -func isValidStatusTransition(from, to string) bool { - validTransitions := map[string][]string{ - "draft": {"pending", "approved", "rejected"}, - "pending": {"approved", "rejected", "revoked", "revision"}, - "approved": {"revoked", "revision"}, - "rejected": {"pending", "revision"}, - "revoked": {"pending"}, - "revision": {"pending"}, - } - - allowed, exists := validTransitions[from] - if !exists { - return false - } - - for _, status := range allowed { - if status == to { - return true - } - } - - return false -} - -// enrichApprovalsBatch выполняет пакетную подгрузку связанных данных для СПИСКА заявок, -// заменяя N+1 отдельных запросов (было: enrichApproval в цикле) несколькими батч-запросами. -func (s *ApprovalsReg) enrichApprovalsBatch(ctx context.Context, approvals []*typescore.Approval, loadSteps bool) { - if len(approvals) == 0 { - return - } - - userIDsSet := make(map[uint64]struct{}) - topicIDsSet := make(map[uint64]struct{}) - departmentIDsSet := make(map[uint64]struct{}) - approvalIDs := make([]uint64, 0, len(approvals)) - - for _, a := range approvals { - if a.InitiatorID != nil { - userIDsSet[*a.InitiatorID] = struct{}{} - } - if a.RevokedByID != nil { - userIDsSet[*a.RevokedByID] = struct{}{} - } - if a.TopicID != nil { - topicIDsSet[*a.TopicID] = struct{}{} - } - if a.DepartmentID != nil { - departmentIDsSet[*a.DepartmentID] = struct{}{} - } - if a.ID != nil { - approvalIDs = append(approvalIDs, *a.ID) - } - } - - userIDs := make([]uint64, 0, len(userIDsSet)) - for id := range userIDsSet { - userIDs = append(userIDs, id) - } - topicIDs := make([]uint64, 0, len(topicIDsSet)) - for id := range topicIDsSet { - topicIDs = append(topicIDs, id) - } - departmentIDs := make([]uint64, 0, len(departmentIDsSet)) - for id := range departmentIDsSet { - departmentIDs = append(departmentIDs, id) - } - - usersMap := make(map[uint64]*typescore.User) - if users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, userIDs); err == nil { - for _, u := range users { - if u.ID != nil { - usersMap[*u.ID] = u - } - } - } - - topicsMap := make(map[uint64]*typescore.ApprovalTopic) - categoryIDsSet := make(map[uint64]struct{}) - if topics, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsByIDsDB(ctx, topicIDs); err == nil { - for _, t := range topics { - if t.ID != nil { - topicsMap[*t.ID] = t - } - if t.CategoryID != nil { - categoryIDsSet[*t.CategoryID] = struct{}{} - } - } - } - - categoryIDs := make([]uint64, 0, len(categoryIDsSet)) - for id := range categoryIDsSet { - categoryIDs = append(categoryIDs, id) - } - categoriesMap := make(map[uint64]*typescore.ApprovalTopicCategory) - if categories, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoriesByIDsDB(ctx, categoryIDs); err == nil { - for _, c := range categories { - if c.ID != nil { - categoriesMap[*c.ID] = c - } - } - } - for _, t := range topicsMap { - if t.CategoryID != nil { - if cat, ok := categoriesMap[*t.CategoryID]; ok { - t.Category = cat - } - } - } - - departmentsMap := make(map[uint64]*typescore.Department) - if departments, err := s.ipc.Database.Department.GetDepartmentsByIDsDB(ctx, departmentIDs); err == nil { - for _, d := range departments { - if d.ID != nil { - departmentsMap[*d.ID] = d - } - } - } - - filesMap := make(map[uint64][]*typescore.ApprovalFile) - if files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDsDB(ctx, approvalIDs); err == nil { - for _, f := range files { - if f.ApprovalID != nil { - filesMap[*f.ApprovalID] = append(filesMap[*f.ApprovalID], f) - } - } - } - - var stepsMap map[uint64][]*typescore.ApprovalStep - if loadSteps { - stepsMap = make(map[uint64][]*typescore.ApprovalStep) - steps, err := s.ipc.Database.ApprovalStep.GetApprovalStepsByApprovalIDsDB(ctx, approvalIDs) - if err == nil { - approverIDsSet := make(map[uint64]struct{}) - for _, st := range steps { - if st.ApprovalID != nil { - stepsMap[*st.ApprovalID] = append(stepsMap[*st.ApprovalID], st) - } - if st.ApproverID != nil { - approverIDsSet[*st.ApproverID] = struct{}{} - } - } - - approverIDs := make([]uint64, 0, len(approverIDsSet)) - for id := range approverIDsSet { - approverIDs = append(approverIDs, id) - } - approversMap := make(map[uint64]*typescore.User) - if approvers, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, approverIDs); err == nil { - for _, u := range approvers { - if u.ID != nil { - approversMap[*u.ID] = u - } - } - } - for _, stepsForApproval := range stepsMap { - for _, st := range stepsForApproval { - if st.ApproverID != nil { - if approver, ok := approversMap[*st.ApproverID]; ok { - st.Approver = approver - } - } - } - } - } - } - - for _, a := range approvals { - if a.InitiatorID != nil { - if u, ok := usersMap[*a.InitiatorID]; ok { - a.Initiator = u - } - } - if a.RevokedByID != nil { - if u, ok := usersMap[*a.RevokedByID]; ok { - a.RevokedBy = u - } - } - if a.TopicID != nil { - if t, ok := topicsMap[*a.TopicID]; ok { - a.Topic = t - } - } - if a.DepartmentID != nil { - if d, ok := departmentsMap[*a.DepartmentID]; ok { - a.Department = d - } - } - if a.ID != nil { - a.Files = filesMap[*a.ID] - if loadSteps { - a.Steps = stepsMap[*a.ID] - } - } - } -} - -// getCurrentAdmin извлекает ID из контекста и получает полные данные администратора из БД -func (s *ApprovalsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - logrus.Warnf("getCurrentAdmin: GetIDFromContext err=%v", err) - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil { - logrus.Warnf("getCurrentAdmin: admin not found for userID=%d err=%v", currentUserID, err) - return nil, false - } - - return admins[0], true -} - ------END service/rest_admin_service/handlers/approvals/handlers.go----- - -File: service/rest_admin_service/handlers/approvals/reports.go -Lines: 73 ------BEGIN service/rest_admin_service/handlers/approvals/reports.go----- -package approvalshandler - -import ( - "bitrix_balancer_api/core/reportcore" - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/rest_admin_service/handlers" - "fmt" - "net/http" - "time" -) - -// DownloadApprovalsReportHandler Скачивание отчёта по заявкам в формате XLSX -// @Summary Скачивание отчёта по заявкам -// @Description Формирует и возвращает XLSX-файл отчёта по заявкам за указанный период -// @Tags approvals -// @Accept json -// @Produce application/vnd.openxmlformats-officedocument.spreadsheetml.sheet -// @Param date_from query string false "Начальная дата (YYYY-MM-DD)" -// @Param date_to query string false "Конечная дата (YYYY-MM-DD)" -// @Param all_access query boolean false "Полный доступ (игнорировать фильтрацию по пользователю)" -// @Success 200 {file} binary "XLSX файл" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/approvals/report/download [get] -func (s *ApprovalsReg) DownloadApprovalsReportHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - filter := typescore.ReportFilter{} - - // Парсим даты - if dateFromStr := queryParams.Get("date_from"); dateFromStr != "" { - dateFrom, err := time.Parse("2006-01-02", dateFromStr) - if err != nil { - return nil, fmt.Errorf("invalid date_from format, use YYYY-MM-DD") - } - filter.DateFrom = &dateFrom - } - - if dateToStr := queryParams.Get("date_to"); dateToStr != "" { - dateTo, err := time.Parse("2006-01-02", dateToStr) - if err != nil { - return nil, fmt.Errorf("invalid date_to format, use YYYY-MM-DD") - } - filter.DateTo = &dateTo - } - - // В админке всегда all_access = true (админ видит все заявки) - filter.AllAccess = true - - ctx := r.Context() - - // Получаем заявки для отчёта - approvals, err := s.ipc.Database.Approval.GetApprovalsForReportDB(ctx, filter) - if err != nil { - return nil, fmt.Errorf("failed to get approvals for report: %w", err) - } - - if len(approvals) == 0 { - return nil, fmt.Errorf("no approvals found for the specified period") - } - - excelBytes, err := reportcore.BuildExcelApprovalsReport(ctx, s.ipc.Database, approvals) - if err != nil { - return nil, fmt.Errorf("failed to build excel report: %w", err) - } - - fileName := fmt.Sprintf("Согласования_%s.xlsx", time.Now().Format("02.01.2006_15-04")) - - return &handlers.ExcelFileResponse{ - Data: excelBytes, - FileName: fileName, - }, nil -} - ------END service/rest_admin_service/handlers/approvals/reports.go----- - -File: service/rest_admin_service/handlers/approvals/routes.go -Lines: 48 ------BEGIN service/rest_admin_service/handlers/approvals/routes.go----- -package approvalshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type ApprovalsReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterApprovalRoutes регистрирует маршруты для группы approvals -func RegisterApprovalRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &ApprovalsReg{ - ipc: ipc, - } - - r.Route("/api/approvals", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetApprovalsListHandler) - handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateApprovalHandler) - handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteApprovalHandler) - - // Отчёты - handlers.RegisterRoute(r, http.MethodGet, "/report", s.GetApprovalsForReportHandler) - handlers.RegisterRoute(r, http.MethodGet, "/report/download", s.DownloadApprovalsReportHandler) - - r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetApprovalByIDHandler, - })) - r.Get("/{approval_id}/files/{file_id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetApprovalFileHandler, - })) - r.Get("/{approval_id}/files/{file_id}/download", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.DownloadApprovalFileHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/approvals/routes.go----- - -File: service/rest_admin_service/handlers/auth/handlers.go -Lines: 204 ------BEGIN service/rest_admin_service/handlers/auth/handlers.go----- -package authhandler - -import ( - "bitrix_balancer_api/core/securecore" - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/core/variables" - "bitrix_balancer_api/rest_admin_service/handlers" - "context" - "encoding/json" - "errors" - "fmt" - "github.com/redis/go-redis/v9" - "io" - "net/http" - "time" - - "github.com/sirupsen/logrus" -) - -// GetServerTimeHandler возвращает текущее серверное время для синхронизации с клиентом -// @Summary Получить серверное время -// @Description Публичный endpoint для синхронизации часов клиента с сервером -// @Tags public -// @Produce json -// @Success 200 {object} map[string]interface{} -// @Router /api/time [get] -func (s *AuthReg) GetServerTimeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - now := time.Now().UTC() - return map[string]interface{}{ - "timestamp": now.Unix(), - "iso": now.Format(time.RFC3339), - }, nil -} - -// TokenAuthHandler -// @Summary Авторизация при помощи JWT-токена -// @Description Авторизация при помощи JWT-токена -// @Tags auth -// @Accept json -// @Produce json -// @Success 200 {object} typescore.AuthHandlerResponse -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/auth/token [post] -func (s *AuthReg) TokenAuthHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - ctx := r.Context() - defer r.Body.Close() - - userID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, err - } - userObjAuthBody := &typescore.Admin{ - ID: &userID, - } - - usersList, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{Filtering: userObjAuthBody}) - if err != nil { - return nil, err - } - - if len(usersList) == 0 { - return nil, errors.New("no users found") - } - - if usersList[0].IsBlocked != nil && *usersList[0].IsBlocked { - return nil, errors.New("user is blocked") - } - - tokens, err := securecore.GenerateTokenJWT("", *usersList[0].ID, r.RemoteAddr, s.ipc.Config.Secrets.AuthJWT.UserSecret, s.ipc.Config.Secrets.AuthJWT.JwtUserSessionLengthHours) - if err != nil { - return nil, err - } - - return &typescore.AuthHandlerResponse{Token: &tokens}, nil -} - -// LoginByPasswordHandler авторизация с помощью связки логин-пароль -// @Summary авторизация с помощью связки логин-пароль -// @Description авторизация с помощью связки логин-пароль -// @Tags auth -// @Accept json -// @Produce json -// @Param request body typescore.AuthReqAccount true "Запрос" -// @Success 200 {object} typescore.AuthHandlerResponse -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/auth/login [post] -func (s *AuthReg) LoginByPasswordHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - ctx := r.Context() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 error LoginByPassword: ReadAll: ", err) - return nil, err - } - - if len(body) == 0 { - return nil, errors.New("body is empty") - } - - deviceID := r.Header.Get("x-device-id") - if deviceID == "" { - return nil, errors.New("device id is empty") - } - - var req typescore.AuthReqAccount - if err := json.Unmarshal(body, &req); err != nil { - return nil, err - } - - tokens, err := s.loginAcc(ctx, req.Login, req.Password, utilscore.GetClientIP(r), deviceID) - if err != nil { - return nil, err - } - if tokens == nil { - return nil, errors.New("token is nil") - } - - return &typescore.AuthHandlerResponse{Token: tokens}, nil -} - -func (s *AuthReg) loginAcc(ctx context.Context, login, password *string, ip, deviceID string) (*string, error) { - usersList, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{Filtering: &typescore.Admin{Login: login}}) - if err != nil { - return nil, err - } - - if usersList == nil || len(usersList) == 0 { - return nil, errors.New("no users found") - } - - loggedUser := usersList[0] - if password != nil && *password != "" { - validPass := securecore.CheckPasswordHash(password, loggedUser.PasswordHash) - if !validPass { - return nil, errors.New("invalid login or password") - } - } - - if loggedUser.IsBlocked != nil && *loggedUser.IsBlocked { - return nil, errors.New("user is blocked") - } - - lastLogin, err := time.Parse("2006-01-02 15:04:05", time.Now().UTC().Format("2006-01-02 15:04:05")) - if err != nil { - return nil, err - } - - keyPath := fmt.Sprintf("%s:admin:%d", variables.RedisPathUserAuthSessions, *loggedUser.ID) - sessionJSON, err := s.ipc.RedisClient.Get(ctx, keyPath) - if err != nil && !errors.Is(err, redis.Nil) { - return nil, err - } - - var session typescore.UsersSessions - - if sessionJSON != "" { - if err := json.Unmarshal([]byte(sessionJSON), &session); err != nil { - return nil, err - } - } else { - session = typescore.UsersSessions{ - UserID: loggedUser.ID, - LastIP: ip, - } - } - - foundDevice := securecore.FindDeviceID(session.AuthorizedDevices, deviceID) - if !foundDevice { - now := time.Now().UTC() - session.AuthorizedDevices = append(session.AuthorizedDevices, typescore.DeviceList{ - DeviceID: deviceID, - CreatedAt: &now, - }) - - sessionJSONBytes, err := json.Marshal(session) - if err != nil { - return nil, fmt.Errorf("failed to marshal session: %w", err) - } - - err = s.ipc.RedisClient.Set(ctx, keyPath, string(sessionJSONBytes), 0) - if err != nil { - return nil, fmt.Errorf("failed to save session to Redis: %w", err) - } - } - - loggedUser.LastLogin = &lastLogin - loggedUser.LastIPLogin = &ip - - upUser, _, err := s.ipc.Database.Admin.UpdateAdminDB(nil, loggedUser, true) - if err != nil { - return nil, err - } - - tokens, err := securecore.GenerateTokenJWT("", *upUser.ID, ip, s.ipc.Config.Secrets.AuthJWT.AdminSecret, s.ipc.Config.Secrets.AuthJWT.JwtAdminSessionLengthHours) - if err != nil { - return nil, err - } - - return &tokens, nil -} - ------END service/rest_admin_service/handlers/auth/handlers.go----- - -File: service/rest_admin_service/handlers/auth/routes.go -Lines: 40 ------BEGIN service/rest_admin_service/handlers/auth/routes.go----- -package authhandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "github.com/go-chi/chi/v5" - "net/http" -) - -const ( - oauthURLogin = "/auth/login" // вход по паролю -) - -type AuthReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterAuthRoutes регистрирует маршруты для группы auth -func RegisterAuthRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &AuthReg{ - ipc: ipc, - } - - handlers.RegisterRoute(r, http.MethodGet, "/api/time", s.GetServerTimeHandler) - - r.Route("/api", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - handlers.RegisterRoute(r, http.MethodPost, oauthURLogin, s.LoginByPasswordHandler) - }) - - r.Route("/api/auth/token", func(r chi.Router) { - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, s.ipc.RedisClient)) - handlers.RegisterRoute(r, http.MethodPost, "/", s.TokenAuthHandler) - }) - - return nil -} - ------END service/rest_admin_service/handlers/auth/routes.go----- - -File: service/rest_admin_service/handlers/dashboard/handlers.go -Lines: 908 ------BEGIN service/rest_admin_service/handlers/dashboard/handlers.go----- -package dashboardhandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "context" - "encoding/json" - "fmt" - "net/http" - "regexp" - "strconv" - "strings" - "time" -) - -// GetDashboardStatsHandler — возвращает все данные для дашборда одним запросом -func (s *DashboardReg) GetDashboardStatsHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - ctx := r.Context() - - // === 1. KPI: считаем сущности === - totalUsers := s.countUsers(ctx, &typescore.User{}) - activeUsers := s.countUsers(ctx, &typescore.User{IsBlocked: boolPtr(false), IsFired: boolPtr(false)}) - blockedUsers := s.countUsers(ctx, &typescore.User{IsBlocked: boolPtr(true)}) - - totalApprovals := s.countApprovals(ctx, &typescore.Approval{}) - pendingApprovals := s.countApprovalsByStatus(ctx, "pending") - revisionApprovals := s.countApprovalsByStatus(ctx, "revision") - approvedToday := s.countApprovalsByStatusAndDate(ctx, "approved", time.Now()) - - totalTopics := s.countTopics(ctx, &typescore.ApprovalTopic{}) - activeTopics := s.countTopics(ctx, &typescore.ApprovalTopic{IsActive: boolPtr(true)}) - totalCategories := s.countCategories(ctx) - totalDepartments := s.countDepartments(ctx) - totalRoles := s.countRoles(ctx) - totalExecutors := s.countExecutors(ctx) - - // === 2. Распределение заявок по статусам === - statuses := []string{"draft", "pending", "approved", "rejected", "revoked", "revision"} - statusData := make([]map[string]interface{}, 0, len(statuses)) - for _, status := range statuses { - count := s.countApprovalsByStatus(ctx, status) - statusData = append(statusData, map[string]interface{}{ - "status": status, - "count": count, - }) - } - - // === 3. Динамика за последние 7 дней === - dailyData := make([]map[string]interface{}, 0, 7) - now := time.Now() - for i := 6; i >= 0; i-- { - date := now.AddDate(0, 0, -i) - created := s.countApprovalsCreatedOn(ctx, date) - approved := s.countApprovalsApprovedOn(ctx, date) - - dailyData = append(dailyData, map[string]interface{}{ - "date": date.Format("2006-01-02"), - "created": created, - "approved": approved, - }) - } - - // === 4. Разбивка по категориям (вместо топ-5 тем) === - categoryBreakdown := s.getCategoryBreakdown(ctx) - - // === 5. Узкие места: согласующие с просроченными заявками (вместо топ-5 по активности) === - bottleneckApprovers := s.getBottleneckApprovers(ctx, 5, 7) - - // === 6. Старые pending заявки (>7 дней) === - oldPendingCount := s.countOldPendingApprovals(ctx, 7) - - // === 7. 🆕 Задачи: распределение по статусам + динамика за 7 дней === - taskStatusData := s.getTaskStatusData(ctx) - taskDailyData := s.getTaskDailyData(ctx) - - // === 8. 🆕 Кто отсутствует сегодня (отгул/отпуск/больничный) === - absentToday := s.getAbsentToday(ctx) - - // === 9. 🆕 Проблемы конфигурации: темы без назначенного порядка - // согласования для конкретного пользователя + пользователи вообще - // без иерархии в своём отделе === - topicGaps, usersWithoutHierarchy := s.getInitiatorConfigWarnings(ctx) - - return map[string]interface{}{ - "users": map[string]int{ - "total": totalUsers, - "active": activeUsers, - "blocked": blockedUsers, - }, - "approvals": map[string]int{ - "total": totalApprovals, - "pending": pendingApprovals, - "revision": revisionApprovals, - "today": approvedToday, - }, - "topics": map[string]int{ - "total": totalTopics, - "active": activeTopics, - }, - "categories": totalCategories, - "departments": totalDepartments, - "roles": totalRoles, - "executors": totalExecutors, - "statusData": statusData, - "dailyData": dailyData, - "categoryBreakdown": categoryBreakdown, - "bottleneckApprovers": bottleneckApprovers, - "oldPendingCount": oldPendingCount, - "oldPendingDays": 7, - "taskStatusData": taskStatusData, - "taskDailyData": taskDailyData, - "absentToday": absentToday, - "topicGaps": topicGaps, - "usersWithoutHierarchy": usersWithoutHierarchy, - }, nil -} - -// ============================================================ -// Вспомогательные методы для подсчёта -// ============================================================ - -func (s *DashboardReg) countUsers(ctx context.Context, filter *typescore.User) int { - opts := typescore.ListDbOptions{ - Filtering: filter, - Limit: utilscore.PointerToUint64(10000), // считаем через len - } - list, _, err := s.ipc.Database.User.GetUsersListDB(ctx, opts) - if err != nil { - return 0 - } - return len(list) -} - -func (s *DashboardReg) countApprovals(ctx context.Context, filter *typescore.Approval) int { - opts := typescore.ListDbOptions{ - Filtering: filter, - Limit: utilscore.PointerToUint64(10000), - } - list, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts) - if err != nil { - return 0 - } - return len(list) -} - -func (s *DashboardReg) countApprovalsByStatus(ctx context.Context, status string) int { - return s.countApprovals(ctx, &typescore.Approval{Status: &status}) -} - -func (s *DashboardReg) countApprovalsByStatusAndDate(ctx context.Context, status string, date time.Time) int { - opts := typescore.ListDbOptions{ - Filtering: &typescore.Approval{Status: &status}, - Limit: utilscore.PointerToUint64(10000), - } - list, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts) - if err != nil { - return 0 - } - - count := 0 - today := date.Format("2006-01-02") - for _, a := range list { - if a.CreatedAt != nil && a.CreatedAt.Format("2006-01-02") == today { - count++ - } - } - return count -} - -func (s *DashboardReg) countApprovalsCreatedOn(ctx context.Context, date time.Time) int { - opts := typescore.ListDbOptions{ - Filtering: &typescore.Approval{}, - Limit: utilscore.PointerToUint64(10000), - } - list, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts) - if err != nil { - return 0 - } - - count := 0 - target := date.Format("2006-01-02") - for _, a := range list { - if a.CreatedAt != nil && a.CreatedAt.Format("2006-01-02") == target { - count++ - } - } - return count -} - -func (s *DashboardReg) countApprovalsApprovedOn(ctx context.Context, date time.Time) int { - opts := typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{Status: strPtr("approved")}, - Limit: utilscore.PointerToUint64(10000), - } - steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, opts) - if err != nil { - return 0 - } - - uniqueApprovals := make(map[uint64]bool) - target := date.Format("2006-01-02") - for _, step := range steps { - if step.ActedAt != nil && step.ActedAt.Format("2006-01-02") == target && step.ApprovalID != nil { - uniqueApprovals[*step.ApprovalID] = true - } - } - return len(uniqueApprovals) -} - -func (s *DashboardReg) countTopics(ctx context.Context, filter *typescore.ApprovalTopic) int { - opts := typescore.ListDbOptions{ - Filtering: filter, - Limit: utilscore.PointerToUint64(10000), - } - list, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, opts) - if err != nil { - return 0 - } - return len(list) -} - -func (s *DashboardReg) countCategories(ctx context.Context) int { - opts := typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopicCategory{}, - Limit: utilscore.PointerToUint64(10000), - } - list, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, opts) - if err != nil { - return 0 - } - return len(list) -} - -func (s *DashboardReg) countDepartments(ctx context.Context) int { - opts := typescore.ListDbOptions{ - Filtering: &typescore.Department{}, - Limit: utilscore.PointerToUint64(10000), - } - list, _, err := s.ipc.Database.Department.GetDepartmentsListDB(ctx, opts) - if err != nil { - return 0 - } - return len(list) -} - -func (s *DashboardReg) countRoles(ctx context.Context) int { - opts := typescore.ListDbOptions{ - Filtering: &typescore.Role{}, - Limit: utilscore.PointerToUint64(10000), - } - list, _, err := s.ipc.Database.Role.GetRolesListDB(ctx, opts) - if err != nil { - return 0 - } - return len(list) -} - -func (s *DashboardReg) countExecutors(ctx context.Context) int { - opts := typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopicExecutor{}, - Limit: utilscore.PointerToUint64(10000), - } - list, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, opts) - if err != nil { - return 0 - } - return len(list) -} - -func (s *DashboardReg) countOldPendingApprovals(ctx context.Context, days int) int { - opts := typescore.ListDbOptions{ - Filtering: &typescore.Approval{Status: strPtr("pending")}, - Limit: utilscore.PointerToUint64(10000), - } - list, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts) - if err != nil { - return 0 - } - - cutoff := time.Now().AddDate(0, 0, -days) - count := 0 - for _, a := range list { - if a.CreatedAt != nil && a.CreatedAt.Before(cutoff) { - count++ - } - } - return count -} - -// ============================================================ -// Разбивка заявок по категориям (заменяет прежний "топ-5 тем"). -// ============================================================ - -func (s *DashboardReg) getCategoryBreakdown(ctx context.Context) []map[string]interface{} { - topicOpts := typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{}, - Limit: utilscore.PointerToUint64(10000), - } - topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, topicOpts) - if err != nil { - return []map[string]interface{}{} - } - topicToCategory := make(map[uint64]uint64, len(topics)) - for _, t := range topics { - if t.ID != nil && t.CategoryID != nil { - topicToCategory[*t.ID] = *t.CategoryID - } - } - - categoryOpts := typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopicCategory{}, - Limit: utilscore.PointerToUint64(10000), - } - categories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, categoryOpts) - if err != nil { - return []map[string]interface{}{} - } - categoryNames := make(map[uint64]string, len(categories)) - for _, c := range categories { - if c.ID != nil && c.Name != nil { - categoryNames[*c.ID] = *c.Name - } - } - - approvalOpts := typescore.ListDbOptions{ - Filtering: &typescore.Approval{}, - Limit: utilscore.PointerToUint64(10000), - } - approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, approvalOpts) - if err != nil { - return []map[string]interface{}{} - } - - type catStat struct { - total int - pending int - } - byCategory := make(map[uint64]*catStat) - for _, a := range approvals { - if a.TopicID == nil { - continue - } - categoryID, ok := topicToCategory[*a.TopicID] - if !ok { - continue - } - if byCategory[categoryID] == nil { - byCategory[categoryID] = &catStat{} - } - byCategory[categoryID].total++ - if a.Status != nil && *a.Status == "pending" { - byCategory[categoryID].pending++ - } - } - - type entry struct { - id uint64 - total int - pending int - } - entries := make([]entry, 0, len(byCategory)) - for id, st := range byCategory { - entries = append(entries, entry{id: id, total: st.total, pending: st.pending}) - } - for i := 0; i < len(entries); i++ { - for j := i + 1; j < len(entries); j++ { - if entries[j].total > entries[i].total { - entries[i], entries[j] = entries[j], entries[i] - } - } - } - - result := make([]map[string]interface{}, 0, len(entries)) - for _, e := range entries { - name := categoryNames[e.id] - if name == "" { - continue - } - result = append(result, map[string]interface{}{ - "id": e.id, - "name": name, - "total_count": e.total, - "pending_count": e.pending, - }) - } - - return result -} - -// ============================================================ -// Узкие места: согласующие с просроченными (>days дней с подачи) заявками. -// ============================================================ - -func (s *DashboardReg) getBottleneckApprovers(ctx context.Context, limit int, days int) []map[string]interface{} { - stepOpts := typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{Status: strPtr("pending")}, - Limit: utilscore.PointerToUint64(10000), - } - steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, stepOpts) - if err != nil { - return []map[string]interface{}{} - } - - cutoff := time.Now().AddDate(0, 0, -days) - - type approverStat struct { - pendingTotal int - overdue int - } - stats := make(map[uint64]*approverStat) - - for _, step := range steps { - if step.ApproverID == nil || step.ApprovalID == nil { - continue - } - approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID) - if err != nil || approval == nil || approval.CreatedAt == nil { - continue - } - - id := *step.ApproverID - if stats[id] == nil { - stats[id] = &approverStat{} - } - stats[id].pendingTotal++ - if approval.CreatedAt.Before(cutoff) { - stats[id].overdue++ - } - } - - type entry struct { - id uint64 - pendingTotal int - overdue int - } - entries := make([]entry, 0, len(stats)) - for id, st := range stats { - if st.overdue == 0 { - continue - } - entries = append(entries, entry{id: id, pendingTotal: st.pendingTotal, overdue: st.overdue}) - } - for i := 0; i < len(entries); i++ { - for j := i + 1; j < len(entries); j++ { - if entries[j].overdue > entries[i].overdue { - entries[i], entries[j] = entries[j], entries[i] - } - } - } - - result := make([]map[string]interface{}, 0, limit) - for i := 0; i < len(entries) && i < limit; i++ { - e := entries[i] - user, err := s.ipc.Database.User.GetUserByIDDB(ctx, e.id) - if err != nil || user == nil { - continue - } - - fullName := "" - if user.FullName != nil { - fullName = *user.FullName - } - - deptName := "" - if user.DepartmentID != nil { - dept, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *user.DepartmentID) - if err == nil && dept != nil && dept.Name != nil { - deptName = *dept.Name - } - } - - result = append(result, map[string]interface{}{ - "user_id": e.id, - "full_name": fullName, - "department_name": deptName, - "pending_total": e.pendingTotal, - "overdue_count": e.overdue, - }) - } - - return result -} - -// ============================================================ -// 🆕 Задачи: распределение по статусам + динамика за 7 дней. -// Полностью аналогично разделам про заявки — те же графики, другая -// таблица (ApprovalTask вместо Approval). -// ============================================================ - -func (s *DashboardReg) getTaskStatusData(ctx context.Context) []map[string]interface{} { - statuses := []string{"pending", "waiting", "completed", "cancelled"} - result := make([]map[string]interface{}, 0, len(statuses)) - for _, status := range statuses { - st := status - opts := typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTask{Status: &st}, - Limit: utilscore.PointerToUint64(10000), - } - list, _, err := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, opts) - count := 0 - if err == nil { - count = len(list) - } - result = append(result, map[string]interface{}{ - "status": status, - "count": count, - }) - } - return result -} - -func (s *DashboardReg) getTaskDailyData(ctx context.Context) []map[string]interface{} { - opts := typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTask{}, - Limit: utilscore.PointerToUint64(10000), - } - tasks, _, err := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, opts) - if err != nil { - tasks = nil - } - - result := make([]map[string]interface{}, 0, 7) - now := time.Now() - for i := 6; i >= 0; i-- { - date := now.AddDate(0, 0, -i) - target := date.Format("2006-01-02") - - created := 0 - completed := 0 - for _, t := range tasks { - if t.CreatedAt != nil && t.CreatedAt.Format("2006-01-02") == target { - created++ - } - if t.CompletedAt != nil && t.CompletedAt.Format("2006-01-02") == target { - completed++ - } - } - - result = append(result, map[string]interface{}{ - "date": target, - "created": created, - "completed": completed, - }) - } - return result -} - -// ============================================================ -// 🆕 Кто отсутствует сегодня (отгул/отпуск/больничный). -// -// 🩹 Логика разбора дат намеренно продублирована из -// scheduler/daily_reminder.go (getAbsentEmployeesToday) — тот же самый -// терпимый к опечаткам подход через regexp, т.к. у заявок на отсутствие -// нет отдельного структурированного поля с датами. rest_admin_service -// использует свой ipc-тип, отличный от telegram_service, поэтому -// переиспользовать функцию напрямую нельзя — общий пакет пока не заводили. -// -// Упрощение по сравнению с ботом: здесь НЕ подмешивается контакт-делегат -// (ApprovalDelegation) — просто список отсутствующих с описанием. -// ============================================================ - -type dashboardAbsenceMetadata struct { - Extra struct { - TimeType string `json:"time_type"` - AbsenceType string `json:"absence_type"` - } `json:"extra"` -} - -var dashboardAbsenceDateRe = regexp.MustCompile(`(\d{1,2})[.,](\d{1,2})\.(\d{4})`) -var dashboardAbsenceTimeRe = regexp.MustCompile(`(?:с|от)\s*(\d{1,2})[:\.](\d{2})\s*(?:до|по|-|—|–)\s*(\d{1,2})[:\.](\d{2})`) - -func (s *DashboardReg) getAbsentToday(ctx context.Context) []map[string]interface{} { - loc, err := time.LoadLocation("Europe/Moscow") - if err != nil { - loc = time.FixedZone("MSK", 3*3600) - } - today := time.Now().In(loc) - todayY, todayM, todayD := today.Date() - - approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Approval{Status: strPtr("approved")}, - Limit: utilscore.PointerToUint64(10000), - }) - if err != nil { - return []map[string]interface{}{} - } - - seenUsers := make(map[uint64]bool) - result := []map[string]interface{}{} - - for _, a := range approvals { - if a.Metadata == nil || *a.Metadata == "" || a.Content == nil || a.InitiatorID == nil { - continue - } - if seenUsers[*a.InitiatorID] { - continue - } - - var meta dashboardAbsenceMetadata - if err := json.Unmarshal([]byte(*a.Metadata), &meta); err != nil || meta.Extra.AbsenceType == "" { - continue - } - - dates := parseDashboardAbsenceDates(*a.Content) - if len(dates) == 0 || !dashboardAbsenceCoversDate(dates, *a.Content, todayY, todayM, todayD) { - continue - } - - name := "" - if user, uErr := s.ipc.Database.User.GetUserByIDDB(ctx, *a.InitiatorID); uErr == nil && user != nil && user.FullName != nil { - name = *user.FullName - } - - var description string - switch meta.Extra.AbsenceType { - case "timeoff": - if meta.Extra.TimeType == "partial" { - if mm := dashboardAbsenceTimeRe.FindStringSubmatch(*a.Content); mm != nil { - description = "отгул с " + mm[1] + ":" + mm[2] + " до " + mm[3] + ":" + mm[4] - } else { - description = "отгул весь день" - } - } else { - description = "отгул весь день" - } - case "vacation": - description = "отпуск до " + maxDashboardAbsenceDate(dates).Format("02.01.2006") - case "sickleave": - description = "больничный до " + maxDashboardAbsenceDate(dates).Format("02.01.2006") - default: - description = "отсутствует" - } - - seenUsers[*a.InitiatorID] = true - result = append(result, map[string]interface{}{ - "name": name, - "description": description, - }) - } - - return result -} - -func parseDashboardAbsenceDates(content string) []time.Time { - matches := dashboardAbsenceDateRe.FindAllStringSubmatch(content, -1) - var dates []time.Time - for _, m := range matches { - day, errD := strconv.Atoi(m[1]) - month, errM := strconv.Atoi(m[2]) - year, errY := strconv.Atoi(m[3]) - if errD != nil || errM != nil || errY != nil { - continue - } - if month < 1 || month > 12 || day < 1 || day > 31 { - continue - } - dates = append(dates, time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)) - } - return dates -} - -func dashboardAbsenceCoversDate(dates []time.Time, content string, y int, m time.Month, d int) bool { - target := time.Date(y, m, d, 0, 0, 0, 0, time.UTC) - if len(dates) == 2 && strings.Contains(content, "-") { - start, end := dates[0], dates[1] - if end.Before(start) { - start, end = end, start - } - return !target.Before(start) && !target.After(end) - } - for _, dt := range dates { - if dt.Equal(target) { - return true - } - } - return false -} - -func maxDashboardAbsenceDate(dates []time.Time) time.Time { - max := dates[0] - for _, d := range dates[1:] { - if d.After(max) { - max = d - } - } - return max -} - -// ============================================================ -// 🆕 Проблемы конфигурации инициаторов. -// -// Воспроизводит ТУ ЖЕ логику резолва согласующих, что и сам бот при -// реальной отправке заявки (submitApproval → UserHierarchy по -// SubordinateID+DepartmentID, с приоритетом TopicID → TopicCategoryID → -// глобальное правило) — но заранее, для ВСЕХ пользователей и ВСЕХ тем, -// на которые у них есть право "create", чтобы найти дыры ДО того, как -// сотрудник наткнётся на них в боте ("⚠️ Для вас в данной теме не -// настроены согласующие"). -// -// Возвращает два среза: -// 1. topicGaps — точечные пробелы: у пользователя ЕСТЬ право создавать -// заявку по теме, но НИ ОДНО правило иерархии её не покрывает. -// 2. usersWithoutHierarchy — более базовый случай: у пользователя нет -// вообще ни одной строки UserHierarchy для его отдела (полностью -// не настроен, даже глобального правила нет). -// -// ⚠️ Предположения, которые стоит проверить при первом запуске: -// - Permission.GetUserPermissionsDB(ctx, userID, "create") доступен -// из rest_admin_service так же, как используется ботом -// (telegram_service/handlers/approval, getAllowedTopicCodes) — -// сама структура Permission (поля TopicID/TopicCategoryID) взята -// оттуда же, полностью структуру Permission я не видел. -// - Пользователи без DepartmentID пропускаются целиком (это отдельная, -// более базовая проблема — некому резолвить иерархию в принципе, -// не про конкретные темы). -// ============================================================ - -func (s *DashboardReg) getInitiatorConfigWarnings(ctx context.Context) ([]map[string]interface{}, []map[string]interface{}) { - users, _, err := s.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.User{IsBlocked: boolPtr(false), IsFired: boolPtr(false)}, - Limit: utilscore.PointerToUint64(10000), - }) - if err != nil { - return []map[string]interface{}{}, []map[string]interface{}{} - } - - topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{IsActive: boolPtr(true)}, - Limit: utilscore.PointerToUint64(10000), - }) - if err != nil { - return []map[string]interface{}{}, []map[string]interface{}{} - } - - categories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ - Limit: utilscore.PointerToUint64(10000), - }) - categoryNames := make(map[uint64]string, len(categories)) - if err == nil { - for _, c := range categories { - if c.ID != nil && c.Name != nil { - categoryNames[*c.ID] = *c.Name - } - } - } - - departments, _, err := s.ipc.Database.Department.GetDepartmentsListDB(ctx, typescore.ListDbOptions{ - Limit: utilscore.PointerToUint64(10000), - }) - departmentNames := make(map[uint64]string, len(departments)) - if err == nil { - for _, d := range departments { - if d.ID != nil && d.Name != nil { - departmentNames[*d.ID] = *d.Name - } - } - } - - topicByID := make(map[uint64]*typescore.ApprovalTopic, len(topics)) - topicsByCategory := make(map[uint64][]*typescore.ApprovalTopic) - for _, t := range topics { - if t.ID == nil { - continue - } - topicByID[*t.ID] = t - if t.CategoryID != nil { - topicsByCategory[*t.CategoryID] = append(topicsByCategory[*t.CategoryID], t) - } - } - - hierarchies, _, err := s.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{ - Limit: utilscore.PointerToUint64(10000), - }) - if err != nil { - return []map[string]interface{}{}, []map[string]interface{}{} - } - - type coverage struct { - topics map[uint64]bool - categories map[uint64]bool - global bool - } - coverageKey := func(userID, deptID uint64) string { - return fmt.Sprintf("%d:%d", userID, deptID) - } - coverageByUserDept := make(map[string]*coverage) - for _, h := range hierarchies { - if h.SubordinateID == nil || h.DepartmentID == nil { - continue - } - k := coverageKey(*h.SubordinateID, *h.DepartmentID) - cov, ok := coverageByUserDept[k] - if !ok { - cov = &coverage{topics: map[uint64]bool{}, categories: map[uint64]bool{}} - coverageByUserDept[k] = cov - } - switch { - case h.TopicID != nil: - cov.topics[*h.TopicID] = true - case h.TopicCategoryID != nil: - cov.categories[*h.TopicCategoryID] = true - default: - cov.global = true - } - } - - isCovered := func(userID, deptID, topicID uint64, categoryID *uint64) bool { - cov, ok := coverageByUserDept[coverageKey(userID, deptID)] - if !ok { - return false - } - if cov.global { - return true - } - if cov.topics[topicID] { - return true - } - if categoryID != nil && cov.categories[*categoryID] { - return true - } - return false - } - - var topicGaps []map[string]interface{} - var usersWithoutHierarchy []map[string]interface{} - - for _, user := range users { - if user.ID == nil || user.DepartmentID == nil { - continue - } - - perms, err := s.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "create") - if err != nil || len(perms) == 0 { - continue // нет права создавать ничего — не наша забота здесь - } - - userName := "" - if user.FullName != nil { - userName = *user.FullName - } - deptName := departmentNames[*user.DepartmentID] - - // --- Проверка "вообще нет иерархии для этого отдела" --- - if _, hasAny := coverageByUserDept[coverageKey(*user.ID, *user.DepartmentID)]; !hasAny { - usersWithoutHierarchy = append(usersWithoutHierarchy, map[string]interface{}{ - "user_id": *user.ID, - "full_name": userName, - "department_name": deptName, - }) - continue // если вообще ничего нет — детальный разбор по темам избыточен - } - - // --- Точечные пробелы по темам --- - allowedTopicIDs := make(map[uint64]bool) - for _, p := range perms { - if p.TopicID != nil { - allowedTopicIDs[*p.TopicID] = true - } - if p.TopicCategoryID != nil { - for _, t := range topicsByCategory[*p.TopicCategoryID] { - if t.ID != nil { - allowedTopicIDs[*t.ID] = true - } - } - } - } - - for topicID := range allowedTopicIDs { - topic := topicByID[topicID] - if topic == nil { - continue - } - if isCovered(*user.ID, *user.DepartmentID, topicID, topic.CategoryID) { - continue - } - - topicName := "" - if topic.Name != nil { - topicName = *topic.Name - } - categoryName := "" - if topic.CategoryID != nil { - categoryName = categoryNames[*topic.CategoryID] - } - - topicGaps = append(topicGaps, map[string]interface{}{ - "user_id": *user.ID, - "full_name": userName, - "department_name": deptName, - "topic_id": topicID, - "topic_name": topicName, - "category_name": categoryName, - }) - } - } - - if topicGaps == nil { - topicGaps = []map[string]interface{}{} - } - if usersWithoutHierarchy == nil { - usersWithoutHierarchy = []map[string]interface{}{} - } - - return topicGaps, usersWithoutHierarchy -} - -func boolPtr(b bool) *bool { return &b } -func strPtr(s string) *string { return &s } - ------END service/rest_admin_service/handlers/dashboard/handlers.go----- - -File: service/rest_admin_service/handlers/dashboard/routes.go -Lines: 33 ------BEGIN service/rest_admin_service/handlers/dashboard/routes.go----- -package dashboardhandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type DashboardReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterDashboardRoutes регистрирует маршруты для дашборда -func RegisterDashboardRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &DashboardReg{ - ipc: ipc, - } - - r.Route("/api/dashboard", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - // 📊 Основная статистика (всё сразу одним запросом) - handlers.RegisterRoute(r, http.MethodGet, "/stats", s.GetDashboardStatsHandler) - }) - - return nil -} - ------END service/rest_admin_service/handlers/dashboard/routes.go----- - -File: service/rest_admin_service/handlers/departments/handlers.go -Lines: 344 ------BEGIN service/rest_admin_service/handlers/departments/handlers.go----- -package departmentshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - "context" - "encoding/json" - "errors" - "fmt" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strconv" - "strings" - - "github.com/go-chi/chi/v5" -) - -// GetDepartmentsListHandler Получение списка отделов -// @Summary Получение списка отделов -// @Description Получение списка отделов с пагинацией и фильтрацией -// @Tags departments -// @Accept json -// @Produce json -// @Param offset query integer false "Смещение для пагинации" -// @Param limit query integer false "Количество записей на странице" -// @Param is_active query boolean false "Фильтр по активности" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/departments [get] -func (s *DepartmentsReg) GetDepartmentsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - departmentParams := &typescore.Department{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, departmentParams) - if errW != nil { - return nil, errW - } - - options := typescore.ListDbOptions{ - Filtering: departmentParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - ctx := r.Context() - departmentsDbLst, total, errW := s.ipc.Database.Department.GetDepartmentsListDB(ctx, options) - if errW != nil { - return nil, errW - } - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: departmentsDbLst, - }, nil -} - -// GetDepartmentByIDHandler Получение отдела по ID -// @Summary Получение отдела по ID -// @Description Получение детальной информации об отделе по его ID -// @Tags departments -// @Accept json -// @Produce json -// @Param id path integer true "ID отдела" -// @Success 200 {object} typescore.Department "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Отдел не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/departments/{id} [get] -func (s *DepartmentsReg) GetDepartmentByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("department id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid department id") - } - - ctx := r.Context() - department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, id) - if err != nil { - return nil, err - } - - if department == nil { - return nil, errors.New("department not found") - } - - return department, nil -} - -// CreateDepartmentHandler Создание отдела -// @Summary Создание отдела -// @Description Создание нового отдела -// @Tags departments -// @Accept json -// @Produce json -// @Param request body typescore.Department true "Данные отдела" -// @Success 200 {object} typescore.Department "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/departments [post] -func (s *DepartmentsReg) CreateDepartmentHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 CreateDepartmentHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.Department - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.Name == nil || *req.Name == "" { - return nil, errors.New("department name is required") - } - if req.Code == nil || *req.Code == "" { - return nil, errors.New("department code is required") - } - - ctx := r.Context() - existingDepts, _, err := s.ipc.Database.Department.GetDepartmentsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Department{Code: req.Code}, - }) - if err != nil { - return nil, err - } - if len(existingDepts) > 0 { - return nil, errors.New("department code already exists") - } - - if req.IsActive == nil { - isActive := true - req.IsActive = &isActive - } - - createdDept, _, err := s.ipc.Database.Department.CreateDepartmentDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "name": utilscore.DerefStr(createdDept.Name), - "code": utilscore.DerefStr(createdDept.Code), - "is_active": utilscore.DerefBool(createdDept.IsActive), - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "create", "department", createdDept.ID, - fmt.Sprintf("Создан отдел «%s»", utilscore.DerefStr(createdDept.Name)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return createdDept, nil -} - -// UpdateDepartmentHandler Обновление отдела -// @Summary Обновление отдела -// @Description Обновление данных существующего отдела -// @Tags departments -// @Accept json -// @Produce json -// @Param request body typescore.Department true "Данные отдела" -// @Success 200 {object} typescore.Department "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Отдел не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/departments [put] -func (s *DepartmentsReg) UpdateDepartmentHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 UpdateDepartmentHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.Department - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("department id is required") - } - - ctx := r.Context() - existingDept, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existingDept == nil { - return nil, errors.New("department not found") - } - - if req.Code != nil && *req.Code != "" { - if existingDept.Code == nil || *existingDept.Code != *req.Code { - existingDepts, _, err := s.ipc.Database.Department.GetDepartmentsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Department{Code: req.Code}, - }) - if err != nil { - return nil, err - } - if len(existingDepts) > 0 { - return nil, errors.New("department code already exists") - } - } - } - - type fieldChange struct { - Field string `json:"field"` - Old interface{} `json:"old"` - New interface{} `json:"new"` - } - var changes []fieldChange - var summary []string - - if req.Name != nil && !utilscore.StrEq(existingDept.Name, req.Name) { - changes = append(changes, fieldChange{"name", utilscore.DerefStr(existingDept.Name), *req.Name}) - summary = append(summary, fmt.Sprintf("название: «%s» → «%s»", utilscore.DerefStr(existingDept.Name), *req.Name)) - } - if req.Code != nil && !utilscore.StrEq(existingDept.Code, req.Code) { - changes = append(changes, fieldChange{"code", utilscore.DerefStr(existingDept.Code), *req.Code}) - summary = append(summary, fmt.Sprintf("код: «%s» → «%s»", utilscore.DerefStr(existingDept.Code), *req.Code)) - } - if req.IsActive != nil && !utilscore.BoolEq(existingDept.IsActive, req.IsActive) { - changes = append(changes, fieldChange{"is_active", utilscore.DerefBool(existingDept.IsActive), *req.IsActive}) - if *req.IsActive { - summary = append(summary, "активирован") - } else { - summary = append(summary, "деактивирован") - } - } - - updatedDept, _, err := s.ipc.Database.Department.UpdateDepartmentDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - if len(changes) > 0 { - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - description := fmt.Sprintf("Изменён отдел «%s»: %s", utilscore.DerefStr(existingDept.Name), strings.Join(summary, "; ")) - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "department", req.ID, - description, - map[string]interface{}{"changes": changes}, - ) - } - } - - return updatedDept, nil -} - -// DeleteDepartmentHandler Удаление отдела -// @Summary Удаление отдела -// @Description Удаление отдела по ID -// @Tags departments -// @Accept json -// @Produce json -// @Param request body typescore.Department true "ID отдела для удаления" -// @Success 200 {object} bool "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Отдел не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/departments [delete] -func (s *DepartmentsReg) DeleteDepartmentHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 DeleteDepartmentHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.Department - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("department id is required") - } - - ctx := r.Context() - existingDept, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existingDept == nil { - return nil, errors.New("department not found") - } - - err = s.ipc.Database.Department.DeleteDepartmentDB(ctx, &req) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "name": utilscore.DerefStr(existingDept.Name), - "code": utilscore.DerefStr(existingDept.Code), - "is_active": utilscore.DerefBool(existingDept.IsActive), - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "delete", "department", req.ID, - fmt.Sprintf("Удалён отдел «%s»", utilscore.DerefStr(existingDept.Name)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return true, nil -} - -func (s *DepartmentsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - return nil, false - } - - return admins[0], true -} - ------END service/rest_admin_service/handlers/departments/handlers.go----- - -File: service/rest_admin_service/handlers/departments/routes.go -Lines: 47 ------BEGIN service/rest_admin_service/handlers/departments/routes.go----- -package departmentshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type DepartmentsReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterDepartmentRoutes регистрирует маршруты для группы departments -func RegisterDepartmentRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &DepartmentsReg{ - ipc: ipc, - } - - r.Route("/api/departments", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - // GET /api/departments - список отделов - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetDepartmentsListHandler) - - // POST /api/departments - создание отдела - handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateDepartmentHandler) - - // PUT /api/departments - обновление отдела - handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateDepartmentHandler) - - // DELETE /api/departments - удаление отдела - handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteDepartmentHandler) - - // GET /api/departments/{id} - получение отдела по ID - r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetDepartmentByIDHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/departments/routes.go----- - -File: service/rest_admin_service/handlers/flow_nodes/handler.go -Lines: 837 ------BEGIN service/rest_admin_service/handlers/flow_nodes/handler.go----- -package nodeshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "strconv" - - "github.com/go-chi/chi/v5" -) - -func (s *FlowNodesReg) GetFlowNodesByCategoryIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - categoryIDStr := chi.URLParam(r, "category_id") - categoryID, err := strconv.ParseUint(categoryIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid category_id") - } - - ctx := r.Context() - - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID) - if err != nil { - return nil, err - } - if category == nil { - return nil, errors.New("category not found") - } - - nodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID}, - }) - if err != nil { - return nil, err - } - - tree := s.buildTreeFromNodes(nodes) - - return &typescore.ApiResponseBase{ - TotalCount: uint64(len(nodes)), - Data: tree, - }, nil -} - -func (s *FlowNodesReg) GetFlowNodeByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("node id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid node id") - } - - ctx := r.Context() - node, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id) - if err != nil { - return nil, err - } - if node == nil { - return nil, errors.New("node not found") - } - - return node, nil -} - -func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - body, err := io.ReadAll(r.Body) - if err != nil { - return nil, err - } - - var req typescore.ApprovalFlowNode - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.CategoryID == nil { - return nil, errors.New("category_id is required") - } - if req.Key == nil || *req.Key == "" { - return nil, errors.New("key is required") - } - if req.Label == nil || *req.Label == "" { - return nil, errors.New("label is required") - } - - ctx := r.Context() - - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.CategoryID) - if err != nil { - return nil, err - } - if category == nil { - return nil, errors.New("category not found") - } - - if req.ParentID != nil { - parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ParentID) - if err != nil { - return nil, err - } - if parent == nil { - return nil, errors.New("parent node not found") - } - if parent.CategoryID == nil || *parent.CategoryID != *req.CategoryID { - return nil, errors.New("parent node belongs to a different category") - } - } - - existing, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalFlowNode{ - CategoryID: req.CategoryID, - Key: req.Key, - }, - }) - if err != nil { - return nil, err - } - if len(existing) > 0 { - return nil, fmt.Errorf("node with key '%s' already exists in this category", *req.Key) - } - - if req.IsInput == nil { - v := false - req.IsInput = &v - } - if req.IsMultiSelect == nil { - v := false - req.IsMultiSelect = &v - } - if req.SortOrder == nil { - v := 0 - req.SortOrder = &v - } - - created, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - s.bumpFlowVersion(ctx) - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "key": utilscore.DerefStr(created.Key), - "label": utilscore.DerefStr(created.Label), - "category_id": *req.CategoryID, - } - if created.ParentID != nil { - snapshot["parent_id"] = *created.ParentID - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "create", "flow_node", created.ID, - fmt.Sprintf("Создан узел «%s» (%s)", utilscore.DerefStr(created.Label), utilscore.DerefStr(created.Key)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return created, nil -} - -func (s *FlowNodesReg) UpdateFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - body, err := io.ReadAll(r.Body) - if err != nil { - return nil, err - } - - var req typescore.ApprovalFlowNode - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("id is required") - } - - ctx := r.Context() - - existing, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existing == nil { - return nil, errors.New("node not found") - } - - if req.ParentID != nil && (existing.ParentID == nil || *existing.ParentID != *req.ParentID) { - parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ParentID) - if err != nil { - return nil, err - } - if parent == nil { - return nil, errors.New("parent node not found") - } - if parent.CategoryID == nil || existing.CategoryID == nil || *parent.CategoryID != *existing.CategoryID { - return nil, errors.New("parent node belongs to a different category") - } - if err := s.checkNoCyclicReference(ctx, *req.ID, *req.ParentID); err != nil { - return nil, err - } - } - - if req.Key != nil && *req.Key != "" { - if existing.Key == nil || *existing.Key != *req.Key { - categoryID := existing.CategoryID - if req.CategoryID != nil { - categoryID = req.CategoryID - } - existingNodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalFlowNode{ - CategoryID: categoryID, - Key: req.Key, - }, - }) - if err != nil { - return nil, err - } - if len(existingNodes) > 0 { - return nil, fmt.Errorf("node with key '%s' already exists in this category", *req.Key) - } - } - } - - type fieldChange struct { - Field string `json:"field"` - Old interface{} `json:"old"` - New interface{} `json:"new"` - } - var changes []fieldChange - - if req.Key != nil && !utilscore.StrEq(existing.Key, req.Key) { - changes = append(changes, fieldChange{"key", utilscore.DerefStr(existing.Key), *req.Key}) - } - if req.Label != nil && !utilscore.StrEq(existing.Label, req.Label) { - changes = append(changes, fieldChange{"label", utilscore.DerefStr(existing.Label), *req.Label}) - } - if req.DataKey != nil && !utilscore.StrEq(existing.DataKey, req.DataKey) { - changes = append(changes, fieldChange{"data_key", utilscore.DerefStr(existing.DataKey), *req.DataKey}) - } - if req.DataValue != nil && !utilscore.StrEq(existing.DataValue, req.DataValue) { - changes = append(changes, fieldChange{"data_value", utilscore.DerefStr(existing.DataValue), *req.DataValue}) - } - if req.MessageTemplate != nil && !utilscore.StrEq(existing.MessageTemplate, req.MessageTemplate) { - changes = append(changes, fieldChange{"message_template", utilscore.DerefStr(existing.MessageTemplate), *req.MessageTemplate}) - } - if req.CodeTemplate != nil && !utilscore.StrEq(existing.CodeTemplate, req.CodeTemplate) { - changes = append(changes, fieldChange{"code_template", utilscore.DerefStr(existing.CodeTemplate), *req.CodeTemplate}) - } - if req.SortOrder != nil && !utilscore.IntEq(existing.SortOrder, req.SortOrder) { - var oldVal interface{} - if existing.SortOrder != nil { - oldVal = *existing.SortOrder - } - changes = append(changes, fieldChange{"sort_order", oldVal, *req.SortOrder}) - } - if req.ParentID != nil && !utilscore.Uint64Eq(existing.ParentID, req.ParentID) { - var oldVal interface{} - if existing.ParentID != nil { - oldVal = *existing.ParentID - } - changes = append(changes, fieldChange{"parent_id", oldVal, *req.ParentID}) - } - - updated, _, err := s.ipc.Database.ApprovalFlowNode.UpdateApprovalFlowNodeDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - s.bumpFlowVersion(ctx) - - if len(changes) > 0 { - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "flow_node", req.ID, - fmt.Sprintf("Изменён узел «%s»", utilscore.DerefStr(existing.Label)), - map[string]interface{}{"changes": changes}, - ) - } - } - - return updated, nil -} - -func (s *FlowNodesReg) DeleteFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - body, err := io.ReadAll(r.Body) - if err != nil { - return nil, err - } - - var req typescore.ApprovalFlowNode - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("id is required") - } - - ctx := r.Context() - - existing, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existing == nil { - return nil, errors.New("node not found") - } - - children, _, _ := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalFlowNode{ParentID: req.ID}, - }) - - err = s.ipc.Database.ApprovalFlowNode.DeleteApprovalFlowNodeDB(ctx, &req) - if err != nil { - return nil, err - } - - s.bumpFlowVersion(ctx) - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "key": utilscore.DerefStr(existing.Key), - "label": utilscore.DerefStr(existing.Label), - "direct_children": len(children), - } - if existing.CategoryID != nil { - snapshot["category_id"] = *existing.CategoryID - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "delete", "flow_node", req.ID, - fmt.Sprintf("Удалён узел «%s» (каскадно удалено дочерних: %d)", utilscore.DerefStr(existing.Label), len(children)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return true, nil -} - -func (s *FlowNodesReg) SaveEntireTreeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - categoryIDStr := chi.URLParam(r, "category_id") - categoryID, err := strconv.ParseUint(categoryIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid category_id") - } - - defer r.Body.Close() - body, err := io.ReadAll(r.Body) - if err != nil { - return nil, err - } - - var req struct { - Nodes []*typescore.ApprovalFlowNode `json:"nodes"` - } - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - ctx := r.Context() - - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID) - if err != nil { - return nil, err - } - if category == nil { - return nil, errors.New("category not found") - } - - oldNodes, _, _ := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID}, - }) - - if err := s.ipc.Database.ApprovalFlowNode.DeleteFlowNodesByCategoryIDDB(ctx, categoryID); err != nil { - return nil, err - } - - if err := s.saveNodesRecursive(ctx, req.Nodes, categoryID, nil); err != nil { - return nil, err - } - - s.bumpFlowVersion(ctx) - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - categoryName := utilscore.DerefStr(category.Name) - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "flow_tree", &categoryID, - fmt.Sprintf("Пересохранено дерево категории «%s» (было узлов: %d, стало: %d)", categoryName, len(oldNodes), countNodesRecursive(req.Nodes)), - map[string]interface{}{ - "category_id": categoryID, - "nodes_before": len(oldNodes), - "nodes_after": countNodesRecursive(req.Nodes), - }, - ) - } - - return true, nil -} - -func (s *FlowNodesReg) MoveFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid node id") - } - - defer r.Body.Close() - body, err := io.ReadAll(r.Body) - if err != nil { - return nil, err - } - - var req struct { - NewParentID *uint64 `json:"new_parent_id"` - NewSortOrder *int `json:"new_sort_order"` - } - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - ctx := r.Context() - - node, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id) - if err != nil { - return nil, err - } - if node == nil { - return nil, errors.New("node not found") - } - - if req.NewParentID != nil { - if *req.NewParentID == id { - return nil, errors.New("node cannot be its own parent") - } - - parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.NewParentID) - if err != nil { - return nil, err - } - if parent == nil { - return nil, errors.New("new parent node not found") - } - - if parent.CategoryID == nil || node.CategoryID == nil || *parent.CategoryID != *node.CategoryID { - return nil, errors.New("new parent belongs to a different category") - } - - if err := s.checkNoCyclicReference(ctx, id, *req.NewParentID); err != nil { - return nil, err - } - } - - update := &typescore.ApprovalFlowNode{ID: &id} - if req.NewParentID != nil { - update.ParentID = req.NewParentID - } - if req.NewSortOrder != nil { - update.SortOrder = req.NewSortOrder - } - - updated, _, err := s.ipc.Database.ApprovalFlowNode.UpdateApprovalFlowNodeDB(ctx, nil, update, true) - if err != nil { - return nil, err - } - - s.bumpFlowVersion(ctx) - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - var oldParent interface{} - if node.ParentID != nil { - oldParent = *node.ParentID - } - metadata := map[string]interface{}{ - "old_parent_id": oldParent, - "new_parent_id": req.NewParentID, - "new_sort_order": req.NewSortOrder, - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "flow_node", &id, - fmt.Sprintf("Перемещён узел «%s»", utilscore.DerefStr(node.Label)), - metadata, - ) - } - - return updated, nil -} - -func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid node id") - } - - ctx := r.Context() - - original, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id) - if err != nil { - return nil, err - } - if original == nil { - return nil, errors.New("node not found") - } - - allNodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalFlowNode{CategoryID: original.CategoryID}, - }) - if err != nil { - return nil, err - } - - descendants := s.collectDescendants(id, allNodes) - suffix := s.generateCopySuffix(ctx, original) - - newKey := *original.Key + suffix - newLabel := *original.Label + " (копия)" - - copyNode := &typescore.ApprovalFlowNode{ - CategoryID: original.CategoryID, - TopicID: original.TopicID, - ParentID: original.ParentID, - Key: &newKey, - Label: &newLabel, - DataKey: original.DataKey, - DataValue: original.DataValue, - IsInput: original.IsInput, - InputKey: original.InputKey, - InputHint: original.InputHint, - IsMultiSelect: original.IsMultiSelect, - MultiSelectKey: original.MultiSelectKey, - MultiSelectValue: original.MultiSelectValue, - TopicCode: original.TopicCode, - SortOrder: original.SortOrder, - MessageTemplate: original.MessageTemplate, - CodeTemplate: original.CodeTemplate, - } - - createdCopy, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, copyNode, true) - if err != nil { - return nil, err - } - - if len(descendants) > 0 { - idMapping := map[uint64]uint64{ - id: *createdCopy.ID, - } - - sortedDescendants := s.sortByDepth(id, descendants, allNodes) - - for _, desc := range sortedDescendants { - descKey := *desc.Key + suffix - descCopy := &typescore.ApprovalFlowNode{ - CategoryID: desc.CategoryID, - TopicID: desc.TopicID, - Key: &descKey, - Label: desc.Label, - DataKey: desc.DataKey, - DataValue: desc.DataValue, - IsInput: desc.IsInput, - InputKey: desc.InputKey, - InputHint: desc.InputHint, - IsMultiSelect: desc.IsMultiSelect, - MultiSelectKey: desc.MultiSelectKey, - MultiSelectValue: desc.MultiSelectValue, - TopicCode: desc.TopicCode, - SortOrder: desc.SortOrder, - MessageTemplate: desc.MessageTemplate, - CodeTemplate: desc.CodeTemplate, - } - - if desc.ParentID != nil { - if newParentID, ok := idMapping[*desc.ParentID]; ok { - descCopy.ParentID = &newParentID - } - } - - createdDesc, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, descCopy, true) - if err != nil { - return nil, err - } - if desc.ID != nil && createdDesc != nil && createdDesc.ID != nil { - idMapping[*desc.ID] = *createdDesc.ID - } - } - } - - s.bumpFlowVersion(ctx) - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "create", "flow_node", createdCopy.ID, - fmt.Sprintf("Продублирован узел «%s» (с потомками: %d)", utilscore.DerefStr(original.Label), len(descendants)), - map[string]interface{}{ - "duplicated_from": id, - "descendants": len(descendants), - }, - ) - } - - return createdCopy, nil -} - -func (s *FlowNodesReg) buildTreeFromNodes(nodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode { - nodeMap := make(map[uint64]*typescore.ApprovalFlowNode) - var roots []*typescore.ApprovalFlowNode - - for _, n := range nodes { - if n.ID != nil { - nodeMap[*n.ID] = n - } - } - - for _, n := range nodes { - if n.ParentID == nil { - roots = append(roots, n) - } else if parent, ok := nodeMap[*n.ParentID]; ok { - parent.Children = append(parent.Children, n) - } - } - - return roots -} - -func (s *FlowNodesReg) saveNodesRecursive(ctx context.Context, nodes []*typescore.ApprovalFlowNode, categoryID uint64, parentID *uint64) error { - for i, node := range nodes { - node.CategoryID = &categoryID - node.ParentID = parentID - - sortOrder := i - node.SortOrder = &sortOrder - - created, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, node, true) - if err != nil { - return err - } - - if len(node.Children) > 0 { - if err := s.saveNodesRecursive(ctx, node.Children, categoryID, created.ID); err != nil { - return err - } - } - } - return nil -} - -// checkNoCyclicReference идёт вверх по родителям от newParentID — если -// встретит nodeID, значит перемещение создаёт цикл. -func (s *FlowNodesReg) checkNoCyclicReference(ctx context.Context, nodeID, newParentID uint64) error { - currentID := newParentID - visited := make(map[uint64]bool) - - for currentID != 0 { - if visited[currentID] { - break - } - visited[currentID] = true - - if currentID == nodeID { - return errors.New("cyclic reference detected: cannot move node under its own descendant") - } - - parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, currentID) - if err != nil || parent == nil { - break - } - if parent.ParentID == nil { - break - } - currentID = *parent.ParentID - } - - return nil -} - -func (s *FlowNodesReg) collectDescendants(rootID uint64, allNodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode { - childrenMap := make(map[uint64][]*typescore.ApprovalFlowNode) - for _, n := range allNodes { - if n.ParentID != nil { - childrenMap[*n.ParentID] = append(childrenMap[*n.ParentID], n) - } - } - - var result []*typescore.ApprovalFlowNode - queue := []uint64{rootID} - - for len(queue) > 0 { - current := queue[0] - queue = queue[1:] - - for _, child := range childrenMap[current] { - result = append(result, child) - if child.ID != nil { - queue = append(queue, *child.ID) - } - } - } - - return result -} - -func (s *FlowNodesReg) sortByDepth(rootID uint64, descendants, allNodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode { - depthMap := make(map[uint64]int) - depthMap[rootID] = 0 - - nodeMap := make(map[uint64]*typescore.ApprovalFlowNode) - for _, n := range allNodes { - if n.ID != nil { - nodeMap[*n.ID] = n - } - } - - for _, d := range descendants { - if d.ID == nil { - continue - } - depth := 0 - currentID := d.ID - for { - node, ok := nodeMap[*currentID] - if !ok || node.ParentID == nil { - break - } - depth++ - currentID = node.ParentID - if *currentID == rootID { - break - } - } - depthMap[*d.ID] = depth - } - - sorted := make([]*typescore.ApprovalFlowNode, len(descendants)) - copy(sorted, descendants) - for i := 0; i < len(sorted); i++ { - for j := i + 1; j < len(sorted); j++ { - depthI := 0 - depthJ := 0 - if sorted[i].ID != nil { - depthI = depthMap[*sorted[i].ID] - } - if sorted[j].ID != nil { - depthJ = depthMap[*sorted[j].ID] - } - if depthJ < depthI { - sorted[i], sorted[j] = sorted[j], sorted[i] - } - } - } - - return sorted -} - -func (s *FlowNodesReg) generateCopySuffix(ctx context.Context, original *typescore.ApprovalFlowNode) string { - if original.CategoryID == nil || original.Key == nil { - return "_copy" - } - - existing, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalFlowNode{CategoryID: original.CategoryID}, - }) - if err != nil { - return "_copy" - } - - baseKey := *original.Key - maxNum := 0 - - for _, n := range existing { - if n.Key == nil { - continue - } - key := *n.Key - if len(key) > len(baseKey) && key[:len(baseKey)] == baseKey { - suffix := key[len(baseKey):] - if len(suffix) >= 6 && suffix[:5] == "_copy" { - if len(suffix) > 5 { - numStr := suffix[6:] - if num, err := strconv.Atoi(numStr); err == nil && num > maxNum { - maxNum = num - } - } else if suffix == "_copy" { - if maxNum < 1 { - maxNum = 1 - } - } - } - } - } - - return fmt.Sprintf("_copy_%d", maxNum+1) -} - -func countNodesRecursive(nodes []*typescore.ApprovalFlowNode) int { - count := len(nodes) - for _, n := range nodes { - count += countNodesRecursive(n.Children) - } - return count -} - -func (s *FlowNodesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - return nil, false - } - - return admins[0], true -} - ------END service/rest_admin_service/handlers/flow_nodes/handler.go----- - -File: service/rest_admin_service/handlers/flow_nodes/preview.go -Lines: 111 ------BEGIN service/rest_admin_service/handlers/flow_nodes/preview.go----- -package nodeshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "encoding/json" - "errors" - "io" - "net/http" - "strconv" - - "github.com/go-chi/chi/v5" -) - -type previewFlowRequest struct { - // Collected — все data_key/data_value, накопленные по пути от корня - // дерева категории до узла, для которого считаем предпросмотр. - Collected map[string]string `json:"collected"` - // InitiatorName — необязательно, для более живого предпросмотра - // сообщения (по умолчанию подставляется тестовое имя). - InitiatorName string `json:"initiator_name"` -} - -type previewFlowResponse struct { - // Code — код темы, который реально будет использован для поиска - // ApprovalTopic при подаче заявки. Пусто, если по текущим данным - // код ещё нельзя посчитать (путь не завершён). - Code string `json:"code"` - // Message — как будет выглядеть уведомление согласующему (с HTML-разметкой, - // как оно уйдёт в Telegram). - Message string `json:"message"` - // Incomplete — true, если для расчёта кода не хватает данных - // (это не ошибка, а нормальная ситуация для промежуточного узла). - Incomplete bool `json:"incomplete"` - // TopicExists — есть ли уже в approval_topics тема с таким кодом. - TopicExists bool `json:"topic_exists"` - TopicID uint64 `json:"topic_id,omitempty"` - TopicName string `json:"topic_name,omitempty"` -} - -func (s *FlowNodesReg) PreviewFlowHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - categoryIDStr := chi.URLParam(r, "category_id") - categoryID, err := strconv.ParseUint(categoryIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid category_id") - } - - defer r.Body.Close() - body, err := io.ReadAll(r.Body) - if err != nil { - return nil, err - } - - var req previewFlowRequest - if len(body) > 0 { - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - } - if req.Collected == nil { - req.Collected = map[string]string{} - } - if req.InitiatorName == "" { - req.InitiatorName = "Иван Иванов" - } - - ctx := r.Context() - - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID) - if err != nil { - return nil, err - } - if category == nil { - return nil, errors.New("category not found") - } - - nodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID}, - }) - if err != nil { - return nil, err - } - - dynamicTopic := approvalflow.NewDynamicTopic(category, nodes) - - resp := &previewFlowResponse{} - - code, err := dynamicTopic.TopicCodeFromCollected(req.Collected) - if err != nil { - // Ожидаемо для промежуточного узла: пути ещё не хватает данных. - resp.Incomplete = true - } else { - resp.Code = code - - existingTopic, exErr := s.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, code) - if exErr == nil && existingTopic != nil { - resp.TopicExists = true - if existingTopic.ID != nil { - resp.TopicID = *existingTopic.ID - } - if existingTopic.Name != nil { - resp.TopicName = *existingTopic.Name - } - } - } - - initiator := &typescore.User{FullName: &req.InitiatorName} - resp.Message = dynamicTopic.FormatApproverMessage(initiator, req.Collected) - - return resp, nil -} - ------END service/rest_admin_service/handlers/flow_nodes/preview.go----- - -File: service/rest_admin_service/handlers/flow_nodes/router.go -Lines: 61 ------BEGIN service/rest_admin_service/handlers/flow_nodes/router.go----- -package nodeshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type FlowNodesReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterFlowNodesRoutes регистрирует маршруты для управления узлами дерева. -// Дерево навигации принадлежит категории (category_id) — см. ApprovalFlowNode.CategoryID -// и Registry.LoadFromDB, которые строят Topic-интерфейс по категории + узлам. -func RegisterFlowNodesRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &FlowNodesReg{ - ipc: ipc, - } - - r.Route("/api/flow-nodes", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - // Получить дерево узлов для категории - handlers.RegisterRoute(r, http.MethodGet, "/category/{category_id}", s.GetFlowNodesByCategoryIDHandler) - - // CRUD операции с узлами - handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateFlowNodeHandler) - handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateFlowNodeHandler) - handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteFlowNodeHandler) - - // Сохранить всё дерево целиком (для UI конструктора) - handlers.RegisterRoute(r, http.MethodPost, "/category/{category_id}/tree", s.SaveEntireTreeHandler) - - // Переместить узел (изменить порядок или родителя) — используется - // и обычным ↑/↓, и кнопками "поднять/опустить уровень" в новом UI. - handlers.RegisterRoute(r, http.MethodPost, "/{id}/move", s.MoveFlowNodeHandler) - - // Дублировать узел с детьми - handlers.RegisterRoute(r, http.MethodPost, "/{id}/duplicate", s.DuplicateFlowNodeHandler) - - // НОВОЕ: живой предпросмотр кода темы и сообщения согласующему - // для конкретного пути по дереву — см. preview.go - handlers.RegisterRoute(r, http.MethodPost, "/category/{category_id}/preview", s.PreviewFlowHandler) - - // НОВОЕ: кнопка "Обновить бота" — форсирует бамп версии дерева тем, - // бот подхватит на ближайшем тике фонового воркера — см. reload.go - handlers.RegisterRoute(r, http.MethodPost, "/reload-bot", s.ReloadBotHandler) - - // Получить узел по ID - handlers.RegisterRoute(r, http.MethodGet, "/{id}", s.GetFlowNodeByIDHandler) - }) - - return nil -} - ------END service/rest_admin_service/handlers/flow_nodes/router.go----- - -File: service/rest_admin_service/handlers/flow_nodes/utils.go -Lines: 20 ------BEGIN service/rest_admin_service/handlers/flow_nodes/utils.go----- -package nodeshandler - -import ( - "context" - "fmt" - "net/http" - "time" -) - -const flowVersionRedisKey = "approval_flow:version" - -func (s *FlowNodesReg) bumpFlowVersion(ctx context.Context) { - version := fmt.Sprintf("%d", time.Now().UnixNano()) - _ = s.ipc.RedisClient.Set(ctx, flowVersionRedisKey, version, 24*time.Hour) -} - -func (s *FlowNodesReg) ReloadBotHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - s.bumpFlowVersion(r.Context()) - return true, nil -} - ------END service/rest_admin_service/handlers/flow_nodes/utils.go----- - -File: service/rest_admin_service/handlers/middleware.go -Lines: 328 ------BEGIN service/rest_admin_service/handlers/middleware.go----- -package handlers - -import ( - configcore "bitrix_balancer_api/core/config" - dbcore "bitrix_balancer_api/core/db/methods" - redismodule "bitrix_balancer_api/core/lib/internally/redis" - "bitrix_balancer_api/core/securecore" - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/core/variables" - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "strconv" - "strings" - "time" - - "github.com/sirupsen/logrus" -) - -// JWTVerifier middleware для проверки JWT токена и соответствия IP -func JWTVerifier(cfg *configcore.Config, adminDB dbcore.AdminDBI, redisModule *redismodule.ModuleRedis) 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.AuthJWT.AdminSecret == "" { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - }).Error("JWTVerifier: AdminSecret is empty") - http.Error(w, "Internal server error", http.StatusInternalServerError) - return - } - - authHeader := r.Header.Get("Authorization") - if authHeader == "" { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - }).Warn("JWTVerifier: Authorization header is empty") - http.Error(w, "Unauthorized", http.StatusUnauthorized) - return - } - - deviceID := r.Header.Get("x-device-id") - if deviceID == "" { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - }).Warn("JWTVerifier: x-device-id header is empty") - http.Error(w, "Unauthorized device", http.StatusUnauthorized) - return - } - - if redisModule == nil { - logrus.Error("JWTVerifier: Redis storage not initialized") - http.Error(w, "Internal server error: Redis storage not initialized", http.StatusInternalServerError) - return - } - - parts := strings.Split(authHeader, " ") - if len(parts) != 2 || parts[0] != "Bearer" { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "auth_header": authHeader, - }).Warn("JWTVerifier: Invalid authorization header format") - http.Error(w, "Invalid authorization header", http.StatusUnauthorized) - return - } - tokenString := parts[1] - - _, claims, err := securecore.VerifyToken(tokenString, cfg.Secrets.AuthJWT.AdminSecret) - if err != nil { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "error": err.Error(), - }).Warn("JWTVerifier: Token verification failed") - http.Error(w, "Invalid token", http.StatusUnauthorized) - return - } - - userIDFloat, ok := claims[securecore.IDContextKey.String()].(float64) - if !ok { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - }).Warn("JWTVerifier: Missing user_id in token claims") - http.Error(w, "Invalid token: missing user_id", http.StatusUnauthorized) - return - } - userID := uint64(userIDFloat) - - adminList, _, errW := adminDB.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ - ID: &userID, - IsBlocked: utilscore.PointerToBool(false), - }, - }) - if errW != nil || len(adminList) == 0 { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "user_id": userID, - "error": errW, - }).Warn("JWTVerifier: Admin not found or blocked") - http.Error(w, "Admin not found or blocked", http.StatusUnauthorized) - return - } - - if adminList[0].IsBlocked == nil || *adminList[0].IsBlocked { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "user_id": userID, - }).Warn("JWTVerifier: Account is blocked") - http.Error(w, "Forbidden: account is blocked", http.StatusUnauthorized) - return - } - - ctx := context.WithValue(r.Context(), securecore.IDContextKey, userID) - - sessionJSON, err := redisModule.Get(ctx, fmt.Sprintf("%s:admin:%d", variables.RedisPathUserAuthSessions, userID)) - if err != nil || sessionJSON == "" { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "user_id": userID, - "error": err, - }).Warn("JWTVerifier: User session not found in Redis") - http.Error(w, "User session not found. Please authorize again", http.StatusUnauthorized) - return - } - - var session typescore.UsersSessions - if err := json.Unmarshal([]byte(sessionJSON), &session); err != nil { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "user_id": userID, - "error": err.Error(), - }).Warn("JWTVerifier: Failed to unmarshal session") - http.Error(w, "Failed to get user session data. Please authorize again", http.StatusUnauthorized) - return - } - - if !securecore.FindDeviceID(session.AuthorizedDevices, deviceID) { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "user_id": userID, - "device_id": deviceID, - }).Warn("JWTVerifier: Device not authorized") - http.Error(w, "Unauthorized device", http.StatusUnauthorized) - return - } - - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "user_id": userID, - "device_id": deviceID, - }).Debug("JWTVerifier: Request authorized") - - next.ServeHTTP(w, r.WithContext(ctx)) - }) - } -} - -// AccessCodeVerifier middleware для проверки Access Code для валидного фронта -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) { - // 🆕 Логируем начало проверки - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "method": r.Method, - "remote": r.RemoteAddr, - }).Debug("AccessCodeVerifier: Starting verification") - - // Проверка 1: Секреты в конфиге - if cfg.Secrets.ApiPublicAdmin == "" || cfg.Secrets.ApiPrivateAdmin == "" { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "api_public_empty": cfg.Secrets.ApiPublicAdmin == "", - "api_private_empty": cfg.Secrets.ApiPrivateAdmin == "", - }).Error("AccessCodeVerifier: API secrets not configured") - http.Error(w, "Internal server error", http.StatusInternalServerError) - return - } - - // Получаем заголовки - authHeader := r.Header.Get("ApiKey") - timestampStr := r.Header.Get("X-Timestamp") - deviceID := r.Header.Get("x-device-id") - - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "has_api_key": authHeader != "", - "has_timestamp": timestampStr != "", - "device_id": deviceID, - }).Debug("AccessCodeVerifier: Headers received") - - // Проверка 2: Наличие заголовков - if authHeader == "" || timestampStr == "" { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "api_key_empty": authHeader == "", - "timestamp_empty": timestampStr == "", - "all_headers": r.Header, - }).Warn("AccessCodeVerifier: Missing required headers") - http.Error(w, "Unauthorized client", http.StatusUnauthorized) - return - } - - // Проверка 3: Парсинг timestamp - timestampUnix, err := strconv.ParseInt(timestampStr, 10, 64) - if err != nil { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "timestamp": timestampStr, - "error": err.Error(), - }).Warn("AccessCodeVerifier: Invalid timestamp format") - http.Error(w, "Invalid timestamp", http.StatusBadRequest) - return - } - - // Конвертируем Unix timestamp в time.Time - 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, - ) - - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "timestamp_received": timestampTime.Format(time.RFC3339), - "timestamp_rounded": timestampTimeRounded.Format(time.RFC3339), - "now": now.Format(time.RFC3339), - "now_rounded": nowRounded.Format(time.RFC3339), - }).Debug("AccessCodeVerifier: Timestamp parsed") - - // Проверка 4: Timestamp не старше 3 минут - threeMinutesAgo := nowRounded.Add(-3 * time.Minute) - - if timestampTimeRounded.Before(threeMinutesAgo) { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "timestamp": timestampTimeRounded.Format(time.RFC3339), - "three_minutes_ago": threeMinutesAgo.Format(time.RFC3339), - "now": nowRounded.Format(time.RFC3339), - }).Warn("AccessCodeVerifier: Timestamp expired") - http.Error(w, "Timestamp expired", http.StatusUnauthorized) - return - } - - // Проверка 5: Timestamp не в будущем - if timestampTimeRounded.After(nowRounded) { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "timestamp": timestampTimeRounded.Format(time.RFC3339), - "now": nowRounded.Format(time.RFC3339), - }).Warn("AccessCodeVerifier: Timestamp in future") - http.Error(w, "Timestamp in future", http.StatusUnauthorized) - return - } - - // Проверка 6: Генерация и сравнение подписи - expectedSignature := utilscore.GenerateHMACSignature( - cfg.Secrets.ApiPublicAdmin, - timestampStr, - cfg.Secrets.ApiPrivateAdmin, - ) - - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "public_key": cfg.Secrets.ApiPublicAdmin[:min(10, len(cfg.Secrets.ApiPublicAdmin))] + "...", - "timestamp": timestampStr, - "expected_signature": expectedSignature[:min(20, len(expectedSignature))] + "...", - "received_signature": authHeader[:min(20, len(authHeader))] + "...", - "signatures_match": expectedSignature == authHeader, - }).Debug("AccessCodeVerifier: Comparing signatures") - - // Безопасное сравнение - if !utilscore.HmacEquals(expectedSignature, authHeader) { - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - "expected_signature": expectedSignature, - "received_signature": authHeader, - "expected_length": len(expectedSignature), - "received_length": len(authHeader), - }).Warn("AccessCodeVerifier: Signature mismatch") - http.Error(w, "Unauthorized client", http.StatusUnauthorized) - return - } - - logrus.WithFields(logrus.Fields{ - "path": r.URL.Path, - }).Debug("AccessCodeVerifier: Verification successful") - - ctx := context.WithValue(r.Context(), securecore.AccessContextKey, authHeader) - next.ServeHTTP(w, r.WithContext(ctx)) - }) - } -} - -// GetIDFromContext извлекает user id из контекста -func GetIDFromContext(ctx context.Context) (uint64, error) { - address, ok := ctx.Value(securecore.IDContextKey).(uint64) - if !ok { - return 0, errors.New("no id found in context") - } - return address, nil -} - -// GetIPFromContext извлекает user ip из контекста -func GetIPFromContext(ctx context.Context) (string, error) { - address, ok := ctx.Value(securecore.IpContextKey).(string) - if !ok { - return "", errors.New("no ip found in context") - } - return address, nil -} - -// min возвращает минимальное из двух int -func min(a, b int) int { - if a < b { - return a - } - return b -} - ------END service/rest_admin_service/handlers/middleware.go----- - -File: service/rest_admin_service/handlers/notification/handlers.go -Lines: 306 ------BEGIN service/rest_admin_service/handlers/notification/handlers.go----- -package notificationshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - typesm "bitrix_balancer_api/rest_admin_service/types" - "context" - "encoding/json" - "errors" - "fmt" - "github.com/go-chi/chi/v5" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strconv" -) - -type NotificationReg struct { - ipc *typesm.InternalProviderControl -} - -func (s *NotificationReg) CreateNotificationHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - body, err := io.ReadAll(r.Body) - if err != nil { - return nil, err - } - defer r.Body.Close() - - var req typescore.CreateNotificationReq - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - if req.Title == "" || req.MessageHTML == "" { - return nil, errors.New("title and message_html are required") - } - - ctx := r.Context() - - recipients, err := s.resolveRecipients(ctx, req.Targets) - if err != nil { - return nil, err - } - if len(recipients) == 0 { - return nil, errors.New("no recipients matched the given filters") - } - - targetFiltersJSON, err := json.Marshal(req.Targets) - if err != nil { - return nil, err - } - targetFiltersStr := string(targetFiltersJSON) - - status := "sending" - totalCount := len(recipients) - notification := &typescore.Notification{ - Title: &req.Title, - MessageHTML: &req.MessageHTML, - PhotoBase64: req.PhotoBase64, - PhotoFileName: req.PhotoFileName, - TargetFilters: &targetFiltersStr, - Status: &status, - TotalCount: &totalCount, - } - - notification, err = s.ipc.Database.Notification.CreateNotificationDB(ctx, notification) - if err != nil { - return nil, err - } - - pendingStatus := "pending" - recipientRows := make([]*typescore.NotificationRecipient, 0, len(recipients)) - for _, u := range recipients { - recipientRows = append(recipientRows, &typescore.NotificationRecipient{ - NotificationID: notification.ID, - UserID: u.ID, - Status: &pendingStatus, - }) - } - if err := s.ipc.Database.Notification.CreateNotificationRecipientsDB(ctx, recipientRows); err != nil { - return nil, err - } - - sentCount, failedCount := s.sendToRecipients(ctx, notification, recipients) - - finalStatus := "completed" - notification.Status = &finalStatus - notification.SentCount = &sentCount - notification.FailedCount = &failedCount - if err := s.ipc.Database.Notification.UpdateNotificationDB(ctx, notification); err != nil { - logrus.Warnf("CreateNotificationHandler: failed to update final status: %v", err) - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "create", "notification", notification.ID, - fmt.Sprintf("Отправлена рассылка «%s» (получателей: %d, отправлено: %d, ошибок: %d)", - req.Title, totalCount, sentCount, failedCount), - map[string]interface{}{ - "title": req.Title, - "total_count": totalCount, - "sent_count": sentCount, - "failed_count": failedCount, - "target_filters": req.Targets, - }, - ) - } - - return notification, nil -} - -// resolveRecipients объединяет пользователей из всех критериев без дублей -func (s *NotificationReg) resolveRecipients(ctx context.Context, filters typescore.TargetFilters) ([]*typescore.User, error) { - usersMap := make(map[uint64]*typescore.User) - - addUsers := func(list []*typescore.User) { - for _, u := range list { - if u.ID != nil { - usersMap[*u.ID] = u - } - } - } - - if len(filters.UserIDs) > 0 { - users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, filters.UserIDs) - if err != nil { - return nil, err - } - addUsers(users) - } - - if len(filters.RoleIDs) > 0 { - users, _, err := s.ipc.Database.User.GetUsersListByRoleIDsDB(ctx, typescore.ListDbOptions{}, filters.RoleIDs) - if err != nil { - return nil, err - } - addUsers(users) - } - - if len(filters.RoleTypeFlags) > 0 { - users, err := s.ipc.Database.User.GetUsersByRoleFlagsDB(ctx, filters.RoleTypeFlags) - if err != nil { - return nil, err - } - addUsers(users) - } - - if len(filters.DepartmentIDs) > 0 { - users, err := s.ipc.Database.User.GetUsersByDepartmentIDsDB(ctx, filters.DepartmentIDs) - if err != nil { - return nil, err - } - addUsers(users) - } - - result := make([]*typescore.User, 0, len(usersMap)) - for _, u := range usersMap { - if u.IsBlocked != nil && *u.IsBlocked { - continue - } - result = append(result, u) - } - return result, nil -} - -// sendToRecipients рассылает сообщение всем найденным пользователям и фиксирует результат по каждому -func (s *NotificationReg) sendToRecipients(ctx context.Context, n *typescore.Notification, users []*typescore.User) (sent int, failed int) { - pendingRecipients, err := s.ipc.Database.Notification.GetNotificationRecipientsDB(ctx, *n.ID) - if err != nil { - logrus.Errorf("sendToRecipients: failed to load recipients: %v", err) - return 0, len(users) - } - - recipientByUserID := make(map[uint64]*typescore.NotificationRecipient) - for _, r := range pendingRecipients { - if r.UserID != nil { - recipientByUserID[*r.UserID] = r - } - } - - sentStatus := "sent" - failedStatus := "failed" - - for _, u := range users { - if u.TelegramID == nil { - continue - } - rec, ok := recipientByUserID[*u.ID] - if !ok { - continue - } - - var sendErr error - var msgID int - - if n.PhotoBase64 != nil && *n.PhotoBase64 != "" { - fileName := "notification.jpg" - if n.PhotoFileName != nil { - fileName = *n.PhotoFileName - } - sentMsg, err := s.ipc.TGBotClient.SendPhoto(*u.TelegramID, *n.PhotoBase64, *n.MessageHTML) - if err != nil { - sendErr = err - } else { - msgID = sentMsg.MessageID - } - _ = fileName - } else { - sentMsg, err := s.ipc.TGBotClient.Send(*u.TelegramID, *n.MessageHTML) - if err != nil { - sendErr = err - } else { - msgID = sentMsg.MessageID - } - } - - if sendErr != nil { - errStr := sendErr.Error() - rec.Status = &failedStatus - rec.ErrorMessage = &errStr - failed++ - } else { - rec.Status = &sentStatus - rec.TelegramMessageID = &msgID - sent++ - } - - if err := s.ipc.Database.Notification.UpdateNotificationRecipientDB(ctx, rec); err != nil { - logrus.Warnf("sendToRecipients: failed to update recipient status: %v", err) - } - } - - return sent, failed -} - -// GetNotificationListHandler — история отправленных уведомлений -func (s *NotificationReg) GetNotificationListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - notificationParams := &typescore.Notification{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, notificationParams) - if errW != nil { - return nil, errW - } - - options := typescore.ListDbOptions{ - Filtering: notificationParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - list, total, err := s.ipc.Database.Notification.GetNotificationsListDB(r.Context(), options) - if err != nil { - return nil, err - } - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: list, - }, nil -} - -// GetNotificationByIDHandler — детали конкретной рассылки с постатейной историей доставки -func (s *NotificationReg) GetNotificationByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid notification id") - } - - ctx := r.Context() - notification, err := s.ipc.Database.Notification.GetNotificationByIDDB(ctx, id) - if err != nil { - return nil, err - } - if notification == nil { - return nil, errors.New("notification not found") - } - - recipients, err := s.ipc.Database.Notification.GetNotificationRecipientsDB(ctx, id) - if err == nil { - notification.Recipients = recipients - } - - return notification, nil -} - -func (s *NotificationReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - return nil, false - } - - return admins[0], true -} - ------END service/rest_admin_service/handlers/notification/handlers.go----- - -File: service/rest_admin_service/handlers/notification/routes.go -Lines: 26 ------BEGIN service/rest_admin_service/handlers/notification/routes.go----- -package notificationshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -func RegisterNotificationRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error { - s := &NotificationReg{ipc: ipc} - - r.Route("/api/notifications", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateNotificationHandler) - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetNotificationListHandler) - r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetNotificationByIDHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/notification/routes.go----- - -File: service/rest_admin_service/handlers/permission/handlers.go -Lines: 648 ------BEGIN service/rest_admin_service/handlers/permission/handlers.go----- -package permissionshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - "context" - "encoding/json" - "errors" - "fmt" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strconv" - - "github.com/go-chi/chi/v5" -) - -// GetPermissionsListHandler Получение списка прав -// @Summary Получение списка прав -// @Description Получение списка прав ролей с пагинацией и фильтрацией -// @Tags permissions -// @Accept json -// @Produce json -// @Param offset query integer false "Смещение для пагинации" -// @Param limit query integer false "Количество записей на странице" -// @Param role_id query integer false "Фильтр по роли" -// @Param action query string false "Фильтр по действию (create, read, update, delete, approve, revoke)" -// @Param topic_category_id query integer false "Фильтр по категории тем" -// @Param topic_id query integer false "Фильтр по теме" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/permissions [get] -func (s *PermissionsReg) GetPermissionsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - permissionParams := &typescore.Permission{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, permissionParams) - if errW != nil { - return nil, errW - } - - options := typescore.ListDbOptions{ - Filtering: permissionParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - ctx := r.Context() - permissionsDbLst, total, errW := s.ipc.Database.Permission.GetPermissionsListDB(ctx, options) - if errW != nil { - return nil, errW - } - - s.enrichPermissionsBatch(ctx, permissionsDbLst) - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: permissionsDbLst, - }, nil -} - -// GetPermissionsByRoleIDHandler Получение всех прав для роли -// @Summary Получение прав по роли -// @Description Получение списка всех прав для указанной роли -// @Tags permissions -// @Accept json -// @Produce json -// @Param role_id path integer true "ID роли" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Роль не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/permissions/by-role/{role_id} [get] -func (s *PermissionsReg) GetPermissionsByRoleIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - roleIDStr := chi.URLParam(r, "role_id") - if roleIDStr == "" { - return nil, errors.New("role_id is required") - } - - roleID, err := strconv.ParseUint(roleIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid role_id") - } - - ctx := r.Context() - - role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, roleID) - if err != nil { - return nil, err - } - if role == nil { - return nil, errors.New("role not found") - } - - permissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Permission{RoleID: &roleID}, - }) - if err != nil { - return nil, err - } - - s.enrichPermissionsBatch(ctx, permissions) - - return &typescore.ApiResponseBase{ - TotalCount: uint64(len(permissions)), - Data: permissions, - }, nil -} - -// enrichPermissionsBatch пакетно подгружает роли, категории и темы для списка прав -func (s *PermissionsReg) enrichPermissionsBatch(ctx context.Context, permissions []*typescore.Permission) { - if len(permissions) == 0 { - return - } - - roleIDsSet := make(map[uint64]struct{}) - categoryIDsSet := make(map[uint64]struct{}) - topicIDsSet := make(map[uint64]struct{}) - - for _, p := range permissions { - if p.RoleID != nil { - roleIDsSet[*p.RoleID] = struct{}{} - } - if p.TopicCategoryID != nil { - categoryIDsSet[*p.TopicCategoryID] = struct{}{} - } - if p.TopicID != nil { - topicIDsSet[*p.TopicID] = struct{}{} - } - } - - roleIDs := make([]uint64, 0, len(roleIDsSet)) - for id := range roleIDsSet { - roleIDs = append(roleIDs, id) - } - categoryIDs := make([]uint64, 0, len(categoryIDsSet)) - for id := range categoryIDsSet { - categoryIDs = append(categoryIDs, id) - } - topicIDs := make([]uint64, 0, len(topicIDsSet)) - for id := range topicIDsSet { - topicIDs = append(topicIDs, id) - } - - rolesMap := make(map[uint64]*typescore.Role) - if roles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs); err == nil { - for _, role := range roles { - if role.ID != nil { - rolesMap[*role.ID] = role - } - } - } - - categoriesMap := make(map[uint64]*typescore.ApprovalTopicCategory) - if categories, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoriesByIDsDB(ctx, categoryIDs); err == nil { - for _, c := range categories { - if c.ID != nil { - categoriesMap[*c.ID] = c - } - } - } - - topicsMap := make(map[uint64]*typescore.ApprovalTopic) - if topics, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsByIDsDB(ctx, topicIDs); err == nil { - for _, t := range topics { - if t.ID != nil { - topicsMap[*t.ID] = t - } - } - } - - for _, p := range permissions { - if p.RoleID != nil { - if role, ok := rolesMap[*p.RoleID]; ok { - p.Role = role - } - } - if p.TopicCategoryID != nil { - if cat, ok := categoriesMap[*p.TopicCategoryID]; ok { - p.TopicCategory = cat - } - } - if p.TopicID != nil { - if topic, ok := topicsMap[*p.TopicID]; ok { - p.Topic = topic - } - } - } -} - -// GetPermissionByIDHandler Получение права по ID -// @Summary Получение права по ID -// @Description Получение детальной информации о праве по его ID -// @Tags permissions -// @Accept json -// @Produce json -// @Param id path integer true "ID права" -// @Success 200 {object} typescore.Permission "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Право не найдено" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/permissions/{id} [get] -func (s *PermissionsReg) GetPermissionByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("permission id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid permission id") - } - - ctx := r.Context() - permissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Permission{ID: &id}, - }) - if err != nil { - return nil, err - } - if len(permissions) == 0 { - return nil, errors.New("permission not found") - } - - permission := permissions[0] - s.enrichPermission(ctx, permission) - - return permission, nil -} - -// CreatePermissionHandler Создание права -// @Summary Создание права -// @Description Назначение права на действие для роли -// @Tags permissions -// @Accept json -// @Produce json -// @Param request body typescore.Permission true "Данные права" -// @Success 200 {object} typescore.Permission "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Роль, категория или тема не найдены" -// @Failure 409 {object} handlers.ErrorResponse "Такое право уже существует" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/permissions [post] -func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 CreatePermissionHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.Permission - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.RoleID == nil { - return nil, errors.New("role_id is required") - } - if req.Action == nil || *req.Action == "" { - return nil, errors.New("action is required") - } - - if !isValidAction(*req.Action) { - return nil, errors.New("invalid action: must be one of create, read, update, delete, approve, revoke, observe") - } - - ctx := r.Context() - - role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.RoleID) - if err != nil { - return nil, err - } - if role == nil { - return nil, errors.New("role not found") - } - - if req.TopicCategoryID != nil { - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID) - if err != nil { - return nil, err - } - if category == nil { - return nil, errors.New("topic category not found") - } - } - - if req.TopicID != nil { - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID) - if err != nil { - return nil, err - } - if topic == nil { - return nil, errors.New("topic not found") - } - - if req.TopicCategoryID != nil && topic.CategoryID != nil { - if *topic.CategoryID != *req.TopicCategoryID { - return nil, errors.New("topic does not belong to the specified category") - } - } - } - - existingPermissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Permission{ - RoleID: req.RoleID, - TopicCategoryID: req.TopicCategoryID, - TopicID: req.TopicID, - Action: req.Action, - }, - }) - if err != nil { - return nil, err - } - if len(existingPermissions) > 0 { - return nil, errors.New("this permission already exists") - } - - createdPermission, _, err := s.ipc.Database.Permission.CreatePermissionDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - s.enrichPermission(ctx, createdPermission) - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "role_id": *createdPermission.RoleID, - "action": utilscore.DerefStr(createdPermission.Action), - } - if createdPermission.TopicCategoryID != nil { - snapshot["topic_category_id"] = *createdPermission.TopicCategoryID - } - if createdPermission.TopicID != nil { - snapshot["topic_id"] = *createdPermission.TopicID - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "create", "permission", createdPermission.ID, - fmt.Sprintf("Выдано право «%s» роли «%s» на %s", utilscore.DerefStr(createdPermission.Action), roleLabel(createdPermission.Role), scopeLabel(createdPermission)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return createdPermission, nil -} - -// UpdatePermissionHandler Обновление права -// @Summary Обновление права -// @Description Обновление данных существующего права -// @Tags permissions -// @Accept json -// @Produce json -// @Param request body typescore.Permission true "Данные права" -// @Success 200 {object} typescore.Permission "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Право не найдено" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/permissions [put] -func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 UpdatePermissionHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.Permission - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("permission id is required") - } - - ctx := r.Context() - - existingPermissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Permission{ID: req.ID}, - }) - if err != nil { - return nil, err - } - if len(existingPermissions) == 0 { - return nil, errors.New("permission not found") - } - existing := existingPermissions[0] - - if req.Action != nil && *req.Action != "" { - if !isValidAction(*req.Action) { - return nil, errors.New("invalid action: must be one of create, read, update, delete, approve, revoke, observe") - } - } - - if req.RoleID != nil { - if existing.RoleID == nil || *existing.RoleID != *req.RoleID { - role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.RoleID) - if err != nil { - return nil, err - } - if role == nil { - return nil, errors.New("role not found") - } - } - } - - if req.TopicCategoryID != nil { - if existing.TopicCategoryID == nil || *existing.TopicCategoryID != *req.TopicCategoryID { - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID) - if err != nil { - return nil, err - } - if category == nil { - return nil, errors.New("topic category not found") - } - } - } - - if req.TopicID != nil { - if existing.TopicID == nil || *existing.TopicID != *req.TopicID { - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID) - if err != nil { - return nil, err - } - if topic == nil { - return nil, errors.New("topic not found") - } - - categoryIDToCheck := req.TopicCategoryID - if categoryIDToCheck == nil { - categoryIDToCheck = existing.TopicCategoryID - } - if categoryIDToCheck != nil && topic.CategoryID != nil && *topic.CategoryID != *categoryIDToCheck { - return nil, errors.New("topic does not belong to the specified category") - } - } - } - - type fieldChange struct { - Field string `json:"field"` - Old interface{} `json:"old"` - New interface{} `json:"new"` - } - var changes []fieldChange - - if req.Action != nil && !utilscore.StrEq(existing.Action, req.Action) { - changes = append(changes, fieldChange{"action", utilscore.DerefStr(existing.Action), *req.Action}) - } - if req.RoleID != nil && !utilscore.Uint64Eq(existing.RoleID, req.RoleID) { - var oldVal interface{} - if existing.RoleID != nil { - oldVal = *existing.RoleID - } - changes = append(changes, fieldChange{"role_id", oldVal, *req.RoleID}) - } - if req.TopicCategoryID != nil && !utilscore.Uint64Eq(existing.TopicCategoryID, req.TopicCategoryID) { - var oldVal interface{} - if existing.TopicCategoryID != nil { - oldVal = *existing.TopicCategoryID - } - changes = append(changes, fieldChange{"topic_category_id", oldVal, *req.TopicCategoryID}) - } - if req.TopicID != nil && !utilscore.Uint64Eq(existing.TopicID, req.TopicID) { - var oldVal interface{} - if existing.TopicID != nil { - oldVal = *existing.TopicID - } - changes = append(changes, fieldChange{"topic_id", oldVal, *req.TopicID}) - } - - updatedPermission, _, err := s.ipc.Database.Permission.UpdatePermissionDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - s.enrichPermission(ctx, updatedPermission) - - if len(changes) > 0 { - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "permission", req.ID, - fmt.Sprintf("Изменено право роли «%s»", roleLabel(updatedPermission.Role)), - map[string]interface{}{"changes": changes}, - ) - } - } - - return updatedPermission, nil -} - -// DeletePermissionHandler Удаление права -// @Summary Удаление права -// @Description Удаление права по ID -// @Tags permissions -// @Accept json -// @Produce json -// @Param request body typescore.Permission true "ID права для удаления" -// @Success 200 {object} bool "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Право не найдено" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/permissions [delete] -func (s *PermissionsReg) DeletePermissionHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 DeletePermissionHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.Permission - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("permission id is required") - } - - ctx := r.Context() - - existingPermissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Permission{ID: req.ID}, - }) - if err != nil { - return nil, err - } - if len(existingPermissions) == 0 { - return nil, errors.New("permission not found") - } - existing := existingPermissions[0] - s.enrichPermission(ctx, existing) - - err = s.ipc.Database.Permission.DeletePermissionDB(ctx, &req) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "action": utilscore.DerefStr(existing.Action), - } - if existing.RoleID != nil { - snapshot["role_id"] = *existing.RoleID - } - if existing.TopicCategoryID != nil { - snapshot["topic_category_id"] = *existing.TopicCategoryID - } - if existing.TopicID != nil { - snapshot["topic_id"] = *existing.TopicID - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "delete", "permission", req.ID, - fmt.Sprintf("Отозвано право «%s» у роли «%s» на %s", utilscore.DerefStr(existing.Action), roleLabel(existing.Role), scopeLabel(existing)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return true, nil -} - -// enrichPermission подгружает связанные данные для права -func (s *PermissionsReg) enrichPermission(ctx context.Context, perm *typescore.Permission) { - if perm == nil { - return - } - - if perm.RoleID != nil { - role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *perm.RoleID) - if err == nil && role != nil { - perm.Role = role - } - } - - if perm.TopicCategoryID != nil { - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *perm.TopicCategoryID) - if err == nil && category != nil { - perm.TopicCategory = category - } - } - - if perm.TopicID != nil { - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *perm.TopicID) - if err == nil && topic != nil { - perm.Topic = topic - } - } -} - -// isValidAction проверяет валидность действия -func isValidAction(action string) bool { - validActions := map[string]bool{ - "create": true, - "read": true, - "update": true, - "delete": true, - "approve": true, - "revoke": true, - "observe": true, - } - return validActions[action] -} - -func roleLabel(role *typescore.Role) string { - if role == nil || role.Name == nil { - return "—" - } - return *role.Name -} - -func scopeLabel(perm *typescore.Permission) string { - if perm.Topic != nil && perm.Topic.Name != nil { - return "тему «" + *perm.Topic.Name + "»" - } - if perm.TopicCategory != nil && perm.TopicCategory.Name != nil { - return "категорию «" + *perm.TopicCategory.Name + "»" - } - return "все темы" -} - -func (s *PermissionsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - return nil, false - } - - return admins[0], true -} - ------END service/rest_admin_service/handlers/permission/handlers.go----- - -File: service/rest_admin_service/handlers/permission/routes.go -Lines: 43 ------BEGIN service/rest_admin_service/handlers/permission/routes.go----- -package permissionshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type PermissionsReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterPermissionRoutes регистрирует маршруты для группы permissions -func RegisterPermissionRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &PermissionsReg{ - ipc: ipc, - } - - r.Route("/api/permissions", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetPermissionsListHandler) - handlers.RegisterRoute(r, http.MethodPost, "/", s.CreatePermissionHandler) - handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdatePermissionHandler) - handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeletePermissionHandler) - - r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetPermissionByIDHandler, - })) - - r.Get("/by-role/{role_id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetPermissionsByRoleIDHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/permission/routes.go----- - -File: service/rest_admin_service/handlers/profile/handlers.go -Lines: 102 ------BEGIN service/rest_admin_service/handlers/profile/handlers.go----- -package profilehandler - -import ( - "bitrix_balancer_api/core/securecore" - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - "encoding/json" - "errors" - "github.com/sirupsen/logrus" - "io" - "net/http" -) - -// GetProfileHandler Получение профиля пользователя -// @Summary Получение профиля пользователя -// @Description Получение профиля пользователя -// @Tags profile -// @Accept json -// @Produce json -// @Success 200 {object} typescore.Admin -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/admin/profile [get] -func (h *ProfileReg) GetProfileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - ctx := r.Context() - - userID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, err - } - userObjBody := &typescore.Admin{ - ID: &userID, - } - - usersList, _, err := h.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{Filtering: userObjBody}) - if err != nil { - return nil, err - } - - if usersList == nil || len(usersList) == 0 { - return nil, errors.New("no users found") - } - - return usersList[0], nil -} - -// UpdateProfileHandler Обновление профиля пользователя -// @Summary Обновление профиля пользователя -// @Description Обновление профиля пользователя -// @Tags profile -// @Accept json -// @Produce json -// @Param request body typescore.AdminReq true "Запрос" -// @Success 200 {object} typescore.Admin -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/admin/profile [put] -func (h *ProfileReg) UpdateProfileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - ctx := r.Context() - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 error LoginByPassword: ReadAll: ", err) - return nil, err - } - - var req typescore.AdminReq - if err := json.Unmarshal(body, &req); err != nil { - return nil, err - } - - userID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, err - } - userObjBody := &typescore.Admin{ - ID: &userID, - } - - if req.Password != nil { - err := utilscore.ValidatePassword(*req.Password) - if err != nil { - return nil, err - } - - hash, err := securecore.HashPassword(req.Password) - - if err != nil { - return nil, err - } - userObjBody.PasswordHash = hash - } - - upUser, _, err := h.ipc.Database.Admin.UpdateAdminDB(nil, userObjBody, true) - if err != nil { - return nil, err - } - - return upUser, nil -} - ------END service/rest_admin_service/handlers/profile/handlers.go----- - -File: service/rest_admin_service/handlers/profile/routes.go -Lines: 36 ------BEGIN service/rest_admin_service/handlers/profile/routes.go----- -package profilehandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "github.com/go-chi/chi/v5" - "net/http" -) - -const ( - profileURI = "/" -) - -type ProfileReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterProfileRoutes регистрирует маршруты для группы profile -func RegisterProfileRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &ProfileReg{ - ipc: ipc, - } - - r.Route("/api/admin/profile", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, profileURI, s.GetProfileHandler) - handlers.RegisterRoute(r, http.MethodPut, profileURI, s.UpdateProfileHandler) - }) - - return nil -} - ------END service/rest_admin_service/handlers/profile/routes.go----- - -File: service/rest_admin_service/handlers/register.go -Lines: 162 ------BEGIN service/rest_admin_service/handlers/register.go----- -package handlers - -import ( - "encoding/json" - "errors" - "fmt" - "github.com/go-chi/chi/v5" - "io" - "net/http" - "strconv" -) - -// ErrorResponse структура для возврата ошибок -type ErrorResponse struct { - ErrorCode int `json:"error_code"` - ErrorDescription string `json:"error_description"` -} - -// 🆕 ExcelFileResponse — специальный тип ответа для скачивания файлов -type ExcelFileResponse struct { - Data []byte // Содержимое файла - FileName string // Имя файла для скачивания -} - -// WrapHandlerParams структура для параметров обертки -type WrapHandlerParams struct { - HandlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error) -} - -// responseWriterWrapper предотвращает повторный вызов WriteHeader -type responseWriterWrapper struct { - http.ResponseWriter - wroteHeader bool -} - -func (rw *responseWriterWrapper) WriteHeader(statusCode int) { - if !rw.wroteHeader { - rw.ResponseWriter.WriteHeader(statusCode) - rw.wroteHeader = true - } -} - -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) - - // 🆕 Проверяем, не файл ли это - if fileResp, ok := payload.(*ExcelFileResponse); ok && err == nil { - serveExcelFile(rw, fileResp) - return - } - - // Обычный JSON ответ - respondWithJSON(rw, err, payload) - } -} - -// 🆕 serveExcelFile отправляет файл как бинарный ответ -func serveExcelFile(w http.ResponseWriter, fileResp *ExcelFileResponse) { - // Устанавливаем заголовки ДО отправки тела - w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") - w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileResp.FileName)) - w.Header().Set("Content-Length", strconv.Itoa(len(fileResp.Data))) - w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") - - w.WriteHeader(http.StatusOK) - - // Отправляем содержимое файла - if _, err := w.Write(fileResp.Data); err != nil { - // Логируем ошибку, но заголовки уже отправлены - // Можно добавить логгер здесь - _ = err - } -} - -// 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 - } - } - - if rw, ok := w.(*responseWriterWrapper); ok { - if !rw.wroteHeader { - rw.WriteHeader(status) - } - } else { - w.WriteHeader(status) - } - - _, _ = w.Write(response) -} - ------END service/rest_admin_service/handlers/register.go----- - -File: service/rest_admin_service/handlers/roles/handlers.go -Lines: 385 ------BEGIN service/rest_admin_service/handlers/roles/handlers.go----- -package roleshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - "context" - "encoding/json" - "errors" - "fmt" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strconv" - "strings" - - "github.com/go-chi/chi/v5" -) - -// GetRolesListHandler Получение списка ролей -// @Summary Получение списка ролей -// @Description Получение списка ролей с пагинацией и фильтрацией -// @Tags roles -// @Accept json -// @Produce json -// @Param offset query integer false "Смещение для пагинации" -// @Param limit query integer false "Количество записей на странице" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/roles [get] -func (s *RolesReg) GetRolesListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - roleParams := &typescore.Role{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, roleParams) - if errW != nil { - return nil, errW - } - - options := typescore.ListDbOptions{ - Filtering: roleParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - ctx := r.Context() - rolesDbLst, total, errW := s.ipc.Database.Role.GetRolesListDB(ctx, options) - if errW != nil { - return nil, errW - } - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: rolesDbLst, - }, nil -} - -// GetRoleByIDHandler Получение роли по ID -// @Summary Получение роли по ID -// @Description Получение детальной информации о роли по её ID -// @Tags roles -// @Accept json -// @Produce json -// @Param id path integer true "ID роли" -// @Success 200 {object} typescore.Role "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Роль не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/roles/{id} [get] -func (s *RolesReg) GetRoleByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("role id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid role id") - } - - ctx := r.Context() - role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, id) - if err != nil { - return nil, err - } - - if role == nil { - return nil, errors.New("role not found") - } - - return role, nil -} - -// CreateRoleHandler Создание роли -// @Summary Создание роли -// @Description Создание новой роли -// @Tags roles -// @Accept json -// @Produce json -// @Param request body typescore.Role true "Данные роли" -// @Success 200 {object} typescore.Role "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/roles [post] -func (s *RolesReg) CreateRoleHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 CreateRoleHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.Role - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.Name == nil || *req.Name == "" { - return nil, errors.New("role name is required") - } - if req.Code == nil || *req.Code == "" { - return nil, errors.New("role code is required") - } - - ctx := r.Context() - existingRoles, _, err := s.ipc.Database.Role.GetRolesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Role{Code: req.Code}, - }) - if err != nil { - return nil, err - } - if len(existingRoles) > 0 { - return nil, errors.New("role code already exists") - } - - if req.IsDefault == nil { - v := false - req.IsDefault = &v - } - if req.IsDirector == nil { - v := false - req.IsDirector = &v - } - if req.IsApprover == nil { - v := false - req.IsApprover = &v - } - if req.IsObserver == nil { - v := false - req.IsObserver = &v - } - if req.IsExecutor == nil { - v := false - req.IsExecutor = &v - } - - createdRole, _, err := s.ipc.Database.Role.CreateRoleDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "name": utilscore.DerefStr(createdRole.Name), - "code": utilscore.DerefStr(createdRole.Code), - "is_default": utilscore.DerefBool(createdRole.IsDefault), - "is_director": utilscore.DerefBool(createdRole.IsDirector), - "is_approver": utilscore.DerefBool(createdRole.IsApprover), - "is_observer": utilscore.DerefBool(createdRole.IsObserver), - "is_executor": utilscore.DerefBool(createdRole.IsExecutor), - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "create", "role", createdRole.ID, - fmt.Sprintf("Создана роль «%s»", utilscore.DerefStr(createdRole.Name)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return createdRole, nil -} - -// UpdateRoleHandler Обновление роли -// @Summary Обновление роли -// @Description Обновление данных существующей роли -// @Tags roles -// @Accept json -// @Produce json -// @Param request body typescore.Role true "Данные роли" -// @Success 200 {object} typescore.Role "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Роль не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/roles [put] -func (s *RolesReg) UpdateRoleHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 UpdateRoleHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.Role - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("role id is required") - } - - ctx := r.Context() - existingRole, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existingRole == nil { - return nil, errors.New("role not found") - } - - if req.Code != nil && *req.Code != "" { - if existingRole.Code == nil || *existingRole.Code != *req.Code { - existingRoles, _, err := s.ipc.Database.Role.GetRolesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Role{Code: req.Code}, - }) - if err != nil { - return nil, err - } - if len(existingRoles) > 0 { - return nil, errors.New("role code already exists") - } - } - } - - type fieldChange struct { - Field string `json:"field"` - Old interface{} `json:"old"` - New interface{} `json:"new"` - } - var changes []fieldChange - var summary []string - - if req.Name != nil && !utilscore.StrEq(existingRole.Name, req.Name) { - changes = append(changes, fieldChange{"name", utilscore.DerefStr(existingRole.Name), *req.Name}) - summary = append(summary, fmt.Sprintf("название: «%s» → «%s»", utilscore.DerefStr(existingRole.Name), *req.Name)) - } - if req.Code != nil && !utilscore.StrEq(existingRole.Code, req.Code) { - changes = append(changes, fieldChange{"code", utilscore.DerefStr(existingRole.Code), *req.Code}) - summary = append(summary, fmt.Sprintf("код: «%s» → «%s»", utilscore.DerefStr(existingRole.Code), *req.Code)) - } - - boolFields := []struct { - name string - old *bool - new *bool - flag string - }{ - {"is_default", existingRole.IsDefault, req.IsDefault, "по умолчанию"}, - {"is_director", existingRole.IsDirector, req.IsDirector, "директор"}, - {"is_approver", existingRole.IsApprover, req.IsApprover, "согласующий"}, - {"is_observer", existingRole.IsObserver, req.IsObserver, "наблюдатель"}, - {"is_executor", existingRole.IsExecutor, req.IsExecutor, "исполнитель"}, - } - for _, f := range boolFields { - if f.new != nil && !utilscore.BoolEq(f.old, f.new) { - changes = append(changes, fieldChange{f.name, utilscore.DerefBool(f.old), *f.new}) - if *f.new { - summary = append(summary, fmt.Sprintf("включён флаг «%s»", f.flag)) - } else { - summary = append(summary, fmt.Sprintf("выключен флаг «%s»", f.flag)) - } - } - } - - updatedRole, _, err := s.ipc.Database.Role.UpdateRoleDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - if len(changes) > 0 { - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - description := fmt.Sprintf("Изменена роль «%s»: %s", utilscore.DerefStr(existingRole.Name), strings.Join(summary, "; ")) - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "role", req.ID, - description, - map[string]interface{}{"changes": changes}, - ) - } - } - - return updatedRole, nil -} - -// DeleteRoleHandler Удаление роли -// @Summary Удаление роли -// @Description Удаление роли по ID -// @Tags roles -// @Accept json -// @Produce json -// @Param request body typescore.Role true "ID роли для удаления" -// @Success 200 {object} bool "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Роль не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/roles [delete] -func (s *RolesReg) DeleteRoleHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 DeleteRoleHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.Role - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("role id is required") - } - - ctx := r.Context() - existingRole, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existingRole == nil { - return nil, errors.New("role not found") - } - - if existingRole.IsDefault != nil && *existingRole.IsDefault { - return nil, errors.New("cannot delete default role") - } - - err = s.ipc.Database.Role.DeleteRoleDB(ctx, &req) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "name": utilscore.DerefStr(existingRole.Name), - "code": utilscore.DerefStr(existingRole.Code), - "is_director": utilscore.DerefBool(existingRole.IsDirector), - "is_approver": utilscore.DerefBool(existingRole.IsApprover), - "is_observer": utilscore.DerefBool(existingRole.IsObserver), - "is_executor": utilscore.DerefBool(existingRole.IsExecutor), - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "delete", "role", req.ID, - fmt.Sprintf("Удалена роль «%s»", utilscore.DerefStr(existingRole.Name)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return true, nil -} - -func (s *RolesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - return nil, false - } - - return admins[0], true -} - ------END service/rest_admin_service/handlers/roles/handlers.go----- - -File: service/rest_admin_service/handlers/roles/routes.go -Lines: 39 ------BEGIN service/rest_admin_service/handlers/roles/routes.go----- -package roleshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type RolesReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterRoleRoutes регистрирует маршруты для группы roles -func RegisterRoleRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &RolesReg{ - ipc: ipc, - } - - r.Route("/api/roles", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetRolesListHandler) - handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateRoleHandler) - handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateRoleHandler) - handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteRoleHandler) - - r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetRoleByIDHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/roles/routes.go----- - -File: service/rest_admin_service/handlers/system_monitoring/handlers.go -Lines: 259 ------BEGIN service/rest_admin_service/handlers/system_monitoring/handlers.go----- -package monitoringhandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "context" - "net/http" - "os" - "os/exec" - "strconv" - "strings" - "syscall" - "time" - - "github.com/go-chi/chi/v5" -) - -type MonitoringReg struct { - ipc *typesm.InternalProviderControl - // 🆕 ВАЖНО: впишите реальные имена systemd-юнитов ваших сервисов — - // я не знаю точных названий, использовал правдоподобные заглушки. - // Узнать реальные: `systemctl list-units --type=service | grep -i bitrix` - // (или как вы их называли при настройке systemd-юнитов). - monitoredUnits []monitoredUnit -} - -type monitoredUnit struct { - Label string // как показывать в интерфейсе - Unit string // реальное имя systemd-юнита, например "bitrix-bot.service" -} - -func RegisterMonitoringRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error { - s := &MonitoringReg{ - ipc: ipc, - monitoredUnits: []monitoredUnit{ - {Label: "Telegram-бот", Unit: "bitrix-telegram-bot.service"}, - {Label: "Admin REST API", Unit: "bitrix-rest-admin.service"}, - {Label: "nginx", Unit: "nginx.service"}, - {Label: "PostgreSQL", Unit: "postgresql.service"}, - {Label: "Redis", Unit: "redis-server.service"}, - }, - } - - r.Route("/api/monitoring", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetMonitoringStatusHandler) - }) - - return nil -} - -func (s *MonitoringReg) GetMonitoringStatusHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - ctx := r.Context() - - services := make([]map[string]interface{}, 0, len(s.monitoredUnits)) - for _, u := range s.monitoredUnits { - services = append(services, s.checkSystemdUnit(u)) - } - - resources := getHostResources() - - dbHealthy, dbLatencyMs := s.checkDatabase(ctx) - redisHealthy, redisLatencyMs := s.checkRedis(ctx) - - return map[string]interface{}{ - "services": services, - "resources": resources, - "health": map[string]interface{}{ - "database": map[string]interface{}{ - "healthy": dbHealthy, - "latency_ms": dbLatencyMs, - }, - "redis": map[string]interface{}{ - "healthy": redisHealthy, - "latency_ms": redisLatencyMs, - }, - }, - "checked_at": time.Now().Format(time.RFC3339), - }, nil -} - -func (s *MonitoringReg) checkSystemdUnit(u monitoredUnit) map[string]interface{} { - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - defer cancel() - - cmd := exec.CommandContext(ctx, "systemctl", "show", u.Unit, - "--property=ActiveState,SubState,ActiveEnterTimestamp", "--value") - output, err := cmd.Output() - - result := map[string]interface{}{ - "label": u.Label, - "unit": u.Unit, - } - - if err != nil { - result["active"] = false - result["state"] = "unknown" - result["error"] = "не удалось получить статус (юнит не найден или нет прав)" - return result - } - - lines := strings.Split(strings.TrimSpace(string(output)), "\n") - activeState := "" - subState := "" - since := "" - if len(lines) >= 1 { - activeState = strings.TrimSpace(lines[0]) - } - if len(lines) >= 2 { - subState = strings.TrimSpace(lines[1]) - } - if len(lines) >= 3 { - since = strings.TrimSpace(lines[2]) - } - - result["active"] = activeState == "active" - result["state"] = activeState + "/" + subState - if since != "" { - result["since"] = since - } - - return result -} - -func getHostResources() map[string]interface{} { - return map[string]interface{}{ - "load_average": getLoadAverage(), - "memory": getMemoryInfo(), - "disk": getDiskInfo("/"), - "uptime_seconds": getUptimeSeconds(), - } -} - -// getLoadAverage — /proc/loadavg: "0.52 0.58 0.59 1/234 5678" -func getLoadAverage() map[string]interface{} { - data, err := readFile("/proc/loadavg") - if err != nil { - return map[string]interface{}{"error": "недоступно"} - } - fields := strings.Fields(data) - if len(fields) < 3 { - return map[string]interface{}{"error": "не удалось разобрать"} - } - l1, _ := strconv.ParseFloat(fields[0], 64) - l5, _ := strconv.ParseFloat(fields[1], 64) - l15, _ := strconv.ParseFloat(fields[2], 64) - return map[string]interface{}{"1m": l1, "5m": l5, "15m": l15} -} - -// getMemoryInfo — /proc/meminfo, ключевые поля в килобайтах у ядра -func getMemoryInfo() map[string]interface{} { - data, err := readFile("/proc/meminfo") - if err != nil { - return map[string]interface{}{"error": "недоступно"} - } - - values := map[string]uint64{} - for _, line := range strings.Split(data, "\n") { - parts := strings.Fields(line) - if len(parts) < 2 { - continue - } - key := strings.TrimSuffix(parts[0], ":") - val, err := strconv.ParseUint(parts[1], 10, 64) - if err != nil { - continue - } - values[key] = val * 1024 // kB -> bytes - } - - total := values["MemTotal"] - available := values["MemAvailable"] - used := uint64(0) - if total > available { - used = total - available - } - - percent := 0.0 - if total > 0 { - percent = float64(used) / float64(total) * 100 - } - - return map[string]interface{}{ - "total_bytes": total, - "used_bytes": used, - "available_bytes": available, - "used_percent": percent, - } -} - -// getDiskInfo — syscall.Statfs по корневой ФС (Linux) -func getDiskInfo(path string) map[string]interface{} { - var stat syscall.Statfs_t - if err := syscall.Statfs(path, &stat); err != nil { - return map[string]interface{}{"error": "недоступно"} - } - - total := stat.Blocks * uint64(stat.Bsize) - free := stat.Bavail * uint64(stat.Bsize) - used := total - free - - percent := 0.0 - if total > 0 { - percent = float64(used) / float64(total) * 100 - } - - return map[string]interface{}{ - "path": path, - "total_bytes": total, - "used_bytes": used, - "free_bytes": free, - "used_percent": percent, - } -} - -func getUptimeSeconds() float64 { - data, err := readFile("/proc/uptime") - if err != nil { - return 0 - } - fields := strings.Fields(data) - if len(fields) < 1 { - return 0 - } - seconds, _ := strconv.ParseFloat(fields[0], 64) - return seconds -} - -func (s *MonitoringReg) checkDatabase(ctx context.Context) (bool, int64) { - start := time.Now() - timeoutCtx, cancel := context.WithTimeout(ctx, 2*time.Second) - defer cancel() - - _, _, err := s.ipc.Database.User.GetUsersListDB(timeoutCtx) - latency := time.Since(start).Milliseconds() - - return err == nil, latency -} - -func (s *MonitoringReg) checkRedis(ctx context.Context) (bool, int64) { - start := time.Now() - timeoutCtx, cancel := context.WithTimeout(ctx, 2*time.Second) - defer cancel() - - err := s.ipc.RedisClient.RedisClient.Ping(timeoutCtx) - latency := time.Since(start).Milliseconds() - - return err == nil, latency -} - -func readFile(path string) (string, error) { - data, err := os.ReadFile(path) - if err != nil { - return "", err - } - return string(data), nil -} - ------END service/rest_admin_service/handlers/system_monitoring/handlers.go----- - -File: service/rest_admin_service/handlers/topic_categories/handlers.go -Lines: 361 ------BEGIN service/rest_admin_service/handlers/topic_categories/handlers.go----- -package categorieshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - "context" - "encoding/json" - "errors" - "fmt" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strconv" - "strings" - - "github.com/go-chi/chi/v5" -) - -// GetCategoriesListHandler Получение списка категорий тем -// @Summary Получение списка категорий тем -// @Description Получение списка категорий тем с пагинацией и фильтрацией -// @Tags categories -// @Accept json -// @Produce json -// @Param offset query integer false "Смещение для пагинации" -// @Param limit query integer false "Количество записей на странице" -// @Param is_active query boolean false "Фильтр по активности" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/categories [get] -func (s *CategoriesReg) GetCategoriesListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - categoryParams := &typescore.ApprovalTopicCategory{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, categoryParams) - if errW != nil { - return nil, errW - } - - options := typescore.ListDbOptions{ - Filtering: categoryParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - ctx := r.Context() - categoriesDbLst, total, errW := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, options) - if errW != nil { - return nil, errW - } - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: categoriesDbLst, - }, nil -} - -// GetCategoryByIDHandler Получение категории по ID -// @Summary Получение категории по ID -// @Description Получение детальной информации о категории по её ID -// @Tags categories -// @Accept json -// @Produce json -// @Param id path integer true "ID категории" -// @Success 200 {object} typescore.ApprovalTopicCategory "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Категория не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/categories/{id} [get] -func (s *CategoriesReg) GetCategoryByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("category id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid category id") - } - - ctx := r.Context() - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, id) - if err != nil { - return nil, err - } - - if category == nil { - return nil, errors.New("category not found") - } - - topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{CategoryID: &id}, - }) - if err == nil { - category.Topics = topics - } - - return category, nil -} - -// CreateCategoryHandler Создание категории тем -// @Summary Создание категории тем -// @Description Создание новой категории тем -// @Tags categories -// @Accept json -// @Produce json -// @Param request body typescore.ApprovalTopicCategory true "Данные категории" -// @Success 200 {object} typescore.ApprovalTopicCategory "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/categories [post] -func (s *CategoriesReg) CreateCategoryHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 CreateCategoryHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalTopicCategory - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.Name == nil || *req.Name == "" { - return nil, errors.New("category name is required") - } - if req.Code == nil || *req.Code == "" { - return nil, errors.New("category code is required") - } - - ctx := r.Context() - existingCategories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopicCategory{Code: req.Code}, - }) - if err != nil { - return nil, err - } - if len(existingCategories) > 0 { - return nil, errors.New("category code already exists") - } - - if req.IsActive == nil { - isActive := true - req.IsActive = &isActive - } - - createdCategory, _, err := s.ipc.Database.ApprovalTopicCategory.CreateApprovalTopicCategoryDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "name": utilscore.DerefStr(createdCategory.Name), - "code": utilscore.DerefStr(createdCategory.Code), - "is_active": utilscore.DerefBool(createdCategory.IsActive), - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "create", "category", createdCategory.ID, - fmt.Sprintf("Создана категория «%s»", utilscore.DerefStr(createdCategory.Name)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return createdCategory, nil -} - -// UpdateCategoryHandler Обновление категории -// @Summary Обновление категории -// @Description Обновление данных существующей категории -// @Tags categories -// @Accept json -// @Produce json -// @Param request body typescore.ApprovalTopicCategory true "Данные категории" -// @Success 200 {object} typescore.ApprovalTopicCategory "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Категория не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/categories [put] -func (s *CategoriesReg) UpdateCategoryHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 UpdateCategoryHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalTopicCategory - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("category id is required") - } - - ctx := r.Context() - existingCategory, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existingCategory == nil { - return nil, errors.New("category not found") - } - - if req.Code != nil && *req.Code != "" { - if existingCategory.Code == nil || *existingCategory.Code != *req.Code { - existingCategories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopicCategory{Code: req.Code}, - }) - if err != nil { - return nil, err - } - if len(existingCategories) > 0 { - return nil, errors.New("category code already exists") - } - } - } - - type fieldChange struct { - Field string `json:"field"` - Old interface{} `json:"old"` - New interface{} `json:"new"` - } - var changes []fieldChange - var summary []string - - if req.Name != nil && !utilscore.StrEq(existingCategory.Name, req.Name) { - changes = append(changes, fieldChange{"name", utilscore.DerefStr(existingCategory.Name), *req.Name}) - summary = append(summary, fmt.Sprintf("название: «%s» → «%s»", utilscore.DerefStr(existingCategory.Name), *req.Name)) - } - if req.Code != nil && !utilscore.StrEq(existingCategory.Code, req.Code) { - changes = append(changes, fieldChange{"code", utilscore.DerefStr(existingCategory.Code), *req.Code}) - summary = append(summary, fmt.Sprintf("код: «%s» → «%s»", utilscore.DerefStr(existingCategory.Code), *req.Code)) - } - if req.IsActive != nil && !utilscore.BoolEq(existingCategory.IsActive, req.IsActive) { - changes = append(changes, fieldChange{"is_active", utilscore.DerefBool(existingCategory.IsActive), *req.IsActive}) - if *req.IsActive { - summary = append(summary, "активирована") - } else { - summary = append(summary, "деактивирована") - } - } - - updatedCategory, _, err := s.ipc.Database.ApprovalTopicCategory.UpdateApprovalTopicCategoryDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - if len(changes) > 0 { - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - description := fmt.Sprintf("Изменена категория «%s»: %s", utilscore.DerefStr(existingCategory.Name), strings.Join(summary, "; ")) - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "category", req.ID, - description, - map[string]interface{}{"changes": changes}, - ) - } - } - - return updatedCategory, nil -} - -// DeleteCategoryHandler Удаление категории -// @Summary Удаление категории -// @Description Удаление категории по ID -// @Tags categories -// @Accept json -// @Produce json -// @Param request body typescore.ApprovalTopicCategory true "ID категории для удаления" -// @Success 200 {object} bool "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Категория не найдена" -// @Failure 409 {object} handlers.ErrorResponse "Категория содержит темы" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/categories [delete] -func (s *CategoriesReg) DeleteCategoryHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 DeleteCategoryHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalTopicCategory - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("category id is required") - } - - ctx := r.Context() - existingCategory, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existingCategory == nil { - return nil, errors.New("category not found") - } - - topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{CategoryID: req.ID}, - }) - if err != nil { - return nil, err - } - if len(topics) > 0 { - return nil, errors.New("cannot delete category: it contains topics") - } - - err = s.ipc.Database.ApprovalTopicCategory.DeleteApprovalTopicCategoryDB(ctx, &req) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "name": utilscore.DerefStr(existingCategory.Name), - "code": utilscore.DerefStr(existingCategory.Code), - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "delete", "category", req.ID, - fmt.Sprintf("Удалена категория «%s»", utilscore.DerefStr(existingCategory.Name)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return true, nil -} - -func (s *CategoriesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - return nil, false - } - - return admins[0], true -} - ------END service/rest_admin_service/handlers/topic_categories/handlers.go----- - -File: service/rest_admin_service/handlers/topic_categories/routes.go -Lines: 39 ------BEGIN service/rest_admin_service/handlers/topic_categories/routes.go----- -package categorieshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type CategoriesReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterCategoryRoutes регистрирует маршруты для группы categories -func RegisterCategoryRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &CategoriesReg{ - ipc: ipc, - } - - r.Route("/api/categories", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetCategoriesListHandler) - handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateCategoryHandler) - handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateCategoryHandler) - handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteCategoryHandler) - - r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetCategoryByIDHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/topic_categories/routes.go----- - -File: service/rest_admin_service/handlers/topic_executors/handlers.go -Lines: 603 ------BEGIN service/rest_admin_service/handlers/topic_executors/handlers.go----- -package topicexecutorshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - "context" - "encoding/json" - "errors" - "fmt" - "github.com/go-chi/chi/v5" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strconv" - "strings" -) - -// GetTopicExecutorsListHandler Получение списка исполнителей тем -// @Summary Получение списка исполнителей тем -// @Description Получение списка исполнителей с пагинацией и фильтрацией -// @Tags topic-executors -// @Accept json -// @Produce json -// @Param offset query integer false "Смещение для пагинации" -// @Param limit query integer false "Количество записей на странице" -// @Param topic_id query integer false "Фильтр по теме" -// @Param user_id query integer false "Фильтр по пользователю" -// @Param category_id query integer false "Фильтр по категории темы" -// @Param is_active query boolean false "Фильтр по активности" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/topic-executors [get] -func (s *TopicExecutorsReg) GetTopicExecutorsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - executorParams := &typescore.ApprovalTopicExecutor{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, executorParams) - if errW != nil { - return nil, errW - } - - var categoryID *uint64 - if categoryIDStr := queryParams.Get("category_id"); categoryIDStr != "" { - if id, err := strconv.ParseUint(categoryIDStr, 10, 64); err == nil { - categoryID = &id - } - } - - options := typescore.ListDbOptions{ - Filtering: executorParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - ctx := r.Context() - - var executorsDbLst []*typescore.ApprovalTopicExecutor - var total uint64 - var err error - - if categoryID != nil { - executorsDbLst, total, err = s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListByCategoryDB(ctx, options, *categoryID) - } else { - executorsDbLst, total, err = s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, options) - } - - if err != nil { - return nil, err - } - - s.enrichExecutorsBatch(ctx, executorsDbLst) - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: executorsDbLst, - }, nil -} - -// GetExecutorsByTopicIDHandler Получение всех исполнителей для темы -// @Summary Получение исполнителей по теме -// @Description Получение списка всех активных исполнителей для указанной темы, отсортированных по step_order -// @Tags topic-executors -// @Accept json -// @Produce json -// @Param topic_id path integer true "ID темы" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Тема не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/topic-executors/by-topic/{topic_id} [get] -func (s *TopicExecutorsReg) GetExecutorsByTopicIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - topicIDStr := chi.URLParam(r, "topic_id") - if topicIDStr == "" { - return nil, errors.New("topic_id is required") - } - - topicID, err := strconv.ParseUint(topicIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid topic_id") - } - - ctx := r.Context() - - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID) - if err != nil { - return nil, err - } - if topic == nil { - return nil, errors.New("topic not found") - } - - executors, err := s.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, topicID) - if err != nil { - return nil, err - } - - s.enrichExecutorsBatch(ctx, executors) - - return &typescore.ApiResponseBase{ - TotalCount: uint64(len(executors)), - Data: executors, - }, nil -} - -// enrichExecutorsBatch пакетно подгружает темы и пользователей для списка исполнителей -func (s *TopicExecutorsReg) enrichExecutorsBatch(ctx context.Context, executors []*typescore.ApprovalTopicExecutor) { - if len(executors) == 0 { - return - } - - topicIDsSet := make(map[uint64]struct{}) - userIDsSet := make(map[uint64]struct{}) - for _, e := range executors { - if e.TopicID != nil { - topicIDsSet[*e.TopicID] = struct{}{} - } - if e.UserID != nil { - userIDsSet[*e.UserID] = struct{}{} - } - } - - topicIDs := make([]uint64, 0, len(topicIDsSet)) - for id := range topicIDsSet { - topicIDs = append(topicIDs, id) - } - userIDs := make([]uint64, 0, len(userIDsSet)) - for id := range userIDsSet { - userIDs = append(userIDs, id) - } - - topicsMap := make(map[uint64]*typescore.ApprovalTopic) - if topics, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsByIDsDB(ctx, topicIDs); err == nil { - for _, t := range topics { - if t.ID != nil { - topicsMap[*t.ID] = t - } - } - } - - usersMap := make(map[uint64]*typescore.User) - if users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, userIDs); err == nil { - for _, u := range users { - if u.ID != nil { - usersMap[*u.ID] = u - } - } - } - - for _, e := range executors { - if e.TopicID != nil { - if t, ok := topicsMap[*e.TopicID]; ok { - e.Topic = t - } - } - if e.UserID != nil { - if u, ok := usersMap[*e.UserID]; ok { - e.User = u - } - } - } -} - -// GetTopicExecutorByIDHandler Получение исполнителя по ID -// @Summary Получение исполнителя по ID -// @Description Получение детальной информации об исполнителе по его ID -// @Tags topic-executors -// @Accept json -// @Produce json -// @Param id path integer true "ID исполнителя" -// @Success 200 {object} typescore.ApprovalTopicExecutor "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Исполнитель не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/topic-executors/{id} [get] -func (s *TopicExecutorsReg) GetTopicExecutorByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("executor id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid executor id") - } - - ctx := r.Context() - executors, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopicExecutor{ID: &id}, - }) - if err != nil { - return nil, err - } - if len(executors) == 0 { - return nil, errors.New("topic executor not found") - } - - executor := executors[0] - s.enrichExecutor(ctx, executor) - - return executor, nil -} - -// CreateTopicExecutorHandler Создание исполнителя для темы -// @Summary Создание исполнителя -// @Description Назначение исполнителя для конкретной темы согласования -// @Tags topic-executors -// @Accept json -// @Produce json -// @Param request body typescore.ApprovalTopicExecutor true "Данные исполнителя" -// @Success 200 {object} typescore.ApprovalTopicExecutor "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Тема или пользователь не найдены" -// @Failure 409 {object} handlers.ErrorResponse "Такой исполнитель уже назначен на этот шаг" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/topic-executors [post] -func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 CreateTopicExecutorHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalTopicExecutor - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.TopicID == nil { - return nil, errors.New("topic_id is required") - } - if req.UserID == nil { - return nil, errors.New("user_id is required") - } - - ctx := r.Context() - - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID) - if err != nil { - return nil, err - } - if topic == nil { - return nil, errors.New("topic not found") - } - - user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID) - if err != nil { - return nil, err - } - if user == nil { - return nil, errors.New("user not found") - } - - if user.IsBlocked != nil && *user.IsBlocked { - return nil, errors.New("user is blocked") - } - if user.IsFired != nil && *user.IsFired { - return nil, errors.New("user is fired") - } - - stepOrder := 0 - if req.StepOrder != nil { - stepOrder = *req.StepOrder - } - existingExecutors, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopicExecutor{ - TopicID: req.TopicID, - UserID: req.UserID, - StepOrder: &stepOrder, - }, - }) - if err != nil { - return nil, err - } - if len(existingExecutors) > 0 { - return nil, errors.New("this executor is already assigned to this step for the topic") - } - - if req.StepOrder == nil { - defaultStep := 0 - req.StepOrder = &defaultStep - } - if req.RequireFile == nil { - defaultRequire := false - req.RequireFile = &defaultRequire - } - if req.IsActive == nil { - defaultActive := true - req.IsActive = &defaultActive - } - - createdExecutor, _, err := s.ipc.Database.ApprovalTopicExecutor.CreateApprovalTopicExecutorDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - s.enrichExecutor(ctx, createdExecutor) - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "topic_id": *req.TopicID, - "user_id": *req.UserID, - "step_order": utilscore.DerefInt(createdExecutor.StepOrder), - "require_file": utilscore.DerefBool(createdExecutor.RequireFile), - "is_active": utilscore.DerefBool(createdExecutor.IsActive), - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "create", "topic_executor", createdExecutor.ID, - fmt.Sprintf("Назначен исполнитель «%s» на тему «%s»", userLabel(createdExecutor.User), topicLabel(createdExecutor.Topic)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return createdExecutor, nil -} - -// UpdateTopicExecutorHandler Обновление исполнителя -// @Summary Обновление исполнителя -// @Description Обновление данных исполнителя для темы -// @Tags topic-executors -// @Accept json -// @Produce json -// @Param request body typescore.ApprovalTopicExecutor true "Данные исполнителя" -// @Success 200 {object} typescore.ApprovalTopicExecutor "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Исполнитель не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/topic-executors [put] -func (s *TopicExecutorsReg) UpdateTopicExecutorHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 UpdateTopicExecutorHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalTopicExecutor - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("executor id is required") - } - - ctx := r.Context() - - existingExecutors, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopicExecutor{ID: req.ID}, - }) - if err != nil { - return nil, err - } - if len(existingExecutors) == 0 { - return nil, errors.New("topic executor not found") - } - existing := existingExecutors[0] - s.enrichExecutor(ctx, existing) - - if req.TopicID != nil { - if existing.TopicID == nil || *existing.TopicID != *req.TopicID { - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID) - if err != nil { - return nil, err - } - if topic == nil { - return nil, errors.New("topic not found") - } - } - } - - if req.UserID != nil { - if existing.UserID == nil || *existing.UserID != *req.UserID { - user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID) - if err != nil { - return nil, err - } - if user == nil { - return nil, errors.New("user not found") - } - if user.IsBlocked != nil && *user.IsBlocked { - return nil, errors.New("user is blocked") - } - if user.IsFired != nil && *user.IsFired { - return nil, errors.New("user is fired") - } - } - } - - type fieldChange struct { - Field string `json:"field"` - Old interface{} `json:"old"` - New interface{} `json:"new"` - } - var changes []fieldChange - var summary []string - - if req.UserID != nil && !utilscore.Uint64Eq(existing.UserID, req.UserID) { - var oldVal interface{} - if existing.UserID != nil { - oldVal = *existing.UserID - } - changes = append(changes, fieldChange{"user_id", oldVal, *req.UserID}) - summary = append(summary, "заменён исполнитель") - } - if req.StepOrder != nil && !utilscore.IntEq(existing.StepOrder, req.StepOrder) { - var oldVal interface{} - if existing.StepOrder != nil { - oldVal = *existing.StepOrder - } - changes = append(changes, fieldChange{"step_order", oldVal, *req.StepOrder}) - summary = append(summary, fmt.Sprintf("порядок шага: %v → %d", oldVal, *req.StepOrder)) - } - if req.RequireFile != nil && !utilscore.BoolEq(existing.RequireFile, req.RequireFile) { - changes = append(changes, fieldChange{"require_file", utilscore.DerefBool(existing.RequireFile), *req.RequireFile}) - if *req.RequireFile { - summary = append(summary, "включено обязательное вложение файла") - } else { - summary = append(summary, "отключено обязательное вложение файла") - } - } - if req.IsActive != nil && !utilscore.BoolEq(existing.IsActive, req.IsActive) { - changes = append(changes, fieldChange{"is_active", utilscore.DerefBool(existing.IsActive), *req.IsActive}) - if *req.IsActive { - summary = append(summary, "активирован") - } else { - summary = append(summary, "деактивирован") - } - } - - updatedExecutor, _, err := s.ipc.Database.ApprovalTopicExecutor.UpdateApprovalTopicExecutorDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - s.enrichExecutor(ctx, updatedExecutor) - - if len(changes) > 0 { - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - description := fmt.Sprintf("Изменён исполнитель темы «%s»: %s", topicLabel(existing.Topic), strings.Join(summary, "; ")) - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "topic_executor", req.ID, - description, - map[string]interface{}{"changes": changes}, - ) - } - } - - return updatedExecutor, nil -} - -// DeleteTopicExecutorHandler Удаление исполнителя -// @Summary Удаление исполнителя -// @Description Удаление исполнителя из темы по ID -// @Tags topic-executors -// @Accept json -// @Produce json -// @Param request body typescore.ApprovalTopicExecutor true "ID записи для удаления" -// @Success 200 {object} bool "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Запись не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/topic-executors [delete] -func (s *TopicExecutorsReg) DeleteTopicExecutorHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 DeleteTopicExecutorHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalTopicExecutor - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("executor id is required") - } - - ctx := r.Context() - - existingExecutors, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopicExecutor{ID: req.ID}, - }) - if err != nil { - return nil, err - } - if len(existingExecutors) == 0 { - return nil, errors.New("topic executor not found") - } - existing := existingExecutors[0] - s.enrichExecutor(ctx, existing) - - err = s.ipc.Database.ApprovalTopicExecutor.DeleteApprovalTopicExecutorDB(ctx, &req) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "step_order": utilscore.DerefInt(existing.StepOrder), - "require_file": utilscore.DerefBool(existing.RequireFile), - } - if existing.TopicID != nil { - snapshot["topic_id"] = *existing.TopicID - } - if existing.UserID != nil { - snapshot["user_id"] = *existing.UserID - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "delete", "topic_executor", req.ID, - fmt.Sprintf("Снят исполнитель «%s» с темы «%s»", userLabel(existing.User), topicLabel(existing.Topic)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return true, nil -} - -// enrichExecutor подгружает связанные данные для записи исполнителя -func (s *TopicExecutorsReg) enrichExecutor(ctx context.Context, exec *typescore.ApprovalTopicExecutor) { - if exec == nil { - return - } - - if exec.TopicID != nil { - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *exec.TopicID) - if err == nil && topic != nil { - exec.Topic = topic - } - } - - if exec.UserID != nil { - user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *exec.UserID) - if err == nil && user != nil { - exec.User = user - } - } -} - -func topicLabel(topic *typescore.ApprovalTopic) string { - if topic == nil || topic.Name == nil { - return "—" - } - return *topic.Name -} - -func userLabel(user *typescore.User) string { - if user == nil || user.FullName == nil { - return "—" - } - return *user.FullName -} - -func (s *TopicExecutorsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - return nil, false - } - - return admins[0], true -} - ------END service/rest_admin_service/handlers/topic_executors/handlers.go----- - -File: service/rest_admin_service/handlers/topic_executors/routes.go -Lines: 43 ------BEGIN service/rest_admin_service/handlers/topic_executors/routes.go----- -package topicexecutorshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type TopicExecutorsReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterTopicExecutorRoutes регистрирует маршруты для группы topic-executors -func RegisterTopicExecutorRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &TopicExecutorsReg{ - ipc: ipc, - } - - r.Route("/api/topic-executors", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetTopicExecutorsListHandler) - handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateTopicExecutorHandler) - handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateTopicExecutorHandler) - handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteTopicExecutorHandler) - - r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetTopicExecutorByIDHandler, - })) - - r.Get("/by-topic/{topic_id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetExecutorsByTopicIDHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/topic_executors/routes.go----- - -File: service/rest_admin_service/handlers/topics/handlers.go -Lines: 519 ------BEGIN service/rest_admin_service/handlers/topics/handlers.go----- -package topicshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - "context" - "encoding/json" - "errors" - "fmt" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strconv" - "strings" - - "github.com/go-chi/chi/v5" -) - -// GetTopicsListHandler Получение списка тем -// @Summary Получение списка тем -// @Description Получение списка тем с пагинацией и фильтрацией -// @Tags topics -// @Accept json -// @Produce json -// @Param offset query integer false "Смещение для пагинации" -// @Param limit query integer false "Количество записей на странице" -// @Param category_id query integer false "Фильтр по категории" -// @Param is_active query boolean false "Фильтр по активности" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/topics [get] -func (s *TopicsReg) GetTopicsListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - topicParams := &typescore.ApprovalTopic{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, topicParams) - if errW != nil { - return nil, errW - } - - options := typescore.ListDbOptions{ - Filtering: topicParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - ctx := r.Context() - topicsDbLst, total, errW := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, options) - if errW != nil { - return nil, errW - } - - categoryIDsSet := make(map[uint64]struct{}) - for _, topic := range topicsDbLst { - if topic.CategoryID != nil { - categoryIDsSet[*topic.CategoryID] = struct{}{} - } - } - categoryIDs := make([]uint64, 0, len(categoryIDsSet)) - for id := range categoryIDsSet { - categoryIDs = append(categoryIDs, id) - } - - categoriesMap := make(map[uint64]*typescore.ApprovalTopicCategory) - if categories, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoriesByIDsDB(ctx, categoryIDs); err == nil { - for _, c := range categories { - if c.ID != nil { - categoriesMap[*c.ID] = c - } - } - } - - for _, topic := range topicsDbLst { - if topic.CategoryID != nil { - if cat, ok := categoriesMap[*topic.CategoryID]; ok { - topic.Category = cat - } - } - } - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: topicsDbLst, - }, nil -} - -// GetTopicByIDHandler Получение темы по ID -// @Summary Получение темы по ID -// @Description Получение детальной информации о теме по её ID -// @Tags topics -// @Accept json -// @Produce json -// @Param id path integer true "ID темы" -// @Success 200 {object} typescore.ApprovalTopic "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Тема не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/topics/{id} [get] -func (s *TopicsReg) GetTopicByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("topic id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid topic id") - } - - ctx := r.Context() - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, id) - if err != nil { - return nil, err - } - - if topic == nil { - return nil, errors.New("topic not found") - } - - if topic.CategoryID != nil { - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID) - if err == nil && category != nil { - topic.Category = category - } - } - - return topic, nil -} - -// CreateTopicHandler Создание темы -// @Summary Создание темы -// @Description Создание новой темы согласования -// @Tags topics -// @Accept json -// @Produce json -// @Param request body typescore.ApprovalTopic true "Данные темы" -// @Success 200 {object} typescore.ApprovalTopic "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/topics [post] -func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 CreateTopicHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalTopic - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.Name == nil || *req.Name == "" { - return nil, errors.New("topic name is required") - } - if req.Code == nil || *req.Code == "" { - return nil, errors.New("topic code is required") - } - if req.CategoryID == nil { - return nil, errors.New("category_id is required") - } - - ctx := r.Context() - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.CategoryID) - if err != nil { - return nil, err - } - if category == nil { - return nil, errors.New("category not found") - } - - existingTopics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{Code: req.Code}, - }) - if err != nil { - return nil, err - } - if len(existingTopics) > 0 { - return nil, errors.New("topic code already exists") - } - - if req.IsActive == nil { - isActive := true - req.IsActive = &isActive - } - if req.ApprovalMode == nil { - mode := "sequential" - req.ApprovalMode = &mode - } - if req.AllowsFile == nil { - v := false - req.AllowsFile = &v - } - if req.AllowApproverSelection == nil { - v := false - req.AllowApproverSelection = &v - } - if req.AllowObserverSelection == nil { - v := false - req.AllowObserverSelection = &v - } - if req.RequireApproverComment == nil { - v := false - req.RequireApproverComment = &v - } - if req.RequiresFile == nil { - v := false - req.RequiresFile = &v - } - if req.RequireObserverSelection == nil { - v := false - req.RequireObserverSelection = &v - } - - createdTopic, _, err := s.ipc.Database.ApprovalTopic.CreateApprovalTopicDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - if createdTopic.CategoryID != nil { - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *createdTopic.CategoryID) - if err == nil && category != nil { - createdTopic.Category = category - } - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "name": utilscore.DerefStr(createdTopic.Name), - "code": utilscore.DerefStr(createdTopic.Code), - "category_id": *req.CategoryID, - "approval_mode": utilscore.DerefStr(createdTopic.ApprovalMode), - "allows_file": utilscore.DerefBool(createdTopic.AllowsFile), - "requires_file": utilscore.DerefBool(createdTopic.RequiresFile), - "allow_approver_selection": utilscore.DerefBool(createdTopic.AllowApproverSelection), - "allow_observer_selection": utilscore.DerefBool(createdTopic.AllowObserverSelection), - "require_observer_selection": utilscore.DerefBool(createdTopic.RequireObserverSelection), - "require_approver_comment": utilscore.DerefBool(createdTopic.RequireApproverComment), - "is_active": utilscore.DerefBool(createdTopic.IsActive), - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "create", "topic", createdTopic.ID, - fmt.Sprintf("Создана тема «%s» (%s)", utilscore.DerefStr(createdTopic.Name), categoryLabel(createdTopic.Category)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return createdTopic, nil -} - -// UpdateTopicHandler Обновление темы -// @Summary Обновление темы -// @Description Обновление данных существующей темы -// @Tags topics -// @Accept json -// @Produce json -// @Param request body typescore.ApprovalTopic true "Данные темы" -// @Success 200 {object} typescore.ApprovalTopic "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Тема не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/topics [put] -func (s *TopicsReg) UpdateTopicHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 UpdateTopicHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalTopic - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("topic id is required") - } - - ctx := r.Context() - existingTopic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existingTopic == nil { - return nil, errors.New("topic not found") - } - - if req.CategoryID != nil { - if existingTopic.CategoryID == nil || *existingTopic.CategoryID != *req.CategoryID { - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.CategoryID) - if err != nil { - return nil, err - } - if category == nil { - return nil, errors.New("category not found") - } - } - } - - if req.Code != nil && *req.Code != "" { - if existingTopic.Code == nil || *existingTopic.Code != *req.Code { - existingTopics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{Code: req.Code}, - }) - if err != nil { - return nil, err - } - if len(existingTopics) > 0 { - return nil, errors.New("topic code already exists") - } - } - } - - type fieldChange struct { - Field string `json:"field"` - Old interface{} `json:"old"` - New interface{} `json:"new"` - } - var changes []fieldChange - var summary []string - - strFields := []struct { - name string - old *string - new *string - label string - }{ - {"name", existingTopic.Name, req.Name, "название"}, - {"code", existingTopic.Code, req.Code, "код"}, - {"approval_mode", existingTopic.ApprovalMode, req.ApprovalMode, "режим согласования"}, - {"duration_type", existingTopic.DurationType, req.DurationType, "тип длительности"}, - {"time_type", existingTopic.TimeType, req.TimeType, "тип времени"}, - {"payment_type", existingTopic.PaymentType, req.PaymentType, "тип оплаты"}, - {"first_approver_role_code", existingTopic.FirstApproverRoleCode, req.FirstApproverRoleCode, "роль первого согласующего"}, - } - for _, f := range strFields { - if f.new != nil && !utilscore.StrEq(f.old, f.new) { - changes = append(changes, fieldChange{f.name, utilscore.DerefStr(f.old), *f.new}) - summary = append(summary, fmt.Sprintf("%s: «%s» → «%s»", f.label, utilscore.DerefStr(f.old), *f.new)) - } - } - - boolFields := []struct { - name string - old *bool - new *bool - label string - }{ - {"is_active", existingTopic.IsActive, req.IsActive, "активна"}, - {"allows_file", existingTopic.AllowsFile, req.AllowsFile, "разрешён файл"}, - {"requires_file", existingTopic.RequiresFile, req.RequiresFile, "обязателен файл"}, - {"allow_approver_selection", existingTopic.AllowApproverSelection, req.AllowApproverSelection, "выбор согласующего"}, - {"allow_observer_selection", existingTopic.AllowObserverSelection, req.AllowObserverSelection, "выбор наблюдателя"}, - {"require_observer_selection", existingTopic.RequireObserverSelection, req.RequireObserverSelection, "наблюдатель обязателен"}, - {"require_approver_comment", existingTopic.RequireApproverComment, req.RequireApproverComment, "комментарий обязателен"}, - {"allow_delegation_selection", existingTopic.AllowDelegationSelection, req.AllowDelegationSelection, "делегирование обязанностей"}, - } - for _, f := range boolFields { - if f.new != nil && !utilscore.BoolEq(f.old, f.new) { - changes = append(changes, fieldChange{f.name, utilscore.DerefBool(f.old), *f.new}) - if *f.new { - summary = append(summary, fmt.Sprintf("включено «%s»", f.label)) - } else { - summary = append(summary, fmt.Sprintf("выключено «%s»", f.label)) - } - } - } - - if req.CategoryID != nil && !utilscore.Uint64Eq(existingTopic.CategoryID, req.CategoryID) { - var oldVal interface{} - if existingTopic.CategoryID != nil { - oldVal = *existingTopic.CategoryID - } - changes = append(changes, fieldChange{"category_id", oldVal, *req.CategoryID}) - summary = append(summary, "изменена категория") - } - - updatedTopic, _, err := s.ipc.Database.ApprovalTopic.UpdateApprovalTopicDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - if updatedTopic.CategoryID != nil { - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *updatedTopic.CategoryID) - if err == nil && category != nil { - updatedTopic.Category = category - } - } - - if len(changes) > 0 { - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - description := fmt.Sprintf("Изменена тема «%s»: %s", utilscore.DerefStr(existingTopic.Name), strings.Join(summary, "; ")) - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "topic", req.ID, - description, - map[string]interface{}{"changes": changes}, - ) - } - } - - return updatedTopic, nil -} - -// DeleteTopicHandler Удаление темы -// @Summary Удаление темы -// @Description Удаление темы по ID -// @Tags topics -// @Accept json -// @Produce json -// @Param request body typescore.ApprovalTopic true "ID темы для удаления" -// @Success 200 {object} bool "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Тема не найдена" -// @Failure 409 {object} handlers.ErrorResponse "Тема содержит заявки" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/topics [delete] -func (s *TopicsReg) DeleteTopicHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 DeleteTopicHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.ApprovalTopic - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("topic id is required") - } - - ctx := r.Context() - existingTopic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existingTopic == nil { - return nil, errors.New("topic not found") - } - - approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Approval{TopicID: req.ID}, - }) - if err != nil { - return nil, err - } - if len(approvals) > 0 { - return nil, errors.New("cannot delete topic: it has existing approvals") - } - - if existingTopic.CategoryID != nil { - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *existingTopic.CategoryID) - if err == nil && category != nil { - existingTopic.Category = category - } - } - - err = s.ipc.Database.ApprovalTopic.DeleteApprovalTopicDB(ctx, &req) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "name": utilscore.DerefStr(existingTopic.Name), - "code": utilscore.DerefStr(existingTopic.Code), - } - if existingTopic.CategoryID != nil { - snapshot["category_id"] = *existingTopic.CategoryID - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "delete", "topic", req.ID, - fmt.Sprintf("Удалена тема «%s» (%s)", utilscore.DerefStr(existingTopic.Name), categoryLabel(existingTopic.Category)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return true, nil -} - -func categoryLabel(category *typescore.ApprovalTopicCategory) string { - if category == nil || category.Name == nil { - return "—" - } - return *category.Name -} - -func (s *TopicsReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - return nil, false - } - - return admins[0], true -} - ------END service/rest_admin_service/handlers/topics/handlers.go----- - -File: service/rest_admin_service/handlers/topics/routes.go -Lines: 39 ------BEGIN service/rest_admin_service/handlers/topics/routes.go----- -package topicshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type TopicsReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterTopicRoutes регистрирует маршруты для группы topics -func RegisterTopicRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &TopicsReg{ - ipc: ipc, - } - - r.Route("/api/topics", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetTopicsListHandler) - handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateTopicHandler) - handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateTopicHandler) - handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteTopicHandler) - - r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetTopicByIDHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/topics/routes.go----- - -File: service/rest_admin_service/handlers/user_hierarchy/handlers.go -Lines: 531 ------BEGIN service/rest_admin_service/handlers/user_hierarchy/handlers.go----- -package hierarchieshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - "context" - "encoding/json" - "errors" - "fmt" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strconv" - "strings" - - "github.com/go-chi/chi/v5" -) - -// GetHierarchiesListHandler Получение списка записей иерархии -// @Summary Получение списка записей иерархии -// @Description Получение списка связей подчинённый-согласующий с пагинацией и фильтрацией -// @Tags hierarchies -// @Accept json -// @Produce json -// @Param offset query integer false "Смещение для пагинации" -// @Param limit query integer false "Количество записей на странице" -// @Param subordinate_id query integer false "Фильтр по подчинённому" -// @Param approver_id query integer false "Фильтр по согласующему" -// @Param department_id query integer false "Фильтр по отделу" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/hierarchies [get] -func (s *HierarchiesReg) GetHierarchiesListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - hierarchyParams := &typescore.UserHierarchy{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, hierarchyParams) - if errW != nil { - return nil, errW - } - - options := typescore.ListDbOptions{ - Filtering: hierarchyParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - ctx := r.Context() - hierarchiesDbLst, total, errW := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(ctx, options) - if errW != nil { - return nil, errW - } - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: hierarchiesDbLst, - }, nil -} - -// GetHierarchyByIDHandler Получение записи иерархии по ID -// @Summary Получение записи иерархии по ID -// @Description Получение детальной информации о записи иерархии по её ID -// @Tags hierarchies -// @Accept json -// @Produce json -// @Param id path integer true "ID записи" -// @Success 200 {object} typescore.UserHierarchy "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Запись не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/hierarchies/{id} [get] -func (s *HierarchiesReg) GetHierarchyByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("hierarchy id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid hierarchy id") - } - - ctx := r.Context() - hierarchies, _, err := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(ctx, typescore.ListDbOptions{ - Filtering: &typescore.UserHierarchy{ID: &id}, - }) - if err != nil { - return nil, err - } - if len(hierarchies) == 0 { - return nil, errors.New("hierarchy not found") - } - - hierarchy := hierarchies[0] - return hierarchy, nil -} - -// CreateHierarchyHandler Создание записи иерархии -// @Summary Создание записи иерархии -// @Description Создание новой связи подчинённый-согласующий -// @Tags hierarchies -// @Accept json -// @Produce json -// @Param request body typescore.UserHierarchy true "Данные иерархии" -// @Success 200 {object} typescore.UserHierarchy "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 409 {object} handlers.ErrorResponse "Такая связь уже существует" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/hierarchies [post] -func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 CreateHierarchyHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.UserHierarchy - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.SubordinateID == nil { - return nil, errors.New("subordinate_id is required") - } - if req.ApproverID == nil { - return nil, errors.New("approver_id is required") - } - if req.DepartmentID == nil { - return nil, errors.New("department_id is required") - } - - ctx := r.Context() - - subordinate, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.SubordinateID) - if err != nil { - return nil, err - } - if subordinate == nil { - return nil, errors.New("subordinate user not found") - } - - approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ApproverID) - if err != nil { - return nil, err - } - if approver == nil { - return nil, errors.New("approver user not found") - } - - department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.DepartmentID) - if err != nil { - return nil, err - } - if department == nil { - return nil, errors.New("department not found") - } - - if req.TopicCategoryID != nil { - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID) - if err != nil { - return nil, err - } - if category == nil { - return nil, errors.New("topic category not found") - } - } - - if req.TopicID != nil { - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID) - if err != nil { - return nil, err - } - if topic == nil { - return nil, errors.New("topic not found") - } - - if req.TopicCategoryID != nil && topic.CategoryID != nil { - if *topic.CategoryID != *req.TopicCategoryID { - return nil, errors.New("topic does not belong to the specified category") - } - } - } - - existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.UserHierarchy{ - SubordinateID: req.SubordinateID, - ApproverID: req.ApproverID, - DepartmentID: req.DepartmentID, - TopicID: req.TopicID, - TopicCategoryID: req.TopicCategoryID, - TargetSystem: req.TargetSystem, - }, - }) - if err != nil { - return nil, err - } - if len(existingHierarchies) > 0 { - return nil, errors.New("this hierarchy relation already exists") - } - - if req.Priority == nil { - defaultPriority := 1 - req.Priority = &defaultPriority - } - - createdHierarchy, _, err := s.ipc.Database.UserHierarchy.CreateUserHierarchyDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "subordinate_id": *req.SubordinateID, - "approver_id": *req.ApproverID, - "department_id": *req.DepartmentID, - "priority": *req.Priority, - } - if req.TopicID != nil { - snapshot["topic_id"] = *req.TopicID - } - if req.TopicCategoryID != nil { - snapshot["topic_category_id"] = *req.TopicCategoryID - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "create", "hierarchy", createdHierarchy.ID, - fmt.Sprintf("Создана связь: «%s» → согласующий «%s» (%s)", userLabel(subordinate), userLabel(approver), utilscore.DerefStr(department.Name)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return createdHierarchy, nil -} - -// UpdateHierarchyHandler Обновление записи иерархии -// @Summary Обновление записи иерархии -// @Description Обновление данных существующей записи иерархии -// @Tags hierarchies -// @Accept json -// @Produce json -// @Param request body typescore.UserHierarchy true "Данные иерархии" -// @Success 200 {object} typescore.UserHierarchy "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Запись не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/hierarchies [put] -func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 UpdateHierarchyHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.UserHierarchy - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("hierarchy id is required") - } - - ctx := r.Context() - - existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(ctx, typescore.ListDbOptions{ - Filtering: &typescore.UserHierarchy{ID: req.ID}, - }) - if err != nil { - return nil, err - } - if len(existingHierarchies) == 0 { - return nil, errors.New("hierarchy not found") - } - existing := existingHierarchies[0] - - if req.SubordinateID != nil { - if existing.SubordinateID == nil || *existing.SubordinateID != *req.SubordinateID { - subordinate, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.SubordinateID) - if err != nil { - return nil, err - } - if subordinate == nil { - return nil, errors.New("subordinate user not found") - } - } - } - - if req.ApproverID != nil { - if existing.ApproverID == nil || *existing.ApproverID != *req.ApproverID { - approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ApproverID) - if err != nil { - return nil, err - } - if approver == nil { - return nil, errors.New("approver user not found") - } - } - } - - if req.DepartmentID != nil { - if existing.DepartmentID == nil || *existing.DepartmentID != *req.DepartmentID { - department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.DepartmentID) - if err != nil { - return nil, err - } - if department == nil { - return nil, errors.New("department not found") - } - } - } - - if req.TopicCategoryID != nil { - if existing.TopicCategoryID == nil || *existing.TopicCategoryID != *req.TopicCategoryID { - category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID) - if err != nil { - return nil, err - } - if category == nil { - return nil, errors.New("topic category not found") - } - } - } - - if req.TopicID != nil { - if existing.TopicID == nil || *existing.TopicID != *req.TopicID { - topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID) - if err != nil { - return nil, err - } - if topic == nil { - return nil, errors.New("topic not found") - } - - categoryIDToCheck := req.TopicCategoryID - if categoryIDToCheck == nil { - categoryIDToCheck = existing.TopicCategoryID - } - if categoryIDToCheck != nil && topic.CategoryID != nil && *topic.CategoryID != *categoryIDToCheck { - return nil, errors.New("topic does not belong to the specified category") - } - } - } - - type fieldChange struct { - Field string `json:"field"` - Old interface{} `json:"old"` - New interface{} `json:"new"` - } - var changes []fieldChange - var summary []string - - if req.SubordinateID != nil && !utilscore.Uint64Eq(existing.SubordinateID, req.SubordinateID) { - var oldVal interface{} - if existing.SubordinateID != nil { - oldVal = *existing.SubordinateID - } - changes = append(changes, fieldChange{"subordinate_id", oldVal, *req.SubordinateID}) - summary = append(summary, "изменён подчинённый") - } - if req.ApproverID != nil && !utilscore.Uint64Eq(existing.ApproverID, req.ApproverID) { - var oldVal interface{} - if existing.ApproverID != nil { - oldVal = *existing.ApproverID - } - changes = append(changes, fieldChange{"approver_id", oldVal, *req.ApproverID}) - summary = append(summary, "изменён согласующий") - } - if req.DepartmentID != nil && !utilscore.Uint64Eq(existing.DepartmentID, req.DepartmentID) { - var oldVal interface{} - if existing.DepartmentID != nil { - oldVal = *existing.DepartmentID - } - changes = append(changes, fieldChange{"department_id", oldVal, *req.DepartmentID}) - summary = append(summary, "изменён отдел") - } - if req.TopicID != nil && !utilscore.Uint64Eq(existing.TopicID, req.TopicID) { - var oldVal interface{} - if existing.TopicID != nil { - oldVal = *existing.TopicID - } - changes = append(changes, fieldChange{"topic_id", oldVal, *req.TopicID}) - summary = append(summary, "изменена тема") - } - if req.TopicCategoryID != nil && !utilscore.Uint64Eq(existing.TopicCategoryID, req.TopicCategoryID) { - var oldVal interface{} - if existing.TopicCategoryID != nil { - oldVal = *existing.TopicCategoryID - } - changes = append(changes, fieldChange{"topic_category_id", oldVal, *req.TopicCategoryID}) - summary = append(summary, "изменена категория") - } - if req.Priority != nil && !utilscore.IntEq(existing.Priority, req.Priority) { - var oldVal interface{} - if existing.Priority != nil { - oldVal = *existing.Priority - } - changes = append(changes, fieldChange{"priority", oldVal, *req.Priority}) - summary = append(summary, fmt.Sprintf("приоритет: %v → %d", oldVal, *req.Priority)) - } - - updatedHierarchy, _, err := s.ipc.Database.UserHierarchy.UpdateUserHierarchyDB(ctx, nil, &req, true) - if err != nil { - return nil, err - } - - if len(changes) > 0 { - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - description := fmt.Sprintf("Изменена связь «%s» → «%s»: %s", userLabel(existing.Subordinate), userLabel(existing.Approver), strings.Join(summary, "; ")) - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "hierarchy", req.ID, - description, - map[string]interface{}{"changes": changes}, - ) - } - } - - return updatedHierarchy, nil -} - -// DeleteHierarchyHandler Удаление записи иерархии -// @Summary Удаление записи иерархии -// @Description Удаление связи подчинённый-согласующий по ID -// @Tags hierarchies -// @Accept json -// @Produce json -// @Param request body typescore.UserHierarchy true "ID записи для удаления" -// @Success 200 {object} bool "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Запись не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/hierarchies [delete] -func (s *HierarchiesReg) DeleteHierarchyHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 DeleteHierarchyHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.UserHierarchy - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("hierarchy id is required") - } - - ctx := r.Context() - - existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(ctx, typescore.ListDbOptions{ - Filtering: &typescore.UserHierarchy{ID: req.ID}, - }) - if err != nil { - return nil, err - } - if len(existingHierarchies) == 0 { - return nil, errors.New("hierarchy not found") - } - existing := existingHierarchies[0] - - err = s.ipc.Database.UserHierarchy.DeleteUserHierarchyDB(ctx, &req) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "priority": utilscore.DerefInt(existing.Priority), - } - if existing.SubordinateID != nil { - snapshot["subordinate_id"] = *existing.SubordinateID - } - if existing.ApproverID != nil { - snapshot["approver_id"] = *existing.ApproverID - } - if existing.DepartmentID != nil { - snapshot["department_id"] = *existing.DepartmentID - } - if existing.TopicID != nil { - snapshot["topic_id"] = *existing.TopicID - } - if existing.TopicCategoryID != nil { - snapshot["topic_category_id"] = *existing.TopicCategoryID - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "delete", "hierarchy", req.ID, - fmt.Sprintf("Удалена связь: «%s» → согласующий «%s»", userLabel(existing.Subordinate), userLabel(existing.Approver)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return true, nil -} - -func userLabel(user *typescore.User) string { - if user == nil || user.FullName == nil { - return "—" - } - return *user.FullName -} - -func (s *HierarchiesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - return nil, false - } - - return admins[0], true -} - ------END service/rest_admin_service/handlers/user_hierarchy/handlers.go----- - -File: service/rest_admin_service/handlers/user_hierarchy/routes.go -Lines: 39 ------BEGIN service/rest_admin_service/handlers/user_hierarchy/routes.go----- -package hierarchieshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type HierarchiesReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterHierarchyRoutes регистрирует маршруты для группы hierarchies -func RegisterHierarchyRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &HierarchiesReg{ - ipc: ipc, - } - - r.Route("/api/hierarchies", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetHierarchiesListHandler) - handlers.RegisterRoute(r, http.MethodPost, "/", s.CreateHierarchyHandler) - handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateHierarchyHandler) - handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteHierarchyHandler) - - r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetHierarchyByIDHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/user_hierarchy/routes.go----- - -File: service/rest_admin_service/handlers/user_roles/handlers.go -Lines: 477 ------BEGIN service/rest_admin_service/handlers/user_roles/handlers.go----- -package userroleshandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - "context" - "encoding/json" - "errors" - "fmt" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strconv" - "strings" - - "github.com/go-chi/chi/v5" -) - -// AssignUserRoleRequest — запрос на назначение роли пользователю -type AssignUserRoleRequest struct { - UserID *uint64 `json:"user_id"` - RoleID *uint64 `json:"role_id"` -} - -// BulkAssignRolesRequest — запрос на массовое назначение ролей -type BulkAssignRolesRequest struct { - UserID *uint64 `json:"user_id"` - RoleIDs []*uint64 `json:"role_ids"` -} - -// GetUserRolesListHandler Получение списка ролей пользователя -// @Summary Получение списка ролей пользователя -// @Description Получение списка ролей, назначенных конкретному пользователю -// @Tags user-roles -// @Accept json -// @Produce json -// @Param user_id query integer true "ID пользователя" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/user-roles [get] -func (s *UserRolesReg) GetUserRolesListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - roleParams := &typescore.UserRole{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, roleParams) - if errW != nil { - return nil, errW - } - - if roleParams.UserID == nil { - return nil, errors.New("user_id is required") - } - - options := typescore.ListDbOptions{ - Filtering: roleParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - ctx := r.Context() - userRolesDbLst, total, errW := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, options) - if errW != nil { - return nil, errW - } - - s.enrichUserRolesBatch(ctx, userRolesDbLst) - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: userRolesDbLst, - }, nil -} - -// GetUserRolesByUserIDHandler Получение списка ролей пользователя по ID из URL -// @Summary Получение списка ролей пользователя по ID -// @Description Получение списка ролей, назначенных пользователю с указанным ID -// @Tags user-roles -// @Accept json -// @Produce json -// @Param user_id path integer true "ID пользователя" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Пользователь не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/users/{user_id}/roles [get] -func (s *UserRolesReg) GetUserRolesByUserIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - userIDStr := chi.URLParam(r, "user_id") - if userIDStr == "" { - return nil, errors.New("user_id is required") - } - - userID, err := strconv.ParseUint(userIDStr, 10, 64) - if err != nil { - return nil, errors.New("invalid user_id") - } - - ctx := r.Context() - - user, err := s.ipc.Database.User.GetUserByIDDB(ctx, userID) - if err != nil { - return nil, err - } - if user == nil { - return nil, errors.New("user not found") - } - - userRolesDbLst, _, errW := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.UserRole{UserID: &userID}, - }) - if errW != nil { - return nil, errW - } - - s.enrichUserRolesBatch(ctx, userRolesDbLst) - - return &typescore.ApiResponseBase{ - TotalCount: uint64(len(userRolesDbLst)), - Data: userRolesDbLst, - }, nil -} - -// enrichUserRolesBatch пакетно подгружает роли для списка user_role -func (s *UserRolesReg) enrichUserRolesBatch(ctx context.Context, userRoles []*typescore.UserRole) { - if len(userRoles) == 0 { - return - } - - roleIDsSet := make(map[uint64]struct{}) - for _, ur := range userRoles { - if ur.RoleID != nil { - roleIDsSet[*ur.RoleID] = struct{}{} - } - } - - roleIDs := make([]uint64, 0, len(roleIDsSet)) - for id := range roleIDsSet { - roleIDs = append(roleIDs, id) - } - - rolesMap := make(map[uint64]*typescore.Role) - if roles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs); err == nil { - for _, role := range roles { - if role.ID != nil { - rolesMap[*role.ID] = role - } - } - } - - for _, ur := range userRoles { - if ur.RoleID != nil { - if role, ok := rolesMap[*ur.RoleID]; ok { - ur.Role = role - } - } - } -} - -// BulkAssignRolesHandler Массовое назначение ролей пользователю -// @Summary Массовое назначение ролей -// @Description Полная замена ролей пользователя: удаляет все текущие роли и назначает новые -// @Tags user-roles -// @Accept json -// @Produce json -// @Param request body BulkAssignRolesRequest true "user_id и список role_ids" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Пользователь не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/user-roles/bulk [post] -func (s *UserRolesReg) BulkAssignRolesHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 BulkAssignRolesHandler: ReadAll error:", err) - return nil, err - } - - var req BulkAssignRolesRequest - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.UserID == nil { - return nil, errors.New("user_id is required") - } - - ctx := r.Context() - - user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID) - if err != nil { - return nil, err - } - if user == nil { - return nil, errors.New("user not found") - } - - roleIDsSet := make(map[uint64]struct{}) - roleIDs := make([]uint64, 0, len(req.RoleIDs)) - for _, roleID := range req.RoleIDs { - if roleID == nil { - continue - } - if _, exists := roleIDsSet[*roleID]; exists { - continue - } - roleIDsSet[*roleID] = struct{}{} - roleIDs = append(roleIDs, *roleID) - } - - if len(roleIDs) > 0 { - existingRoles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs) - if err != nil { - return nil, err - } - foundIDs := make(map[uint64]struct{}, len(existingRoles)) - for _, role := range existingRoles { - if role.ID != nil { - foundIDs[*role.ID] = struct{}{} - } - } - for _, roleID := range roleIDs { - if _, ok := foundIDs[roleID]; !ok { - return nil, errors.New("role not found: " + strconv.FormatUint(roleID, 10)) - } - } - } - - // снимаем "было" до удаления — иначе после DeleteUserRolesByUserIDDB это уже не достать - previousRoles, _, _ := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.UserRole{UserID: req.UserID}, - }) - s.enrichUserRolesBatch(ctx, previousRoles) - - if err := s.ipc.Database.UserRole.DeleteUserRolesByUserIDDB(ctx, *req.UserID); err != nil { - logrus.Errorf("BulkAssignRolesHandler: failed to delete user_roles for user_id=%d: %v", *req.UserID, err) - return nil, err - } - - createdRoles, err := s.ipc.Database.UserRole.CreateUserRolesBulkDB(ctx, nil, *req.UserID, roleIDs) - if err != nil { - logrus.Errorf("BulkAssignRolesHandler: failed to bulk create user_roles: %v", err) - return nil, err - } - - s.enrichUserRolesBatch(ctx, createdRoles) - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - oldNames := roleNames(previousRoles) - newNames := roleNames(createdRoles) - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "user_roles", req.UserID, - fmt.Sprintf("Заменены роли «%s»: [%s] → [%s]", userLabel(user), strings.Join(oldNames, ", "), strings.Join(newNames, ", ")), - map[string]interface{}{ - "user_id": *req.UserID, - "roles_before": oldNames, - "roles_after": newNames, - }, - ) - } - - return &typescore.ApiResponseBase{ - TotalCount: uint64(len(createdRoles)), - Data: createdRoles, - }, nil -} - -// AssignUserRoleHandler Назначение роли пользователю -// @Summary Назначение роли пользователю -// @Description Назначение роли пользователю (создание связи user_id + role_id) -// @Tags user-roles -// @Accept json -// @Produce json -// @Param request body AssignUserRoleRequest true "user_id и role_id" -// @Success 200 {object} typescore.UserRole "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Пользователь или роль не найдены" -// @Failure 409 {object} handlers.ErrorResponse "Роль уже назначена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/user-roles [post] -func (s *UserRolesReg) AssignUserRoleHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 AssignUserRoleHandler: ReadAll error:", err) - return nil, err - } - - var req AssignUserRoleRequest - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.UserID == nil { - return nil, errors.New("user_id is required") - } - if req.RoleID == nil { - return nil, errors.New("role_id is required") - } - - ctx := r.Context() - - user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID) - if err != nil { - return nil, err - } - if user == nil { - return nil, errors.New("user not found") - } - - role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.RoleID) - if err != nil { - return nil, err - } - if role == nil { - return nil, errors.New("role not found") - } - - existingRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.UserRole{ - UserID: req.UserID, - RoleID: req.RoleID, - }, - }) - if err != nil { - return nil, err - } - if len(existingRoles) > 0 { - return nil, errors.New("this role is already assigned to the user") - } - - userRoleObj := &typescore.UserRole{ - UserID: req.UserID, - RoleID: req.RoleID, - } - - createdUserRole, _, err := s.ipc.Database.UserRole.CreateUserRoleDB(ctx, nil, userRoleObj, true) - if err != nil { - return nil, err - } - - createdUserRole.Role = role - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "create", "user_role", createdUserRole.ID, - fmt.Sprintf("Назначена роль «%s» пользователю «%s»", roleLabel(role), userLabel(user)), - map[string]interface{}{ - "user_id": *req.UserID, - "role_id": *req.RoleID, - }, - ) - } - - return createdUserRole, nil -} - -// RemoveUserRoleHandler Удаление роли у пользователя -// @Summary Удаление роли у пользователя -// @Description Удаление связи user_id + role_id по ID записи -// @Tags user-roles -// @Accept json -// @Produce json -// @Param request body typescore.UserRole true "ID записи для удаления" -// @Success 200 {object} bool "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Запись не найдена" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/user-roles [delete] -func (s *UserRolesReg) RemoveUserRoleHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - defer r.Body.Close() - - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 RemoveUserRoleHandler: ReadAll error:", err) - return nil, err - } - - var req typescore.UserRole - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("user_role id is required") - } - - ctx := r.Context() - - existingRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.UserRole{ID: req.ID}, - }) - if err != nil { - return nil, err - } - if len(existingRoles) == 0 { - return nil, errors.New("user_role not found") - } - existing := existingRoles[0] - s.enrichUserRolesBatch(ctx, existingRoles) - - var user *typescore.User - if existing.UserID != nil { - user, _ = s.ipc.Database.User.GetUserByIDDB(ctx, *existing.UserID) - } - - err = s.ipc.Database.UserRole.DeleteUserRoleDB(ctx, &req) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{} - if existing.UserID != nil { - snapshot["user_id"] = *existing.UserID - } - if existing.RoleID != nil { - snapshot["role_id"] = *existing.RoleID - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "delete", "user_role", req.ID, - fmt.Sprintf("Снята роль «%s» с пользователя «%s»", roleLabel(existing.Role), userLabel(user)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return true, nil -} - -func userLabel(user *typescore.User) string { - if user == nil || user.FullName == nil { - return "—" - } - return *user.FullName -} - -func roleLabel(role *typescore.Role) string { - if role == nil || role.Name == nil { - return "—" - } - return *role.Name -} - -func roleNames(userRoles []*typescore.UserRole) []string { - names := make([]string, 0, len(userRoles)) - for _, ur := range userRoles { - names = append(names, roleLabel(ur.Role)) - } - return names -} - -func (s *UserRolesReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - return nil, false - } - - return admins[0], true -} - ------END service/rest_admin_service/handlers/user_roles/handlers.go----- - -File: service/rest_admin_service/handlers/user_roles/routes.go -Lines: 53 ------BEGIN service/rest_admin_service/handlers/user_roles/routes.go----- -package userroleshandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type UserRolesReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterUserRoleRoutes регистрирует маршруты для группы user-roles -func RegisterUserRoleRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &UserRolesReg{ - ipc: ipc, - } - - // Основной маршрут для управления ролями - r.Route("/api/user-roles", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - // GET /api/user-roles?user_id=X - список ролей пользователя - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetUserRolesListHandler) - - // POST /api/user-roles - назначить роль пользователю - handlers.RegisterRoute(r, http.MethodPost, "/", s.AssignUserRoleHandler) - - // DELETE /api/user-roles - удалить роль у пользователя - handlers.RegisterRoute(r, http.MethodDelete, "/", s.RemoveUserRoleHandler) - - // POST /api/user-roles/bulk - массовое назначение ролей - handlers.RegisterRoute(r, http.MethodPost, "/bulk", s.BulkAssignRolesHandler) - }) - - // Альтернативный маршрут: GET /api/users/{user_id}/roles - r.Route("/api/users/{user_id}/roles", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - r.Get("/", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetUserRolesByUserIDHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/user_roles/routes.go----- - -File: service/rest_admin_service/handlers/users/handlers.go -Lines: 417 ------BEGIN service/rest_admin_service/handlers/users/handlers.go----- -package usershandler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/rest_admin_service/handlers" - adminloghandler "bitrix_balancer_api/rest_admin_service/handlers/admin_actions" - "context" - "encoding/json" - "errors" - "fmt" - "github.com/sirupsen/logrus" - "io" - "net/http" - "strconv" - "strings" - - "github.com/go-chi/chi/v5" -) - -// GetUserListHandler Получение списка пользователей -// @Summary Получение списка пользователей -// @Description Получение списка пользователей с пагинацией, фильтрацией и подгрузкой связанных данных -// @Tags users -// @Accept json -// @Produce json -// @Param offset query integer false "Смещение для пагинации" -// @Param limit query integer false "Количество записей на странице" -// @Param is_blocked query boolean false "Фильтр по блокировке" -// @Param is_fired query boolean false "Фильтр по увольнению" -// @Param department_id query integer false "Фильтр по отделу" -// @Success 200 {object} typescore.ApiResponseBase "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/users [get] -func (s *UserReg) GetUserListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - queryParams := r.URL.Query() - - userParams := &typescore.User{} - offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, userParams) - if errW != nil { - return nil, errW - } - - search := queryParams.Get("full_name") - if search != "" { - if likeFields == nil { - likeFields = make(map[string]string) - } - likeFields["full_name"] = search - userParams.FullName = nil - } - - var roleIDs []uint64 - if roleIDsStr := queryParams["role_ids[]"]; len(roleIDsStr) > 0 { - for _, idStr := range roleIDsStr { - if id, err := strconv.ParseUint(idStr, 10, 64); err == nil { - roleIDs = append(roleIDs, id) - } - } - } - - options := typescore.ListDbOptions{ - Filtering: userParams, - Offset: offset, - Limit: limit, - LikeFields: likeFields, - } - - ctx := r.Context() - - var userDbLst []*typescore.User - var total uint64 - var err error - - if len(roleIDs) > 0 { - userDbLst, total, err = s.ipc.Database.User.GetUsersListByRoleIDsDB(ctx, options, roleIDs) - } else { - userDbLst, total, err = s.ipc.Database.User.GetUsersListDB(ctx, options) - } - - if err != nil { - return nil, err - } - - s.enrichUsersBatch(ctx, userDbLst) - - return &typescore.ApiResponseBase{ - TotalCount: total, - Data: userDbLst, - }, nil -} - -// UpdateUserHandler Обновление пользователя -// @Summary Обновление пользователя -// @Description Обновление данных существующего пользователя -// @Tags users -// @Accept json -// @Produce json -// @Param request body typescore.UpdateUserReqAdmin true "Данные пользователя" -// @Success 200 {object} typescore.User "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Пользователь не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/users [put] -func (s *UserReg) UpdateUserHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - body, err := io.ReadAll(r.Body) - if err != nil { - logrus.Error("🛑 UpdateUserHandler: ReadAll error:", err) - return nil, err - } - defer r.Body.Close() - - var req typescore.UpdateUserReqAdmin - if err := json.Unmarshal(body, &req); err != nil { - return nil, errors.New("invalid request body") - } - - if req.ID == nil { - return nil, errors.New("user id is required") - } - - ctx := r.Context() - existingUser, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ID) - if err != nil { - return nil, err - } - if existingUser == nil { - return nil, errors.New("user not found") - } - - if req.DepartmentID != nil { - if existingUser.DepartmentID == nil || *existingUser.DepartmentID != *req.DepartmentID { - department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.DepartmentID) - if err != nil { - return nil, err - } - if department == nil { - return nil, errors.New("department not found") - } - } - } - - type fieldChange struct { - Field string `json:"field"` - Old interface{} `json:"old"` - New interface{} `json:"new"` - } - var changes []fieldChange - var summary []string - - if req.DepartmentID != nil && !utilscore.Uint64Eq(existingUser.DepartmentID, req.DepartmentID) { - var oldVal interface{} - if existingUser.DepartmentID != nil { - oldVal = *existingUser.DepartmentID - } - changes = append(changes, fieldChange{"department_id", oldVal, *req.DepartmentID}) - summary = append(summary, "изменён отдел") - } - if req.IsBlocked != nil && !utilscore.BoolEq(existingUser.IsBlocked, req.IsBlocked) { - changes = append(changes, fieldChange{"is_blocked", utilscore.DerefBool(existingUser.IsBlocked), *req.IsBlocked}) - if *req.IsBlocked { - summary = append(summary, "заблокирован") - } else { - summary = append(summary, "разблокирован") - } - } - if req.IsFired != nil && !utilscore.BoolEq(existingUser.IsFired, req.IsFired) { - changes = append(changes, fieldChange{"is_fired", utilscore.DerefBool(existingUser.IsFired), *req.IsFired}) - if *req.IsFired { - summary = append(summary, "уволен") - } else { - summary = append(summary, "восстановлен") - } - } - - upUserObj := &typescore.User{ - ID: req.ID, - DepartmentID: req.DepartmentID, - IsBlocked: req.IsBlocked, - IsFired: req.IsFired, - } - - upUser, _, errW := s.ipc.Database.User.UpdateUserDB(ctx, nil, upUserObj, true) - if errW != nil { - return nil, errW - } - - s.enrichUsersBatch(ctx, []*typescore.User{upUser}) - - if len(changes) > 0 { - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - description := fmt.Sprintf("Изменён пользователь «%s»: %s", userLabel(existingUser), strings.Join(summary, "; ")) - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "update", "user", req.ID, - description, - map[string]interface{}{"changes": changes}, - ) - } - } - - return upUser, nil -} - -// enrichUsersBatch пакетно подгружает отделы и роли для списка пользователей -func (s *UserReg) enrichUsersBatch(ctx context.Context, users []*typescore.User) { - if len(users) == 0 { - return - } - - departmentIDsSet := make(map[uint64]struct{}) - userIDs := make([]uint64, 0, len(users)) - for _, u := range users { - if u.ID != nil { - userIDs = append(userIDs, *u.ID) - } - if u.DepartmentID != nil { - departmentIDsSet[*u.DepartmentID] = struct{}{} - } - } - - departmentIDs := make([]uint64, 0, len(departmentIDsSet)) - for id := range departmentIDsSet { - departmentIDs = append(departmentIDs, id) - } - - departmentsMap := make(map[uint64]*typescore.Department) - if departments, err := s.ipc.Database.Department.GetDepartmentsByIDsDB(ctx, departmentIDs); err == nil { - for _, d := range departments { - if d.ID != nil { - departmentsMap[*d.ID] = d - } - } - } - - userRoles, err := s.ipc.Database.UserRole.GetUserRolesByUserIDsDB(ctx, userIDs) - roleIDsSet := make(map[uint64]struct{}) - userRolesByUser := make(map[uint64][]*typescore.UserRole) - if err == nil { - for _, ur := range userRoles { - if ur.UserID != nil { - userRolesByUser[*ur.UserID] = append(userRolesByUser[*ur.UserID], ur) - } - if ur.RoleID != nil { - roleIDsSet[*ur.RoleID] = struct{}{} - } - } - } - - roleIDs := make([]uint64, 0, len(roleIDsSet)) - for id := range roleIDsSet { - roleIDs = append(roleIDs, id) - } - rolesMap := make(map[uint64]*typescore.Role) - if roles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs); err == nil { - for _, role := range roles { - if role.ID != nil { - rolesMap[*role.ID] = role - } - } - } - - for _, u := range users { - if u.DepartmentID != nil { - if d, ok := departmentsMap[*u.DepartmentID]; ok { - u.Department = d - } - } - if u.ID == nil { - continue - } - userRolesForUser := userRolesByUser[*u.ID] - for _, ur := range userRolesForUser { - if ur.RoleID != nil { - if role, ok := rolesMap[*ur.RoleID]; ok { - ur.Role = role - } - } - } - if len(userRolesForUser) > 0 { - u.UserRoles = userRolesForUser - } - } -} - -// GetUserByIDHandler Получение пользователя по ID -// @Summary Получение пользователя по ID -// @Description Получение детальной информации о пользователе по его ID с подгрузкой связанных данных -// @Tags users -// @Accept json -// @Produce json -// @Param id path integer true "ID пользователя" -// @Success 200 {object} typescore.User "Успех" -// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос" -// @Failure 404 {object} handlers.ErrorResponse "Пользователь не найден" -// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера" -// @Router /api/users/{id} [get] -func (s *UserReg) GetUserByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("user id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid user id") - } - - ctx := r.Context() - user, err := s.ipc.Database.User.GetUserByIDDB(ctx, id) - if err != nil { - return nil, err - } - - if user == nil { - return nil, errors.New("user not found") - } - - if user.DepartmentID != nil { - department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *user.DepartmentID) - if err == nil && department != nil { - user.Department = department - } - } - - userRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.UserRole{UserID: user.ID}, - }) - if err == nil && len(userRoles) > 0 { - for _, ur := range userRoles { - if ur.RoleID != nil { - role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *ur.RoleID) - if err == nil && role != nil { - ur.Role = role - } - } - } - user.UserRoles = userRoles - } - - return user, nil -} - -func (s *UserReg) DeleteUserHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - idStr := chi.URLParam(r, "id") - if idStr == "" { - return nil, errors.New("user id is required") - } - - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - return nil, errors.New("invalid user id") - } - - ctx := r.Context() - - existingUser, err := s.ipc.Database.User.GetUserByIDDB(ctx, id) - if err != nil { - return nil, err - } - if existingUser == nil { - return nil, errors.New("user not found") - } - - err = s.ipc.Database.User.DeleteUserDB(ctx, &typescore.User{ID: &id}) - if err != nil { - return nil, err - } - - if currentAdmin, ok := s.getCurrentAdmin(ctx); ok { - snapshot := map[string]interface{}{ - "full_name": utilscore.DerefStr(existingUser.FullName), - "is_blocked": utilscore.DerefBool(existingUser.IsBlocked), - "is_fired": utilscore.DerefBool(existingUser.IsFired), - } - if existingUser.TelegramID != nil { - snapshot["telegram_id"] = *existingUser.TelegramID - } - if existingUser.DepartmentID != nil { - snapshot["department_id"] = *existingUser.DepartmentID - } - adminloghandler.LogAdminActionWithMetadata( - ctx, s.ipc, - *currentAdmin.ID, *currentAdmin.Login, - "delete", "user", &id, - fmt.Sprintf("Удалён пользователь «%s»", userLabel(existingUser)), - map[string]interface{}{"snapshot": snapshot}, - ) - } - - return true, nil -} - -func userLabel(user *typescore.User) string { - if user == nil || user.FullName == nil { - return "—" - } - return *user.FullName -} - -func (s *UserReg) getCurrentAdmin(ctx context.Context) (*typescore.Admin, bool) { - currentUserID, err := handlers.GetIDFromContext(ctx) - if err != nil { - return nil, false - } - - admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{ - Filtering: &typescore.Admin{ID: ¤tUserID}, - }) - if err != nil || len(admins) == 0 || admins[0] == nil || admins[0].ID == nil || admins[0].Login == nil { - return nil, false - } - - return admins[0], true -} - ------END service/rest_admin_service/handlers/users/handlers.go----- - -File: service/rest_admin_service/handlers/users/routes.go -Lines: 39 ------BEGIN service/rest_admin_service/handlers/users/routes.go----- -package usershandler - -import ( - "bitrix_balancer_api/rest_admin_service/handlers" - typesm "bitrix_balancer_api/rest_admin_service/types" - "net/http" - - "github.com/go-chi/chi/v5" -) - -type UserReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterUserRoutes регистрирует маршруты для группы users -func RegisterUserRoutes( - r chi.Router, - ipc *typesm.InternalProviderControl, -) error { - s := &UserReg{ - ipc: ipc, - } - - r.Route("/api/users", func(r chi.Router) { - r.Use(handlers.AccessCodeVerifier(ipc.Config)) - r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient)) - - handlers.RegisterRoute(r, http.MethodGet, "/", s.GetUserListHandler) - handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateUserHandler) - - handlers.RegisterRoute(r, http.MethodDelete, "/{id}", s.DeleteUserHandler) - - r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{ - HandlerFunc: s.GetUserByIDHandler, - })) - }) - - return nil -} - ------END service/rest_admin_service/handlers/users/routes.go----- - -File: service/rest_admin_service/types/module.go -Lines: 15 ------BEGIN service/rest_admin_service/types/module.go----- -package typesm - -import ( - configcore "bitrix_balancer_api/core/config" - database "bitrix_balancer_api/core/db" - "bitrix_balancer_api/core/lib/external/tgkit" - redismodule "bitrix_balancer_api/core/lib/internally/redis" -) - -type InternalProviderControl struct { - Config *configcore.Config - RedisClient *redismodule.ModuleRedis - TGBotClient *tgkit.Client - Database *database.ModuleDB -} - ------END service/rest_admin_service/types/module.go----- - -File: service/rest_admin_service/types/req.go -Lines: 13 ------BEGIN service/rest_admin_service/types/req.go----- -package typesm - -type LimitRequest struct { - Limit uint64 `json:"limit"` - Offset uint64 `json:"offset"` -} - -type Response struct { - TotalCount *uint64 `json:"total_count,omitempty"` - Count int `json:"count,omitempty"` - Error *string `json:"error,omitempty"` - Data interface{} `json:"data,omitempty"` -} - ------END service/rest_admin_service/types/req.go----- - -File: service/rest_balancer_service/cmd/app.go -Lines: 178 ------BEGIN service/rest_balancer_service/cmd/app.go----- -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: configcore.SecretsOptions{ - UserAccessCode: true, - }, - Server: configcore.ExposedServiceOptions{ - RESTBaseService: true, - }, - } - - controller, err := clientcontrollers.ReturnClientsExternal(options) - if err != nil { - return nil, clientcontrollers.ClientsExternal{}, err - } - return controller.Config, controller, nil -} - -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_balancer_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 -} - ------END service/rest_balancer_service/cmd/app.go----- - -File: service/rest_balancer_service/handler/balancer/handler.go -Lines: 65 ------BEGIN service/rest_balancer_service/handler/balancer/handler.go----- -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 -} - ------END service/rest_balancer_service/handler/balancer/handler.go----- - -File: service/rest_balancer_service/handler/balancer/routes.go -Lines: 30 ------BEGIN service/rest_balancer_service/handler/balancer/routes.go----- -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 -} - ------END service/rest_balancer_service/handler/balancer/routes.go----- - -File: service/rest_balancer_service/handler/balancer/utils.go -Lines: 229 ------BEGIN service/rest_balancer_service/handler/balancer/utils.go----- -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 -} - ------END service/rest_balancer_service/handler/balancer/utils.go----- - -File: service/rest_balancer_service/handler/handler.go -Lines: 131 ------BEGIN service/rest_balancer_service/handler/handler.go----- -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) -} - ------END service/rest_balancer_service/handler/handler.go----- - -File: service/rest_balancer_service/handler/middleware.go -Lines: 76 ------BEGIN service/rest_balancer_service/handler/middleware.go----- -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)) - }) - } -} - ------END service/rest_balancer_service/handler/middleware.go----- - -File: service/rest_balancer_service/types/handler.go -Lines: 12 ------BEGIN service/rest_balancer_service/types/handler.go----- -package types - -import ( - "net/http" -) - -// структура для представления маршрута с добавлением новых параметров -type RouteParams struct { - Method string // метод запроса - Url string // url - HandlerFunc func(w http.ResponseWriter, r *http.Request) (interface{}, *uint64, error) // функция обработчик -} - ------END service/rest_balancer_service/types/handler.go----- - -File: service/rest_balancer_service/types/types.go -Lines: 12 ------BEGIN service/rest_balancer_service/types/types.go----- -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 -} - ------END service/rest_balancer_service/types/types.go----- - -File: service/rest_telephony_service/cmd/app.go -Lines: 151 ------BEGIN service/rest_telephony_service/cmd/app.go----- -package main - -import ( - configcore "bitrix_balancer_api/core/config" - clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers" - "errors" - "fmt" - "log" - "net/http" - "rest_telephony_service/handlers/telephony" - typesm "rest_telephony_service/types" - "time" - - "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" -) - -const ( - readTimeout = 15 * time.Minute - writeTimeout = 15 * time.Minute - idleTimeout = 15 * time.Minute - rateLimit = 50 - rateWindow = 1 * time.Second -) - -func main() { - err := initService() - if err != nil { - logrus.Errorln("🔴 failed to init common: ", err) - } - select {} // блокируем завершение горутины -} - -func initService() error { - clientsExternal, err := getClientsExternal() - if err != nil { - logrus.Errorln("🔴 failed to load config: ", err) - return err - } - - ipc, err := initInternalProvider(clientsExternal) - if err != nil { - logrus.Errorln("🔴 failed to init internal provider: ", err) - return err - } - - router, err := initBaseApiRouter(ipc) - if err != nil { - logrus.Errorln("🔴 failed to init base api router: ", err) - return err - } - - if err := startRestApiServer(ipc, router); err != nil { - logrus.Errorln("🔴 failed to start server: ", err) - return err - } - - return nil -} - -func getClientsExternal() (clientcontrollers.ClientsExternal, error) { - options := &configcore.ConfigLoadOptions{ - Redis: true, - Database: true, - Server: configcore.ExposedServiceOptions{ - RESTBaseService: true, // Берем конфиг для портов из базы - }, - } - - return clientcontrollers.ReturnClientsExternal(options) -} - -func initInternalProvider(clientsExternal clientcontrollers.ClientsExternal) (*typesm.InternalProviderControl, error) { - return &typesm.InternalProviderControl{ - Config: clientsExternal.Config, - RedisClient: clientsExternal.Redis, - Database: clientsExternal.DB, - TGBotClient: clientsExternal.Telegram, - }, nil -} - -func startRestApiServer(ipc *typesm.InternalProviderControl, router *chi.Mux) error { - // Допустим, телефония живет на порту 15002. В будущем вынесем в config.yml - serverPort := "15002" - - serverAddr := ":" + serverPort - httpServer := &http.Server{ - Addr: serverAddr, - Handler: router, - ReadTimeout: readTimeout, - WriteTimeout: writeTimeout, - IdleTimeout: idleTimeout, - } - - log.Printf("✅ Starting Telephony server on %s", serverAddr) - return httpServer.ListenAndServe() -} - -func initBaseApiRouter(ipc *typesm.InternalProviderControl) (*chi.Mux, error) { - router := chi.NewRouter() - corsOptions := cors.New(cors.Options{ - AllowedOrigins: []string{"*"}, - AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodOptions}, - AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "ApiKey", "x-device-id"}, - ExposedHeaders: []string{"Link", "Cache-Control"}, - AllowCredentials: true, - MaxAge: 300, - }) - - router.Use(corsOptions.Handler) - router.Use(middleware.RealIP) - router.Use(middleware.Recoverer) - router.Use(httprate.LimitByIP(rateLimit, rateWindow)) - - if ipc.Database == nil { - return nil, errors.New("failed_to_connect_db") - } - - err := registerRoutes(router, ipc) - if err != nil { - return nil, err - } - - return router, nil -} - -// регистрирует маршруты -func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) error { - // Подключаем наши маршруты - if err := telephony.RegisterTelephonyRoutes(router, ipc); err != nil { - return errors.New(fmt.Sprintf("🔴 failed to register telephony routes: %v", err)) - } - - // Вывод зарегистрированных маршрутов - if err := printRoutes(router, ipc); err != nil { - return errors.New(fmt.Sprintf("🔴 failed to print routes: %v", err)) - } - - return nil -} - -func printRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error { - err := chi.Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error { - logrus.Info(fmt.Sprintf("🩵 [ %s ] %s\n", method, route)) - return nil - }) - return err -} - ------END service/rest_telephony_service/cmd/app.go----- - -File: service/rest_telephony_service/handlers/register.go -Lines: 161 ------BEGIN service/rest_telephony_service/handlers/register.go----- -package handlers - -import ( - "encoding/json" - "errors" - "fmt" - "github.com/go-chi/chi/v5" - "io" - "net/http" - "strconv" -) - -// ErrorResponse структура для возврата ошибок -type ErrorResponse struct { - ErrorCode int `json:"error_code"` - ErrorDescription string `json:"error_description"` -} - -type ExcelFileResponse struct { - Data []byte // Содержимое файла - FileName string // Имя файла для скачивания -} - -// WrapHandlerParams структура для параметров обертки -type WrapHandlerParams struct { - HandlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error) -} - -// responseWriterWrapper предотвращает повторный вызов WriteHeader -type responseWriterWrapper struct { - http.ResponseWriter - wroteHeader bool -} - -func (rw *responseWriterWrapper) WriteHeader(statusCode int) { - if !rw.wroteHeader { - rw.ResponseWriter.WriteHeader(statusCode) - rw.wroteHeader = true - } -} - -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) - - // 🆕 Проверяем, не файл ли это - if fileResp, ok := payload.(*ExcelFileResponse); ok && err == nil { - serveExcelFile(rw, fileResp) - return - } - - // Обычный JSON ответ - respondWithJSON(rw, err, payload) - } -} - -// 🆕 serveExcelFile отправляет файл как бинарный ответ -func serveExcelFile(w http.ResponseWriter, fileResp *ExcelFileResponse) { - // Устанавливаем заголовки ДО отправки тела - w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") - w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileResp.FileName)) - w.Header().Set("Content-Length", strconv.Itoa(len(fileResp.Data))) - w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") - - w.WriteHeader(http.StatusOK) - - // Отправляем содержимое файла - if _, err := w.Write(fileResp.Data); err != nil { - // Логируем ошибку, но заголовки уже отправлены - // Можно добавить логгер здесь - _ = err - } -} - -// 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 - } - } - - if rw, ok := w.(*responseWriterWrapper); ok { - if !rw.wroteHeader { - rw.WriteHeader(status) - } - } else { - w.WriteHeader(status) - } - - _, _ = w.Write(response) -} - ------END service/rest_telephony_service/handlers/register.go----- - -File: service/rest_telephony_service/handlers/telephony/bitrix.go -Lines: 80 ------BEGIN service/rest_telephony_service/handlers/telephony/bitrix.go----- -package telephony - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" - - "github.com/sirupsen/logrus" -) - -// URL вебхука, который ты создал в Битрикс24 -const bitrixWebhookURL = "https://thebest.bitrix24.ru/rest/292/paz20o3316e6cfe7/" - -// BxContactListResp описывает структуру ответа Битрикс24 при поиске -type BxContactListResp struct { - Result []struct { - ID string `json:"ID"` - CompanyID string `json:"COMPANY_ID"` - } `json:"result"` -} - -// PushSmsToBitrix ищет контакт по номеру и пушит SMS в его таймлайн -func PushSmsToBitrix(clientNumber, text string, direction int) { - // 🚀 Выполняем в отдельной горутине, чтобы мгновенно ответить АТС (200 OK) - // и не блокировать работу сервера, пока ждем ответа от Битрикса - go func() { - // 1. Ищем контакт по номеру телефона - searchReqBody, _ := json.Marshal(map[string]interface{}{ - "filter": map[string]string{"PHONE": clientNumber}, - "select": []string{"ID", "COMPANY_ID"}, - }) - - resp, err := http.Post(bitrixWebhookURL+"crm.contact.list.json", "application/json", bytes.NewBuffer(searchReqBody)) - if err != nil { - logrus.Errorf("Bitrix24 search contact error: %v", err) - return - } - defer resp.Body.Close() - - var listResp BxContactListResp - if err := json.NewDecoder(resp.Body).Decode(&listResp); err != nil { - logrus.Errorf("Bitrix24 decode error: %v", err) - return - } - - if len(listResp.Result) == 0 { - logrus.Infof("Bitrix24: Contact with phone %s not found. Skipping timeline comment.", clientNumber) - return - } - - // Берем ID первого найденного контакта - contactID := listResp.Result[0].ID - - // 2. Формируем красивый текст комментария с использованием BBCode (Битрикс его поддерживает) - dirStr := "[b]📥 Входящее SMS[/b]" - if direction == 1 { - dirStr = "[b]📤 Исходящее SMS[/b]" - } - - comment := fmt.Sprintf("%s\nНомер: %s\n\n%s", dirStr, clientNumber, text) - - addReqBody, _ := json.Marshal(map[string]interface{}{ - "fields": map[string]interface{}{ - "ENTITY_ID": contactID, - "ENTITY_TYPE": "contact", // События контакта автоматически видны и в привязанной Компании/Сделке - "COMMENT": comment, - }, - }) - - addResp, err := http.Post(bitrixWebhookURL+"crm.timeline.comment.add.json", "application/json", bytes.NewBuffer(addReqBody)) - if err != nil { - logrus.Errorf("Bitrix24 add comment error: %v", err) - return - } - defer addResp.Body.Close() - - logrus.Infof("Successfully pushed SMS to Bitrix24 timeline for contact ID %s", contactID) - }() -} - ------END service/rest_telephony_service/handlers/telephony/bitrix.go----- - -File: service/rest_telephony_service/handlers/telephony/handlers.go -Lines: 83 ------BEGIN service/rest_telephony_service/handlers/telephony/handlers.go----- -package telephony - -import ( - "bitrix_balancer_api/core/typescore" - "context" - "errors" - "net/http" - "rest_telephony_service/handlers" - typesm "rest_telephony_service/types" - "strconv" - "time" - - "github.com/sirupsen/logrus" -) - -// WebhookTelephonyHandler принимает события от АТС -func (s *TelephonyReg) WebhookTelephonyHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - var req typesm.TelephonyWebhookReq - - // Используем ваш стандартный парсер тела запроса - if err := handlers.ParseRequestBodyPost(r, &req); err != nil { - return nil, errors.New("invalid request body") - } - - // Игнорируем всё, кроме SMS (event_type == 32) - if req.Event.EventType != 32 { - return map[string]string{"status": "ignored", "reason": "not an SMS event"}, nil - } - - eventTime := time.Unix(req.Event.EventCreated, 0) - - smsLog := &typescore.SmsLog{ - AccountID: &req.Webhook.AccountID, - UserID: &req.Webhook.UserID, - ClientNumber: &req.Event.ClientNumber, - Direction: &req.Event.Direction, - Text: &req.Event.Text, - EventCreated: &eventTime, - } - - // Сохраняем SMS в БД - err := s.ipc.Database.SMSLog.CreateSmsLogDB(context.Background(), nil, smsLog) - if err != nil { - logrus.Errorf("Failed to save SMS log: %v", err) - return nil, errors.New("database error") - } - - // 🆕 Отправляем SMS в карточку Битрикс24 (выполнится асинхронно) - PushSmsToBitrix(*smsLog.ClientNumber, *smsLog.Text, *smsLog.Direction) - - logrus.Infof("Successfully logged SMS from client %s", req.Event.ClientNumber) - return map[string]string{"status": "success"}, nil -} - -// GetSmsReportHandler отдает список SMS для Google Script -func (s *TelephonyReg) GetSmsReportHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) { - startStr := r.URL.Query().Get("start") - endStr := r.URL.Query().Get("end") - - if startStr == "" || endStr == "" { - return nil, errors.New("missing 'start' or 'end' query parameters") - } - - startInt, err1 := strconv.ParseInt(startStr, 10, 64) - endInt, err2 := strconv.ParseInt(endStr, 10, 64) - if err1 != nil || err2 != nil { - return nil, errors.New("invalid timestamp format") - } - - startDate := time.Unix(startInt, 0) - endDate := time.Unix(endInt, 0) - - logs, err := s.ipc.Database.SMSLog.GetSmsLogsByDateRangeDB(context.Background(), startDate, endDate) - if err != nil { - logrus.Errorf("Failed to fetch SMS logs: %v", err) - return nil, errors.New("failed to fetch data") - } - - return typesm.SmsReportResponse{ - Success: true, - Data: logs, - }, nil -} - ------END service/rest_telephony_service/handlers/telephony/handlers.go----- - -File: service/rest_telephony_service/handlers/telephony/routes.go -Lines: 30 ------BEGIN service/rest_telephony_service/handlers/telephony/routes.go----- -package telephony - -import ( - "github.com/go-chi/chi/v5" - "net/http" - "rest_telephony_service/handlers" - typesm "rest_telephony_service/types" -) - -type TelephonyReg struct { - ipc *typesm.InternalProviderControl -} - -// RegisterTelephonyRoutes регистрирует маршруты телефонии -func RegisterTelephonyRoutes(r chi.Router, ipc *typesm.InternalProviderControl) error { - s := &TelephonyReg{ - ipc: ipc, - } - - r.Route("/api/v1/telephony", func(r chi.Router) { - // Вебхук открыт для провайдера - handlers.RegisterRoute(r, http.MethodPost, "/webhook", s.WebhookTelephonyHandler) - - // Отдача данных. Если скрипту Google нужен доступ, - // здесь можно добавить r.Use(handlers.AccessCodeVerifier(ipc.Config)) - handlers.RegisterRoute(r, http.MethodGet, "/sms-report", s.GetSmsReportHandler) - }) - - return nil -} - ------END service/rest_telephony_service/handlers/telephony/routes.go----- - -File: service/rest_telephony_service/types/types.go -Lines: 34 ------BEGIN service/rest_telephony_service/types/types.go----- -package typesm - -import ( - configcore "bitrix_balancer_api/core/config" - database "bitrix_balancer_api/core/db" - "bitrix_balancer_api/core/lib/external/tgkit" - redismodule "bitrix_balancer_api/core/lib/internally/redis" - "bitrix_balancer_api/core/typescore" -) - -type InternalProviderControl struct { - Config *configcore.Config - RedisClient *redismodule.ModuleRedis - TGBotClient *tgkit.Client - Database *database.ModuleDB -} - -type TelephonyWebhookReq struct { - Webhook WebhookMeta `json:"webhook"` - Event typescore.CallEvent `json:"event"` -} - -type WebhookMeta struct { - Action string `json:"action"` - AccountID string `json:"account_id"` - AccountName string `json:"account_name"` - UserID string `json:"user_id"` - UserLogin string `json:"user_login"` -} - -type SmsReportResponse struct { - Success bool `json:"success"` - Data []*typescore.SmsLog `json:"data,omitempty"` -} - ------END service/rest_telephony_service/types/types.go----- - -File: service/rest_user_service/cmd/app.go -Lines: 5 ------BEGIN service/rest_user_service/cmd/app.go----- -package main - -func main() { - -} - ------END service/rest_user_service/cmd/app.go----- - -File: service/system_service/cmd/app.go -Lines: 59 ------BEGIN service/system_service/cmd/app.go----- -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) -} - ------END service/system_service/cmd/app.go----- - -File: service/system_service/database_additionally/tables.go -Lines: 2 ------BEGIN service/system_service/database_additionally/tables.go----- -package database_additionally - - ------END service/system_service/database_additionally/tables.go----- - -File: service/system_service/jobs/init.go -Lines: 28 ------BEGIN service/system_service/jobs/init.go----- -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, - } - - if ipc.Config.Environment == "" || ipc.Config.Environment == "dev" { - err := jobs.ipc.Database.Migrate().MigrateDB() - if err != nil { - return err - } - logrus.Info("🟢🟢🟢 Database migration completed successfully") - } else { - logrus.Info("⚠️ production environment variable is set to prod mode. Skip migration") - } - - return nil -} - ------END service/system_service/jobs/init.go----- - -File: service/system_service/types/types.go -Lines: 15 ------BEGIN service/system_service/types/types.go----- -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 -} - ------END service/system_service/types/types.go----- - -File: service/telegram_service/approvalflow/dynamic_topic.go -Lines: 468 ------BEGIN service/telegram_service/approvalflow/dynamic_topic.go----- -package approvalflow - -import ( - "bitrix_balancer_api/core/typescore" - "bytes" - "fmt" - "sort" - "strings" - "text/template" -) - -// DynamicTopic — тема, соответствующая ОДНОЙ КАТЕГОРИИ (approval_topic_categories), -// построенная из всех approval_flow_nodes всех тем (approval_topics), относящихся -// к этой категории. -type DynamicTopic struct { - category *typescore.ApprovalTopicCategory - nodes []*typescore.ApprovalFlowNode - - codeTemplate string - messageTemplate string - - dataValueLabels map[string]string -} - -func NewDynamicTopic(category *typescore.ApprovalTopicCategory, nodes []*typescore.ApprovalFlowNode) *DynamicTopic { - d := &DynamicTopic{ - category: category, - nodes: nodes, - dataValueLabels: make(map[string]string), - } - - for _, n := range nodes { - if n.ParentID == nil { - if n.CodeTemplate != nil { - d.codeTemplate = *n.CodeTemplate - } - if n.MessageTemplate != nil { - d.messageTemplate = *n.MessageTemplate - } - } - - label := safeString(n.Label) - if label == "" { - continue - } - if dk, dv := safeString(n.DataKey), safeString(n.DataValue); dk != "" && dv != "" { - d.dataValueLabels[dataValueLabelKey(dk, dv)] = label - } - if mk, mv := safeString(n.MultiSelectKey), safeString(n.MultiSelectValue); mk != "" && mv != "" { - d.dataValueLabels[dataValueLabelKey(mk, mv)] = label - } - } - - return d -} - -func dataValueLabelKey(key, value string) string { - return key + "\x00" + value -} - -func (d *DynamicTopic) Code() string { - if d.category.Code != nil { - return *d.category.Code - } - return "" -} - -func (d *DynamicTopic) Name() string { - if d.category.Name != nil { - return *d.category.Name - } - return "" -} - -// BuildTree строит дерево FlowNode из плоского списка узлов БД. -// ВАЖНО: ровно один узел на категорию должен иметь ParentID == nil, -// иначе (как и раньше) переменная root будет молча перезаписана -// и часть дерева станет недостижимой через FindNode. -func (d *DynamicTopic) BuildTree() *FlowNode { - if len(d.nodes) == 0 { - return nil - } - - nodeMap := make(map[uint64]*FlowNode) - var root *FlowNode - - for _, dbNode := range d.nodes { - if dbNode.ID == nil { - continue - } - - fn := &FlowNode{ - Key: safeString(dbNode.Key), - Label: safeString(dbNode.Label), - DataKey: safeString(dbNode.DataKey), - DataValue: safeString(dbNode.DataValue), - IsInput: safeBool(dbNode.IsInput), - InputKey: safeString(dbNode.InputKey), - InputHint: safeString(dbNode.InputHint), - IsMultiSelect: safeBool(dbNode.IsMultiSelect), - MultiSelectKey: safeString(dbNode.MultiSelectKey), - MultiSelectValue: safeString(dbNode.MultiSelectValue), - TopicCode: safeString(dbNode.TopicCode), - } - nodeMap[*dbNode.ID] = fn - } - - for _, dbNode := range d.nodes { - if dbNode.ID == nil { - continue - } - fn := nodeMap[*dbNode.ID] - - if dbNode.ParentID == nil { - root = fn - } else if parent, ok := nodeMap[*dbNode.ParentID]; ok { - parent.Children = append(parent.Children, fn) - } - } - - // Сортировка детей — БЕЗ ИЗМЕНЕНИЙ (известный баг: сортирует по Key, - // а не по SortOrder; договорились пока не трогать) - for _, fn := range nodeMap { - sort.Slice(fn.Children, func(i, j int) bool { - return fn.Children[i].Key < fn.Children[j].Key - }) - } - - return root -} - -// TopicCodeFromCollected: если задан codeTemplate на корневом узле дерева -// категории — используем его; иначе прежняя дефолтная генерация кода -// (актуально для delivery_clients и goods_order, где дефолт и так совпадает). -func (d *DynamicTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - baseCode := d.Code() - - if d.codeTemplate != "" { - return d.applyCodeTemplate(d.codeTemplate, collected) - } - - var parts []string - parts = append(parts, baseCode) - - var keys []string - for k := range collected { - if k != "content" && k != "instructions" { - keys = append(keys, k) - } - } - sort.Strings(keys) - - for _, k := range keys { - v := collected[k] - if v != "" { - parts = append(parts, v) - } - } - - return strings.Join(parts, "_"), nil -} - -func createTemplateFuncMap() template.FuncMap { - return template.FuncMap{ - "trimPrefix": strings.TrimPrefix, - "trimSuffix": strings.TrimSuffix, - "toUpper": strings.ToUpper, - "toLower": strings.ToLower, - "replace": strings.ReplaceAll, - - "join": func(items []string, sep string) string { - return strings.Join(items, sep) - }, - "split": func(s, sep string) []string { - return strings.Split(s, sep) - }, - - "eq": func(a, b string) bool { return a == b }, - "ne": func(a, b string) bool { return a != b }, - - "contains": strings.Contains, - "hasPrefix": strings.HasPrefix, - "hasSuffix": strings.HasSuffix, - } -} - -func (d *DynamicTopic) applyCodeTemplate(tmpl string, data map[string]string) (string, error) { - t, err := template.New("code").Funcs(createTemplateFuncMap()).Parse(tmpl) - if err != nil { - return "", fmt.Errorf("parse code template: %w", err) - } - - // Шаблон кода работает с map[string]string напрямую (а не interface{}), - // т.к. использует только .field и eq/ne без доп. переменных. - var buf bytes.Buffer - if err := t.Execute(&buf, data); err != nil { - return "", fmt.Errorf("execute code template: %w", err) - } - - return strings.TrimSpace(buf.String()), nil -} - -func (d *DynamicTopic) applyMessageTemplate(tmpl, initiatorName string, data map[string]string) string { - t, err := template.New("message").Funcs(createTemplateFuncMap()).Parse(tmpl) - if err != nil { - return d.defaultMessage(initiatorName, data) - } - - templateData := make(map[string]interface{}) - for k, v := range data { - templateData[k] = v - } - templateData["initiator_name"] = initiatorName - templateData["topic_name"] = d.Name() - - d.addLabelMappings(templateData, data) - d.addTreeLabelMappings(templateData, data) - - var buf bytes.Buffer - if err := t.Execute(&buf, templateData); err != nil { - return d.defaultMessage(initiatorName, data) - } - - return buf.String() -} - -func (d *DynamicTopic) addTreeLabelMappings(templateData map[string]interface{}, data map[string]string) { - for key, value := range data { - if value == "" { - continue - } - if label, ok := d.dataValueLabels[dataValueLabelKey(key, value)]; ok { - templateData[key+"_label"] = label - continue - } - // Мультивыбор хранится как "value1,value2" — если единого - // совпадения нет, пробуем разобрать по частям и подписать - // каждую по отдельности, объединив через запятую. - if strings.Contains(value, ",") { - parts := strings.Split(value, ",") - var labels []string - for _, p := range parts { - p = strings.TrimSpace(p) - if l, ok := d.dataValueLabels[dataValueLabelKey(key, p)]; ok { - labels = append(labels, l) - } else { - labels = append(labels, p) - } - } - if len(labels) > 0 { - templateData[key+"_label"] = strings.Join(labels, ", ") - } - } - } -} - -// FormatApproverMessage форматирует сообщение для согласующего. -// messageTemplate теперь берётся из корневого узла дерева категории. -func (d *DynamicTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - initiatorName := "—" - if initiator != nil && initiator.FullName != nil { - initiatorName = *initiator.FullName - } - - if d.messageTemplate != "" { - return d.applyMessageTemplate(d.messageTemplate, initiatorName, collected) - } - - content := collected["content"] - if content == "" { - content = "—" - } - - return fmt.Sprintf( - "📋 Заявка на согласование\n\n"+ - "👤 От: %s\n"+ - "📂 Тема: %s\n"+ - "📝 Текст:\n%s", - initiatorName, d.Name(), content, - ) -} - -// addLabelMappings — БЕЗ ИЗМЕНЕНИЙ относительно предыдущей версии -func (d *DynamicTopic) addLabelMappings(templateData map[string]interface{}, data map[string]string) { - if region, ok := data["region"]; ok { - regionLabels := map[string]string{"crimea": "Крым", "krasnodar": "Краснодар", "belarus": "Беларусь"} - if label, exists := regionLabels[region]; exists { - templateData["region_label"] = label - } else { - templateData["region_label"] = region - } - } - - if absenceType, ok := data["absence_type"]; ok { - absenceLabels := map[string]string{"timeoff": "Отгул", "vacation": "Отпуск", "sickleave": "Официальный больничный"} - if label, exists := absenceLabels[absenceType]; exists { - templateData["absence_type_label"] = label - } else { - templateData["absence_type_label"] = absenceType - } - } - - if changeType, ok := data["change_type"]; ok { - changeLabels := map[string]string{"rename": "Поменять название", "change_manager": "Сменить менеджера", "new_client": "Внести нового клиента"} - if label, exists := changeLabels[changeType]; exists { - templateData["change_type_label"] = label - } else { - templateData["change_type_label"] = changeType - } - } - - if paymentType, ok := data["payment_type"]; ok { - paymentLabels := map[string]string{"own_expense": "за свой счёт", "vacation_account": "в счёт ежегодного отпуска", "official": "только официальный больничный"} - if label, exists := paymentLabels[paymentType]; exists { - templateData["payment_type_label"] = label - } else { - templateData["payment_type_label"] = paymentType - } - } - - if branch, ok := data["branch"]; ok { - branchLabels := map[string]string{"f1": "Ф1", "f2": "Ф2"} - if label, exists := branchLabels[branch]; exists { - templateData["branch_label"] = label - } else { - templateData["branch_label"] = branch - } - } - - if expenseType, ok := data["expense_type"]; ok { - expenseLabels := map[string]string{"tmc": "ТМЦ", "expense": "Расход"} - if label, exists := expenseLabels[expenseType]; exists { - templateData["expense_type_label"] = label - } else { - templateData["expense_type_label"] = expenseType - } - } - - if ppRequired, ok := data["pp_required"]; ok { - ppLabels := map[string]string{"yes": "✅ Нужна ПП", "no": "❌ Не нужна ПП"} - if label, exists := ppLabels[ppRequired]; exists { - templateData["pp_required_label"] = label - } else { - templateData["pp_required_label"] = ppRequired - } - } - - if returnType, ok := data["return_type"]; ok { - returnLabels := map[string]string{"supplier": "Возврат поставщику", "other_manager": "Продажа другим менеджером", "self_sale": "Самостоятельная продажа"} - if label, exists := returnLabels[returnType]; exists { - templateData["return_type_label"] = label - } else { - templateData["return_type_label"] = returnType - } - } - - if orderType, ok := data["order_type"]; ok { - orderLabels := map[string]string{"monthly": "На месяц", "additional": "Дополнительный заказ"} - if label, exists := orderLabels[orderType]; exists { - templateData["order_type_label"] = label - } else { - templateData["order_type_label"] = orderType - } - } - - if rateType, ok := data["rate_type"]; ok { - rateLabels := map[string]string{"once": "Разово", "long_term": "Надолго"} - if label, exists := rateLabels[rateType]; exists { - templateData["rate_type_label"] = label - } else { - templateData["rate_type_label"] = rateType - } - } - - if shipmentType, ok := data["shipment_type"]; ok { - shipmentLabels := map[string]string{"real": "Реальная", "limit": "Для лимита"} - if label, exists := shipmentLabels[shipmentType]; exists { - templateData["shipment_type_label"] = label - } else { - templateData["shipment_type_label"] = shipmentType - } - } - - if durationType, ok := data["duration_type"]; ok { - durationLabels := map[string]string{ - "single_day": "На один день", "multi_day": "Несколько дней", "date_range": "Диапазон дат", - "sl_single_day": "На один день", "sl_date_range": "Диапазон дат", - } - if label, exists := durationLabels[durationType]; exists { - templateData["duration_type_label"] = label - } else { - templateData["duration_type_label"] = durationType - } - } - - if timeType, ok := data["time_type"]; ok { - timeLabels := map[string]string{"full_day": "Весь день", "partial": "Частично"} - if label, exists := timeLabels[timeType]; exists { - templateData["time_type_label"] = label - } else { - templateData["time_type_label"] = timeType - } - } - - if paymentCategory, ok := data["payment_category"]; ok { - categoryLabels := map[string]string{"goods": "Товар", "misc": "Разное"} - if label, exists := categoryLabels[paymentCategory]; exists { - templateData["payment_category_label"] = label - } else { - templateData["payment_category_label"] = paymentCategory - } - } - - if systems, ok := data["systems"]; ok { - templateData["systems_label"] = d.mapSystems(systems) - } -} - -func (d *DynamicTopic) mapSystems(systems string) string { - if systems == "" { - return "не указаны" - } - parts := strings.Split(systems, ",") - var labels []string - for _, p := range parts { - p = strings.TrimSpace(p) - switch p { - case "okb": - labels = append(labels, "ОКБ") - case "1c": - labels = append(labels, "1С") - default: - labels = append(labels, p) - } - } - if len(labels) == 0 { - return "не указаны" - } - return strings.Join(labels, ", ") -} - -func (d *DynamicTopic) defaultMessage(initiatorName string, data map[string]string) string { - content := data["content"] - if content == "" { - content = "—" - } - return fmt.Sprintf( - "📋 Заявка на согласование\n\n"+ - "👤 От: %s\n"+ - "📂 Тема: %s\n"+ - "📝 Текст:\n%s", - initiatorName, d.Name(), content, - ) -} - -func safeString(s *string) string { - if s == nil { - return "" - } - return *s -} - -func safeBool(b *bool) bool { - if b == nil { - return false - } - return *b -} - ------END service/telegram_service/approvalflow/dynamic_topic.go----- - -File: service/telegram_service/approvalflow/flow.go -Lines: 40 ------BEGIN service/telegram_service/approvalflow/flow.go----- -package approvalflow - -// FlowNode — узел дерева навигации. -type FlowNode struct { - Key string - Label string - DataKey string - DataValue string - IsInput bool - InputKey string - InputHint string - - // Мультиселект — для выбора нескольких значений на одном уровне - IsMultiSelect bool - MultiSelectKey string // ключ в Collected где хранится результат, например "systems" - MultiSelectValue string // значение этого узла при выборе, например "okb" - - // Код темы в БД — для проверки прав доступа - // Если задан — кнопка показывается только при наличии права "create" на эту тему - TopicCode string - - Children []*FlowNode -} - -// 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 -} - ------END service/telegram_service/approvalflow/flow.go----- - -File: service/telegram_service/approvalflow/topic.go -Lines: 14 ------BEGIN service/telegram_service/approvalflow/topic.go----- -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) -} - ------END service/telegram_service/approvalflow/topic.go----- - -File: service/telegram_service/cmd/app.go -Lines: 76 ------BEGIN service/telegram_service/cmd/app.go----- -package main - -import ( - configcore "bitrix_balancer_api/core/config" - clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers" - tgupdatehandler "bitrix_balancer_api/telegram_service/common/update" - "bitrix_balancer_api/telegram_service/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() - - dailyReminder := scheduler.NewDailyReminder(ipc) - dailyReminder.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) { - return &types.InternalProviderControl{ - Config: cfg, - Database: clientsExternal.DB, - RedisClient: clientsExternal.Redis, - TGBotClient: clientsExternal.Telegram, - }, 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()) - } -} - ------END service/telegram_service/cmd/app.go----- - -File: service/telegram_service/common/update/0_init.go -Lines: 169 ------BEGIN service/telegram_service/common/update/0_init.go----- -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/handlers/suggestion" - "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 - suggestionHandler *suggestion.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, - suggestionHandler: suggestion.NewHandler(ipc), - startHandler: start.NewHandler(ipc, approvalHandler), - faqHandler: faq.NewHandler(ipc), - } - - // TODO: вызывается только после обновлений - //go handlers.broadcastBotUpdated() - //go handlers.sendNewSupportContactNotification() - //go handlers.broadcastCommentsFeatureUpdate() - - return handler -} - -func (s *UpdateHandler) broadcastBotUpdated() { - ctx := context.Background() - bot := s.ipc.TGBotClient.Bot() - - 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)) -} - -// sendNewSupportContactNotification отправляет уведомление о смене ответственного за настройку системы -func (s *UpdateHandler) sendNewSupportContactNotification() { - ctx := context.Background() - bot := s.ipc.TGBotClient.Bot() - - users, _, err := s.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{}) - if err != nil { - logrus.Errorf("sendNewSupportContactNotification: GetUsersListDB err=%v", err) - return - } - - newSupportURL := "https://t.me/ahsailmi" - - text := "📢 Важное обновление!\n\n" + - "Изменился ответственный за настройку системы согласований.\n\n" + - "Теперь по всем вопросам настройки обращайтесь к новому администратору:\n\n" + - "• Изменение порядка согласования\n" + - "• Добавление или удаление согласующих\n" + - "• Изменение прав доступа\n" - - keyboard := tgbotapi.NewInlineKeyboardMarkup( - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonURL("👨‍💻 Написать администратору", newSupportURL), - ), - ) - - for _, user := range users { - if user.TelegramID == nil { - continue - } - msg := tgbotapi.NewMessage(*user.TelegramID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard - msg.DisableWebPagePreview = true - if _, err := bot.Send(msg); err != nil { - logrus.Warnf("sendNewSupportContactNotification: Send to telegramID=%d err=%v", *user.TelegramID, err) - } - time.Sleep(50 * time.Millisecond) - } - - logrus.Infof("sendNewSupportContactNotification: отправлено %d пользователям", len(users)) -} - -// broadcastCommentsFeatureUpdate уведомляет всех пользователей о новой функции комментариев. -func (s *UpdateHandler) broadcastCommentsFeatureUpdate() { - ctx := context.Background() - bot := s.ipc.TGBotClient.Bot() - - users, _, err := s.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{}) - if err != nil { - logrus.Errorf("broadcastCommentsFeatureUpdate: GetUsersListDB err=%v", err) - return - } - - text := "🆕 Что нового в системе согласований\n\n" + - "Мы обновили работу с комментариями - теперь заявка стала похожа на общий чат:\n\n" + - "💬 Комментарии видят все участники\n" + - "Инициатор, согласующий, доп. согласующие, исполнители(только после согласования) и наблюдатели(только после согласования) теперь получают комментарии друг друга и могут сразу ответить.\n\n" + - "📋 Кнопка «Посмотреть все комментарии» в каждой карточке\n" + - "На карточке заявки сразу видно, сколько комментариев уже оставлено - можно открыть полную историю в один клик.\n\n" + - "Нажмите кнопку ниже, чтобы перезапустить бота:" - - keyboard := tgbotapi.NewInlineKeyboardMarkup( - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("🚀 Перезапустить бота", "restart_bot"), - ), - ) - - sent := 0 - 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("broadcastCommentsFeatureUpdate: Send to telegramID=%d err=%v", *user.TelegramID, err) - continue - } - sent++ - time.Sleep(50 * time.Millisecond) - } - - logrus.Infof("broadcastCommentsFeatureUpdate: отправлено %d из %d пользователям", sent, len(users)) -} - ------END service/telegram_service/common/update/0_init.go----- - -File: service/telegram_service/common/update/callback.go -Lines: 694 ------BEGIN service/telegram_service/common/update/callback.go----- -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, "obs_select_confirm"): - s.approvalHandler.HandleObserverConfirmCallback(bot, cq) - - 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 data == "appr_deleg_yes": - s.approvalHandler.HandleDelegationChoiceCallback(bot, cq, true) - - case data == "appr_deleg_no": - s.approvalHandler.HandleDelegationChoiceCallback(bot, cq, false) - - case strings.HasPrefix(data, "appr_deleg_sel:"): - idStr := strings.TrimPrefix(data, "appr_deleg_sel:") - delegateID, _ := strconv.ParseUint(idStr, 10, 64) - s.approvalHandler.HandleDelegateSelectionCallback(bot, cq, delegateID) - - case strings.HasPrefix(data, "appr_deleg_pg:"): - pageStr := strings.TrimPrefix(data, "appr_deleg_pg:") - page, _ := strconv.Atoi(pageStr) - s.approvalHandler.HandleDelegateSelectionPageCallback(bot, cq, page) - - // Мультиселект кнопок - case strings.HasPrefix(data, "appr_ms_toggle:"): - parts := strings.SplitN(strings.TrimPrefix(data, "appr_ms_toggle:"), ":", 3) - if len(parts) == 3 { - s.approvalHandler.HandleMultiSelectToggle(bot, cq, parts[0], parts[1], parts[2]) - } - - case strings.HasPrefix(data, "appr_ms_confirm:"): - topicCode := strings.TrimPrefix(data, "appr_ms_confirm:") - s.approvalHandler.HandleMultiSelectConfirm(bot, cq, topicCode) - - // НА ДОРАБОТКУ - case strings.HasPrefix(data, "revision_attach_cancel:"): - approvalID := parseID(data, "revision_attach_cancel:") - ctx := context.Background() - key := fmt.Sprintf("appr_revision_attach_file:%d", cq.From.ID) - s.ipc.RedisClient.Del(ctx, key) //nolint:errcheck - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck - commentsCount := s.approvalHandler.GetCommentsCount(ctx, approvalID) - - // Возвращаем меню доработки - optMsg := tgbotapi.NewMessage(cq.Message.Chat.ID, fmt.Sprintf("📋 Заявка #%d на доработке:", approvalID)) - optMsg.ParseMode = "HTML" - optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(approvalID, commentsCount) - bot.Send(optMsg) //nolint:errcheck - - case strings.HasPrefix(data, "appr_revision:"): - approvalID := parseID(data, "appr_revision:") - s.approvalHandler.HandleRevisionCallback(bot, cq, approvalID) - - case strings.HasPrefix(data, "appr_revision_comment:"): - approvalID := parseID(data, "appr_revision_comment:") - s.approvalHandler.HandleRevisionCommentStart(bot, cq, approvalID) - - case strings.HasPrefix(data, "appr_revision_skip:"): - approvalID := parseID(data, "appr_revision_skip:") - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck - s.approvalHandler.HandleRevisionWithComment(bot, cq.Message.Chat.ID, cq.From.ID, approvalID, "") - - case strings.HasPrefix(data, "revision_edit_text:"): - approvalID := parseID(data, "revision_edit_text:") - s.approvalHandler.HandleRevisionEditText(bot, cq, approvalID) - - case strings.HasPrefix(data, "revision_add_files:"): - approvalID := parseID(data, "revision_add_files:") - s.approvalHandler.HandleRevisionAddFiles(bot, cq, approvalID) - - case strings.HasPrefix(data, "revision_resubmit:"): - approvalID := parseID(data, "revision_resubmit:") - s.approvalHandler.HandleRevisionResubmit(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_attach:"): - approvalID := parseID(data, "appr_attach:") - s.approvalHandler.HandleAttachFileStart(bot, cq, approvalID) - - case strings.HasPrefix(data, "appr_attach_cancel:"): - s.approvalHandler.HandleAttachCancel(bot, cq) - - // ── НАВИГАЦИЯ ФЛОУ ────────────────────────────────────────── - 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 - - // ── ФЛОУ ДЕЛЕГИРОВАНИЯ ПРАВ ────────────────────────────────────────── - 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, "dir_notif_toggle:"): - parts := strings.Split(strings.TrimPrefix(data, "dir_notif_toggle:"), ":") - if len(parts) == 2 { - var categoryID uint64 - var page int - fmt.Sscanf(parts[0], "%d", &categoryID) - fmt.Sscanf(parts[1], "%d", &page) - s.approvalHandler.HandleDirectorNotificationToggle(bot, cq, categoryID, page) - } - - case strings.HasPrefix(data, "dir_notif_page:"): - page := 0 - fmt.Sscanf(strings.TrimPrefix(data, "dir_notif_page:"), "%d", &page) - s.approvalHandler.HandleDirectorNotificationPage(bot, cq, page) - - case data == "dir_notif_page_noop": - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - case data == "dir_notif_done": - s.approvalHandler.HandleDirectorNotificationDone(bot, cq) - - // ── ПЕРЕДАЧА ЗАДАЧ ────────────────────────────────────────── - case strings.HasPrefix(data, "task_transfer_start:"): - taskID := parseID(data, "task_transfer_start:") - s.approvalHandler.HandleTransferTaskStart(bot, cq, taskID) - - case strings.HasPrefix(data, "task_transfer_page:"): - page := 0 - fmt.Sscanf(strings.TrimPrefix(data, "task_transfer_page:"), "%d", &page) - s.approvalHandler.HandleTransferTaskUserPage(bot, cq, page) - - case data == "task_transfer_noop": - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - case data == "task_transfer_cancel": - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck - - case strings.HasPrefix(data, "task_transfer_user:"): - toUserID := parseID(data, "task_transfer_user:") - s.approvalHandler.HandleTransferTaskUserSelect(bot, cq, toUserID) - - case strings.HasPrefix(data, "task_transfer_accept:"): - transferID := parseID(data, "task_transfer_accept:") - s.approvalHandler.HandleTransferTaskAccept(bot, cq, transferID) - - case strings.HasPrefix(data, "task_transfer_decline:"): - transferID := parseID(data, "task_transfer_decline:") - s.approvalHandler.HandleTransferTaskDecline(bot, cq, transferID) - - // ── ДОБАВЛЕНИЕ СОГЛАСУЮЩЕГО ─────────────────────────────────────────────────── - 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_to_approval:"): - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - approvalIDStr := strings.TrimPrefix(data, "add_appr_to_approval:") - approvalID, err := strconv.ParseUint(approvalIDStr, 10, 64) - if err != nil { - logrus.Errorf("handleCallback: invalid approvalID=%s err=%v", approvalIDStr, err) - return - } - - s.approvalHandler.HandleAddApproverFromApproval(bot, cq.Message.Chat.ID, cq.From.ID, approvalID) - return - - 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_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, "sugg_reply:"): - suggestionID := parseID(data, "sugg_reply:") - s.suggestionHandler.HandleReplyToSuggestion(bot, cq, suggestionID) - - case strings.HasPrefix(data, "sugg_view:"): - suggestionID := parseID(data, "sugg_view:") - s.suggestionHandler.HandleViewSuggestion(bot, cq, suggestionID) - - // КОММЕНТАРИИ К СОГЛАСОВАНИЯМ - case strings.HasPrefix(data, "appr_comment:"): - approvalID := parseID(data, "appr_comment:") - s.approvalHandler.HandleAddCommentCallback(bot, cq, approvalID) - - case strings.HasPrefix(data, "comment_reply:"): - approvalID := parseID(data, "comment_reply:") - s.approvalHandler.HandleCommentReplyCallback(bot, cq, approvalID) - - case strings.HasPrefix(data, "appr_view_comments:"): - approvalID := parseID(data, "appr_view_comments:") - s.approvalHandler.HandleViewCommentsCallback(bot, cq, approvalID) - - // ВЫБОР СОГЛАСУЮЩЕГО - 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 strings.HasPrefix(data, "appr_view_files:"): - approvalID := parseID(data, "appr_view_files:") - s.approvalHandler.HandleViewFilesCallback(bot, cq, approvalID) - - case strings.HasPrefix(data, "appr_show_card:"): - approvalID := parseID(data, "appr_show_card:") - s.approvalHandler.HandleShowApprovalCardCallback(bot, cq, approvalID) - - // ── СОГЛАСОВАНИЕ ОТЗЫВА ──────────────────────────────────── - case strings.HasPrefix(data, "revoke_appr_yes:"): - requestID := parseID(data, "revoke_appr_yes:") - s.approvalHandler.HandleRevocationApproverDecision(bot, cq, requestID, true) - - case strings.HasPrefix(data, "revoke_appr_no:"): - requestID := parseID(data, "revoke_appr_no:") - s.approvalHandler.HandleRevocationApproverDecision(bot, cq, requestID, false) - - // Мои заявки - case strings.HasPrefix(data, "my_appr_topic:"): - topicFilter := strings.TrimPrefix(data, "my_appr_topic:") - s.approvalHandler.HandleMyApprovalsTopicCallback(bot, cq, topicFilter) - - case data == "reminder_revisions": - s.approvalHandler.HandleReminderRevisions(bot, cq) - - case data == "reminder_tasks": - s.approvalHandler.HandleMyTasks(bot, cq.Message.Chat.ID, cq.From.ID) - - case data == "reminder_approvals": - s.approvalHandler.HandleReminderApprovals(bot, cq) - - case strings.HasPrefix(data, "my_appr_status:"): - // формат: my_appr_status:{status}:{topicFilter} - parts := strings.SplitN(strings.TrimPrefix(data, "my_appr_status:"), ":", 2) - status := parts[0] - topicFilter := "all" - if len(parts) > 1 { - topicFilter = parts[1] - } - s.approvalHandler.HandleMyApprovalsStatusCallback(bot, cq, status, topicFilter) - - case strings.HasPrefix(data, "obs_status:"): - parts := strings.SplitN(strings.TrimPrefix(data, "obs_status:"), ":", 3) - if len(parts) == 3 { - status := parts[0] - topicCode := parts[1] - page, _ := strconv.Atoi(parts[2]) - s.approvalHandler.HandleObserverStatusFilterCallback(bot, cq, status, topicCode, page) - } - - case data == "obs_back_list": - s.approvalHandler.HandleObservedApprovals(bot, cq.Message.Chat.ID, cq.From.ID) - bot.Request(tgbotapi.NewCallback(cq.ID, "")) - bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) - - case data == "my_appr_back": - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck - s.approvalHandler.HandleMyApprovals(bot, cq.Message.Chat.ID, cq.From.ID) - - case strings.HasPrefix(data, "appr_appr_topic:"): - topicFilter := strings.TrimPrefix(data, "appr_appr_topic:") - s.approvalHandler.HandleApproverApprovalsTopicCallback(bot, cq, topicFilter) - - case strings.HasPrefix(data, "appr_appr_status:"): - // формат: appr_appr_status:{status}:{topicFilter} - parts := strings.SplitN(strings.TrimPrefix(data, "appr_appr_status:"), ":", 2) - status, topicFilter := parts[0], "all" - if len(parts) == 2 { - topicFilter = parts[1] - } - s.approvalHandler.HandleApproverApprovalsStatusCallback(bot, cq, status, topicFilter) - - case data == "appr_appr_back": - s.approvalHandler.HandleApproverApprovals(bot, cq.Message.Chat.ID, cq.From.ID) - - case strings.HasPrefix(data, "obs_topic_page:"): - page := 0 - fmt.Sscanf(strings.TrimPrefix(data, "obs_topic_page:"), "%d", &page) - bot.Request(tgbotapi.NewCallback(cq.ID, "")) - bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) - s.approvalHandler.HandleObservedApprovalsPage(bot, cq.Message.Chat.ID, cq.From.ID, page) - - case data == "obs_topic_noop": - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - // ВЫБОР ПЕРВОГО НАБЛДАТЕЛЯ - case strings.HasPrefix(data, "obs_select_toggle:"): - observerID := parseID(data, "obs_select_toggle:") - s.approvalHandler.HandleObserverToggleCallback(bot, cq, observerID) - - case strings.HasPrefix(data, "obs_select_page:"): - page := 0 - fmt.Sscanf(strings.TrimPrefix(data, "obs_select_page:"), "%d", &page) - s.approvalHandler.HandleObserverPageCallback(bot, cq, page) - - case strings.HasPrefix(data, "obs_confirm"): - s.approvalHandler.HandleObserverConfirmCallback(bot, cq) - - case data == "obs_select_noop": - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - // ВЫБОР ПЕРВОГО СОГЛАСУЮЩеГО - case strings.HasPrefix(data, "first_approver_select:"): - userID := parseID(data, "first_approver_select:") - s.approvalHandler.HandleFirstApproverSelectCallback(bot, cq, userID) - - case strings.HasPrefix(data, "first_approver_page:"): - page := 0 - fmt.Sscanf(strings.TrimPrefix(data, "first_approver_page:"), "%d", &page) - s.approvalHandler.HandleFirstApproverPageCallback(bot, cq, page) - - case data == "first_approver_noop": - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - case strings.HasPrefix(data, "revoke_task_no_changes:"): - var taskID, approvalID uint64 - fmt.Sscanf(strings.TrimPrefix(data, "revoke_task_no_changes:"), "%d:%d", &taskID, &approvalID) - s.approvalHandler.HandleRevokeTaskNoChanges(bot, cq, taskID, approvalID) - - case strings.HasPrefix(data, "revoke_task_has_changes:"): - var taskID, approvalID uint64 - fmt.Sscanf(strings.TrimPrefix(data, "revoke_task_has_changes:"), "%d:%d", &taskID, &approvalID) - s.approvalHandler.HandleRevokeTaskHasChanges(bot, cq, taskID, approvalID) - - case strings.HasPrefix(data, "executor_attach:"): - parts := strings.Split(data, ":") - if len(parts) >= 3 { - taskID, _ := strconv.ParseUint(parts[1], 10, 64) - approvalID, _ := strconv.ParseUint(parts[2], 10, 64) - s.approvalHandler.HandleExecutorAttachStart(bot, cq, approvalID, taskID) - } - - case strings.HasPrefix(data, "attach_submit:"): - approvalID := parseID(data, "attach_submit:") - s.approvalHandler.HandleAttachSubmit(bot, cq, approvalID) - - case strings.HasPrefix(data, "attach_clear:"): - approvalID := parseID(data, "attach_clear:") - s.approvalHandler.HandleAttachClear(bot, cq, approvalID) - - case strings.HasPrefix(data, "attach_cancel:"): - s.approvalHandler.HandleAttachCancel(bot, cq) - - // ── ПРОЧЕЕ ────────────────────────────────────────────────── - 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 (from user=%d, chat=%d, msgID=%d)", - data, cq.From.ID, cq.Message.Chat.ID, cq.Message.MessageID) - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - } -} - -// 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 -} - ------END service/telegram_service/common/update/callback.go----- - -File: service/telegram_service/common/update/update.go -Lines: 271 ------BEGIN service/telegram_service/common/update/update.go----- -package tgupdatehandler - -import ( - "context" - "fmt" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" - "strings" -) - -func (s *UpdateHandler) GetUpdateTelegram() { - bot := s.ipc.TGBotClient.Bot() - - 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.HandleInitiatorSubmenu(bot, msg.Chat.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) - isDirector, _ := s.ipc.Database.User.IsDirectorDB(ctx, *user.ID) - if !isApprover && !isDirector { - return - } - s.approvalHandler.HandleApproverSubmenu(bot, msg.Chat.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 - } - isDirector, _ := s.ipc.Database.User.IsDirectorDB(ctx, *user.ID) - if !isDirector { - return - } - s.approvalHandler.HandleDirectorSubmenu(bot, msg.Chat.ID) - }) - return - - case "🔔 Настроить уведомления": - s.withDepartmentCheck(bot, msg, func() { - s.approvalHandler.HandleDirectorNotificationSettings(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 - } - isObserver, _ := s.ipc.Database.User.IsObserverDB(ctx, *user.ID) - if !isObserver { - return - } - s.approvalHandler.HandleObserverSubmenu(bot, msg.Chat.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.HandleMyApprovals(bot, msg.Chat.ID, msg.From.ID) - }) - return - - case "Принять согласование в работу": - s.withDepartmentCheck(bot, msg, func() { - 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.approvalHandler.HandleApproverApprovals(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.HandleMyTasks(bot, msg.Chat.ID, msg.From.ID) - }) - return - - case "Все", "Согласованные", "Не согласованные", "Ожидают согласования": - statusMap := map[string]string{ - "Все": "all", "Согласованные": "approved", - "Не согласованные": "rejected", "Ожидают согласования": "pending", - } - s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, statusMap[msg.Text]) - return - - case "❓ Как создать согласование?": - s.withDepartmentCheck(bot, msg, func() { - s.faqHandler.Handle(bot, msg) - }) - return - - case "💬 Предложения и пожелания": - s.withDepartmentCheck(bot, msg, func() { - s.suggestionHandler.HandleCreateSuggestion(bot, msg.Chat.ID, msg.From.ID) - }) - return - - case "← Назад": - s.withDepartmentCheck(bot, msg, func() { - s.approvalHandler.HandleBackNavigation(bot, msg.Chat.ID, msg.From.ID) - }) - return - } - - revisionKey := fmt.Sprintf("appr_revision_pending:%d", msg.From.ID) - if val, err := s.ipc.RedisClient.Get(ctx, revisionKey); err == nil && val != "" { - var approvalID uint64 - fmt.Sscanf(val, "%d", &approvalID) - s.ipc.RedisClient.Del(ctx, revisionKey) //nolint:errcheck - s.approvalHandler.HandleRevisionWithComment(bot, msg.Chat.ID, msg.From.ID, approvalID, strings.TrimSpace(msg.Text)) - return - } - - approveCommentKey := fmt.Sprintf("appr_approve_comment_pending:%d", msg.From.ID) - if val, err := s.ipc.RedisClient.Get(ctx, approveCommentKey); err == nil && val != "" { - var approvalID uint64 - fmt.Sscanf(val, "%d", &approvalID) - s.ipc.RedisClient.Del(ctx, approveCommentKey) //nolint:errcheck - s.approvalHandler.HandleDecisionWithChat(bot, msg.Chat.ID, msg.From.ID, approvalID, true, strings.TrimSpace(msg.Text)) - return - } - - 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, msg.From.ID, approvalID, false, strings.TrimSpace(msg.Text)) - return - } - - if s.approvalHandler.HandleRevisionTextInput(bot, msg) { - return - } - if s.approvalHandler.HandleAttachFileInput(bot, msg) { - return - } - if s.approvalHandler.HandleRevisionFileInput(bot, msg) { - return - } - if s.approvalHandler.HandlePendingCommentInput(bot, msg) { - return - } - if s.approvalHandler.HandleReportTextInput(bot, msg) { - return - } - if s.startHandler.HandleTextInput(bot, msg) { - return - } - if s.approvalHandler.HandleCommentReplyInput(bot, msg) { - return - } - if s.approvalHandler.HandleCommentTextInput(bot, msg) { - return - } - if s.suggestionHandler.HandleSuggestionTextInput(bot, msg) { - return - } - - if msg.Photo != nil || msg.Document != nil { - s.withDepartmentCheck(bot, msg, func() { - s.approvalHandler.HandleFileInput(bot, msg) - }) - return - } - - if s.approvalHandler.HandleDelegationDateInput(bot, msg) { - return - } - if s.approvalHandler.HandleDelegationExtendInput(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() -} - ------END service/telegram_service/common/update/update.go----- - -File: service/telegram_service/handlers/approval/absense_delegation.go -Lines: 376 ------BEGIN service/telegram_service/handlers/approval/absense_delegation.go----- -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" - "regexp" - "strconv" - "time" - - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" -) - -// ============================================================ -// Делегирование обязанностей на время отсутствия (отгул/отпуск/ -// больничный). Включается флагом ApprovalTopic.AllowDelegationSelection -// (тот же паттерн, что AllowObserverSelection) — см. DELEGATION_PATCHES.txt. -// -// 🩹 Жизненный цикл делегирования (важное отличие от первой версии): -// запись ApprovalDelegation создаётся СРАЗУ при подаче заявки на -// отсутствие, но НЕАКТИВНОЙ (IsActive=false) — см. createPendingDelegation, -// вызывается из submitApproval. Активируется она ТОЛЬКО когда сама заявка -// будет полностью согласована — activatePendingDelegation, вызывается из -// processNextStepOrComplete в момент финального approved. Если заявку -// впоследствии отзовут — deactivatePendingDelegation (вызывается из -// performActualRevoke) выключает делегирование обратно, независимо от -// того, успело оно активироваться или нет. -// -// Здесь, в диалоге с ботом, происходит только ВЫБОР делегата — реальная -// запись в БД появляется позже, вместе с самой заявкой. -// ============================================================ - -// showDelegationChoice — экран "делегировать все обязанности?" (Да/Нет). -func (h *Handler) showDelegationChoice(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { - text := "🔁 Делегировать все обязанности по согласованию на другого человека на время вашего отсутствия?\n\n" + - "Делегирование начнёт действовать только после того, как эта заявка будет согласована, " + - "и автоматически отменится, если заявку впоследствии отзовут." - - msg := tgbotapi.NewMessage(chatID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildDelegationChoiceMenu() - bot.Send(msg) //nolint:errcheck -} - -// HandleDelegationChoiceCallback — пользователь ответил Да/Нет на вопрос о делегировании. -func (h *Handler) HandleDelegationChoiceCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, wantsDelegate bool) { - 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 || !flowState.AwaitDelegationChoice { - return - } - - if !wantsDelegate { - flowState.AwaitDelegationChoice = false - flowState.DelegationSelectionDone = true - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - - sendText(bot, chatID, "☑️ Хорошо — обязанности не делегируются, вы решаете вопросы согласования самостоятельно.") - h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) - return - } - - candidates, err := h.getAvailableDelegateCandidates(ctx, telegramID) - if err != nil { - logrus.Errorf("HandleDelegationChoiceCallback: getAvailableDelegateCandidates err=%v", err) - } - if len(candidates) == 0 { - sendText(bot, chatID, "⚠️ Нет доступных сотрудников для делегирования. Обязанности остаются на вас.") - flowState.AwaitDelegationChoice = false - flowState.DelegationSelectionDone = true - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) - return - } - - flowState.AwaitDelegationChoice = false - flowState.AwaitDelegateSelection = true - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - - msg := tgbotapi.NewMessage(chatID, "👤 Выберите, кому передать обязанности:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildDelegateSelectionMenu(candidates, 0) - bot.Send(msg) //nolint:errcheck -} - -// HandleDelegateSelectionPageCallback — пагинация списка кандидатов. -func (h *Handler) HandleDelegateSelectionPageCallback(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 - - flowState, err := h.States.Get(ctx, telegramID) - if err != nil || flowState == nil || !flowState.AwaitDelegateSelection { - return - } - - candidates, err := h.getAvailableDelegateCandidates(ctx, telegramID) - if err != nil { - return - } - - editMsg := tgbotapi.NewEditMessageReplyMarkup( - chatID, - cq.Message.MessageID, - keyboard.BuildDelegateSelectionMenu(candidates, page), - ) - bot.Request(editMsg) //nolint:errcheck -} - -// HandleDelegateSelectionCallback — пользователь выбрал конкретного делегата. -// -// 🩹 ВАЖНО: здесь запись в ApprovalDelegation больше НЕ создаётся. Мы -// только запоминаем выбор в flowState.SelectedDelegateID — реальная -// (неактивная) запись появится в submitApproval/createPendingDelegation, -// когда заявка будет фактически отправлена (это происходит сразу вслед -// за этим шагом в том же диалоге, так что 30-минутный TTL состояния в -// Redis не успевает истечь). -func (h *Handler) HandleDelegateSelectionCallback(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 - - flowState, err := h.States.Get(ctx, telegramID) - if err != nil || flowState == nil || !flowState.AwaitDelegateSelection { - return - } - - delegate, err := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID) - if err != nil || delegate == nil { - sendText(bot, chatID, "⚠️ Сотрудник не найден.") - return - } - - flowState.AwaitDelegateSelection = false - flowState.DelegationSelectionDone = true - flowState.SelectedDelegateID = delegateID - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - - delegateName := "—" - if delegate.FullName != nil { - delegateName = *delegate.FullName - } - - // Дата — только для информации в этом сообщении, реальное значение - // пересчитывается и сохраняется в createPendingDelegation. - validUntil, _ := delegationValidUntil(flowState.Collected) - - sendText(bot, chatID, fmt.Sprintf( - "🔁 Обязанности будут делегированы: %s\n"+ - "📅 Ориентировочно до: %s\n\n"+ - "Начнёт действовать после согласования этой заявки и отменится, если её впоследствии отзовут.", - delegateName, validUntil.Format("02.01.2006"), - )) - - h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) -} - -// getAvailableDelegateCandidates — все активные сотрудники, кроме самого пользователя. -func (h *Handler) getAvailableDelegateCandidates(ctx context.Context, telegramID int64) ([]*typescore.User, error) { - me, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || me == nil || me.ID == nil { - return nil, err - } - - users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.User{IsBlocked: utilscore.PointerToBool(false)}, - }) - if err != nil { - return nil, err - } - - var result []*typescore.User - for _, u := range users { - if u.ID == nil || *u.ID == *me.ID || u.TelegramID == nil { - continue - } - if u.IsFired != nil && *u.IsFired { - continue - } - result = append(result, u) - } - return result, nil -} - -// ============================================================ -// Создание / активация / деактивация делегирования, привязанного к -// конкретной заявке (approval_id — см. DELEGATION_PATCHES.txt). -// ============================================================ - -// createPendingDelegation вызывается из submitApproval сразу после -// создания заявки. Создаёт по одной НЕАКТИВНОЙ записи ApprovalDelegation -// на каждую активную категорию согласований (поиск делегата в -// processNextStepOrComplete/handleDecision матчит строго по конкретному -// TopicID либо конкретному CategoryID — запись "на всё сразу" с обоими -// NULL никогда бы не нашлась). -func (h *Handler) createPendingDelegation(ctx context.Context, initiator *typescore.User, flowState *state.ApprovalFlowState, approval *typescore.Approval) { - if flowState.SelectedDelegateID == 0 { - return - } - if initiator == nil || initiator.ID == nil || approval == nil || approval.ID == nil { - return - } - - delegate, err := h.ipc.Database.User.GetUserByIDDB(ctx, flowState.SelectedDelegateID) - if err != nil || delegate == nil || delegate.ID == nil { - logrus.Errorf("createPendingDelegation: delegate not found id=%d err=%v", flowState.SelectedDelegateID, err) - return - } - - validUntil, datesFound := delegationValidUntil(flowState.Collected) - if !datesFound { - logrus.Warnf("createPendingDelegation: не удалось определить дату окончания отсутствия approvalID=%d — используется запасной срок 30 дней", *approval.ID) - } - - categories, _, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopicCategory{IsActive: utilscore.PointerToBool(true)}, - }) - if err != nil { - logrus.Errorf("createPendingDelegation: GetApprovalTopicCategoriesListDB err=%v", err) - return - } - - inactive := false - notifiedFalse := false - created := 0 - for _, cat := range categories { - if cat.ID == nil { - continue - } - catID := *cat.ID - delegation := &typescore.ApprovalDelegation{ - DelegatorID: initiator.ID, - DelegateID: delegate.ID, - CategoryID: &catID, - ApprovalID: approval.ID, - ValidUntil: &validUntil, - IsActive: &inactive, // включится только после одобрения заявки - NotifiedDay: ¬ifiedFalse, - Notified2h: ¬ifiedFalse, - } - if _, _, err := h.ipc.Database.ApprovalDelegation.CreateApprovalDelegationDB(ctx, nil, delegation); err != nil { - logrus.Errorf("createPendingDelegation: CreateApprovalDelegationDB categoryID=%d approvalID=%d err=%v", catID, *approval.ID, err) - continue - } - created++ - } - - logrus.Infof("createPendingDelegation: создано неактивных делегирований=%d approvalID=%d delegatorID=%d delegateID=%d", - created, *approval.ID, *initiator.ID, *delegate.ID) -} - -// activatePendingDelegation включает делегирование, привязанное к этой -// заявке (см. createPendingDelegation), в момент её полного одобрения. -// Вызывается из processNextStepOrComplete строго в ветке финального -// approved (не при передаче на следующий шаг). -func (h *Handler) activatePendingDelegation(ctx context.Context, approval *typescore.Approval) { - if approval == nil || approval.ID == nil { - return - } - - delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalDelegation{ApprovalID: approval.ID}, - }) - if err != nil { - logrus.Errorf("activatePendingDelegation: GetApprovalDelegationsListDB approvalID=%d err=%v", *approval.ID, err) - return - } - if len(delegations) == 0 { - return // делегирование при подаче этой заявки не настраивалось - } - - active := true - for _, d := range delegations { - d.IsActive = &active - if _, _, err := h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, d); err != nil { - logrus.Errorf("activatePendingDelegation: UpdateApprovalDelegationDB id=%v err=%v", d.ID, err) - } - } - logrus.Infof("activatePendingDelegation: активировано делегирований=%d approvalID=%d", len(delegations), *approval.ID) -} - -// deactivatePendingDelegation отменяет делегирование, привязанное к этой -// заявке, при её отзыве — независимо от того, успело оно активироваться -// (заявка уже была одобрена) или ещё оставалось неактивным (заявку -// отозвали прямо во время согласования). Вызывается из performActualRevoke. -func (h *Handler) deactivatePendingDelegation(ctx context.Context, approval *typescore.Approval) { - if approval == nil || approval.ID == nil { - return - } - - delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalDelegation{ApprovalID: approval.ID}, - }) - if err != nil { - logrus.Errorf("deactivatePendingDelegation: GetApprovalDelegationsListDB approvalID=%d err=%v", *approval.ID, err) - return - } - if len(delegations) == 0 { - return - } - - inactive := false - changed := 0 - for _, d := range delegations { - if d.IsActive != nil && !*d.IsActive { - continue // уже неактивно - } - d.IsActive = &inactive - if _, _, err := h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, d); err != nil { - logrus.Errorf("deactivatePendingDelegation: UpdateApprovalDelegationDB id=%v err=%v", d.ID, err) - continue - } - changed++ - } - logrus.Infof("deactivatePendingDelegation: отменено делегирований=%d approvalID=%d", changed, *approval.ID) -} - -// ============================================================ -// Разбор дат из flowState.Collected — тот же терпимый к опечаткам -// подход, что в scheduler/daily_reminder.go (getAbsentEmployeesToday), -// намеренно продублирован здесь, а не вынесен в общий пакет. -// ============================================================ - -var delegationDateRe = regexp.MustCompile(`(\d{1,2})[.,](\d{1,2})\.(\d{4})`) - -// delegationValidUntil ищет во ВСЕХ собранных на этом шаге значениях -// (обычно дата лежит под ключом "content" — стандартный input_key -// текстового шага, но на случай нестандартной настройки дерева -// проверяем все значения) самую позднюю дату. Если ничего не нашлось — -// возвращает запасной срок в 30 дней от текущего момента, чтобы не -// оставить not-null колонку без значения вовсе. -func delegationValidUntil(collected map[string]string) (time.Time, bool) { - var dates []time.Time - for _, v := range collected { - matches := delegationDateRe.FindAllStringSubmatch(v, -1) - for _, m := range matches { - day, errD := strconv.Atoi(m[1]) - month, errM := strconv.Atoi(m[2]) - year, errY := strconv.Atoi(m[3]) - if errD != nil || errM != nil || errY != nil { - continue - } - if month < 1 || month > 12 || day < 1 || day > 31 { - continue - } - dates = append(dates, time.Date(year, time.Month(month), day, 23, 59, 59, 0, time.UTC)) - } - } - - if len(dates) == 0 { - return time.Now().AddDate(0, 0, 30), false - } - - maxDate := dates[0] - for _, d := range dates[1:] { - if d.After(maxDate) { - maxDate = d - } - } - return maxDate, true -} - ------END service/telegram_service/handlers/approval/absense_delegation.go----- - -File: service/telegram_service/handlers/approval/approval_revocation.go -Lines: 271 ------BEGIN service/telegram_service/handlers/approval/approval_revocation.go----- -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" -) - -// getDistinctApprovedApproverIDs — все, кто реально одобрил хотя бы один шаг этой заявки. -func (h *Handler) getDistinctApprovedApproverIDs(ctx context.Context, approvalID uint64) []uint64 { - steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, - }) - if err != nil { - return nil - } - - seen := make(map[uint64]bool) - var ids []uint64 - for _, s := range steps { - if s.Status == nil || *s.Status != "approved" || s.ApproverID == nil { - continue - } - if !seen[*s.ApproverID] { - seen[*s.ApproverID] = true - ids = append(ids, *s.ApproverID) - } - } - return ids -} - -// startApprovalRevocationRequest создаёт запрос на отзыв уже согласованной заявки -// и рассылает его всем, кто участвовал в согласовании, для получения их согласия. -func (h *Handler) startApprovalRevocationRequest( - bot *tgbotapi.BotAPI, - chatID int64, - approval *typescore.Approval, - initiator *typescore.User, - comment string, -) { - ctx := context.Background() - approvalID := *approval.ID - - if existing, _ := h.ipc.Database.ApprovalRevocation.GetPendingRevocationRequestForApprovalDB(ctx, approvalID); existing != nil { - sendText(bot, chatID, "⚠️ По этой заявке уже есть ожидающий рассмотрения запрос на отзыв.") - return - } - - approverIDs := h.getDistinctApprovedApproverIDs(ctx, approvalID) - if len(approverIDs) == 0 { - // Заявку никто не одобрял (странный случай, но не блокируем инициатора навсегда) - h.HandleRevokeWithComment(bot, chatID, *initiator.TelegramID, approvalID, comment) - return - } - - pendingStatus := "pending" - var reasonPtr *string - if comment != "" { - reasonPtr = &comment - } - - request := &typescore.ApprovalRevocationRequest{ - ApprovalID: &approvalID, - RequestedByID: initiator.ID, - Reason: reasonPtr, - Status: &pendingStatus, - } - created, err := h.ipc.Database.ApprovalRevocation.CreateRevocationRequestDB(ctx, request, true) - if err != nil || created == nil || created.ID == nil { - logrus.Errorf("startApprovalRevocationRequest: CreateRevocationRequestDB err=%v", err) - sendText(bot, chatID, "⚠️ Ошибка при создании запроса на отзыв.") - return - } - - var approvers []*typescore.ApprovalRevocationApprover - for _, id := range approverIDs { - id := id - approvers = append(approvers, &typescore.ApprovalRevocationApprover{ - RevocationRequestID: created.ID, - ApproverID: &id, - Status: &pendingStatus, - }) - } - if err := h.ipc.Database.ApprovalRevocation.CreateRevocationApproversDB(ctx, approvers); err != nil { - logrus.Errorf("startApprovalRevocationRequest: CreateRevocationApproversDB err=%v", err) - sendText(bot, chatID, "⚠️ Ошибка при создании списка согласующих.") - return - } - - initiatorName := "—" - if initiator.FullName != nil { - initiatorName = *initiator.FullName - } - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - content := "—" - if approval.Content != nil { - content = *approval.Content - } - reasonLine := "" - if comment != "" { - reasonLine = fmt.Sprintf("\n💬 Причина: %s", comment) - } - - notifyText := fmt.Sprintf( - "⚠️ Запрос на отзыв согласованной заявки #%d\n\n"+ - "👤 Инициатор: %s\n"+ - "📋 Тема: %s\n"+ - "📝 Текст: %s%s\n\n"+ - "Требуется согласие всех, кто участвовал в согласовании. Ваше решение:", - approvalID, initiatorName, topicFullName, content, reasonLine, - ) - - for _, id := range approverIDs { - approver, err := h.ipc.Database.User.GetUserByIDDB(ctx, id) - if err != nil || approver == nil || approver.TelegramID == nil { - continue - } - msg := tgbotapi.NewMessage(*approver.TelegramID, notifyText) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevocationApprovalDecision(approvalID, *created.ID, h.GetCommentsCount(ctx, approvalID)) - bot.Send(msg) //nolint:errcheck - } - - sendText(bot, chatID, fmt.Sprintf( - "📤 Запрос на отзыв заявки #%d отправлен\n\n"+ - "Ожидаем согласия от всех согласующих (%d чел.). Заявка будет отозвана только после единодушного согласия.", - approvalID, len(approverIDs), - )) -} - -// HandleRevocationApproverDecision — согласующий дал ответ на запрос отзыва. -func (h *Handler) HandleRevocationApproverDecision(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, requestID uint64, approved bool) { - 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 - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID) - if err != nil || user == nil || user.ID == nil { - return - } - - request, err := h.ipc.Database.ApprovalRevocation.GetRevocationRequestByIDDB(ctx, requestID) - if err != nil || request == nil { - sendText(bot, chatID, "⚠️ Запрос не найден.") - return - } - if request.Status == nil || *request.Status != "pending" { - sendText(bot, chatID, "⚠️ Этот запрос уже обработан.") - return - } - - approverRecord, err := h.ipc.Database.ApprovalRevocation.GetRevocationApproverForUserDB(ctx, requestID, *user.ID) - if err != nil || approverRecord == nil { - sendText(bot, chatID, "⚠️ Вы не являетесь участником этого согласования.") - return - } - if approverRecord.Status == nil || *approverRecord.Status != "pending" { - sendText(bot, chatID, "⚠️ Вы уже дали ответ на этот запрос.") - return - } - - now := time.Now() - newStatus := "approved" - if !approved { - newStatus = "rejected" - } - approverRecord.Status = &newStatus - approverRecord.ActedAt = &now - if err := h.ipc.Database.ApprovalRevocation.UpdateRevocationApproverDB(ctx, approverRecord); err != nil { - logrus.Errorf("HandleRevocationApproverDecision: UpdateRevocationApproverDB err=%v", err) - return - } - - responderName := "—" - if user.FullName != nil { - responderName = *user.FullName - } - - if !approved { - // Один отказ — отклоняем весь запрос сразу - rejectedStatus := "rejected" - request.Status = &rejectedStatus - h.ipc.Database.ApprovalRevocation.UpdateRevocationRequestDB(ctx, request) //nolint:errcheck - - sendText(bot, chatID, fmt.Sprintf("❌ Вы отклонили отзыв заявки #%d.", *request.ApprovalID)) - h.notifyRevocationRequestClosed(bot, ctx, request, false, responderName) - return - } - - sendText(bot, chatID, fmt.Sprintf("✅ Вы согласились на отзыв заявки #%d.", *request.ApprovalID)) - - // Проверяем, все ли уже согласились - allApprovers, err := h.ipc.Database.ApprovalRevocation.GetRevocationApproversByRequestIDDB(ctx, requestID) - if err != nil { - return - } - allApproved := true - for _, a := range allApprovers { - if a.Status == nil || *a.Status != "approved" { - allApproved = false - break - } - } - - if !allApproved { - return - } - - approvedStatus := "approved" - request.Status = &approvedStatus - if _, err := h.ipc.Database.ApprovalRevocation.UpdateRevocationRequestDB(ctx, request); err != nil { - logrus.Errorf("HandleRevocationApproverDecision: UpdateRevocationRequestDB err=%v", err) - return - } - - // Все согласились — выполняем фактический отзыв - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *request.ApprovalID) - if err != nil || approval == nil || request.RequestedByID == nil { - return - } - initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *request.RequestedByID) - if err != nil || initiator == nil || initiator.TelegramID == nil { - return - } - - reason := "" - if request.Reason != nil { - reason = *request.Reason - } - - // В этой ветке отзывающий — инициатор (запрос был именно от него), - // isDirectorRevoking всегда false, т.к. в этот путь директор не попадает - steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: request.ApprovalID}, - }) - - h.performActualRevoke(bot, ctx, approval, initiator, "инициатором", reason, steps, true, false) - h.notifyRevocationRequestClosed(bot, ctx, request, true, "") -} - -// notifyRevocationRequestClosed уведомляет инициатора об итоге запроса на отзыв. -func (h *Handler) notifyRevocationRequestClosed(bot *tgbotapi.BotAPI, ctx context.Context, request *typescore.ApprovalRevocationRequest, approved bool, rejectorName string) { - if request.RequestedByID == nil { - return - } - initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *request.RequestedByID) - if err != nil || initiator == nil || initiator.TelegramID == nil { - return - } - - if approved { - sendText(bot, *initiator.TelegramID, fmt.Sprintf( - "✅ Заявка #%d отозвана\n\nВсе согласующие дали согласие на отзыв.", - *request.ApprovalID, - )) - return - } - - sendText(bot, *initiator.TelegramID, fmt.Sprintf( - "❌ Отзыв заявки #%d отклонён\n\n"+ - "👤 Отклонил: %s\n\n"+ - "Заявка остаётся согласованной.", - *request.ApprovalID, rejectorName, - )) -} - ------END service/telegram_service/handlers/approval/approval_revocation.go----- - -File: service/telegram_service/handlers/approval/approval_task_transfer.go -Lines: 316 ------BEGIN service/telegram_service/handlers/approval/approval_task_transfer.go----- -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" -) - -// HandleTransferTaskStart — исполнитель начинает передачу задачи, показываем список пользователей -func (h *Handler) HandleTransferTaskStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64) { - h.showTransferTaskUserPage(bot, cq, taskID, 0, false) -} - -func (h *Handler) HandleTransferTaskUserPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) { - ctx := context.Background() - taskIDKey := fmt.Sprintf("task_transfer_pending:%d", cq.From.ID) - taskIDStr, err := h.ipc.RedisClient.Get(ctx, taskIDKey) - if err != nil || taskIDStr == "" { - bot.Request(tgbotapi.NewCallback(cq.ID, "Сессия истекла, начните заново")) //nolint:errcheck - return - } - var taskID uint64 - fmt.Sscanf(taskIDStr, "%d", &taskID) - h.showTransferTaskUserPage(bot, cq, taskID, page, true) -} - -func (h *Handler) showTransferTaskUserPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64, page int, isEdit bool) { - ctx := context.Background() - chatID := cq.Message.Chat.ID - telegramID := cq.From.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - currentUser, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || currentUser == nil || currentUser.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 != *currentUser.ID { - sendText(bot, chatID, "⚠️ Это не ваша задача.") - return - } - if task.Status == nil || *task.Status != "pending" { - sendText(bot, chatID, "⚠️ Передать можно только активную задачу.") - return - } - - if existing, _ := h.ipc.Database.ApprovalTaskTransfer.GetPendingTransferForTaskDB(ctx, taskID); existing != nil { - sendText(bot, chatID, "⚠️ По этой задаче уже есть ожидающий подтверждения запрос на передачу.") - return - } - - allUsers, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.User{IsBlocked: utilscore.PointerToBool(false)}, - Limit: utilscore.PointerToUint64(500), - }) - if err != nil { - logrus.Errorf("showTransferTaskUserPage: GetUsersListDB err=%v", err) - return - } - - var candidates []*typescore.User - for _, u := range allUsers { - if u.ID != nil && currentUser.ID != nil && *u.ID != *currentUser.ID { - candidates = append(candidates, u) - } - } - - taskIDKey := fmt.Sprintf("task_transfer_pending:%d", telegramID) - h.ipc.RedisClient.Set(ctx, taskIDKey, fmt.Sprintf("%d", taskID), 10*time.Minute) //nolint:errcheck - - markup := keyboard.BuildTaskTransferUserMenu(candidates, page) - - if isEdit { - edit := tgbotapi.NewEditMessageReplyMarkup(chatID, cq.Message.MessageID, markup) - bot.Request(edit) //nolint:errcheck - return - } - - msg := tgbotapi.NewMessage(chatID, "🔁 Кому передать задачу?\n\nВыберите пользователя из списка:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = markup - bot.Send(msg) //nolint:errcheck -} - -// HandleTransferTaskUserSelect — исполнитель выбрал получателя -func (h *Handler) HandleTransferTaskUserSelect(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, toUserID 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 - - taskIDKey := fmt.Sprintf("task_transfer_pending:%d", telegramID) - taskIDStr, err := h.ipc.RedisClient.Get(ctx, taskIDKey) - if err != nil || taskIDStr == "" { - sendText(bot, chatID, "⚠️ Сессия истекла, начните заново.") - return - } - var taskID uint64 - fmt.Sscanf(taskIDStr, "%d", &taskID) - h.ipc.RedisClient.Del(ctx, taskIDKey) //nolint:errcheck - - fromUser, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || fromUser == nil || fromUser.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 != *fromUser.ID { - sendText(bot, chatID, "⚠️ Это не ваша задача.") - return - } - if task.Status == nil || *task.Status != "pending" { - sendText(bot, chatID, "⚠️ Задача больше не активна — передача невозможна.") - return - } - if existing, _ := h.ipc.Database.ApprovalTaskTransfer.GetPendingTransferForTaskDB(ctx, taskID); existing != nil { - sendText(bot, chatID, "⚠️ По этой задаче уже есть ожидающий запрос.") - return - } - - toUser, err := h.ipc.Database.User.GetUserByIDDB(ctx, toUserID) - if err != nil || toUser == nil || toUser.TelegramID == nil { - sendText(bot, chatID, "⚠️ У выбранного пользователя не привязан Telegram, передача невозможна.") - return - } - - pendingStatus := "pending" - transfer := &typescore.ApprovalTaskTransfer{ - TaskID: taskID2Ptr(taskID), - FromExecutorID: fromUser.ID, - ToExecutorID: toUser.ID, - Status: &pendingStatus, - } - created, err := h.ipc.Database.ApprovalTaskTransfer.CreateApprovalTaskTransferDB(ctx, transfer) - if err != nil || created == nil || created.ID == nil { - logrus.Errorf("HandleTransferTaskUserSelect: CreateApprovalTaskTransferDB err=%v", err) - sendText(bot, chatID, "⚠️ Ошибка при создании запроса.") - return - } - - fromName := "—" - if fromUser.FullName != nil { - fromName = *fromUser.FullName - } - - approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID) - topicFullName := "—" - taskText := "—" - if approval != nil { - topicFullName = getTopicFullName(ctx, h.ipc, approval.TopicID) - } - if task.TaskText != nil { - taskText = *task.TaskText - } - - notifyText := fmt.Sprintf( - "🔁 Вам предлагают принять задачу\n\n"+ - "👤 От: %s\n"+ - "📋 Тема: %s\n"+ - "🎯 Задача:\n%s\n\n"+ - "Подтвердите, что принимаете задачу на себя:", - fromName, topicFullName, taskText, - ) - - notifyMsg := tgbotapi.NewMessage(*toUser.TelegramID, notifyText) - notifyMsg.ParseMode = "HTML" - notifyMsg.ReplyMarkup = keyboard.BuildTaskTransferConfirmation(*created.ID) - bot.Send(notifyMsg) //nolint:errcheck - - toName := "—" - if toUser.FullName != nil { - toName = *toUser.FullName - } - sendText(bot, chatID, fmt.Sprintf( - "📤 Запрос отправлен\n\nОжидаем подтверждения от %s.", toName, - )) -} - -// HandleTransferTaskAccept — получатель принял задачу -func (h *Handler) HandleTransferTaskAccept(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, transferID 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 - - transfer, err := h.ipc.Database.ApprovalTaskTransfer.GetApprovalTaskTransferByIDDB(ctx, transferID) - if err != nil || transfer == nil { - sendText(bot, chatID, "⚠️ Запрос не найден.") - return - } - if transfer.Status == nil || *transfer.Status != "pending" { - sendText(bot, chatID, "⚠️ Этот запрос уже обработан.") - return - } - - acceptor, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID) - if err != nil || acceptor == nil || acceptor.ID == nil { - return - } - if transfer.ToExecutorID == nil || *transfer.ToExecutorID != *acceptor.ID { - sendText(bot, chatID, "⚠️ Этот запрос адресован не вам.") - return - } - - task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, *transfer.TaskID) - if err != nil || task == nil { - sendText(bot, chatID, "⚠️ Задача не найдена.") - return - } - - // 🚀 Ключевая защита от гонки: перепроверяем, что задача всё ещё активна - // и всё ещё принадлежит тому, кто инициировал передачу - if task.Status == nil || *task.Status != "pending" || - task.ExecutorID == nil || transfer.FromExecutorID == nil || *task.ExecutorID != *transfer.FromExecutorID { - - declinedStatus := "declined" - transfer.Status = &declinedStatus - now := time.Now() - transfer.RespondedAt = &now - h.ipc.Database.ApprovalTaskTransfer.UpdateApprovalTaskTransferDB(ctx, transfer) //nolint:errcheck - - sendText(bot, chatID, "⚠️ Задача уже была выполнена или передана другому — принять не удалось.") - return - } - - acceptedStatus := "accepted" - transfer.Status = &acceptedStatus - now := time.Now() - transfer.RespondedAt = &now - if _, err := h.ipc.Database.ApprovalTaskTransfer.UpdateApprovalTaskTransferDB(ctx, transfer); err != nil { - logrus.Errorf("HandleTransferTaskAccept: UpdateApprovalTaskTransferDB err=%v", err) - return - } - - task.ExecutorID = acceptor.ID - if _, _, err := h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task); err != nil { - logrus.Errorf("HandleTransferTaskAccept: UpdateApprovalTaskDB err=%v", err) - return - } - - acceptorName := "—" - if acceptor.FullName != nil { - acceptorName = *acceptor.FullName - } - - // Уведомляем исходного исполнителя - if transfer.FromExecutorID != nil { - fromUser, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *transfer.FromExecutorID) - if fromUser != nil && fromUser.TelegramID != nil { - sendText(bot, *fromUser.TelegramID, fmt.Sprintf( - "✅ %s принял(а) задачу\n\nЗадача больше не числится за вами.", acceptorName, - )) - } - } - - sendText(bot, chatID, "✅ Задача принята\n\nОна теперь ваша.") - - // Отправляем получателю полную карточку задачи с кнопками действий - approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID) - if approval != nil { - h.sendTaskCard(bot, chatID, approval, task) - } -} - -// HandleTransferTaskDecline — получатель отклонил задачу -func (h *Handler) HandleTransferTaskDecline(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, transferID 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 - - transfer, err := h.ipc.Database.ApprovalTaskTransfer.GetApprovalTaskTransferByIDDB(ctx, transferID) - if err != nil || transfer == nil || transfer.Status == nil || *transfer.Status != "pending" { - sendText(bot, chatID, "⚠️ Запрос не найден или уже обработан.") - return - } - - declinedStatus := "declined" - transfer.Status = &declinedStatus - now := time.Now() - transfer.RespondedAt = &now - if _, err := h.ipc.Database.ApprovalTaskTransfer.UpdateApprovalTaskTransferDB(ctx, transfer); err != nil { - logrus.Errorf("HandleTransferTaskDecline: UpdateApprovalTaskTransferDB err=%v", err) - return - } - - sendText(bot, chatID, "❌ Вы отклонили передачу задачи.") - - if transfer.FromExecutorID != nil { - fromUser, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *transfer.FromExecutorID) - if fromUser != nil && fromUser.TelegramID != nil { - sendText(bot, *fromUser.TelegramID, "❌ Получатель отклонил передачу задачи\n\nЗадача осталась за вами.") - } - } -} - -func taskID2Ptr(id uint64) *uint64 { return &id } - ------END service/telegram_service/handlers/approval/approval_task_transfer.go----- - -File: service/telegram_service/handlers/approval/approver_approvals.go -Lines: 211 ------BEGIN service/telegram_service/handlers/approval/approver_approvals.go----- -package approval - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "context" - "fmt" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" -) - -// HandleApproverApprovals — вход в флоу: показываем темы, по которым -// пользователь участвовал как согласующий. -func (h *Handler) HandleApproverApprovals(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 - } - - // Категории, в которых пользователь был согласующим - categories, err := h.ipc.Database.ApprovalTopicCategory.GetCategoriesWithApprovalsByApproverDB(ctx, *user.ID) - if err != nil || len(categories) == 0 { - // Сразу показываем все без фильтра по теме - h.HandleApproverApprovalsStatusCallback( - bot, - &tgbotapi.CallbackQuery{ - Message: &tgbotapi.Message{Chat: &tgbotapi.Chat{ID: chatID}}, - From: &tgbotapi.User{ID: telegramID}, - }, - "all", "all", - ) - return - } - - msg := tgbotapi.NewMessage(chatID, "📂 Согласования в работе\n\nВыберите тему:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = buildApproverApprovalsTopicFilter(categories) - bot.Send(msg) //nolint:errcheck -} - -// HandleApproverApprovalsTopicCallback — пользователь выбрал тему. -func (h *Handler) HandleApproverApprovalsTopicCallback( - bot *tgbotapi.BotAPI, - cq *tgbotapi.CallbackQuery, - topicFilter 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 - - header := "Все темы" - if topicFilter != "all" && topicFilter != "" { - cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicFilter) - if cat != nil && cat.Name != nil { - header = *cat.Name - } - } - - msg := tgbotapi.NewMessage(cq.Message.Chat.ID, - fmt.Sprintf("📂 %s\n\nВыберите статус:", header), - ) - msg.ParseMode = "HTML" - msg.ReplyMarkup = buildApproverApprovalsStatusFilter(topicFilter) - bot.Send(msg) //nolint:errcheck -} - -// HandleApproverApprovalsStatusCallback — пользователь выбрал статус, -// показываем список согласований, где он был согласующим. -func (h *Handler) HandleApproverApprovalsStatusCallback( - bot *tgbotapi.BotAPI, - cq *tgbotapi.CallbackQuery, - status, topicFilter 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 - - chatID := cq.Message.Chat.ID - telegramID := cq.From.ID - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return - } - - stepStatus := status - if stepStatus == "all" { - stepStatus = "" - } - - stepFilter := &typescore.ApprovalStep{ - ApproverID: user.ID, - } - if stepStatus != "" { - stepFilter.Status = utilscore.PointerToString(stepStatus) - } - - steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: stepFilter, - }) - if err != nil { - logrus.Errorf("HandleApproverApprovalsStatusCallback: GetApprovalStepsListDB err=%v", err) - sendText(bot, chatID, "Ошибка при получении заявок.") - return - } - - allowedTopicIDs := make(map[uint64]bool) - if topicFilter != "" && topicFilter != "all" { - cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicFilter) - if cat != nil && cat.ID != nil { - topics, _, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{CategoryID: cat.ID}, - }) - for _, t := range topics { - if t.ID != nil { - allowedTopicIDs[*t.ID] = true - } - } - } - } - - // Дедублируем approvalID - seen := make(map[uint64]struct{}) - var filtered []*typescore.ApprovalStep - for _, step := range steps { - if step.ApprovalID == nil { - continue - } - if _, ok := seen[*step.ApprovalID]; ok { - continue - } - seen[*step.ApprovalID] = struct{}{} - filtered = append(filtered, step) - } - - if len(filtered) == 0 { - sendText(bot, chatID, "📭 Заявок по выбранным фильтрам не найдено.") - return - } - - sent := 0 - for _, step := range filtered { - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID) - if err != nil || approval == nil { - continue - } - - // 🚀 Фильтр по теме через map разрешённых ID - if len(allowedTopicIDs) > 0 { - if approval.TopicID == nil || !allowedTopicIDs[*approval.TopicID] { - continue - } - } - - h.sendApprovalCard(bot, chatID, approval, false, false) - sent++ - } - - if sent == 0 { - sendText(bot, chatID, "📭 Заявок по выбранным фильтрам не найдено.") - } -} - -// ─── inline-клавиатуры ─────────────────────────────────────────────────────── - -func buildApproverApprovalsTopicFilter( - categories []*typescore.ApprovalTopicCategory, -) tgbotapi.InlineKeyboardMarkup { - var rows [][]tgbotapi.InlineKeyboardButton - - rows = append(rows, tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("📋 Все темы", "appr_appr_topic:all"), - )) - - for _, c := range categories { - if c.ID == nil || c.Name == nil || c.Code == nil { - continue - } - rows = append(rows, tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData( - *c.Name, - fmt.Sprintf("appr_appr_topic:%s", *c.Code), - ), - )) - } - - return tgbotapi.NewInlineKeyboardMarkup(rows...) -} - -func buildApproverApprovalsStatusFilter(topicFilter string) tgbotapi.InlineKeyboardMarkup { - cb := func(status string) string { - return fmt.Sprintf("appr_appr_status:%s:%s", status, topicFilter) - } - return tgbotapi.NewInlineKeyboardMarkup( - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("Все", cb("all")), - ), - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("✅ Согласованные", cb("approved")), - tgbotapi.NewInlineKeyboardButtonData("❌ Отклонённые", cb("rejected")), - ), - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("⏳ Ожидают", cb("pending")), - ), - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("← Назад", "appr_appr_back"), - ), - ) -} - ------END service/telegram_service/handlers/approval/approver_approvals.go----- - -File: service/telegram_service/handlers/approval/db_watcher.go -Lines: 53 ------BEGIN service/telegram_service/handlers/approval/db_watcher.go----- -package approval - -import ( - "bitrix_balancer_api/core/variables" - "context" - "time" - - "github.com/sirupsen/logrus" -) - -const flowVersionRedisKey = "approval_flow:version" - -// watchRegistryReload — фоновый воркер: раз в pollInterval проверяет, менялась -// ли версия дерева тем/категорий (её бампает rest_admin_service при любом -// изменении дерева/категорий/тем — см. bumpFlowVersion в nodeshandler), и если -// да — перечитывает Registry из БД. -// -// Зачем это нужно: h.Registry.LoadFromDB вызывается один раз в NewHandler, -// при старте процесса бота. Без этого воркера Registry — снимок на момент -// старта, и всё, что создано в конструкторе после этого (новые категории, -// деревья, темы), в боте не появится до перезапуска процесса. -// -// Почему через Redis, а не прямой HTTP-вызов между сервисами: rest_admin_service -// и telegram_service — разные процессы, у telegram_service нет гарантированного -// входящего HTTP-порта (он может работать через long polling к Telegram API), -// а Redis у обоих сервисов уже общий (см. ipc.RedisClient в NewHandler). -func (h *Handler) watchRegistryReload() { - const pollInterval = 5 * time.Second - ticker := time.NewTicker(pollInterval) - defer ticker.Stop() - - lastVersion := "" - for range ticker.C { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - version, err := h.ipc.RedisClient.Get(ctx, flowVersionRedisKey) - cancel() - if err != nil { - continue - } - if version == "" || version == lastVersion { - continue - } - lastVersion = version - - reloadCtx, reloadCancel := context.WithTimeout(context.Background(), variables.ContextTimeoutLong) - if err := h.Registry.Reload(reloadCtx); err != nil { - logrus.Errorf("watchRegistryReload: Registry.Reload err=%v", err) - } else { - logrus.Infof("watchRegistryReload: дерево тем перечитано, версия=%s", version) - } - reloadCancel() - } -} - ------END service/telegram_service/handlers/approval/db_watcher.go----- - -File: service/telegram_service/handlers/approval/director_notification_settings.go -Lines: 118 ------BEGIN service/telegram_service/handlers/approval/director_notification_settings.go----- -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" - "sort" -) - -// HandleDirectorNotificationSettings — показывает мультиселект категорий уведомлений (страница 0) -func (h *Handler) HandleDirectorNotificationSettings(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { - h.showDirectorNotificationPage(bot, chatID, 0, telegramID, 0) -} - -// showDirectorNotificationPage — общая логика показа/перерисовки страницы категорий. -// prevMessageID != 0 — редактируем существующее сообщение вместо отправки нового. -func (h *Handler) showDirectorNotificationPage(bot *tgbotapi.BotAPI, chatID int64, page int, telegramID int64, prevMessageID int) { - ctx := context.Background() - - director, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || director == nil || director.ID == nil { - sendText(bot, chatID, "⚠️ Пользователь не найден.") - return - } - - isDirector, err := h.ipc.Database.User.IsDirectorDB(ctx, *director.ID) - if err != nil || !isDirector { - sendText(bot, chatID, "⚠️ У вас нет прав директора.") - return - } - - isActive := true - categories, _, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopicCategory{IsActive: &isActive}, - }) - if err != nil { - logrus.Errorf("showDirectorNotificationPage: GetApprovalTopicCategoryListDB err=%v", err) - sendText(bot, chatID, "⚠️ Ошибка загрузки категорий.") - return - } - - sort.Slice(categories, func(i, j int) bool { - if categories[i].Name == nil || categories[j].Name == nil { - return false - } - return *categories[i].Name < *categories[j].Name - }) - - subscribedIDs, err := h.ipc.Database.DirectorNotifications.GetSubscribedCategoryIDsDB(ctx, *director.ID) - if err != nil { - logrus.Errorf("showDirectorNotificationPage: GetSubscribedCategoryIDsDB err=%v", err) - } - - markup := keyboard.BuildDirectorNotificationCategoriesMenu(categories, subscribedIDs, page) - - if prevMessageID != 0 { - edit := tgbotapi.NewEditMessageReplyMarkup(chatID, prevMessageID, markup) - bot.Request(edit) //nolint:errcheck - return - } - - msg := tgbotapi.NewMessage(chatID, "🔔 Уведомления по категориям\n\nВыберите категории, по которым хотите получать уведомления о финально согласованных заявках. По умолчанию все выключены.") - msg.ParseMode = "HTML" - msg.ReplyMarkup = markup - bot.Send(msg) //nolint:errcheck -} - -// HandleDirectorNotificationToggle — обрабатывает нажатие на категорию (callback dir_notif_toggle:{categoryID}:{page}) -func (h *Handler) HandleDirectorNotificationToggle(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64, page int) { - ctx := context.Background() - chatID := cq.Message.Chat.ID - telegramID := cq.From.ID - - director, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || director == nil || director.ID == nil { - bot.Request(tgbotapi.NewCallback(cq.ID, "Пользователь не найден")) //nolint:errcheck - return - } - - enabled, err := h.ipc.Database.DirectorNotifications.ToggleSubscriptionDB(ctx, *director.ID, categoryID) - if err != nil { - logrus.Errorf("HandleDirectorNotificationToggle: ToggleSubscriptionDB err=%v", err) - bot.Request(tgbotapi.NewCallback(cq.ID, "Ошибка сохранения")) //nolint:errcheck - return - } - - statusText := "выключены" - if enabled { - statusText = "включены" - } - bot.Request(tgbotapi.NewCallback(cq.ID, fmt.Sprintf("Уведомления %s", statusText))) //nolint:errcheck - - // Перерисовываем ту же страницу, где был клик - h.showDirectorNotificationPage(bot, chatID, page, telegramID, cq.Message.MessageID) -} - -// HandleDirectorNotificationPage — переключение страниц пагинации -func (h *Handler) HandleDirectorNotificationPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) { - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - h.showDirectorNotificationPage(bot, cq.Message.Chat.ID, page, cq.From.ID, cq.Message.MessageID) -} - -// HandleDirectorNotificationDone — закрывает меню настройки уведомлений -func (h *Handler) HandleDirectorNotificationDone(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 -} - -// HandleDirectorSubmenu — подменю директора -func (h *Handler) HandleDirectorSubmenu(bot *tgbotapi.BotAPI, chatID int64) { - msg := tgbotapi.NewMessage(chatID, "Директор\n\nВыберите действие:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildDirectorSubmenu() - bot.Send(msg) //nolint:errcheck -} - ------END service/telegram_service/handlers/approval/director_notification_settings.go----- - -File: service/telegram_service/handlers/approval/handle_attachment.go -Lines: 4 ------BEGIN service/telegram_service/handlers/approval/handle_attachment.go----- -// telegram_service/handlers/approval/attachment.go - ЗАМЕНИТЬ полностью - -package approval - - ------END service/telegram_service/handlers/approval/handle_attachment.go----- - -File: service/telegram_service/handlers/approval/handle_files.go -Lines: 466 ------BEGIN service/telegram_service/handlers/approval/handle_files.go----- -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" - "sync" - "time" -) - -const maxAttachFiles = 10 - -var ( - albumDebounce = make(map[int64]*time.Timer) - albumDebounceMu sync.Mutex -) - -var ( - fileInputMu = make(map[int64]*sync.Mutex) - fileInputMuMu sync.Mutex -) - -func getFileInputMutex(telegramID int64) *sync.Mutex { - fileInputMuMu.Lock() - defer fileInputMuMu.Unlock() - - if _, ok := fileInputMu[telegramID]; !ok { - fileInputMu[telegramID] = &sync.Mutex{} - } - return fileInputMu[telegramID] -} - -// HandleAttachFileStart — начало прикрепления файлов (согласующий/исполнитель) -func (h *Handler) HandleAttachFileStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { - ctx := context.Background() - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID) - 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, cq.Message.Chat.ID, "⚠️ Заявка не найдена.") - return - } - - canAttach, _ := h.canUserCommentApproval(ctx, *user.ID, approval) - if !canAttach { - sendText(bot, cq.Message.Chat.ID, "⚠️ Нет прав на прикрепление файлов.") - return - } - - session := &state.AttachmentSession{ - ApprovalID: approvalID, - Files: []state.FileAttachment{}, - Stage: "collecting", - } - h.States.SetAttachmentSession(ctx, cq.From.ID, session) //nolint:errcheck - - msg := tgbotapi.NewMessage(cq.Message.Chat.ID, - fmt.Sprintf( - "📎 Прикрепление файлов к заявке #%d\n\n"+ - "Отправляйте файлы по одному или альбомом.\n"+ - "Максимум %d файлов за раз.\n\n"+ - "Когда закончите — нажмите «Отправить».", - approvalID, maxAttachFiles, - ), - ) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildAttachSessionKeyboard(approvalID, 0) - bot.Send(msg) //nolint:errcheck -} - -// HandleAttachFileInput — пользователь отправил файл в режиме прикрепления -func (h *Handler) HandleAttachFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { - ctx := context.Background() - telegramID := msg.From.ID - chatID := msg.Chat.ID - - mu := getFileInputMutex(telegramID) - mu.Lock() - defer mu.Unlock() - - session, err := h.States.GetAttachmentSession(ctx, telegramID) - if err != nil || session == nil || session.Stage != "collecting" { - return false - } - - if len(session.Files) >= maxAttachFiles { - sendText(bot, chatID, fmt.Sprintf("⚠️ Максимум %d файлов. Сначала отправьте текущие.", maxAttachFiles)) - return true - } - - var fileID, fileName string - switch { - case msg.Document != nil: - fileID = msg.Document.FileID - fileName = msg.Document.FileName - if fileName == "" { - fileName = fmt.Sprintf("document_%s", time.Now().Format("20060102_150405")) - } - case msg.Photo != nil && len(msg.Photo) > 0: - fileID = msg.Photo[len(msg.Photo)-1].FileID - fileName = fmt.Sprintf("photo_%s.jpg", time.Now().Format("20060102_150405.000")) - default: - sendText(bot, chatID, "⚠️ Отправьте фото или документ.") - return true - } - - fileURL, err := bot.GetFileDirectURL(fileID) - if err != nil { - logrus.Errorf("HandleAttachFileInput: GetFileDirectURL err=%v", err) - sendText(bot, chatID, "Ошибка при получении файла.") - return true - } - - base64Data, err := fetchFileAsBase64(fileURL) - if err != nil { - logrus.Errorf("HandleAttachFileInput: fetchFileAsBase64 err=%v", err) - sendText(bot, chatID, "Ошибка при обработке файла.") - return true - } - - session.Files = append(session.Files, state.FileAttachment{ - Base64: base64Data, - FileName: fileName, - }) - h.States.SetAttachmentSession(ctx, telegramID, session) //nolint:errcheck - - if msg.MediaGroupID != "" { - albumDebounceMu.Lock() - if t, ok := albumDebounce[telegramID]; ok { - t.Stop() - } - albumDebounce[telegramID] = time.AfterFunc(500*time.Millisecond, func() { - albumDebounceMu.Lock() - delete(albumDebounce, telegramID) - albumDebounceMu.Unlock() - - mu := getFileInputMutex(telegramID) - mu.Lock() - defer mu.Unlock() - - fresh, err := h.States.GetAttachmentSession(ctx, telegramID) - if err != nil || fresh == nil { - return - } - h.sendAttachStatusMessage(bot, chatID, fresh) - }) - albumDebounceMu.Unlock() - } else { - h.sendAttachStatusMessage(bot, chatID, session) - } - - return true -} - -func (h *Handler) sendAttachStatusMessage(bot *tgbotapi.BotAPI, chatID int64, session *state.AttachmentSession) { - fileListText := fmt.Sprintf( - "📎 Прикрепление файлов к заявке #%d\n\n"+ - "✅ Добавлено файлов: %d/%d\n\n", - session.ApprovalID, len(session.Files), maxAttachFiles, - ) - for i, f := range session.Files { - fileListText += fmt.Sprintf("%d. %s\n", i+1, f.FileName) - } - fileListText += "\nОтправьте ещё или нажмите «Отправить»." - - statusMsg := tgbotapi.NewMessage(chatID, fileListText) - statusMsg.ParseMode = "HTML" - statusMsg.ReplyMarkup = keyboard.BuildAttachSessionKeyboard(session.ApprovalID, len(session.Files)) - bot.Send(statusMsg) //nolint:errcheck -} - -// HandleAttachSubmit — пользователь нажал "Отправить файлы" -func (h *Handler) HandleAttachSubmit(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 - - session, err := h.States.GetAttachmentSession(ctx, telegramID) - if err != nil || session == nil { - sendText(bot, chatID, "⚠️ Сессия истекла. Начните заново.") - return - } - - if len(session.Files) == 0 { - sendText(bot, chatID, "⚠️ Нет файлов для отправки.") - return - } - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return - } - - // 🚀 Если это прикрепление к задаче — получаем taskID из сессии - var taskIDPtr *uint64 - if session.TaskID > 0 { - taskIDPtr = &session.TaskID - } - - // Сохраняем все файлы пакетом - savedCount := 0 - for _, f := range session.Files { - fileCopy := f - file := &typescore.ApprovalFile{ - ApprovalID: &approvalID, - FileBase64: &fileCopy.Base64, - FileName: &fileCopy.FileName, - AttachedByID: user.ID, - TaskID: taskIDPtr, // 🚀 НОВОЕ: связываем с задачей - } - if _, _, err := h.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, file); err != nil { - logrus.Errorf("HandleAttachSubmit: CreateApprovalFileDB file=%s err=%v", f.FileName, err) - continue - } - savedCount++ - } - - h.States.ClearAttachmentSession(ctx, telegramID) //nolint:errcheck - - sendText(bot, chatID, fmt.Sprintf( - "✅ Файлы прикреплены к заявке #%d\n\n📎 Сохранено файлов: %d", - approvalID, savedCount, - )) - - // Если это было прикрепление к задаче — показываем карточку задачи - if session.TaskID > 0 { - task, _ := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, session.TaskID) - if task != nil { - approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if approval != nil { - h.sendTaskCard(bot, chatID, approval, task) - } - } - } - - // Уведомляем всех участников с отправкой самих файлов медиагруппами - fileDesc := fmt.Sprintf("%d файл(ов)", savedCount) - go h.notifyAllParticipantsAboutFile(bot, approvalID, user, fileDesc) -} - -// HandleAttachClear — очистить список файлов -func (h *Handler) HandleAttachClear(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { - ctx := context.Background() - telegramID := cq.From.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - session, _ := h.States.GetAttachmentSession(ctx, telegramID) - if session != nil { - session.Files = []state.FileAttachment{} - h.States.SetAttachmentSession(ctx, telegramID, session) //nolint:errcheck - } - - editMsg := tgbotapi.NewEditMessageReplyMarkup( - cq.Message.Chat.ID, - cq.Message.MessageID, - keyboard.BuildAttachSessionKeyboard(approvalID, 0), - ) - bot.Request(editMsg) //nolint:errcheck - - sendText(bot, cq.Message.Chat.ID, "🗑 Список файлов очищен. Отправьте новые файлы.") -} - -// HandleAttachCancel — отмена прикрепления -func (h *Handler) HandleAttachCancel(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { - 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.States.ClearAttachmentSession(ctx, cq.From.ID) //nolint:errcheck - sendText(bot, cq.Message.Chat.ID, "❌ Прикрепление файлов отменено.") -} - -// HandleFileInput обрабатывает прикреплённый файл (фото или документ) во время флоу. -func (h *Handler) HandleFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { - ctx := context.Background() - telegramID := msg.From.ID - chatID := msg.Chat.ID - - mu := getFileInputMutex(telegramID) - mu.Lock() - defer mu.Unlock() - - flowState, err := h.States.Get(ctx, telegramID) - if err != nil || flowState == nil || !flowState.AwaitFileInput { - return false - } - - var fileID, fileName string - - switch { - case msg.Document != nil: - fileID = msg.Document.FileID - fileName = msg.Document.FileName - if fileName == "" { - fileName = fmt.Sprintf("document_%s", time.Now().Format("20060102_150405")) - } - case msg.Photo != nil && len(msg.Photo) > 0: - fileID = msg.Photo[len(msg.Photo)-1].FileID - fileName = fmt.Sprintf("photo_%s.jpg", time.Now().Format("20060102_150405.000")) - default: - sendText(bot, chatID, "⚠️ Пожалуйста, отправьте фото или документ.") - return true - } - - fileURL, err := bot.GetFileDirectURL(fileID) - if err != nil { - logrus.Errorf("HandleFileInput: GetFileDirectURL fileID=%s err=%v", fileID, err) - sendText(bot, chatID, "Ошибка при получении файла. Попробуйте ещё раз.") - return true - } - - if fileURL == "" { - logrus.Errorf("HandleFileInput: empty fileURL for fileID=%s", fileID) - sendText(bot, chatID, "Ошибка: не удалось получить ссылку на файл.") - return true - } - - base64Data, err := fetchFileAsBase64(fileURL) - if err != nil { - logrus.Errorf("HandleFileInput: fetchFileAsBase64 url=%s err=%v", fileURL, err) - sendText(bot, chatID, "Ошибка при обработке файла. Попробуйте ещё раз.") - return true - } - - if base64Data == "" { - logrus.Errorf("HandleFileInput: empty base64 for fileID=%s", fileID) - sendText(bot, chatID, "Ошибка: файл пустой. Попробуйте ещё раз.") - return true - } - - flowState.Files = append(flowState.Files, state.FileAttachment{ - Base64: base64Data, - FileName: fileName, - MessageID: msg.MessageID, - }) - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - - logrus.Infof("HandleFileInput: attached file=%s size=%d telegramID=%d total=%d", - fileName, len(base64Data), telegramID, len(flowState.Files)) - - // Дебаунс для альбомов - if msg.MediaGroupID != "" { - albumDebounceMu.Lock() - if t, ok := albumDebounce[telegramID]; ok { - t.Stop() - } - albumDebounce[telegramID] = time.AfterFunc(500*time.Millisecond, func() { - albumDebounceMu.Lock() - delete(albumDebounce, telegramID) - albumDebounceMu.Unlock() - - mu := getFileInputMutex(telegramID) - mu.Lock() - defer mu.Unlock() - - fresh, err := h.States.Get(ctx, telegramID) - if err != nil || fresh == nil { - return - } - h.showFileStatus(bot, chatID, telegramID, fresh, false) - }) - albumDebounceMu.Unlock() - } else { - h.showFileStatus(bot, chatID, telegramID, flowState, false) - } - - 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] - - // Удаляем сообщение с файлом из чата - if removed.MessageID != 0 { - bot.Request(tgbotapi.NewDeleteMessage(chatID, removed.MessageID)) //nolint:errcheck - } - - flowState.Files = append(flowState.Files[:index], flowState.Files[index+1:]...) - logrus.Infof("HandleDetachFile: removed file %q, remaining=%d", removed.FileName, len(flowState.Files)) - - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - isRequired := false - if topic, err := h.Registry.Get(flowState.TopicCode); err == nil { - if code, err := topic.TopicCodeFromCollected(flowState.Collected); err == nil { - if at, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, code); at != nil { - isRequired = (at.RequiresFile != nil && *at.RequiresFile) || - flowState.Collected["payment_type"] == "official" - } - } - } - h.showFileStatus(bot, chatID, telegramID, flowState, isRequired) -} - -// 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 == false { - topic, _ := h.Registry.Get(flowState.TopicCode) - if topic != nil { - topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) - approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) - - isRequired := (approvalTopic != nil && approvalTopic.RequiresFile != nil && *approvalTopic.RequiresFile) || - flowState.Collected["payment_type"] == "official" - - if isRequired { - // Нельзя отправить без файла — показываем предупреждение - sendText(bot, chatID, - "⚠️ Файл обязателен для этой темы.\n\n"+ - "Прикрепите файл чтобы продолжить.") - // Перерисовываем экран файлов - h.showFileStatus(bot, chatID, telegramID, flowState, true) - return - } - } - } - - if !withFiles { - flowState.Files = nil - } - - if flowState.FileStatusMsgID != 0 { - bot.Request(tgbotapi.NewDeleteMessage(chatID, flowState.FileStatusMsgID)) //nolint:errcheck - flowState.FileStatusMsgID = 0 - } - - flowState.AwaitFileInput = false - flowState.FilesStepCompleted = true - - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) -} - ------END service/telegram_service/handlers/approval/handle_files.go----- - -File: service/telegram_service/handlers/approval/handle_multiselect.go -Lines: 156 ------BEGIN service/telegram_service/handlers/approval/handle_multiselect.go----- -package approval - -import ( - "bitrix_balancer_api/telegram_service/approvalflow" - "bitrix_balancer_api/telegram_service/keyboard" - "context" - "fmt" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "strings" -) - -// HandleMultiSelectToggle — пользователь нажал на один из вариантов мультиселекта -func (h *Handler) HandleMultiSelectToggle(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode, nodeKey, value string) { - ctx := context.Background() - chatID := cq.Message.Chat.ID - telegramID := cq.From.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - flowState, err := h.States.Get(ctx, telegramID) - if err != nil || flowState == nil || !flowState.AwaitMultiSelectConfirm { - return - } - - if flowState.MultiSelected == nil { - flowState.MultiSelected = make(map[string][]string) - } - - // Toggle значения - current := flowState.MultiSelected[flowState.MultiSelectNodeKey] - found := false - updated := make([]string, 0, len(current)) - for _, v := range current { - if v == value { - found = true // убираем - } else { - updated = append(updated, v) - } - } - if !found { - updated = append(updated, value) - } - flowState.MultiSelected[flowState.MultiSelectNodeKey] = updated - - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - - // Перестраиваем клавиатуру - topic, _ := h.Registry.Get(topicCode) - if topic == nil { - return - } - tree := topic.BuildTree() - node := approvalflow.FindNode(tree, flowState.MultiSelectNodeKey) - if node == nil { - return - } - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil { - return - } - - _ = h.filterNodesByAccess(ctx, telegramID, node.Children) - - editMsg := tgbotapi.NewEditMessageReplyMarkup( - chatID, - cq.Message.MessageID, - keyboard.BuildMultiSelectStep(topicCode, node.Children, updated, nil), - ) - bot.Request(editMsg) //nolint:errcheck -} - -// HandleMultiSelectConfirm — пользователь подтвердил выбор -func (h *Handler) HandleMultiSelectConfirm(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, "")) - bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) - - flowState, err := h.States.Get(ctx, telegramID) - if err != nil || flowState == nil { - sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.") - return - } - - selected := flowState.MultiSelected[flowState.MultiSelectNodeKey] - if len(selected) == 0 { - bot.Request(tgbotapi.NewCallback(cq.ID, "⚠️ Выберите хотя бы один вариант")) - return - } - - topic, _ := h.Registry.Get(topicCode) - if topic == nil { - return - } - tree := topic.BuildTree() - node := approvalflow.FindNode(tree, flowState.MultiSelectNodeKey) - if node == nil { - return - } - - if len(node.Children) > 0 { - msKey := node.Children[0].MultiSelectKey - if msKey != "" { - flowState.Collected[msKey] = strings.Join(selected, ",") - - var labels []string - for _, child := range node.Children { - for _, sel := range selected { - if child.MultiSelectValue == sel { - labels = append(labels, child.Label) - break - } - } - } - flowState.Collected[msKey+"_label"] = strings.Join(labels, ", ") - } - } - - flowState.AwaitMultiSelectConfirm = false - flowState.MultiSelectNodeKey = "" - - // Переходим к вводу текста - var inputNode *approvalflow.FlowNode - for _, child := range node.Children { - for _, sel := range selected { - if child.MultiSelectValue == sel && len(child.Children) > 0 && child.Children[0].IsInput { - inputNode = child.Children[0] - break - } - } - if inputNode != nil { - break - } - } - - if inputNode != nil { - flowState.AwaitInput = true - flowState.InputKey = inputNode.InputKey - flowState.NodeKey = flowState.MultiSelectNodeKey - - h.States.Set(ctx, telegramID, flowState) - - hint := fmt.Sprintf("Введите данные по шаблону:\n%s", inputNode.InputHint) - msg := tgbotapi.NewMessage(chatID, hint) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApprovalInputPrompt(topicCode) - bot.Send(msg) - return - } - - h.States.Set(ctx, telegramID, flowState) - h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) -} - ------END service/telegram_service/handlers/approval/handle_multiselect.go----- - -File: service/telegram_service/handlers/approval/handler.go -Lines: 852 ------BEGIN service/telegram_service/handlers/approval/handler.go----- -package approval - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/variables" - "bitrix_balancer_api/telegram_service/approvalflow" - "bitrix_balancer_api/telegram_service/keyboard" - "bitrix_balancer_api/telegram_service/state" - "bitrix_balancer_api/telegram_service/types" - "context" - "encoding/base64" - "fmt" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" - "time" -) - -type Handler struct { - ipc *types.InternalProviderControl - Registry *Registry - States *state.StateManager -} - -func NewHandler(ipc *types.InternalProviderControl) *Handler { - h := &Handler{ - ipc: ipc, - Registry: NewRegistry(ipc), - States: state.NewStateManager(ipc.RedisClient), - } - - // Загружаем темы из БД при старте - ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutLong) - if err := h.Registry.LoadFromDB(ctx); err != nil { - logrus.Errorf("Failed to load topics from DB: %v", err) - } - cancel() - - // Фоновая проверка изменений дерева тем/категорий из конструктора — - // см. reload_watcher.go (новый файл, package approval). - go h.watchRegistryReload() - - return h -} - -// HandleMenu — первая страница меню. -func (h *Handler) HandleMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { - h.HandleMenuPage(bot, chatID, telegramID, 0, 0) -} - -func (h *Handler) HandleInitiatorSubmenu(bot *tgbotapi.BotAPI, chatID int64) { - msg := tgbotapi.NewMessage(chatID, "👤 Инициатор\n\nВыберите действие:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildInitiatorSubmenu() - bot.Send(msg) //nolint:errcheck -} - -// HandleApproverSubmenu — подменю для согласующего -func (h *Handler) HandleApproverSubmenu(bot *tgbotapi.BotAPI, chatID int64) { - msg := tgbotapi.NewMessage(chatID, "✅ Согласующий\n\nВыберите действие:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverSubmenu() - bot.Send(msg) //nolint:errcheck -} - -// HandleObserverSubmenu — подменю для наблюдателя -func (h *Handler) HandleObserverSubmenu(bot *tgbotapi.BotAPI, chatID int64) { - msg := tgbotapi.NewMessage(chatID, "✅ Наблюдатель\n\nВыберите действие:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverSubmenu() - bot.Send(msg) //nolint:errcheck -} - -// 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 - - 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 - - visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children) - if len(visibleChildren) == 0 { - sendText(bot, chatID, "⚠️ У вас нет доступа к подкатегориям этого раздела.") - h.States.Clear(ctx, telegramID) - return - } - - // Детектируем мультиселект - isMultiSelect := len(visibleChildren) > 0 && visibleChildren[0].IsMultiSelect - if isMultiSelect { - if flowState.MultiSelected == nil { - flowState.MultiSelected = make(map[string][]string) - } - flowState.AwaitMultiSelectConfirm = true - flowState.MultiSelectNodeKey = nodeKey - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - - msg := tgbotapi.NewMessage(chatID, "Выберите системы (можно несколько):") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildMultiSelectStep(topicCode, visibleChildren, nil, nil) - bot.Send(msg) //nolint:errcheck - return - } - - msg := tgbotapi.NewMessage(chatID, "Выберите:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApprovalStep(topicCode, visibleChildren) - 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 - - commentKey := fmt.Sprintf("appr_approve_comment_pending:%d", telegramID) - commentApprovalIDStr, err := h.ipc.RedisClient.Get(ctx, commentKey) - if err == nil && commentApprovalIDStr != "" { - var approvalID uint64 - if _, scanErr := fmt.Sscanf(commentApprovalIDStr, "%d", &approvalID); scanErr == nil { - h.ipc.RedisClient.Del(ctx, commentKey) //nolint:errcheck - - h.HandleDecisionWithChat(bot, chatID, telegramID, approvalID, true, msg.Text) - return true - } - } - - commentState, _ := h.States.GetCommentFlow(ctx, telegramID) - if commentState != nil && commentState.Stage == "await_text" { - // Делегируем в HandleCommentTextInput - return h.HandleCommentTextInput(bot, msg) - } - - replyState, _ := h.States.GetCommentReply(ctx, telegramID) - if replyState != nil && replyState.Stage == "await_text" { - return h.HandleCommentReplyInput(bot, msg) - } - - 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 - - topic, _ := h.Registry.Get(flowState.TopicCode) - if topic != nil { - tree := topic.BuildTree() - parentNode := approvalflow.FindNode(tree, flowState.NodeKey) - if parentNode != nil && len(parentNode.Children) == 1 && parentNode.Children[0].IsInput { - inputNode := parentNode.Children[0] - if len(inputNode.Children) > 0 { - visibleChildren := h.filterNodesByAccess(ctx, telegramID, inputNode.Children) - if len(visibleChildren) == 0 { - sendText(bot, chatID, "⚠️ У вас нет доступа к подкатегориям этого раздела.") - h.States.Clear(ctx, telegramID) //nolint:errcheck - return true - } - - flowState.NodeKey = inputNode.Key - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - - msg := tgbotapi.NewMessage(chatID, "Выберите:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApprovalStep(flowState.TopicCode, visibleChildren) - bot.Send(msg) //nolint:errcheck - return true - } - } - } - - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) - return true -} - -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 - } - - if approval.Status == nil { - sendText(bot, chatID, "⚠️ Статус заявки не определён.") - return - } - - isInitiator := approval.InitiatorID != nil && *approval.InitiatorID == *revoker.ID - isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *revoker.ID) - - isApprover := false - steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, - }) - for _, step := range steps { - if step.ApproverID != nil && *step.ApproverID == *revoker.ID { - isApprover = true - break - } - } - - switch *approval.Status { - case "revoked": - sendText(bot, chatID, "Заявка уже отозвана.") - return - case "rejected": - sendText(bot, chatID, "Нельзя отозвать отклонённую заявку.") - return - case "pending", "revision": - if !isInitiator && !isDirector { - sendText(bot, chatID, "⚠️ В процессе согласования заявку может отозвать только инициатор или директор.") - return - } - case "approved": - if !isInitiator && !isDirector && !isApprover { - sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.") - return - } - - // Инициатор (не директор) отзывает уже согласованную заявку — - // требуется согласие всех, кто участвовал в согласовании - if isInitiator && !isDirector { - h.startApprovalRevocationRequest(bot, chatID, approval, revoker, comment) - return - } - default: - if !isInitiator && !isDirector { - sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.") - return - } - } - - revokerRole := "" - switch { - case isInitiator: - revokerRole = "инициатором" - case isDirector: - revokerRole = "директором" - case isApprover: - revokerRole = "согласующим" - } - - h.performActualRevoke(bot, ctx, approval, revoker, revokerRole, comment, steps, isInitiator, isDirector) - - // Обратная связь тому, кто выполнил отзыв - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - content := "—" - if approval.Content != nil { - content = *approval.Content - } - approvalCard := fmt.Sprintf( - "📋 Тема: %s\n📝 Текст: %s\n💬 Причина отзыва: %s", - topicFullName, content, comment, - ) - feedbackMsg := tgbotapi.NewMessage(chatID, fmt.Sprintf( - "↩️ Заявка #%d отозвана\n\n%s", - approvalID, approvalCard, - )) - feedbackMsg.ParseMode = "HTML" - feedbackMsg.ReplyMarkup = keyboard.BuildCommentNotificationKeyboard(approvalID, h.GetCommentsCount(ctx, approvalID)) - bot.Send(feedbackMsg) //nolint:errcheck -} - -// performActualRevoke выполняет отзыв заявки в БД и уведомляет всех участников -// с возможностью комментирования. Вызывается либо напрямую (директор/согласующий/ -// инициатор для pending), либо после того как все согласующие подтвердили согласие -// на отзыв уже одобренной заявки. -func (h *Handler) performActualRevoke( - bot *tgbotapi.BotAPI, - ctx context.Context, - approval *typescore.Approval, - revoker *typescore.User, - revokerRole string, - comment string, - steps []*typescore.ApprovalStep, - isInitiatorRevoking bool, - isDirectorRevoking bool, -) { - if approval.ID == nil { - return - } - approvalID := *approval.ID - - now := time.Now().UTC() - 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("performActualRevoke: UpdateApprovalDB err=%v", err) - return - } - - h.deactivatePendingDelegation(ctx, approval) - - h.handleRevokeCancellationTask(bot, ctx, approval) - - revokerName := "—" - if revoker.FullName != nil { - revokerName = *revoker.FullName - } - - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - content := "—" - if approval.Content != nil { - content = *approval.Content - } - - approvalCard := fmt.Sprintf( - "📋 Тема: %s\n"+ - "📝 Текст: %s\n"+ - "💬 Причина отзыва: %s", - topicFullName, content, comment, - ) - - commentsCount := h.GetCommentsCount(ctx, approvalID) - commentKeyboard := keyboard.BuildCommentNotificationKeyboard(approvalID, commentsCount) - - notify := func(chatID int64, text string) { - go func() { - msg := tgbotapi.NewMessage(chatID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = commentKeyboard - bot.Send(msg) //nolint:errcheck - }() - } - - // Инициатор (если не сам отзывал) - if !isInitiatorRevoking && approval.InitiatorID != nil { - initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) - if err == nil && initiator != nil && initiator.TelegramID != nil { - notify(*initiator.TelegramID, fmt.Sprintf( - "↩️ Ваша заявка #%d отозвана %s %s\n\n%s", - approvalID, revokerRole, revokerName, approvalCard, - )) - } - } - - // Директора (если не сам отзывал) - if !isDirectorRevoking { - directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx) - for _, director := range directors { - if director.TelegramID == nil { - continue - } - if revoker.ID != nil && director.ID != nil && *director.ID == *revoker.ID { - continue - } - notify(*director.TelegramID, fmt.Sprintf( - "↩️ Заявка #%d отозвана %s %s\n\n%s", - approvalID, revokerRole, revokerName, approvalCard, - )) - } - } - - // Согласующие (кроме самого отозвавшего) - notifiedApprovers := make(map[uint64]bool) - for _, step := range steps { - if step.ApproverID == nil { - continue - } - if revoker.ID != nil && *step.ApproverID == *revoker.ID { - continue - } - if notifiedApprovers[*step.ApproverID] { - continue - } - notifiedApprovers[*step.ApproverID] = true - - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID) - if approver == nil || approver.TelegramID == nil { - continue - } - notify(*approver.TelegramID, fmt.Sprintf( - "↩️ Заявка #%d отозвана %s %s\n\n%s", - approvalID, revokerRole, revokerName, approvalCard, - )) - } - - // Наблюдатели - categoryCode := h.getTopicCodeByApproval(ctx, approval) - observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID) - for _, obs := range observers { - if obs.TelegramID == nil { - continue - } - if revoker.ID != nil && obs.ID != nil && *obs.ID == *revoker.ID { - continue - } - notify(*obs.TelegramID, fmt.Sprintf( - "↩️ Заявка #%d отозвана %s %s\n\n%s", - approvalID, revokerRole, revokerName, 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 - - // Фильтруем по правам - visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children) - - msg := tgbotapi.NewMessage(chatID, "Выберите:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApprovalStep(topicCode, visibleChildren) - bot.Send(msg) //nolint:errcheck -} - -func (h *Handler) continueFlowAfterInput( - bot *tgbotapi.BotAPI, - ctx context.Context, - chatID int64, - telegramID int64, - flowState *state.ApprovalFlowState, -) { - topic, _ := h.Registry.Get(flowState.TopicCode) - if topic == nil { - h.States.Clear(ctx, telegramID) //nolint:errcheck - return - } - - topicCode, err := topic.TopicCodeFromCollected(flowState.Collected) - if err != nil { - logrus.Warnf("continueFlowAfterInput: TopicCodeFromCollected err=%v", err) - h.States.Clear(ctx, telegramID) //nolint:errcheck - return - } - - approvalTopic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) - if err != nil { - logrus.Errorf("continueFlowAfterInput: GetApprovalTopicByCodeDB topicCode=%s err=%v", topicCode, err) - } - - if approvalTopic != nil && !flowState.FilesStepCompleted { - requiresFile := approvalTopic.RequiresFile != nil && *approvalTopic.RequiresFile - allowsFile := approvalTopic.AllowsFile != nil && *approvalTopic.AllowsFile - isOfficial := flowState.Collected["payment_type"] == "official" - - needFileStep := requiresFile || allowsFile || isOfficial - - if needFileStep && !flowState.AwaitFileInput { - flowState.AwaitFileInput = true - flowState.FilesStepCompleted = false - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - h.showFileStatus(bot, chatID, telegramID, flowState, requiresFile || isOfficial) - return - } - } - - if approvalTopic != nil && - approvalTopic.FirstApproverRoleCode != nil && - *approvalTopic.FirstApproverRoleCode != "" && - flowState.SelectedFirstApproverID == 0 && - !flowState.AwaitFirstApproverSelection { - - flowState.AwaitFirstApproverSelection = true - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - - roleCode := *approvalTopic.FirstApproverRoleCode - roleLabel := roleCode - role := h.getRoleLabelByCode(ctx, roleCode) - if role != nil && role.Name != nil { - roleLabel = *role.Name - } - h.showFirstApproverSelection(bot, ctx, chatID, telegramID, roleCode, roleLabel) - return - } - - if approvalTopic != nil && - approvalTopic.AllowApproverSelection != nil && - *approvalTopic.AllowApproverSelection && - flowState.SelectedApproverID == 0 && - !flowState.AwaitApproverSelection { - - flowState.AwaitApproverSelection = true - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - h.showApproverSelection(bot, ctx, chatID, telegramID, approvalTopic) - return - } - - if approvalTopic != nil && - approvalTopic.AllowDelegationSelection != nil && - *approvalTopic.AllowDelegationSelection && - !flowState.DelegationSelectionDone { - - flowState.AwaitDelegationChoice = true - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - h.showDelegationChoice(bot, chatID, telegramID) - return - } - - if approvalTopic != nil && - approvalTopic.AllowObserverSelection != nil && - *approvalTopic.AllowObserverSelection && - !flowState.ObserverSelectionDone { - - flowState.ObserverSelectionDone = true - flowState.AwaitObserverSelection = true - h.States.Set(ctx, telegramID, flowState) - h.showObserverSelection(bot, ctx, chatID, telegramID, flowState, approvalTopic) - return - } - - h.States.Clear(ctx, telegramID) //nolint:errcheck - h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState) -} - -func (h *Handler) HandleViewFilesCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { - ctx := context.Background() - chatID := cq.Message.Chat.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) - if err != nil || len(files) == 0 { - sendText(bot, chatID, "📭 Файлы не найдены.") - return - } - - caption := fmt.Sprintf("📎 Файлы к заявке #%d (%d шт.):", approvalID, len(files)) - - for i, f := range files { - if f.FileBase64 == nil || f.FileName == nil { - continue - } - - go func(fileBase64 string, fileName string, isFirst bool) { - data, err := base64.StdEncoding.DecodeString(fileBase64) - if err != nil { - logrus.Errorf("HandleViewFilesCallback: decode err=%v", err) - return - } - doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{ - Name: fileName, - Bytes: data, - }) - doc.ParseMode = "HTML" - if isFirst { - doc.Caption = caption - } - if _, err := bot.Send(doc); err != nil { - logrus.Errorf("HandleViewFilesCallback: Send err=%v", err) - } - }(*f.FileBase64, *f.FileName, i == 0) - } -} - -// HandleShowApprovalCardCallback показывает карточку заявки с кнопками, -// соответствующими роли нажавшего пользователя именно в этой заявке. -// Порядок проверки важен: сначала более специфичные роли (исполнитель активной -// задачи, активный согласующий), затем инициатор, затем директор/наблюдатель. -func (h *Handler) HandleShowApprovalCardCallback(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 - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - sendText(bot, chatID, "⚠️ Пользователь не найден.") - return - } - currentUserID := *user.ID - - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if err != nil || approval == nil { - sendText(bot, chatID, "⚠️ Заявка не найдена.") - return - } - - files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) - approval.Files = files - filesCount := len(files) - commentsCount := h.GetCommentsCount(ctx, approvalID) - - status := "" - if approval.Status != nil { - status = *approval.Status - } - - collected := h.getCollectedFromApproval(ctx, approval) - card := h.buildApprovalCard(ctx, approval, collected) - - // 1. Исполнитель активной задачи по этой заявке - tasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTask{ApprovalID: &approvalID, ExecutorID: ¤tUserID}, - }) - if err == nil { - for _, task := range tasks { - if task.Status != nil && *task.Status == "pending" { - h.sendTaskCard(bot, chatID, approval, task) - return - } - } - } - - // 2. Активный согласующий (включая делегатов) по этой заявке - categoryCode := h.getTopicCodeByApproval(ctx, approval) - approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - isAnyOf := approvalTopic != nil && approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of" - - if status == "pending" { - if step := h.findStepForCurrentApprover(ctx, approvalID, currentUserID, approval, isAnyOf); step != nil { - msg := tgbotapi.NewMessage(chatID, card) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, filesCount > 0, filesCount, commentsCount) - bot.Send(msg) //nolint:errcheck - return - } - } - - // 3. Дополнительный согласующий (pending) по этой заявке - additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID}, - }) - for _, aa := range additionalApprovers { - if aa.ApproverID != nil && *aa.ApproverID == currentUserID && aa.Status != nil && *aa.Status == "pending" { - msg := tgbotapi.NewMessage(chatID, card) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, filesCount > 0, filesCount, commentsCount) - bot.Send(msg) //nolint:errcheck - return - } - } - - // 4. Инициатор заявки - if approval.InitiatorID != nil && *approval.InitiatorID == currentUserID { - msg := tgbotapi.NewMessage(chatID, card) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevokeButton(approvalID, status, filesCount, commentsCount) - bot.Send(msg) //nolint:errcheck - return - } - - // 5. Директор - if isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, currentUserID); isDirector { - msg := tgbotapi.NewMessage(chatID, card) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevokeButton(approvalID, status, filesCount, commentsCount) - bot.Send(msg) //nolint:errcheck - return - } - - // 6. Наблюдатель категории/темы - if h.canUserAccessObserverView(ctx, currentUserID, categoryCode, approval.TopicID) { - msg := tgbotapi.NewMessage(chatID, card) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverActions(approvalID, "", status, filesCount, commentsCount) - bot.Send(msg) //nolint:errcheck - return - } - - // 7. Ни одна роль не подошла — показываем карточку без действий (просмотр) - msg := tgbotapi.NewMessage(chatID, card) - msg.ParseMode = "HTML" - bot.Send(msg) //nolint:errcheck -} - -// canUserAccessObserverView проверяет, входит ли пользователь в список наблюдателей -// для категории/темы этой заявки. -func (h *Handler) canUserAccessObserverView(ctx context.Context, userID uint64, categoryCode string, topicID *uint64) bool { - observers, err := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, topicID) - if err != nil { - return false - } - for _, obs := range observers { - if obs.ID != nil && *obs.ID == userID { - return true - } - } - return false -} - ------END service/telegram_service/handlers/approval/handler.go----- - -File: service/telegram_service/handlers/approval/handler_add_approver.go -Lines: 548 ------BEGIN service/telegram_service/handlers/approval/handler_add_approver.go----- -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" -) - -// HandleAddApproverFromApproval — добавление согласующего к конкретной заявке (прямой вход) -func (h *Handler) HandleAddApproverFromApproval(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, approvalID uint64) { - ctx := context.Background() - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - sendText(bot, chatID, "⚠️ Пользователь не найден.") - return - } - isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID) - isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID) - if !isApprover && !isDirector { - sendText(bot, chatID, "У вас нет прав для добавления согласующих.") - 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("HandleAddApproverFromApproval: GetUsersListDB err=%v", err) - sendText(bot, chatID, "Ошибка при получении списка пользователей.") - 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] && u.TelegramID != nil { - availableUsers = append(availableUsers, u) - } - } - - if len(availableUsers) == 0 { - sendText(bot, chatID, "Нет доступных пользователей для добавления.") - return - } - - h.States.SetAddApprover(ctx, telegramID, &state.AddApproverFlowState{ - ApprovalID: approvalID, - CategoryID: 0, // не нужно, т.к. заявка уже известна - Stage: "select_user", - }) //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\n\n📋 Тема: %s\n\n👇 Выберите пользователя:", - approvalID, topicName, - )) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildAddApproverUserMenu(availableUsers, approvalID, 0, 0) // page=0, categoryID=0 - bot.Send(msg) //nolint:errcheck -} - -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 := typescore.ApprovalStatusPending.String() - 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, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, addApproverState.ApprovalID) - if err != nil || approval == nil { - logrus.Errorf("HandleAddApproverUserCallback: GetApprovalByIDDB err=%v", err) - sendText(bot, chatID, "Ошибка. Сообщите в технический отдел.") - return - } - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - - 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, topicFullName, approverName, - )) - - // Уведомляем добавленного согласующего - if addedApprover != nil && addedApprover.TelegramID != 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 - } - - status := "" - if approval.Status != nil { - status = *approval.Status - } - - files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - commentsSection := h.formatCommentsSection(ctx, addApproverState.ApprovalID, 4) - - notifyMsg := tgbotapi.NewMessage(*addedApprover.TelegramID, fmt.Sprintf( - "➕ Вас добавили к согласованию заявки #%d\n\n"+ - "👤 Инициатор: %s\n"+ - "📋 Тема: %s\n"+ - "📝 Текст: %s%s", - addApproverState.ApprovalID, initiatorName, topicFullName, content, commentsSection, - )) - notifyMsg.ParseMode = "HTML" - notifyMsg.ReplyMarkup = keyboard.BuildApproverDecision(addApproverState.ApprovalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) - 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 typescore.ApprovalStatusApproved.String(): - statusText = "✅ Одобрено" - case typescore.ApprovalStatusRejected.String(): - 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 -} - -// getApproverCategoriesWithPendingApprovals возвращает категории, в которых у -// пользователя ЕСТЬ реальные pending-шаги согласования прямо сейчас. -// -// 🩹 ФИКС: раньше эта функция шла от UserHierarchy (правил "кто чей -// согласующий") и имела два независимых бага: -// 1. Учитывала только topic-scoped записи иерархии (hier.TopicID != nil) — -// category-scoped и глобальные правила игнорировались полностью, такой -// согласующий никогда не видел эти категории в меню добавления. -// 2. Проверка "есть ли pending" делала запрос БЕЗ фильтра по категории — -// "есть ли у меня вообще хоть один pending-шаг где угодно" — и если да, -// помечала ЛЮБУЮ категорию из иерархии как имеющую pending, даже если -// реальный pending-шаг был совсем в другой категории. -// -// Теперь функция просто берёт реальные pending ApprovalStep пользователя и -// смотрит, в каких категориях лежат их темы — точно то же самое, что уже -// корректно делает соседняя getPendingApprovalsByCategory, только не для -// одной категории, а сгруппированно. -func (h *Handler) getApproverCategoriesWithPendingApprovals(ctx context.Context, userID uint64) ([]*typescore.ApprovalTopicCategory, error) { - steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ - ApproverID: &userID, - Status: utilscore.PointerToString(typescore.ApprovalStatusPending.String()), - }, - }) - if err != nil { - return nil, err - } - - categoryIDs := make(map[uint64]bool) - 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 { - continue - } - 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(typescore.ApprovalStatusPending.String()), - }, - }) - 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 -} - ------END service/telegram_service/handlers/approval/handler_add_approver.go----- - -File: service/telegram_service/handlers/approval/handler_comment.go -Lines: 490 ------BEGIN service/telegram_service/handlers/approval/handler_comment.go----- -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" - "strings" -) - -func (h *Handler) HandleAddCommentCallback(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 - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil { - logrus.Errorf("HandleAddCommentCallback: GetUserByTelegramIDDB err=%v", err) - sendText(bot, chatID, "⚠️ Ошибка при получении данных пользователя.") - return - } - - if user == nil || user.ID == nil { - logrus.Warn("HandleAddCommentCallback: user or user.ID is nil") - sendText(bot, chatID, "⚠️ Пользователь не найден.") - return - } - - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if err != nil { - logrus.Errorf("HandleAddCommentCallback: GetApprovalByIDDB err=%v", err) - sendText(bot, chatID, "⚠️ Ошибка при получении заявки.") - return - } - - if approval == nil { - logrus.Warnf("HandleAddCommentCallback: approval not found approvalID=%d", approvalID) - sendText(bot, chatID, "⚠️ Заявка не найдена.") - return - } - - // Проверяем, может ли пользователь комментировать эту заявку - canComment, err := h.canUserCommentApproval(ctx, *user.ID, approval) - if err != nil { - logrus.Errorf("HandleAddCommentCallback: canUserCommentApproval err=%v", err) - sendText(bot, chatID, "Ошибка при проверке прав.") - return - } - - if !canComment { - sendText(bot, chatID, "⚠️ Вы не можете комментировать эту заявку в текущем статусе.") - return - } - - // Сохраняем состояние ожидания комментария - commentState := &state.CommentFlowState{ - ApprovalID: approvalID, - Stage: "await_text", - } - - if err := h.States.SetCommentFlow(ctx, telegramID, commentState); err != nil { - logrus.Errorf("HandleAddCommentCallback: SetCommentFlow err=%v", err) - sendText(bot, chatID, "Ошибка при сохранении состояния.") - return - } - - sendText(bot, chatID, "💬 Введите текст комментария:") -} - -func (h *Handler) canUserCommentApproval(ctx context.Context, userID uint64, approval *typescore.Approval) (bool, error) { - if approval == nil || approval.ID == nil { - return false, fmt.Errorf("approval or approval ID is nil") - } - - if approval.InitiatorID != nil && *approval.InitiatorID == userID { - return true, nil - } - - // Проверяем, является ли пользователь текущим согласующим - activeStep, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, *approval.ID) - if err == nil && activeStep != nil && activeStep.ApproverID != nil && *activeStep.ApproverID == userID { - return true, nil - } - - // Проверяем, является ли пользователь дополнительным согласующим с pending статусом - additionalApprovers, _, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ - ApprovalID: approval.ID, - }, - }) - if err == nil && additionalApprovers != nil { - for _, aa := range additionalApprovers { - if aa.ApproverID != nil && *aa.ApproverID == userID { - if aa.Status != nil && *aa.Status == "pending" { - return true, nil - } - } - } - } - - // Проверяем, является ли пользователь наблюдателем этой категории - if approval.TopicID != nil { - topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if err == nil && topic != nil && topic.Code != nil { - isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, userID) - if isObserver { - isFinal := approval.Status != nil && - (*approval.Status == "approved" || *approval.Status == "rejected" || *approval.Status == "revoked") - - var relevant []*typescore.User - if isFinal { - // после завершения — комментировать может любой наблюдатель темы - relevant, _ = h.ipc.Database.User.GetObserversForApprovalDB(ctx, *topic.Code, topic.ID) - } else { - // в процессе — только контролёр - relevant, _ = h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, *topic.Code, topic.ID) - } - - for _, obs := range relevant { - if obs.ID != nil && *obs.ID == userID { - return true, nil - } - } - } - } - } - - // Проверяем, является ли пользователь исполнителем задачи по этой заявке - task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByApprovalIDDB(ctx, *approval.ID) - if err == nil && task != nil && task.ExecutorID != nil && *task.ExecutorID == userID { - if task.Status != nil && *task.Status == "pending" { - return true, nil - } - } - - isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, userID) - return isDirector, nil -} - -// formatCommentsSection возвращает секцию с последними limit комментариями. -func (h *Handler) formatCommentsSection(ctx context.Context, approvalID uint64, limit int) string { - comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID) - if err != nil { - logrus.Errorf("formatCommentsSection: GetCommentsByApprovalIDDB err=%v", err) - return "" - } - - if len(comments) == 0 { - return "" - } - - total := len(comments) - if limit > 0 && total > limit { - comments = comments[total-limit:] - } - - header := "\n\n💬 Комментарии:" - if limit > 0 && total > limit { - header = fmt.Sprintf("\n\n💬 Последние %d комментариев (из %d):", limit, total) - } - - result := header - - for _, comment := range comments { - if comment == nil || comment.UserID == nil || comment.Comment == nil { - continue - } - - user, err := h.ipc.Database.User.GetUserByIDDB(ctx, *comment.UserID) - if err != nil || user == nil { - continue - } - - userName := "—" - if user.FullName != nil { - userName = *user.FullName - } - - timestamp := "" - if comment.CreatedAt != nil { - timestamp = comment.CreatedAt.Format("02.01.2006 15:04") - } - - result += fmt.Sprintf("\n\n%s (%s):\n%s", userName, timestamp, *comment.Comment) - } - - return result -} - -func (h *Handler) HandleCommentReplyCallback(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 - - replyState := &state.CommentReplyState{ - ApprovalID: approvalID, - Stage: "await_text", - } - h.States.SetCommentReply(ctx, telegramID, replyState) //nolint:errcheck - - sendText(bot, chatID, "↩️ Введите текст ответа:") -} - -func (h *Handler) HandleCommentTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { - ctx := context.Background() - telegramID := msg.From.ID - chatID := msg.Chat.ID - - commentState, err := h.States.GetCommentFlow(ctx, telegramID) - if err != nil || commentState == nil || commentState.Stage != "await_text" { - return false - } - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return false - } - - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, commentState.ApprovalID) - if err != nil || approval == nil { - sendText(bot, chatID, "⚠️ Заявка не найдена.") - h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck - return true - } - - comment := &typescore.ApprovalComment{ - ApprovalID: &commentState.ApprovalID, - UserID: user.ID, - Comment: &msg.Text, - } - - _, _, err = h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment) - if err != nil { - logrus.Errorf("HandleCommentTextInput: CreateApprovalCommentDB err=%v", err) - sendText(bot, chatID, "Ошибка при сохранении комментария.") - h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck - return true - } - - h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck - - userName := "—" - if user.FullName != nil { - userName = *user.FullName - } - - sendText(bot, chatID, fmt.Sprintf( - "✅ Комментарий добавлен\n\n"+ - "📋 Заявка: #%d\n"+ - "👤 Автор: %s\n"+ - "💬 Текст: %s", - commentState.ApprovalID, userName, msg.Text, - )) - - h.notifyAllParticipantsAboutComment(bot, ctx, approval, user, comment, telegramID) - - return true -} - -func (h *Handler) notifyAllParticipantsAboutComment( - bot *tgbotapi.BotAPI, - ctx context.Context, - approval *typescore.Approval, - commenter *typescore.User, - comment *typescore.ApprovalComment, - skipTelegramID int64, -) { - if approval == nil || approval.ID == nil { - return - } - - commenterName := "—" - if commenter != nil && commenter.FullName != nil { - commenterName = *commenter.FullName - } - - topicName := h.getTopicNameByApproval(ctx, approval) - content := "—" - if approval.Content != nil { - content = *approval.Content - } - - text := fmt.Sprintf( - "💬 Новый комментарий к заявке #%d\n\n"+ - "📋 Тема: %s\n"+ - "📝 Текст заявки: %s\n\n"+ - "👤 Автор комментария: %s\n"+ - "💬 Комментарий:\n%s", - *approval.ID, topicName, content, commenterName, *comment.Comment, - ) - - commentsCount := h.GetCommentsCount(ctx, *approval.ID) - - participants := h.getChatParticipants(ctx, approval) - for _, u := range participants { - if u.TelegramID == nil || *u.TelegramID == skipTelegramID { - continue - } - msg := tgbotapi.NewMessage(*u.TelegramID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildCommentReplyKeyboard(*approval.ID, commentsCount) - if _, err := bot.Send(msg); err != nil { - logrus.Errorf("notifyAllParticipantsAboutComment: Send to %d err=%v", *u.TelegramID, err) - } - } -} - -func (h *Handler) HandleCommentReplyInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { - ctx := context.Background() - telegramID := msg.From.ID - chatID := msg.Chat.ID - - replyState, err := h.States.GetCommentReply(ctx, telegramID) - if err != nil || replyState == nil || replyState.Stage != "await_text" { - return false - } - - h.States.ClearCommentReply(ctx, telegramID) //nolint:errcheck - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return false - } - - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, replyState.ApprovalID) - if err != nil || approval == nil { - sendText(bot, chatID, "⚠️ Заявка не найдена.") - return true - } - - comment := &typescore.ApprovalComment{ - ApprovalID: &replyState.ApprovalID, - UserID: user.ID, - Comment: &msg.Text, - } - _, _, err = h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment) - if err != nil { - sendText(bot, chatID, "⚠️ Ошибка при создании комментария: "+err.Error()) - return false - } - sendText(bot, chatID, "✅ Ответ отправлен.") - - h.notifyAllParticipantsAboutComment(bot, ctx, approval, user, comment, telegramID) - - return true -} - -func (h *Handler) HandleViewCommentsCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { - ctx := context.Background() - chatID := cq.Message.Chat.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID) - if err != nil { - logrus.Errorf("HandleViewCommentsCallback: GetCommentsByApprovalIDDB err=%v", err) - sendText(bot, chatID, "⚠️ Ошибка при получении комментариев.") - return - } - - if len(comments) == 0 { - sendText(bot, chatID, fmt.Sprintf("📭 По заявке #%d пока нет комментариев.", approvalID)) - return - } - - var sb strings.Builder - sb.WriteString(fmt.Sprintf("💬 Комментарии по заявке #%d (%d):\n", approvalID, len(comments))) - - for _, c := range comments { - if c.UserID == nil || c.Comment == nil { - continue - } - user, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *c.UserID) - name := "—" - if user != nil && user.FullName != nil { - name = *user.FullName - } - timestamp := "—" - if c.CreatedAt != nil { - timestamp = c.CreatedAt.Format("02.01.2006 15:04") - } - sb.WriteString(fmt.Sprintf("\n👤 %s (%s):\n%s\n", name, timestamp, *c.Comment)) - } - - msg := tgbotapi.NewMessage(chatID, sb.String()) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildCommentNotificationKeyboard(approvalID, h.GetCommentsCount(ctx, approvalID)) - bot.Send(msg) //nolint:errcheck -} - -// getChatParticipants собирает всех участников "виртуального чата" заявки: -// инициатор, активный согласующий, доп. согласующие, исполнители, -// наблюдатели категории/темы, доп. наблюдатели. -func (h *Handler) getChatParticipants(ctx context.Context, approval *typescore.Approval) []*typescore.User { - if approval == nil || approval.ID == nil { - return nil - } - - seen := make(map[uint64]bool) - var result []*typescore.User - - add := func(u *typescore.User) { - if u == nil || u.ID == nil || u.TelegramID == nil { - return - } - if seen[*u.ID] { - return - } - seen[*u.ID] = true - result = append(result, u) - } - - if approval.InitiatorID != nil { - initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) - add(initiator) - } - - if activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, *approval.ID); activeStep != nil && activeStep.ApproverID != nil { - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) - add(approver) - } - - additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: approval.ID}, - }) - for _, aa := range additionalApprovers { - if aa.ApproverID == nil { - continue - } - u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) - add(u) - } - - tasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTask{ApprovalID: approval.ID}, - }) - for _, t := range tasks { - if t.ExecutorID == nil { - continue - } - u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *t.ExecutorID) - add(u) - } - - categoryCode := h.getTopicCodeByApproval(ctx, approval) - isFinal := approval.Status != nil && - (*approval.Status == "approved" || *approval.Status == "rejected" || *approval.Status == "revoked") - - if isFinal { - observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID) - for _, obs := range observers { - add(obs) - } - } else { - controllers, _ := h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, categoryCode, approval.TopicID) - for _, c := range controllers { - add(c) - } - } - - additionalObservers, _, _ := h.ipc.Database.ApprovalAdditionalObserver.GetApprovalAdditionalObserversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalObserver{ - ApprovalID: approval.ID, - }, - }) - for _, ao := range additionalObservers { - if ao.UserID == nil { - continue - } - u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *ao.UserID) - add(u) - } - - return result -} - -func (h *Handler) GetCommentsCount(ctx context.Context, approvalID uint64) int { - comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID) - if err != nil { - return 0 - } - return len(comments) -} - ------END service/telegram_service/handlers/approval/handler_comment.go----- - -File: service/telegram_service/handlers/approval/handler_decision.go -Lines: 886 ------BEGIN service/telegram_service/handlers/approval/handler_decision.go----- -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" -) - -// 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 - } - var telegramID int64 - if cq != nil { - telegramID = cq.From.ID - } - h.handleDecision(bot, cq, approverChatID, telegramID, approvalID, approved, comment) -} - -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 - } - } - } - } - } - } - } - - currentApproverName := "—" - if currentStep.ApproverNameSnapshot != nil { - currentApproverName = *currentStep.ApproverNameSnapshot - } - - nextApproverName := "—" - if actualApprover != nil && actualApprover.FullName != nil { - nextApproverName = *actualApprover.FullName - } - - // Уведомляем инициатора о прогрессе - if initiator.TelegramID != nil { - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - - 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, topicFullName, 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 controllers, cErr := h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, categoryCode, approval.TopicID); cErr != nil { - logrus.Warnf("processNextStepOrComplete: GetControllerObserversForApprovalDB err=%v", cErr) - } else if len(controllers) > 0 { - commentsCount := h.GetCommentsCount(ctx, approvalID) - commentsSection := h.formatCommentsSection(ctx, approvalID, 4) - - controllerText := fmt.Sprintf( - "👁 Заявка #%d передана следующему согласующему\n\n"+ - "✅ Согласовал: %s\n"+ - "⏳ Передано: %s\n\n%s%s", - approvalID, currentApproverName, nextApproverName, approvalCard, commentsSection, - ) - - for _, controller := range controllers { - if controller.TelegramID == nil { - continue - } - controllerMsg := tgbotapi.NewMessage(*controller.TelegramID, controllerText) - controllerMsg.ParseMode = "HTML" - controllerMsg.ReplyMarkup = keyboard.BuildObserverActions(approvalID, "", "pending", len(approval.Files), commentsCount) - bot.Send(controllerMsg) //nolint:errcheck - } - } - - 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 - - h.activatePendingDelegation(ctx, approval) - - 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, - ) - } - - notifyMsg := tgbotapi.NewMessage(*mainApprover.TelegramID, messageText) - notifyMsg.ParseMode = "HTML" - bot.Send(notifyMsg) //nolint:errcheck - } - } - - h.createTasksForApproval(bot, ctx, approval, initiator) - - 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 - } - } - } - } - } - - var subscribedDirectors []*typescore.User - if approval.TopicID != nil { - topicForCategory, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if err == nil && topicForCategory != nil && topicForCategory.CategoryID != nil { - subscribedDirectors, err = h.ipc.Database.DirectorNotifications.GetDirectorsSubscribedToCategoryDB(ctx, *topicForCategory.CategoryID) - if err != nil { - logrus.Warnf("processNextStepOrComplete: GetDirectorsSubscribedToCategoryDB err=%v", err) - } - } - } - - for _, director := range subscribedDirectors { - if director.TelegramID != nil { - notifier.NotifyDirector(bot, director, initiator, approval, collected) - } - } - - observers, obsErr := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID) - if obsErr != nil { - logrus.Errorf("❌ processNextStepOrComplete: GetObserversForApprovalDB err=%v (categoryCode=%s, topicID=%v)", - obsErr, categoryCode, approval.TopicID) - } else { - logrus.Infof("👁 processNextStepOrComplete: found %d observers for approvalID=%d categoryCode=%s topicID=%v", - len(observers), approvalID, categoryCode, approval.TopicID) - - if len(observers) > 0 { - stepApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *currentStep.ApproverID) - notifier.NotifyObserversDecision(bot, observers, initiator, stepApprover, approval, collected) - } else { - logrus.Warnf("⚠️ processNextStepOrComplete: no observers found for categoryCode=%s topicID=%v", - categoryCode, approval.TopicID) - } - } -} - -// HandleDecisionWithChat — вызывается при текстовом вводе комментария. -// chatID — чат согласующего для отправки обратной связи. -func (h *Handler) HandleDecisionWithChat( - bot *tgbotapi.BotAPI, - chatID int64, - telegramID int64, - approvalID uint64, - approved bool, - comment string, -) { - h.handleDecision(bot, nil, chatID, telegramID, approvalID, approved, comment) -} - -// handleDecision — основная логика, принимает chatID явно. -func (h *Handler) handleDecision( - bot *tgbotapi.BotAPI, - cq *tgbotapi.CallbackQuery, - approverChatID int64, - telegramID 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 - } - - user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - 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 - } - - if approval.Status != nil && *approval.Status == typescore.ApprovalStatusRevision.String() { - if approverChatID != 0 { - sendText(bot, approverChatID, "⚠️ Заявка находится на доработке у инициатора.") - } - return - } - - approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - requireComment := approvalTopic != nil && approvalTopic.RequireApproverComment != nil && *approvalTopic.RequireApproverComment - isAnyOf := approvalTopic != nil && approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of" - - 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 - } - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - content := "—" - if approval.Content != nil { - content = *approval.Content - } - - approvalCard := fmt.Sprintf( - "👤 Инициатор: %s\n📋 Тема: %s\n📝 Текст: %s", - initiatorName, topicFullName, 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() - - // 🚀 Вспомогательная функция: сохранить решение/комментарий в общую таблицу комментариев - saveCommentToApproval := func(commentText string) { - if strings.TrimSpace(commentText) == "" || user.ID == nil { - return - } - approvalComment := &typescore.ApprovalComment{ - ApprovalID: &approvalID, - UserID: user.ID, - Comment: &commentText, - } - if _, _, err := h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, approvalComment); err != nil { - logrus.Errorf("handleDecision: CreateApprovalCommentDB err=%v", err) - } - } - - // 🚀 Вспомогательная функция: проверить, является ли текущий шаг последним - isLastStep := func(currentStepOrder int) bool { - allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, - }) - for _, s := range allSteps { - if s.StepOrder == nil { - continue - } - if *s.StepOrder > currentStepOrder { - // Есть следующий шаг — значит текущий не последний - return false - } - } - return true - } - - notifyRejection := func(stepApproverID *uint64) { - 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 { - var stepApprover *typescore.User - if stepApproverID != nil { - stepApprover, _ = h.ipc.Database.User.GetUserByIDDB(ctx, *stepApproverID) - } else { - stepApprover = actualExecutor - } - notifier.NotifyInitiatorRejected(bot, initiator, stepApprover, approval, collected, comment) - } - if observers, err := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID); err == nil && len(observers) > 0 { - var stepApprover *typescore.User - if stepApproverID != nil { - stepApprover, _ = h.ipc.Database.User.GetUserByIDDB(ctx, *stepApproverID) - } else { - stepApprover = actualExecutor - } - notifier.NotifyObserversDecision(bot, observers, initiator, stepApprover, approval, collected) - } - } - - // ========================================== - // === БЛОК ОТКЛОНЕНИЯ === - // ========================================== - 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 - - // 🚀 Сохраняем комментарий отклонения в общую таблицу - if comment != "" { - commentText := fmt.Sprintf("❌ Отклонение (доп. согласующий): %s", comment) - saveCommentToApproval(commentText) - } - - approval.Status = &rejectedStatus - h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck - notifyRejection(nil) - return - } - - step := h.findStepForCurrentApprover(ctx, approvalID, currentUserID, approval, isAnyOf) - if step == nil { - logrus.Warnf("handleDecision: active step not found for user approvalID=%d userID=%d", approvalID, currentUserID) - if approverChatID != 0 { - sendText(bot, approverChatID, "⚠️ Шаг согласования не найден или уже обработан.") - } - return - } - - 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 - - // 🚀 Сохраняем комментарий отклонения в общую таблицу - if comment != "" { - commentText := fmt.Sprintf("❌ Отклонение: %s", comment) - saveCommentToApproval(commentText) - } - - if isAnyOf { - allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, - }) - for _, s := range allSteps { - if s.ID == nil || (step.ID != nil && *s.ID == *step.ID) { - continue - } - if s.Status == nil || (*s.Status != "waiting" && *s.Status != "pending") { - continue - } - cancelledStatus := "cancelled_any_of" - s.Status = &cancelledStatus - h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, s) //nolint:errcheck - - if s.ApproverID != nil { - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID) - if approver != nil && approver.TelegramID != nil { - deciderName := "—" - if actualExecutor != nil && actualExecutor.FullName != nil { - deciderName = *actualExecutor.FullName - } - sendText(bot, *approver.TelegramID, fmt.Sprintf( - "ℹ️ Заявка #%d отклонена\n\n👤 Отклонил: %s\n\nВаше участие в согласовании больше не требуется.", - approvalID, deciderName, - )) - } - } - } - approval.Status = &rejectedStatus - h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck - notifyRejection(step.ApproverID) - return - } - - approval.Status = &rejectedStatus - h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck - notifyRejection(step.ApproverID) - - 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 - } - return - } - - // ========================================== - // === БЛОК ОДОБРЕНИЯ === - // ========================================== - - // Запрос обязательного комментария для первого шага - if requireComment && comment == "" && !isAdditionalApprover { - activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) - if activeStep != nil && activeStep.StepOrder != nil && *activeStep.StepOrder == 0 { - commentKey := fmt.Sprintf("appr_approve_comment_pending:%d", telegramID) - h.ipc.RedisClient.Set(ctx, commentKey, fmt.Sprintf("%d", approvalID), 10*time.Minute) //nolint:errcheck - - if approverChatID != 0 { - msg := tgbotapi.NewMessage(approverChatID, - "💬 Для согласования этой заявки необходимо оставить комментарий.\n\nВведите комментарий:") - msg.ParseMode = "HTML" - bot.Send(msg) //nolint:errcheck - } - return - } - } - - getPendingAdditionalInfo := func() (int, []string) { - var pendingNames []string - count := 0 - for _, aa := range additionalApprovers { - if isAdditionalApprover && additionalApproverRecord != nil && aa.ID != nil && additionalApproverRecord.ID != nil && *aa.ID == *additionalApproverRecord.ID { - continue - } - if aa.Status != nil && *aa.Status == "pending" && aa.ApproverID != nil { - count++ - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) - if approver != nil && approver.FullName != nil { - pendingNames = append(pendingNames, *approver.FullName) - } - } - } - return count, pendingNames - } - - // --- Дополнительный согласующий --- - if isAdditionalApprover { - approvedStatus := "approved" - additionalApproverRecord.Status = &approvedStatus - additionalApproverRecord.ActedAt = &now - h.ipc.Database.ApprovalAdditionalApprover.UpdateApprovalAdditionalApproverDB(ctx, nil, additionalApproverRecord) //nolint:errcheck - - // 🚀 Сохраняем одобрение доп. согласующего в комментарии (если есть комментарий) - if comment != "" { - commentText := fmt.Sprintf("✅ Одобрение (доп. согласующий): %s", comment) - saveCommentToApproval(commentText) - } - - allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, - }) - - var mainStep *typescore.ApprovalStep - - for _, s := range allSteps { - if s.Status != nil && *s.Status == "pending" { - mainStep = s - break - } - } - - if mainStep == nil { - var highestApproved *typescore.ApprovalStep - for _, s := range allSteps { - if s.Status != nil && *s.Status == "approved" { - if highestApproved == nil || (s.StepOrder != nil && highestApproved.StepOrder != nil && *s.StepOrder > *highestApproved.StepOrder) { - highestApproved = s - } - } - } - mainStep = highestApproved - } - - if mainStep == nil { - logrus.Warnf("handleDecision: active step not found approvalID=%d (доп. согласующий userID=%d)", approvalID, currentUserID) - if approverChatID != 0 { - sendText(bot, approverChatID, "⚠️ Шаг согласования не найден или уже обработан.") - } - return - } - - if mainStep.ApproverID != nil && *mainStep.ApproverID != currentUserID { - mainApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *mainStep.ApproverID) - if mainApprover != nil && mainApprover.TelegramID != nil { - addApproverName := "—" - if actualExecutor != nil && actualExecutor.FullName != nil { - addApproverName = *actualExecutor.FullName - } - notifyMsg := tgbotapi.NewMessage(*mainApprover.TelegramID, fmt.Sprintf( - "✅ Дополнительный согласующий одобрил заявку #%d\n\n"+ - "👤 Согласующий: %s\n%s", - approvalID, addApproverName, approvalCard, - )) - notifyMsg.ParseMode = "HTML" - bot.Send(notifyMsg) //nolint:errcheck - } - } - - 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 - } - if aa.Status != nil && *aa.Status == "rejected" { - allAdditionalApproved = false - break - } - } - - mainApproverApproved := mainStep.Status != nil && *mainStep.Status == "approved" - - if approverChatID != 0 { - pendingCount, pendingNames := getPendingAdditionalInfo() - pendingText := "" - if pendingCount > 0 { - pendingText = fmt.Sprintf("\n\n⏳ Ожидается решение других дополнительных согласующих (%d):\n• %s", - pendingCount, strings.Join(pendingNames, "\n• ")) - } - - if !mainApproverApproved { - sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nОжидается решение основного согласующего.", approvalID, approvalCard)) - } else if !allAdditionalApproved { - sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s%s", approvalID, approvalCard, pendingText)) - } else { - // 🚀 Все доп. согласующие одобрили, но нужно проверить, последний ли это шаг - var currentOrder int - if mainStep.StepOrder != nil { - currentOrder = *mainStep.StepOrder - } - if isLastStep(currentOrder) { - sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nВсе согласующие одобрили заявку.", approvalID, approvalCard)) - } else { - sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nЗаявка передана следующему согласующему.", approvalID, approvalCard)) - } - } - } - - if mainApproverApproved && allAdditionalApproved { - // 🩹 ФИКС 2: передаём исполнителя ОСНОВНОГО шага (mainStep.ApproverID), - // а не currentUserID (доп. согласующего). Иначе - // processNextStepOrComplete считает доп. согласующего "делегатом" - // основного согласующего только из-за разных ID — и рассылает - // неверные уведомления вида "ваш делегат согласовал заявку". - mainExecutorID := currentUserID - if mainStep.ApproverID != nil { - mainExecutorID = *mainStep.ApproverID - } - h.processNextStepOrComplete(bot, ctx, approval, mainStep, approvalCard, categoryCode, notifier, initiator, collected, mainExecutorID) - } - 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 - } - - 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 - } - - updated, _, err := h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, step, true) - if err != nil || updated == nil { - if approverChatID != 0 { - sendText(bot, approverChatID, "⚠️ Ошибка при сохранении решения.") - } - return - } - - // 🚀 Сохраняем одобрение/комментарий в общую таблицу комментариев - if comment != "" { - commentText := fmt.Sprintf("✅ Одобрение: %s", comment) - saveCommentToApproval(commentText) - } - - // --- Режим any_of --- - if isAnyOf { - allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, - }) - for _, s := range allSteps { - if s.ID == nil || s.Status == nil || (*s.Status != "waiting" && *s.Status != "pending") { - continue - } - if s.ID != nil && step.ID != nil && *s.ID == *step.ID { - continue - } - cancelledStatus := "cancelled_any_of" - s.Status = &cancelledStatus - h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, s) //nolint:errcheck - - if s.ApproverID != nil { - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID) - if approver != nil && approver.TelegramID != nil { - deciderName := "—" - if actualExecutor != nil && actualExecutor.FullName != nil { - deciderName = *actualExecutor.FullName - } - sendText(bot, *approver.TelegramID, fmt.Sprintf( - "ℹ️ Заявка #%d уже согласована\n\n"+ - "👤 Согласовал: %s\n\n"+ - "Ваше участие в согласовании больше не требуется.", - approvalID, deciderName, - )) - } - } - } - - h.processNextStepOrComplete(bot, ctx, approval, step, approvalCard, categoryCode, notifier, initiator, collected, currentUserID) - return - } - - freshApproval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if freshApproval != nil && freshApproval.Status != nil && *freshApproval.Status != "pending" { - if approverChatID != 0 { - sendText(bot, approverChatID, fmt.Sprintf("✅ Заявка #%d уже обработана.", approvalID)) - } - return - } - - allAdditionalApproved := true - var 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 { - pendingCount, pendingNames := getPendingAdditionalInfo() - 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", approvalID, approvalCard)) - } - } - return - } - - // 🚀 Все доп. согласующие одобрили — проверяем, последний ли это шаг - if approverChatID != 0 { - var currentOrder int - if step.StepOrder != nil { - currentOrder = *step.StepOrder - } - if isLastStep(currentOrder) { - sendText(bot, approverChatID, fmt.Sprintf("✅ Вы одобрили заявку #%d\n\n%s\n\nВсе согласующие одобрили заявку.", approvalID, approvalCard)) - } else { - 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) -} - -// Вспомогательный метод рядом: -func (h *Handler) getApproverName(ctx context.Context, userID uint64) string { - user, _ := h.ipc.Database.User.GetUserByIDDB(ctx, userID) - if user != nil && user.FullName != nil { - return *user.FullName - } - return "—" -} - ------END service/telegram_service/handlers/approval/handler_decision.go----- - -File: service/telegram_service/handlers/approval/handler_delegation.go -Lines: 703 ------BEGIN service/telegram_service/handlers/approval/handler_delegation.go----- -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 -} - ------END service/telegram_service/handlers/approval/handler_delegation.go----- - -File: service/telegram_service/handlers/approval/handler_executor.go -Lines: 589 ------BEGIN service/telegram_service/handlers/approval/handler_executor.go----- -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" - "sort" - "strings" - "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 - } - } - - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - - 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, topicFullName, content, createdAt, taskText, - ) - - allFiles, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - var taskFiles []string - for _, f := range allFiles { - if f.TaskID != nil && *f.TaskID == *task.ID && f.FileName != nil { - taskFiles = append(taskFiles, *f.FileName) - } - } - if len(taskFiles) > 0 { - text += "\n\n📎 Прикреплённые файлы к задаче:\n" - for i, name := range taskFiles { - text += fmt.Sprintf("%d. %s\n", i+1, name) - } - } - - commentsSection := h.formatCommentsSection(ctx, *approval.ID, 4) - text += commentsSection - - msg := tgbotapi.NewMessage(chatID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, len(allFiles), h.GetCommentsCount(ctx, *approval.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 - } - - 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 - } - } - - requireFile := task.RequireFile != nil && *task.RequireFile - if requireFile { - files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *task.ApprovalID) - hasExecutorFile := false - for _, f := range files { - if f.AttachedByID != nil && *f.AttachedByID == *user.ID && - f.TaskID != nil && *f.TaskID == *task.ID { - hasExecutorFile = true - break - } - } - if !hasExecutorFile { - files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *task.ApprovalID) - - msg := tgbotapi.NewMessage(chatID, - "⚠️ Для завершения необходимо прикрепить файл.\n\n"+ - "Нажмите «📎 Прикрепить файл», прикрепите документ, затем нажмите «Выполнено».") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, len(files), h.GetCommentsCount(ctx, *approval.ID)) - bot.Send(msg) //nolint:errcheck - 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 - } - - sendText(bot, chatID, fmt.Sprintf( - "✅ Задача выполнена\n\n"+ - "📋 Заявка: #%d — %s\n\n"+ - "Инициатор уведомлён.", - *task.ApprovalID, topicName, - )) - - h.activateNextTask(bot, ctx, approval, task) - - // Уведомляем инициатора - 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 - } - - // 🆕 Текст самой выполненной задачи (task.TaskText) — раньше в - // уведомлении был только текст заявки целиком (approval.Content), - // а что конкретно исполнитель делал — нет. - completedTaskText := "—" - if task.TaskText != nil { - completedTaskText = *task.TaskText - } - - notifyMsg := tgbotapi.NewMessage(*initiator.TelegramID, fmt.Sprintf( - "✅ Исполнитель завершил задачу\n\n"+ - "📋 Заявка #%d — %s\n"+ - "👤 Исполнитель: %s\n"+ - "📝 Текст: %s\n"+ - "🎯 Задача: %s", - *task.ApprovalID, topicName, executorName, content, completedTaskText, - )) - notifyMsg.ParseMode = "HTML" - bot.Send(notifyMsg) //nolint:errcheck - - if approval.TopicID != nil { - approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if approvalTopic != nil && approvalTopic.Code != nil { - topicCode := *approvalTopic.Code - if strings.HasPrefix(topicCode, "goods_order_") { - hintMsg := tgbotapi.NewMessage(*initiator.TelegramID, - "📦 Следи за выполнением заказа") - hintMsg.ParseMode = "HTML" - bot.Send(hintMsg) //nolint:errcheck - } - } - } - } - } -} - -// activateNextTask активирует следующую задачу в очереди после завершения текущей -func (h *Handler) activateNextTask(bot *tgbotapi.BotAPI, ctx context.Context, approval *typescore.Approval, completedTask *typescore.ApprovalTask) { - if approval == nil || approval.ID == nil || completedTask.StepOrder == nil { - return - } - - allTasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTask{ApprovalID: approval.ID}, - }) - if err != nil || len(allTasks) == 0 { - return - } - - var nextTask *typescore.ApprovalTask - for _, t := range allTasks { - if t.Status != nil && *t.Status == "waiting" && t.StepOrder != nil && completedTask.StepOrder != nil { - if *t.StepOrder == *completedTask.StepOrder+1 { - nextTask = t - break - } - } - } - - if nextTask == nil || nextTask.ExecutorID == nil { - return - } - - pendingStatus := "pending" - nextTask.Status = &pendingStatus - _, _, err = h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, nextTask) - if err != nil { - logrus.Errorf("activateNextTask: UpdateApprovalTaskDB err=%v", err) - return - } - - executor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *nextTask.ExecutorID) - if executor != nil && executor.TelegramID != nil { - initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) - if initiator == nil { - return - } - h.notifyExecutor(bot, ctx, executor, initiator, approval, nextTask) - } -} - -// handleRevokeCancellationTask — вызывается при отзыве заявки. -// Если задача выполнена — создаём задачу на обращение изменений. -// Если задача ожидает — спрашиваем исполнителя, вносил ли он изменения. -func (h *Handler) handleRevokeCancellationTask(bot *tgbotapi.BotAPI, ctx context.Context, approval *typescore.Approval) { - if approval.ID == nil { - return - } - - allSteps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID}, - }) - if err != nil { - logrus.Errorf("handleRevokeCancellationTask: GetApprovalStepsListDB err=%v", err) - } - - cancelledStepStatus := "cancelled" - for _, s := range allSteps { - if s.Status == nil { - continue - } - if *s.Status == "pending" || *s.Status == "waiting" { - s.Status = &cancelledStepStatus - if _, _, err := h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, s); err != nil { - logrus.Errorf("handleRevokeCancellationTask: UpdateApprovalStepDB stepID=%v err=%v", s.ID, err) - } - } - } - - additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: approval.ID}, - }) - cancelledAAStatus := "cancelled" - for _, aa := range additionalApprovers { - if aa.Status != nil && *aa.Status == "pending" { - aa.Status = &cancelledAAStatus - h.ipc.Database.ApprovalAdditionalApprover.UpdateApprovalAdditionalApproverDB(ctx, nil, aa) //nolint:errcheck - } - } - - tasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTask{ApprovalID: approval.ID}, - }) - if err != nil || len(tasks) == 0 { - return - } - - sort.Slice(tasks, func(i, j int) bool { - if tasks[i].StepOrder == nil || tasks[j].StepOrder == nil { - return false - } - return *tasks[i].StepOrder < *tasks[j].StepOrder - }) - - for _, task := range tasks { - if task.Status == nil || task.ExecutorID == nil || task.ID == nil { - continue - } - - executor, err := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID) - if err != nil || executor == nil || executor.TelegramID == nil { - continue - } - - switch *task.Status { - case "completed": - h.createReversalTask(bot, ctx, approval, task, executor) - - case "pending": - h.askExecutorAboutChanges(bot, ctx, approval, task, executor) - - case "waiting": - cancelledStatus := "cancelled" - task.Status = &cancelledStatus - h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task) //nolint:errcheck - - if executor.TelegramID != nil { - sendText(bot, *executor.TelegramID, fmt.Sprintf( - "↩️ Заявка #%d отозвана\n\nВаша задача отменена.", - *approval.ID, - )) - } - } - } -} - -// createReversalTask — создаёт задачу "обратить изменения" и уведомляет исполнителя. -func (h *Handler) createReversalTask( - bot *tgbotapi.BotAPI, - ctx context.Context, - approval *typescore.Approval, - originalTask *typescore.ApprovalTask, - executor *typescore.User, -) { - if approval.ID == nil || executor.TelegramID == nil { - return - } - - originalTaskText := "—" - if originalTask.TaskText != nil { - originalTaskText = *originalTask.TaskText - } - - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - content := "—" - if approval.Content != nil { - content = *approval.Content - } - - reversalText := fmt.Sprintf( - "Обратить изменения по заявке #%d\n\nТема: %s\nИсходная задача: %s", - *approval.ID, topicFullName, originalTaskText, - ) - - pendingStatus := "pending" - reversalTask := &typescore.ApprovalTask{ - ApprovalID: approval.ID, - ExecutorID: originalTask.ExecutorID, - TaskText: &reversalText, - Status: &pendingStatus, - } - - created, _, err := h.ipc.Database.ApprovalTasks.CreateApprovalTaskDB(ctx, nil, reversalTask, true) - if err != nil || created == nil || created.ID == nil { - logrus.Errorf("createReversalTask: CreateApprovalTaskDB err=%v", err) - return - } - - files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - - msg := tgbotapi.NewMessage(*executor.TelegramID, fmt.Sprintf( - "⚠️ Заявка #%d отозвана — требуется обратить изменения\n\n"+ - "📋 Тема: %s\n"+ - "📝 Текст заявки: %s\n\n"+ - "🔄 Новая задача:\n%s", - *approval.ID, topicFullName, content, reversalText, - )) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*created.ID, *approval.ID, len(files), h.GetCommentsCount(ctx, *approval.ID)) - bot.Send(msg) //nolint:errcheck -} - -// askExecutorAboutChanges — спрашивает исполнителя, вносил ли он изменения -// по задаче, которая ещё не выполнена на момент отзыва заявки. -func (h *Handler) askExecutorAboutChanges( - bot *tgbotapi.BotAPI, - ctx context.Context, - approval *typescore.Approval, - task *typescore.ApprovalTask, - executor *typescore.User, -) { - if approval.ID == nil || task.ID == nil || executor.TelegramID == nil { - return - } - - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - content := "—" - if approval.Content != nil { - content = *approval.Content - } - taskText := "—" - if task.TaskText != nil { - taskText = *task.TaskText - } - - msg := tgbotapi.NewMessage(*executor.TelegramID, fmt.Sprintf( - "↩️ Заявка #%d отозвана\n\n"+ - "📋 Тема: %s\n"+ - "📝 Текст заявки: %s\n\n"+ - "🎯 Ваша задача: %s\n\n"+ - "Вы уже вносили какие-либо изменения по этой задаче?", - *approval.ID, topicFullName, content, taskText, - )) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevokeTaskConfirmation(*task.ID, *approval.ID) - bot.Send(msg) //nolint:errcheck -} - -// HandleRevokeTaskNoChanges — исполнитель подтвердил, что изменений не вносил. -func (h *Handler) HandleRevokeTaskNoChanges(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64, approvalID 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 - - task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID) - if err != nil || task == nil { - sendText(bot, chatID, "⚠️ Задача не найдена.") - return - } - - cancelledStatus := "cancelled" - task.Status = &cancelledStatus - if _, _, err := h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task); err != nil { - logrus.Errorf("HandleRevokeTaskNoChanges: UpdateApprovalTaskDB err=%v", err) - sendText(bot, chatID, "Ошибка при отмене задачи.") - return - } - - sendText(bot, chatID, fmt.Sprintf( - "✅ Подтверждено\n\n"+ - "Задача по заявке #%d отменена.\n"+ - "Спасибо за подтверждение.", - approvalID, - )) -} - -// HandleRevokeTaskHasChanges — исполнитель подтвердил, что уже вносил изменения. -func (h *Handler) HandleRevokeTaskHasChanges(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64, approvalID 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 - - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if err != nil || approval == nil { - sendText(bot, chatID, "⚠️ Заявка не найдена.") - return - } - - task, err := h.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID) - if err != nil || task == nil { - sendText(bot, chatID, "⚠️ Задача не найдена.") - return - } - - // Отменяем исходную задачу - cancelledStatus := "cancelled" - task.Status = &cancelledStatus - if _, _, err := h.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, task); err != nil { - logrus.Errorf("HandleRevokeTaskHasChanges: UpdateApprovalTaskDB err=%v", err) - } - - // Получаем исполнителя для уведомления - executor, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID) - if err != nil || executor == nil { - sendText(bot, chatID, "⚠️ Пользователь не найден.") - return - } - - // Создаём задачу на обращение изменений - h.createReversalTask(bot, ctx, approval, task, executor) - - sendText(bot, chatID, fmt.Sprintf( - "📋 Создана задача на обращение изменений по заявке #%d.", - approvalID, - )) -} - -func (h *Handler) HandleExecutorAttachStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID, taskID uint64) { - ctx := context.Background() - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, cq.From.ID) - 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, cq.Message.Chat.ID, "⚠️ Заявка не найдена.") - return - } - - // Создаём сессию прикрепления (как в HandleAttachFileStart) - session := &state.AttachmentSession{ - ApprovalID: approvalID, - TaskID: taskID, - Files: []state.FileAttachment{}, - Stage: "collecting", - } - h.States.SetAttachmentSession(ctx, cq.From.ID, session) //nolint:errcheck - - msg := tgbotapi.NewMessage(cq.Message.Chat.ID, - fmt.Sprintf( - "📎 Прикрепление файла к задаче по заявке #%d\n\n"+ - "Отправьте фото или документ.\n"+ - "Когда закончите — нажмите «Отправить».", - approvalID, - ), - ) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildAttachSessionKeyboard(approvalID, 0) - bot.Send(msg) //nolint:errcheck -} - ------END service/telegram_service/handlers/approval/handler_executor.go----- - -File: service/telegram_service/handlers/approval/handler_observer.go -Lines: 440 ------BEGIN service/telegram_service/handlers/approval/handler_observer.go----- -package approval - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "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) -} - -func (h *Handler) HandleObservedApprovals(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { - h.HandleObservedApprovalsPage(bot, chatID, telegramID, 0) -} - -func (h *Handler) HandleObservedApprovalsPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int) { - ctx := context.Background() - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return - } - - perms, err := h.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "observe") - if err != nil { - logrus.Errorf("HandleObservedApprovalsPage: GetUserPermissionsDB err=%v", err) - return - } - - if len(perms) == 0 { - sendText(bot, chatID, "У вас нет прав наблюдателя ни по одной теме.") - return - } - - var visibleTopics []*typescore.ApprovalTopic - seenTopicIDs := make(map[uint64]bool) - - for _, p := range perms { - if p.TopicID != nil && !seenTopicIDs[*p.TopicID] { - topicDB, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *p.TopicID) - if err != nil || topicDB == nil || !*topicDB.IsActive { - continue - } - seenTopicIDs[*p.TopicID] = true - visibleTopics = append(visibleTopics, topicDB) - } - - if p.TopicCategoryID != nil { - topics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{ - CategoryID: p.TopicCategoryID, - IsActive: utilscore.PointerToBool(true), - }, - }) - if err != nil { - logrus.Warnf("HandleObservedApprovalsPage: GetApprovalTopicsListDB err=%v", err) - continue - } - for _, t := range topics { - if t.ID == nil || seenTopicIDs[*t.ID] { - continue - } - seenTopicIDs[*t.ID] = true - visibleTopics = append(visibleTopics, t) - } - } - } - - if len(visibleTopics) == 0 { - sendText(bot, chatID, "Нет доступных тем для наблюдения.") - return - } - - logrus.Infof("👁 HandleObservedApprovalsPage: found %d topics for user %d", len(visibleTopics), *user.ID) - - msg := tgbotapi.NewMessage(chatID, "👁 Наблюдение за согласованиями\n\nВыберите тему:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverTopicMenuFromDB(visibleTopics, page) - bot.Send(msg) //nolint:errcheck -} - -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 - - msg := tgbotapi.NewMessage(chatID, "👁 Выберите статус заявок для отображения:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverStatusFilterMenu(topicCode) - bot.Send(msg) //nolint:errcheck -} - -func (h *Handler) HandleObserverStatusFilterCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, status, topicCode string, page int) { - 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 - - h.sendObserverTopicApprovals(bot, ctx, chatID, topicCode, status, page) -} - -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, "all", 0) -} - -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) -} - -func (h *Handler) HandleObserverApprovalCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID 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 - - 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 - } - } - - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - - 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 - } - - // Получаем код темы для кнопки "Назад" - topicCode := "" - if approval.TopicID != nil { - if topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID); topic != nil && topic.Code != nil { - topicCode = *topic.Code - } - } - - // ✅ ИСПРАВЛЕНО: approverName теперь используется в тексте - text := fmt.Sprintf( - "📄 Заявка #%d\n\n"+ - "📋 Тема: %s\n"+ - "👤 Инициатор: %s\n"+ - "🏢 Отдел: %s\n"+ - "📅 Создана: %s\n"+ - "📝 Содержание: %s\n\n"+ - "🔄 У согласующего: %s\n"+ - "📊 Статус: %s", - approvalID, topicFullName, initiatorName, deptName, createdAt, content, approverName, h.getStatusLabel(approval.Status), - ) - - msg := tgbotapi.NewMessage(chatID, text) - msg.ParseMode = "HTML" - - // ✅ ИСПРАВЛЕНО: правильные аргументы (approvalID, topicCode, commentsCount) - msg.ReplyMarkup = keyboard.BuildObserverApprovalDetail(approvalID, topicCode, h.getCommentsCount(ctx, *approval.ID)) - bot.Send(msg) //nolint:errcheck -} - -// ✅ ИСПРАВЛЕНО: добавлен вспомогательный метод -func (h *Handler) getCommentsCount(ctx context.Context, approvalID uint64) int { - comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID) - if err != nil { - return 0 - } - return len(comments) -} - -func (h *Handler) getStatusLabel(status *string) string { - if status == nil { - return "Неизвестно" - } - switch *status { - case "pending": - return "⏳ На согласовании" - case "approved": - return "✅ Согласована" - case "rejected": - return "❌ Отклонена" - case "revoked": - return "↩️ Отозвана" - case "revision": - return "🛠 На доработке" - default: - return *status - } -} - -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 - } - - status := "" - if approval.Status != nil { - status = *approval.Status - } - reminder := fmt.Sprintf( - "🔔 Напоминание о заявке #%d\n\n"+ - "👤 Инициатор: %s\n"+ - "📝 %s\n\n"+ - "Заявка ожидает вашего решения.", - approvalID, initiatorName, content, - ) - files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - - reminderMsg := tgbotapi.NewMessage(*approver.TelegramID, reminder) - reminderMsg.ParseMode = "HTML" - - // ✅ ИСПРАВЛЕНО: добавлен 5-й аргумент commentsCount - reminderMsg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files), h.getCommentsCount(ctx, *approval.ID)) - bot.Send(reminderMsg) //nolint:errcheck - - approverName := "согласующему" - if approver.FullName != nil { - approverName = *approver.FullName - } - sendText(bot, chatID, fmt.Sprintf("✅ Напоминание отправлено: %s.", approverName)) -} - -func (h *Handler) sendObserverTopicApprovals(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, topicCode, statusFilter string, page int) { - var approvals []*typescore.Approval - var err error - var topicName string - - category, catErr := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicCode) - if catErr == nil && category != nil { - topicName = *category.Name - approvals, err = h.ipc.Database.Approval.GetApprovalsByCategoryDB(ctx, topicCode) - } else { - topic, topicErr := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) - if topicErr != nil || topic == nil || topic.ID == nil { - sendText(bot, chatID, "⚠️ Тема не найдена.") - return - } - topicName = *topic.Name - approvals, _, err = h.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Approval{ - TopicID: topic.ID, - }, - }) - } - - if err != nil { - logrus.Errorf("sendObserverTopicApprovals: err=%v", err) - sendText(bot, chatID, "Ошибка при получении заявок.") - return - } - - var filtered []*typescore.Approval - for _, a := range approvals { - if a.Status == nil { - continue - } - - if statusFilter == "all" { - if *a.Status == "pending" || *a.Status == "approved" { - filtered = append(filtered, a) - } - } else { - if *a.Status == statusFilter { - filtered = append(filtered, a) - } - } - } - - if len(filtered) == 0 { - statusText := "ожидающих согласования" - if statusFilter == "approved" { - statusText = "согласованных" - } else if statusFilter == "all" { - statusText = "активных или согласованных" - } - - msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("👁 %s\n\nНет %s заявок.", topicName, statusText)) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverApprovalList(nil, nil, nil, statusFilter, topicCode, page) - bot.Send(msg) //nolint:errcheck - return - } - - initiators := make(map[uint64]*typescore.User) - departments := make(map[uint64]*typescore.Department) - for _, a := range filtered { - 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 - } - } - } - - statusText := "Ожидают согласования" - if statusFilter == "approved" { - statusText = "Согласованные заявки" - } else if statusFilter == "all" { - statusText = "Активные и согласованные заявки" - } - - msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( - "👁 %s\n\n%s: %d", topicName, statusText, len(filtered), - )) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverApprovalList(filtered, initiators, departments, statusFilter, topicCode, page) - bot.Send(msg) //nolint:errcheck -} - -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 -} - ------END service/telegram_service/handlers/approval/handler_observer.go----- - -File: service/telegram_service/handlers/approval/handler_pending_comments.go -Lines: 209 ------BEGIN service/telegram_service/handlers/approval/handler_pending_comments.go----- -package approval - -import ( - "bitrix_balancer_api/telegram_service/keyboard" - "bitrix_balancer_api/telegram_service/state" - "context" - "fmt" - "strings" - - 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, msg.Chat.ID, msg.From.ID, approvalID, false, strings.TrimSpace(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: GetPendingComments err=%v", err) - sendText(bot, chatID, "Ошибка при получении отложенных согласований.") - return - } - - logrus.Infof("HandlePendingCommentsList: telegramID=%d items=%d", telegramID, len(items)) - - if len(items) == 0 { - sendText(bot, chatID, "📭 Нет отложенных согласований.") - 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 - } - - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - - 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, topicFullName, 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 -} - ------END service/telegram_service/handlers/approval/handler_pending_comments.go----- - -File: service/telegram_service/handlers/approval/handler_report.go -Lines: 266 ------BEGIN service/telegram_service/handlers/approval/handler_report.go----- -package approval - -import ( - "bitrix_balancer_api/core/reportcore" - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/variables" - "bitrix_balancer_api/telegram_service/keyboard" - "bitrix_balancer_api/telegram_service/state" - "context" - "fmt" - "time" - - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" -) - -// getReportCategoryCodes — объединяет категории согласующего и наблюдателя. -func (h *Handler) getReportCategoryCodes(ctx context.Context, user *typescore.User) []string { - return reportcore.GetReportCategoryCodes(ctx, h.ipc.Database, user) -} - -// buildExcelApprovalsReport — строит xlsx-файл отчёта по согласованиям и возвращает байты. -func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*typescore.Approval) ([]byte, error) { - return reportcore.BuildExcelApprovalsReport(ctx, h.ipc.Database, approvals) -} - -func (h *Handler) getTopicCodeByApproval(ctx context.Context, a *typescore.Approval) string { - return reportcore.GetTopicCategoryCodeByApproval(ctx, h.ipc.Database, a) -} - -const reportDateLayout = "02.01.2006" - -// HandleReportMenu — сразу показываем выбор периода (тип отчёта один — согласования). -func (h *Handler) HandleReportMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { - ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase) - defer cancel() - - 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.BuildReportDateToMenu() - 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 - - 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) -} - ------END service/telegram_service/handlers/approval/handler_report.go----- - -File: service/telegram_service/handlers/approval/helper.go -Lines: 847 ------BEGIN service/telegram_service/handlers/approval/helper.go----- -package approval - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "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" - "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 создаёт запись в БД и уведомляет согласующих. -// submitApproval — точка входа. Если инициатор выбрал несколько систем -// (мультиселект "systems"), создаёт по ОТДЕЛЬНОЙ заявке на каждую систему, -// каждая — со своим порядком согласования. Если система одна или не задана — -// поведение как раньше, одна заявка. -func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, telegramID int64, flowState *state.ApprovalFlowState) ([]*typescore.Approval, error) { - var systems []string - if s := flowState.Collected["systems"]; s != "" { - systems = strings.Split(s, ",") - for i := range systems { - systems[i] = strings.TrimSpace(systems[i]) - } - } - - if len(systems) <= 1 { - approval, err := h.submitApprovalForSystem(ctx, bot, telegramID, flowState, systems) - if err != nil { - return nil, err - } - return []*typescore.Approval{approval}, nil - } - - var created []*typescore.Approval - for _, system := range systems { - approval, err := h.submitApprovalForSystem(ctx, bot, telegramID, flowState, []string{system}) - if err != nil { - // Частичный отказ — откатываем уже созданные заявки по другим системам, - // чтобы не оставлять пользователя с "половиной" мультизаявки. - for _, a := range created { - h.ipc.Database.Approval.DeleteApprovalDB(ctx, a) //nolint:errcheck - } - return nil, fmt.Errorf("система %s: %w", system, err) - } - created = append(created, approval) - } - - return created, nil -} - -// submitApprovalForSystem создаёт ровно одну заявку для ровно одной системы -// (или без привязки к системе, если systems пуст). Раньше это было телом -func (h *Handler) submitApprovalForSystem(ctx context.Context, bot *tgbotapi.BotAPI, telegramID int64, flowState *state.ApprovalFlowState, systems []string) (*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" - - metadata := &typescore.ApprovalMetadata{ - Region: flowState.Collected["region"], - ChangeType: flowState.Collected["change_type"], - Extra: make(map[string]string), - } - - // В отличие от старой версии — тут максимум одна система (эта заявка = эта система). - if len(systems) > 0 { - metadata.SelectedSystems = systems - } - - for k, v := range flowState.Collected { - if k != "content" && k != "region" && k != "change_type" && k != "systems" { - metadata.Extra[k] = v - } - } - - metadataJSON, err := metadata.ToJSON() - if err != nil { - logrus.Warnf("submitApprovalForSystem: metadata marshal err=%v", err) - } - - approval := &typescore.Approval{ - InitiatorID: initiator.ID, - TopicID: approvalTopic.ID, - DepartmentID: initiator.DepartmentID, - Content: &content, - Status: &status, - Metadata: metadataJSON, - } - - 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 - - if base64Copy == "" || nameCopy == "" { - logrus.Warnf("submitApprovalForSystem: skipping empty file name=%q base64_len=%d", nameCopy, len(base64Copy)) - continue - } - - file := &typescore.ApprovalFile{ - ApprovalID: created.ID, - FileBase64: &base64Copy, - FileName: &nameCopy, - AttachedByID: initiator.ID, - } - if _, _, err := h.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, file); err != nil { - logrus.Errorf("submitApprovalForSystem: CreateApprovalFileDB name=%s err=%v", nameCopy, err) - } else { - logrus.Infof("submitApprovalForSystem: saved file=%s approvalID=%d attachedByID=%d", - nameCopy, *created.ID, *initiator.ID) - } - } - - files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *created.ID) - if err != nil { - logrus.Warnf("submitApprovalForSystem: GetFilesByApprovalIDDB err=%v", err) - } - created.Files = files - - h.createPendingDelegation(ctx, initiator, flowState, created) - - var approvers []*typescore.User - - var firstRoleApprover *typescore.User - if flowState.SelectedFirstApproverID > 0 { - firstRoleApprover, err = h.ipc.Database.User.GetUserByIDDB(ctx, flowState.SelectedFirstApproverID) - if err != nil || firstRoleApprover == nil { - return nil, fmt.Errorf("selected first approver not found: %d", flowState.SelectedFirstApproverID) - } - } - - // ИСПРАВЛЕНО: раньше flowState.SelectedApproverID (ОДИН согласующий, - // выбранный вручную ДО разбивки заявки по системам) применялся - // одинаково в каждой итерации цикла по системам в submitApproval. - // Он подбирался из списка, отфильтрованного (после фикса - // getAvailableApproversForTopic) под ВСЕ выбранные системы сразу — - // но нет гарантии, что конкретно этот человек валиден именно для - // текущей system в этой итерации: например, при override - // "okb -> Иванов, 1c -> Петров" пользователь мог выбрать Иванова, - // и Иванов стал бы согласующим и по заявке на 1С тоже. - // - // flowState хранит только один ID на весь флоу, поэтому корректно - // "угадать" per-system выбор здесь невозможно без изменения модели - // состояния. Безопасное решение: ручной выбор применяем только когда - // заявка одна на одну систему (или система не важна). При мультисистемном - // сабмите ручной выбор игнорируется и согласующие резолвятся - // автоматически по иерархии для каждой системы отдельно — это не даёт - // назначить не подходящего человека согласующим по системе, для которой - // его не выбирали. - if flowState.SelectedApproverID > 0 && len(systems) <= 1 { - 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 { - if flowState.SelectedApproverID > 0 { - logrus.Warnf( - "submitApprovalForSystem: ignoring manually selected approverID=%d for multi-system submission (systems=%v) — falling back to automatic hierarchy resolution to avoid assigning an approver not validated for this specific system", - flowState.SelectedApproverID, systems, - ) - } - approvers, err = h.ipc.Database.UserHierarchy.GetApproversDB(ctx, - *initiator.ID, - *initiator.DepartmentID, - *approvalTopic.ID, - *approvalTopic.CategoryID, - systems, - ) - if err != nil { - return nil, fmt.Errorf("GetApproversDB: %w", err) - } - } - - if firstRoleApprover != nil { - approvers = append([]*typescore.User{firstRoleApprover}, approvers...) - } - - if len(approvers) == 0 { - logrus.Warnf("submitApprovalForSystem: no approvers found for userID=%d deptID=%d topicID=%d systems=%v", - *initiator.ID, *initiator.DepartmentID, *approvalTopic.ID, systems) - - h.ipc.Database.Approval.DeleteApprovalDB(ctx, created) //nolint:errcheck - return nil, fmt.Errorf("⚠️ Для вас в данной теме не настроены согласующие. Пожалуйста, обратитесь к руководителю с просьбой о настройке прав в системе согласований") - } - - priorityGroups := make(map[int][]*typescore.User) - - if approvalTopic.ApprovalMode != nil { - logrus.Infof("submitApprovalForSystem: approvalMode=%s for topicID=%d", *approvalTopic.ApprovalMode, *approvalTopic.ID) - } else { - logrus.Warnf("submitApprovalForSystem: approvalMode is NIL for topicID=%d — будет использован sequential!", *approvalTopic.ID) - } - - for i, approver := range approvers { - p := i - if approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of" { - p = 0 - } - priorityGroups[p] = append(priorityGroups[p], approver) - } - - for p, group := range priorityGroups { - var ids []string - for _, a := range group { - if a.ID != nil { - ids = append(ids, fmt.Sprintf("%d", *a.ID)) - } - } - logrus.Infof("submitApprovalForSystem: priorityGroup[%d] contains approvers: %s (count=%d)", p, strings.Join(ids, ","), len(group)) - } - - stepOrder := 0 - for priority := 0; priority <= len(priorityGroups); priority++ { - group, ok := priorityGroups[priority] - if !ok { - continue - } - for _, approver := range group { - if approver.ID == nil { - continue - } - stepStatus := "waiting" - if priority == 0 { - stepStatus = "pending" - } - order := stepOrder - approverName := "" - if approver.FullName != nil { - approverName = *approver.FullName - } - - step := &typescore.ApprovalStep{ - ApprovalID: created.ID, - ApproverID: approver.ID, - StepOrder: &order, - Status: &stepStatus, - ApproverNameSnapshot: &approverName, - } - h.ipc.Database.ApprovalStep.CreateApprovalStepDB(ctx, nil, step) //nolint:errcheck - stepOrder++ - } - } - - if len(flowState.SelectedObserverIDs) > 0 { - h.saveSelectedObservers(ctx, *created.ID, *initiator.ID, flowState.SelectedObserverIDs) - } - - controllers, cErr := h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, topic.Code(), approvalTopic.ID) - if cErr != nil { - logrus.Warnf("submitApprovalForSystem: GetControllerObserversForApprovalDB err=%v", cErr) - } - for _, controller := range controllers { - h.notifyControllerAboutCreation(bot, ctx, controller, initiator, created, flowState.Collected) - } - - firstGroup := priorityGroups[0] - notifier := NewNotifier(h.ipc, topic) - - for _, approver := range firstGroup { - actualApprover := approver - - if actualApprover.TelegramID == nil { - if actualApprover.ID != nil { - logrus.Warnf("submitApprovalForSystem: approver.TelegramID is nil, userID=%d", *actualApprover.ID) - } - continue - } - - 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 == *actualApprover.ID && deleg.DelegateID != nil { - delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID) - if delegate != nil && delegate.TelegramID != nil { - actualApprover = 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 == *actualApprover.ID && deleg.DelegateID != nil { - delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *deleg.DelegateID) - if delegate != nil && delegate.TelegramID != nil { - actualApprover = delegate - break - } - } - } - } - } - } - - collectedForMessage := flowState.Collected - if len(systems) > 0 { - collectedForMessage = make(map[string]string, len(flowState.Collected)) - for k, v := range flowState.Collected { - collectedForMessage[k] = v - } - collectedForMessage["systems"] = strings.Join(systems, ",") - } - - notifier.NotifyApprover(bot, actualApprover, initiator, created, collectedForMessage) - } - - return created, nil -} - -func (h *Handler) getTopicNameByApproval(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 || topic.Name == nil { - return "—" - } - return *topic.Name -} - -// 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 - } - if topic.Instructions != nil && *topic.Instructions != "" { - collected["instructions"] = *topic.Instructions - } - } - - if approval.Metadata != nil { - if meta, err := typescore.ParseApprovalMetadata(approval.Metadata); err == nil && meta != nil { - if meta.Region != "" { - collected["region"] = meta.Region - } - if meta.ChangeType != "" { - collected["change_type"] = meta.ChangeType - } - - if len(meta.SelectedSystems) > 0 { - systemsStr := strings.Join(meta.SelectedSystems, ", ") - collected["target_system"] = systemsStr - collected["target_systems"] = systemsStr - collected["systems"] = systemsStr - collected["selected_systems"] = systemsStr - } - - for k, v := range meta.Extra { - collected[k] = v - } - } - } - - 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 - } - - 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 - } - if p.TopicID != nil { - allowedTopicIDs[*p.TopicID] = true - } - } - - for _, t := range h.Registry.All() { - category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, t.Code()) - if err != nil { - logrus.Warnf("getAllowedTopicCodes: GetApprovalTopicCategoryByCodeDB err=%v", err) - continue - } - if category == nil { - logrus.Warnf("getAllowedTopicCodes: category not found for code=%s", t.Code()) - continue - } - - if !allowed[t.Code()] && t.Code() == "absence" { - childCodes := []string{"timeoff", "vacation", "sickleave"} - for _, childCode := range childCodes { - childCategory, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, childCode) - if err != nil || childCategory == nil || childCategory.ID == nil { - continue - } - if allowedCategoryIDs[*childCategory.ID] { - allowed[t.Code()] = true - break - } - // Или по конкретным подтемам - childTopics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{CategoryID: childCategory.ID}, - }) - if err != nil { - continue - } - for _, ct := range childTopics { - if ct.ID != nil && allowedTopicIDs[*ct.ID] { - allowed[t.Code()] = true - break - } - } - if allowed[t.Code()] { - break - } - } - } - if allowedCategoryIDs[*category.ID] { - allowed[t.Code()] = true - continue - } - - topics, _, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{CategoryID: category.ID}, - }) - if err != nil { - logrus.Warnf("getAllowedTopicCodes: GetApprovalTopicsListDB err=%v", err) - continue - } - for _, topic := range topics { - if allowedTopicIDs[*topic.ID] { - allowed[t.Code()] = true - break - } - } - } - - logrus.Infof("getAllowedTopicCodes: result allowed=%v", allowed) - return allowed, nil -} - -func (h *Handler) canUserAccessNode(ctx context.Context, userID uint64, topicCode string) bool { - if topicCode == "" { - return true // нет ограничений — показываем всем - } - allowed, err := h.ipc.Database.Permission.UserCanCreateTopicDB(ctx, userID, topicCode) - if err != nil { - logrus.Warnf("canUserAccessNode: UserCanCreateTopicDB topicCode=%s err=%v", topicCode, err) - return true // при ошибке не скрываем кнопку - } - return allowed -} - -func (h *Handler) filterNodesByAccess(ctx context.Context, telegramID int64, nodes []*approvalflow.FlowNode) []*approvalflow.FlowNode { - // Проверяем нужна ли фильтрация вообще - needsFilter := false - for _, n := range nodes { - if n != nil && n.TopicCode != "" { - needsFilter = true - break - } - } - if !needsFilter { - return nodes - } - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return nodes // не можем проверить — показываем всё - } - - var filtered []*approvalflow.FlowNode - for _, n := range nodes { - if n == nil { - continue - } - if h.canUserAccessNode(ctx, *user.ID, n.TopicCode) { - filtered = append(filtered, n) - } - } - return filtered -} - -func (h *Handler) showFileStatus(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, flowState *state.ApprovalFlowState, required bool) { - 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 { - if required { - sb.WriteString("📎 Необходимо прикрепить файл\n\n") - sb.WriteString("⚠️ Для этой темы прикрепление файла обязательно.\n") - sb.WriteString("Отправьте файл или фото.") - } else { - 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, required) - - sent, err := bot.Send(msg) - if err != nil { - logrus.Errorf("showFileStatus: Send err=%v", err) - return - } - - flowState.FileStatusMsgID = sent.MessageID - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck -} - -func (h *Handler) buildApprovalCard(ctx context.Context, approval *typescore.Approval, collected map[string]string) string { - if approval.ID == nil { - return "" - } - - approvalID := *approval.ID - initiatorName := "—" - if approval.InitiatorID != nil { - initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) - if initiator != nil && initiator.FullName != nil { - initiatorName = *initiator.FullName - } - } - - topicName := getTopicFullName(ctx, h.ipc, approval.TopicID) - - content := "—" - if approval.Content != nil { - content = *approval.Content - } - - paymentLabel := "" - if approval.TopicID != nil { - topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if topic != nil { - switch { - case topic.PaymentType != nil && *topic.PaymentType == "own_expense": - paymentLabel = "За свой счёт" - case topic.PaymentType != nil && *topic.PaymentType == "vacation_account": - paymentLabel = "В счёт ежегодного отпуска" - case topic.PaymentType != nil && *topic.PaymentType == "official": - paymentLabel = "Официальный больничный" - } - } - } - - files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) - filesLabel := "Без файлов" - if len(files) > 0 { - filesLabel = fmt.Sprintf("📎 %d файл(ов)", len(files)) - } - - paymentLine := "" - if paymentLabel != "" { - paymentLine = fmt.Sprintf("\nДоп. информация: %s", paymentLabel) - } - - region := "" - if approval.Metadata != nil { - meta, err := typescore.ParseApprovalMetadata(approval.Metadata) - if err == nil && meta != nil { - switch meta.Region { - case "crimea": - region = "Крым" - case "krasnodar": - region = "Краснодар" - case "belarus": - region = "Беларусь" - default: - region = meta.Region - } - } - } - - regionLine := "" - if region != "" { - regionLine = fmt.Sprintf("\n🌍 Регион: %s", region) - } - - status := "⏳ ожидает" - if approval.Status != nil { - switch *approval.Status { - case "approved": - status = "✅ согласована" - case "rejected": - status = "❌ отклонена" - case "revoked": - status = "🔙 отозвана" - } - } - - createdAt := "—" - if approval.CreatedAt != nil { - createdAt = approval.CreatedAt.Format("02.01.2006 15:04") - } - - card := fmt.Sprintf( - "📋 Заявка #%d\n\n"+ - "👤 Инициатор: %s\n"+ - "📂 Тема: %s\n"+ - "📝 Текст: %s%s%s\n"+ - "📎 Файлы: %s\n"+ - "📅 Создана: %s\n"+ - "📊 Статус: %s", - approvalID, initiatorName, topicName, content, regionLine, paymentLine, - filesLabel, createdAt, status, - ) - - // Добавляем информацию о текущем согласующем если заявка в процессе - if approval.Status != nil && *approval.Status == "pending" { - activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) - if activeStep != nil && activeStep.ApproverID != nil { - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) - if approver != nil && approver.FullName != nil { - card += fmt.Sprintf("\n🔄 У согласующего: %s", *approver.FullName) - } - } - } - - // Добавляем информацию о дополнительных согласующих - additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ - ApprovalID: &approvalID, - }, - }) - if len(additionalApprovers) > 0 { - card += "\n\n👥 Дополнительные согласующие:" - for _, aa := range additionalApprovers { - if aa.ApproverID == nil { - continue - } - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) - if approver == nil || approver.FullName == nil { - continue - } - - statusIcon := "⏳" - if aa.Status != nil { - switch *aa.Status { - case "approved": - statusIcon = "✅" - case "rejected": - statusIcon = "❌" - } - } - card += fmt.Sprintf("\n• %s %s", statusIcon, *approver.FullName) - } - } - - // Добавляем комментарии - commentsSection := h.formatCommentsSection(ctx, approvalID, 4) - card += commentsSection - - return card -} - -// getTopicFullName возвращает строку вида "Категория: Тема" (или просто "Тема", если категория не найдена). -func getTopicFullName(ctx context.Context, ipc *types.InternalProviderControl, topicID *uint64) string { - if ipc == nil { - logrus.Error("ipc is nil") - return "—" - } - if topicID == nil { - return "—" - } - topic, err := ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *topicID) - if err != nil { - logrus.Errorf("getTopicFullName: Send err=%v", err) - return "—" - } - if topic == nil || topic.Name == nil { - return "—" - } - if topic.CategoryID == nil { - return *topic.Name - } - category, err := ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID) - if err != nil { - logrus.Errorf("getTopicFullName: Send err=%v", err) - return "—" - } - if category == nil || category.Name == nil { - return *topic.Name - } - return fmt.Sprintf("%s: %s", *category.Name, *topic.Name) -} - -// findStepForCurrentApprover находит активный шаг, принадлежащий текущему пользователю -func (h *Handler) findStepForCurrentApprover(ctx context.Context, approvalID uint64, currentUserID uint64, approval *typescore.Approval, isAnyOf bool) *typescore.ApprovalStep { - allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, - }) - - if !isAnyOf { - for _, s := range allSteps { - if s.Status != nil && (*s.Status == "pending" || *s.Status == "waiting") { - return s - } - } - return nil - } - - for _, s := range allSteps { - if s.Status == nil || (*s.Status != "pending" && *s.Status != "waiting") { - continue - } - if s.ApproverID != nil && *s.ApproverID == currentUserID { - return s - } - } - - if approval.TopicID != nil { - topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if topic != nil && topic.CategoryID != nil { - var allDelegations []*typescore.ApprovalDelegation - - if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalDelegation{ - IsActive: utilscore.PointerToBool(true), - TopicID: approval.TopicID, - }, - }); err == nil { - allDelegations = append(allDelegations, delegations...) - } - - if delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalDelegation{ - IsActive: utilscore.PointerToBool(true), - CategoryID: topic.CategoryID, - }, - }); err == nil { - allDelegations = append(allDelegations, delegations...) - } - - for _, s := range allSteps { - if s.Status == nil || (*s.Status != "pending" && *s.Status != "waiting") { - continue - } - if s.ApproverID == nil { - continue - } - for _, deleg := range allDelegations { - if deleg.DelegatorID != nil && *deleg.DelegatorID == *s.ApproverID && - deleg.DelegateID != nil && *deleg.DelegateID == currentUserID { - return s - } - } - } - } - } - - return nil -} - ------END service/telegram_service/handlers/approval/helper.go----- - -File: service/telegram_service/handlers/approval/http_fetch.go -Lines: 146 ------BEGIN service/telegram_service/handlers/approval/http_fetch.go----- -package approval - -import ( - "bitrix_balancer_api/core/variables" - "bytes" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "sync" - "time" - - "github.com/sirupsen/logrus" -) - -var ( - fileHTTPClient *http.Client - fileHTTPClientOnce sync.Once -) - -// APIProxyRequest описывает структуру тела запроса к прокси-сервису -type APIProxyRequest struct { - URL string `json:"url"` - Method string `json:"method"` - Body interface{} `json:"body"` -} - -// FileProxyTransport перехватывает GET-запросы на скачивание файлов и заворачивает их в API-прокси -type FileProxyTransport struct { - wrapped http.RoundTripper -} - -func (t *FileProxyTransport) RoundTrip(req *http.Request) (*http.Response, error) { - // Для скачивания файлов используется GET, поэтому body всегда пустой объект {} - proxyReqPayload := APIProxyRequest{ - URL: req.URL.String(), - Method: req.Method, - Body: map[string]interface{}{}, - } - - proxyJsonBytes, err := json.Marshal(proxyReqPayload) - if err != nil { - return nil, fmt.Errorf("file proxy transport: failed to marshal payload: %w", err) - } - - // Формируем POST-запрос к API-прокси шлюзу - proxyReq, err := http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(proxyJsonBytes)) - if err != nil { - return nil, fmt.Errorf("file proxy transport: failed to create request: %w", err) - } - - // Проставляем обязательные заголовки - proxyReq.Header.Set("Content-Type", "application/json") - proxyReq.Header.Set(variables.ProxySecretHeader, variables.ProxySecretKey) - - resp, err := t.wrapped.RoundTrip(proxyReq) - if err != nil { - return nil, err - } - - // Если прокси вернул статус отличный от 200 OK, вычитываем ошибку - if resp.StatusCode != http.StatusOK { - defer resp.Body.Close() - errorBody, _ := io.ReadAll(resp.Body) - return nil, fmt.Errorf("file proxy returned status %d (%s): %s", resp.StatusCode, resp.Status, string(errorBody)) - } - - return resp, nil -} - -func buildFileHTTPClient() (*http.Client, error) { - fileHTTPClientOnce.Do(func() { - baseTransport := &http.Transport{ - TLSHandshakeTimeout: 10 * time.Second, - ResponseHeaderTimeout: 10 * time.Second, - MaxIdleConns: 100, - MaxIdleConnsPerHost: 10, - IdleConnTimeout: 90 * time.Second, - } - - fileHTTPClient = &http.Client{ - Timeout: 30 * time.Second, - // Оборачиваем базовый транспорт в наш FileProxyTransport - Transport: &FileProxyTransport{ - wrapped: baseTransport, - }, - } - }) - - return fileHTTPClient, nil -} - -// fetchFileAsBase64 скачивает файл по URL через API-прокси и возвращает base64-строку. -func fetchFileAsBase64(url string) (string, error) { - client, err := buildFileHTTPClient() - if err != nil { - return "", err - } - - const maxRetries = 3 - const baseDelay = 500 * time.Millisecond - - var lastErr error - for attempt := 1; attempt <= maxRetries; attempt++ { - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) - if err != nil { - cancel() - return "", fmt.Errorf("create request: %w", err) - } - - resp, err := client.Do(req) - if err == nil && resp.StatusCode == http.StatusOK { - data, readErr := io.ReadAll(resp.Body) - resp.Body.Close() - cancel() - - if readErr != nil { - return "", fmt.Errorf("read body: %w", readErr) - } - return base64.StdEncoding.EncodeToString(data), nil - } - - if resp != nil { - resp.Body.Close() - } - cancel() - - if err != nil { - lastErr = err - logrus.Warnf("fetchFileAsBase64: attempt %d/%d failed: %v", attempt, maxRetries, err) - } else if resp != nil { - lastErr = fmt.Errorf("bad status code: %s", resp.Status) - logrus.Warnf("fetchFileAsBase64: attempt %d/%d bad status: %s", attempt, maxRetries, resp.Status) - } - - if attempt < maxRetries { - delay := baseDelay * time.Duration(1<<(attempt-1)) - time.Sleep(delay) - } - } - - return "", fmt.Errorf("all retries failed: %w", lastErr) -} - ------END service/telegram_service/handlers/approval/http_fetch.go----- - -File: service/telegram_service/handlers/approval/list.go -Lines: 537 ------BEGIN service/telegram_service/handlers/approval/list.go----- -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" - "sort" -) - -// 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 { - return - } - - // Получаем только те категории, по которым у пользователя есть заявки - categories, err := h.ipc.Database.ApprovalTopicCategory.GetCategoriesWithApprovalsByInitiatorDB(ctx, *user.ID) - if err != nil || len(categories) == 0 { - // Нет заявок вообще — сразу показываем все - h.HandleMyApprovalsStatusCallback( - bot, - &tgbotapi.CallbackQuery{ - Message: &tgbotapi.Message{Chat: &tgbotapi.Chat{ID: chatID}}, - From: &tgbotapi.User{ID: telegramID}, - }, - "all", - "all", - ) - return - } - - msg := tgbotapi.NewMessage(chatID, "📂 Инициированные согласования\n\nВыберите тему:") - msg.ParseMode = "HTML" - msg.ReplyMarkup = buildMyApprovalsTopicFilter(categories) - bot.Send(msg) //nolint:errcheck -} - -func (h *Handler) HandleMyApprovalsTopicCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicFilter 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 - - // Получаем название выбранной категории - header := "Все темы" - if topicFilter != "all" && topicFilter != "" { - cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicFilter) - if cat != nil && cat.Name != nil { - header = *cat.Name - } - } - - msg := tgbotapi.NewMessage(cq.Message.Chat.ID, - fmt.Sprintf("📂 %s\n\nВыберите статус:", header), - ) - msg.ParseMode = "HTML" - msg.ReplyMarkup = buildMyApprovalStatusFilter(topicFilter) - bot.Send(msg) //nolint:errcheck -} - -func buildMyApprovalStatusFilter(topicFilter string) tgbotapi.InlineKeyboardMarkup { - cb := func(status string) string { - return fmt.Sprintf("my_appr_status:%s:%s", status, topicFilter) - } - return tgbotapi.NewInlineKeyboardMarkup( - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("Все", cb("all")), - ), - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("✅ Согласованные", cb("approved")), - tgbotapi.NewInlineKeyboardButtonData("❌ Отклонённые", cb("rejected")), - ), - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("⏳ Ожидают", cb("pending")), - ), - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("← Назад", "my_appr_back"), - ), - ) -} - -func (h *Handler) HandleMyApprovalsStatusCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, status, topicFilter 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 - - chatID := cq.Message.Chat.ID - telegramID := cq.From.ID - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return - } - - var filterStatus *string - if status != "" && status != "all" { - filterStatus = &status - } - - approvals, _, err := h.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Approval{ - Status: filterStatus, - InitiatorID: user.ID, - }, - }) - if err != nil { - logrus.Errorf("HandleMyApprovalsStatusCallback: err=%v", err) - sendText(bot, chatID, "Ошибка при получении заявок.") - return - } - - if topicFilter != "" && topicFilter != "all" { - cat, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, topicFilter) - if cat != nil && cat.ID != nil { - topics, _, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopic{CategoryID: cat.ID}, - }) - // Собираем ID разрешённых тем - allowedTopicIDs := make(map[uint64]bool) - for _, t := range topics { - if t.ID != nil { - allowedTopicIDs[*t.ID] = true - } - } - // Фильтруем заявки - var filtered []*typescore.Approval - for _, a := range approvals { - if a.TopicID != nil && allowedTopicIDs[*a.TopicID] { - filtered = append(filtered, a) - } - } - approvals = filtered - } - } - - if len(approvals) == 0 { - sendText(bot, chatID, "📭 Заявок по выбранным фильтрам не найдено.") - return - } - - for _, approval := range approvals { - if approval.ID == nil { - continue - } - card := h.buildApprovalCard(ctx, approval, h.getCollectedFromApproval(ctx, approval)) - approvalStatus := "" - if approval.Status != nil { - approvalStatus = *approval.Status - } - files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - msg := tgbotapi.NewMessage(chatID, card) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildInitiatorCard(*approval.ID, approvalStatus, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) - bot.Send(msg) //nolint:errcheck - } -} - -func buildMyApprovalsTopicFilter(categories []*typescore.ApprovalTopicCategory) tgbotapi.InlineKeyboardMarkup { - var rows [][]tgbotapi.InlineKeyboardButton - - // Кнопка "Все" - rows = append(rows, tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("📋 Все темы", "my_appr_topic:all"), - )) - - // Кнопки по категориям из БД - for _, c := range categories { - if c.ID == nil || c.Name == nil { - continue - } - rows = append(rows, tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData( - *c.Name, - fmt.Sprintf("my_appr_topic:%s", *c.Code), - ), - )) - } - - return tgbotapi.NewInlineKeyboardMarkup(rows...) -} - -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 - } - - type validStep struct { - step *typescore.ApprovalStep - approval *typescore.Approval - } - var validSteps []validStep - for _, step := range steps { - if step.ApprovalID == nil { - continue - } - approval, aErr := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID) - if aErr != nil || approval == nil { - continue - } - if approval.Status == nil || (*approval.Status != "pending" && *approval.Status != "revision") { - approvalStatus := "nil" - if approval.Status != nil { - approvalStatus = *approval.Status - } - stepID := uint64(0) - if step.ID != nil { - stepID = *step.ID - } - logrus.Warnf( - "HandleIncomingApprovals: осиротевший шаг stepID=%d approvalID=%d approverID=%d — статус шага=pending, статус заявки=%s; шаг пропущен из выдачи. Похоже на рассинхронизацию между ApprovalStep и Approval — стоит проверить эту заявку вручную", - stepID, *step.ApprovalID, *user.ID, approvalStatus, - ) - continue - } - validSteps = append(validSteps, validStep{step: step, approval: approval}) - } - - // Дополнительные согласования — та же логика: не доверяем одному только - // статусу ApprovalAdditionalApprover, сверяем со статусом заявки. - 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) - } - - type validAdditional struct { - aa *typescore.ApprovalAdditionalApprover - approval *typescore.Approval - } - var validAdditionals []validAdditional - for _, aa := range additionalApprovers { - if aa.ApprovalID == nil { - continue - } - approval, aErr := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *aa.ApprovalID) - if aErr != nil || approval == nil { - continue - } - if approval.Status == nil || (*approval.Status != "pending" && *approval.Status != "revision") { - approvalStatus := "nil" - if approval.Status != nil { - approvalStatus = *approval.Status - } - logrus.Warnf( - "HandleIncomingApprovals: осиротевший доп.согласующий approvalID=%d approverID=%d — статус=pending, статус заявки=%s; пропущен из выдачи", - *aa.ApprovalID, *user.ID, approvalStatus, - ) - continue - } - validAdditionals = append(validAdditionals, validAdditional{aa: aa, approval: approval}) - } - - totalCount := len(validSteps) + len(validAdditionals) - if totalCount == 0 { - sendText(bot, chatID, "📭 Нет заявок для согласования.") - return - } - - sendText(bot, chatID, fmt.Sprintf("📬 Входящие согласования (%d):", totalCount)) - - // Отправляем основные согласования - for _, vs := range validSteps { - addedApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ - ApprovalID: vs.step.ApprovalID, - Status: utilscore.PointerToString("pending"), - }, - }) - h.sendApprovalCard(bot, chatID, vs.approval, true, true, addedApprovers) - } - - // Отправляем дополнительные согласования - for _, va := range validAdditionals { - h.sendAdditionalApprovalCard(bot, chatID, va.approval, va.aa) - } -} - -// sendApprovalCard отправляет карточку одной заявки. -// withDecision=true — добавляет кнопки Да/Нет для согласующего. -func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval, withButtons, showAddApprover 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 - } - } - - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - - 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, topicFullName, 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" { - files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - markup := keyboard.BuildApproverDecision(*approval.ID, *approval.Status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) - - //if showAddApprover { - // addBtn := tgbotapi.NewInlineKeyboardButtonData( - // "➕ Добавить согласующего", - // fmt.Sprintf("appr:add_approver:%d", *approval.ID), - // ) - // markup.InlineKeyboard = append(markup.InlineKeyboard, []tgbotapi.InlineKeyboardButton{addBtn}) - //} - - msg.ReplyMarkup = markup - - } else if approval.Status != nil && (*approval.Status == "pending" || *approval.Status == "approved") { - files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - if err != nil { - logrus.Errorf("failed to load files for approval, %v", err) - } - markup := keyboard.BuildInitiatorCard(*approval.ID, *approval.Status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) - - msg.ReplyMarkup = markup - } - - bot.Send(msg) //nolint:errcheck -} - -func (h *Handler) HandleApprovalStages(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { - ctx := context.Background() - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if err != nil || approval == nil { - sendText(bot, cq.Message.Chat.ID, "⚠️ Заявка не найдена.") - return - } - - steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID}, - }) - if err != nil { - return - } - 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 - }) - - text := fmt.Sprintf("📊 Стадии согласования заявки #%d\n\n", approvalID) - - if len(steps) == 0 { - if approval.Status != nil && *approval.Status == "approved" { - text += "✅ Заявка согласована автоматически\n\n" - text += "Согласующие не были назначены для этой темы.\n" - text += "Заявка принята без этапа согласования.\n" - } else { - text += "⚠️ Этапы согласования отсутствуют\n\n" - text += "Для этой заявки не созданы этапы согласования.\n" - } - } else { - statusIcons := map[string]string{ - "pending": "⏳", - "approved": "✅", - "rejected": "❌", - "waiting": "🔜", - } - - for i, step := range steps { - icon := "🔜" - if step.Status != nil { - if ic, ok := statusIcons[*step.Status]; ok { - icon = ic - } - } - name := "—" - if step.ApproverNameSnapshot != nil { - name = *step.ApproverNameSnapshot - } - text += fmt.Sprintf("%d. %s %s\n", i+1, icon, name) - if step.ActedAt != nil { - text += fmt.Sprintf(" 📅 %s\n", step.ActedAt.Format("02.01.2006 15:04")) - } - } - } - - // НОВОЕ: доп. согласующие — отдельная сущность от основной цепочки шагов, - // без своего StepOrder (все они назначаются параллельно, независимо от - // того, в каком порядке идут ApprovalStep), поэтому выводим отдельным - // блоком, а не пытаемся встроить в нумерованный список выше. - additionalApprovers, _, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID}, - }) - if err != nil { - logrus.Warnf("HandleApprovalStages: GetApprovalAdditionalApproversListDB approvalID=%d err=%v", approvalID, err) - } - - if len(additionalApprovers) > 0 { - text += "\n➕ Дополнительные согласующие:\n" - additionalStatusIcons := map[string]string{ - "pending": "⏳", - "approved": "✅", - "rejected": "❌", - } - for _, aa := range additionalApprovers { - icon := "⏳" - if aa.Status != nil { - if ic, ok := additionalStatusIcons[*aa.Status]; ok { - icon = ic - } - } - name := "—" - if aa.ApproverID != nil { - if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID); u != nil && u.FullName != nil { - name = *u.FullName - } - } - text += fmt.Sprintf("%s %s\n", icon, name) - if aa.ActedAt != nil { - text += fmt.Sprintf(" 📅 %s\n", aa.ActedAt.Format("02.01.2006 15:04")) - } - if aa.Comment != nil && *aa.Comment != "" { - text += fmt.Sprintf(" 💬 %s\n", *aa.Comment) - } - } - } - - // Статус задач - tasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTask{ApprovalID: &approvalID}, - }) - - if len(tasks) > 0 { - text += "\n🎯 Задачи:\n" - taskStatusLabels := map[string]string{ - "pending": "⏳ Ожидает выполнения", - "completed": "✅ Выполнена", - "cancelled": "❌ Отменена", - "cancellation": "⚠️ Требует отмены изменений", - } - for _, task := range tasks { - statusLabel := "—" - if task.Status != nil { - if l, ok := taskStatusLabels[*task.Status]; ok { - statusLabel = l - } - } - executorName := "—" - if task.ExecutorID != nil { - if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID); u != nil && u.FullName != nil { - executorName = *u.FullName - } - } - text += fmt.Sprintf("• %s — %s", executorName, statusLabel) - if task.CompletedAt != nil { - text += fmt.Sprintf(" (%s)", task.CompletedAt.Format("02.01.2006 15:04")) - } - text += "\n" - } - } - - msg := tgbotapi.NewMessage(cq.Message.Chat.ID, text) - msg.ParseMode = "HTML" - bot.Send(msg) //nolint:errcheck -} - ------END service/telegram_service/handlers/approval/list.go----- - -File: service/telegram_service/handlers/approval/navigation.go -Lines: 168 ------BEGIN service/telegram_service/handlers/approval/navigation.go----- -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 typescore.ApprovalStatusApproved.String(): - statusText = "✅ Принятые заявки" - case typescore.ApprovalStatusRejected.String(): - statusText = "❌ Отклонённые заявки" - case typescore.ApprovalStatusPending.String(): - 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, 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) - } - - isDirector := false - if user != nil && user.ID != nil { - isDirector, _ = h.ipc.Database.User.IsDirectorDB(ctx, *user.ID) - } - - replyMarkup := keyboard.BuildMainMenu(keyboard.UserRole{ - IsApprover: isApprover, - IsObserver: isObserver, - IsExecutor: isExecutor, - IsDirector: isDirector, - }) - - msg := tgbotapi.NewMessage(chatID, "🏠 Главное меню") - msg.ParseMode = "HTML" - msg.ReplyMarkup = replyMarkup - bot.Send(msg) //nolint:errcheck -} - ------END service/telegram_service/handlers/approval/navigation.go----- - -File: service/telegram_service/handlers/approval/notify.go -Lines: 891 ------BEGIN service/telegram_service/handlers/approval/notify.go----- -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, task *typescore.ApprovalTask) { - if executor.TelegramID == nil || task.ID == nil || approval.ID == nil { - return - } - - initiatorName := "—" - if initiator.FullName != nil { - initiatorName = *initiator.FullName - } - - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - - 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, topicFullName, content, taskText, - ) - - // Добавляем комментарии - commentsSection := h.formatCommentsSection(ctx, *approval.ID, 4) - text += commentsSection - - // 🆕 Получаем все файлы заявки - allFiles, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - filesCount := len(allFiles) - - // 🆕 Информация о файлах, приложенных к этой задаче - var taskFiles []string - for _, f := range allFiles { - if f.TaskID != nil && *f.TaskID == *task.ID && f.FileName != nil { - taskFiles = append(taskFiles, *f.FileName) - } - } - if len(taskFiles) > 0 { - text += "\n\n📎 Файлы к этой задаче:\n" - for i, name := range taskFiles { - text += fmt.Sprintf("%d. %s\n", i+1, name) - } - } else if filesCount > 0 { - // 🆕 Если есть файлы заявки, но не к этой задаче — показываем кнопку - text += fmt.Sprintf("\n\n📂 В заявке есть файлы (%d шт.) — см. кнопку ниже", filesCount) - } - - // 🆕 Передаём filesCount в клавиатуру - msg := tgbotapi.NewMessage(*executor.TelegramID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, filesCount, h.GetCommentsCount(ctx, *approval.ID)) - bot.Send(msg) //nolint:errcheck -} - -func (n *Notifier) ensureInstructions(ctx context.Context, approval *typescore.Approval, collected map[string]string) map[string]string { - if collected == nil { - collected = make(map[string]string) - } - - // Если инструкция уже есть — ничего не делаем - if _, ok := collected["instructions"]; ok && collected["instructions"] != "" { - return collected - } - - // Подгружаем тему из БД и берём инструкцию - if approval != nil && approval.TopicID != nil { - topic, err := n.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if err == nil && topic != nil && topic.Instructions != nil && *topic.Instructions != "" { - collected["instructions"] = *topic.Instructions - } - } - - return collected -} - -// 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 || approval.ID == nil { - return - } - - ctx := context.Background() - - collected = n.ensureInstructions(ctx, approval, collected) - - msgText := fmt.Sprintf("📬 Новая заявка #%d на согласование\n\n", *approval.ID) + - n.topic.FormatApproverMessage(initiator, collected) - - // Добавляем комментарии если есть - msgText += n.formatCommentsSection(ctx, *approval.ID, 4) - - // Отправляем с файлами или без - if len(approval.Files) == 0 { - n.sendTextToApprover(bot, approver, approval, msgText) - return - } - - status := "" - if approval.Status != nil { - status = *approval.Status - } - - files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - - n.sendFilesToRecipient( - bot, - *approver.TelegramID, - approval, - msgText, - keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files), n.GetCommentsCount(ctx, *approval.ID)), - ) -} - -func (n *Notifier) sendTextToApprover(bot *tgbotapi.BotAPI, approver *typescore.User, approval *typescore.Approval, text string) { - status := "" - if approval.Status != nil { - status = *approval.Status - } - ctx := context.Background() - files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - - msg := tgbotapi.NewMessage(*approver.TelegramID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files), n.GetCommentsCount(ctx, *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 - } - - approverName := "—" - if lastApprover != nil && lastApprover.FullName != nil { - approverName = *lastApprover.FullName - } - - status := "" - if approval.Status != nil { - status = *approval.Status - } - - ctx := context.Background() - - initiatorCollected := make(map[string]string, len(collected)) - for k, v := range collected { - if k == "instructions" { - continue - } - initiatorCollected[k] = v - } - - card := n.topic.FormatApproverMessage(initiator, initiatorCollected) - - text := fmt.Sprintf( - "✅ Заявка #%d согласована\n"+ - "👤 Последний согласующий: %s\n\n%s", - *approval.ID, approverName, card, - ) - - filesCount := len(approval.Files) - if filesCount == 0 { - files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - filesCount = len(files) - } - - msg := tgbotapi.NewMessage(*initiator.TelegramID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount, n.GetCommentsCount(ctx, *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 - } - - initiatorCollected := make(map[string]string, len(collected)) - for k, v := range collected { - if k == "instructions" { - continue - } - initiatorCollected[k] = v - } - - card := n.topic.FormatApproverMessage(initiator, initiatorCollected) - - text := fmt.Sprintf( - "❌ Заявка #%d отклонена\n\n"+ - "👤 Согласующий: %s\n\n%s", - *approval.ID, approverName, card, - ) - - 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 - } - - ctx := context.Background() - card := n.buildApprovalCard(ctx, approval, initiator, collected) - - text := "📌 Финально согласовано\n\n" + card - - status := "" - if approval.Status != nil { - status = *approval.Status - } - - // Считаем файлы для кнопки - filesCount := len(approval.Files) - if filesCount == 0 { - files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - filesCount = len(files) - } - - msg := tgbotapi.NewMessage(*director.TelegramID, text) - msg.ParseMode = "HTML" - // 🚀 Передаем filesCount в клавиатуру - msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount, n.GetCommentsCount(ctx, *approval.ID)) - bot.Send(msg) //nolint:errcheck -} - -// NotifyObserversDecision — кто, кому и что согласовал/отклонил. -// NotifyObserversDecision — кто, кому и что согласовал/отклонил. -func (n *Notifier) NotifyObserversDecision( - bot *tgbotapi.BotAPI, - observers []*typescore.User, - initiator *typescore.User, - approver *typescore.User, - approval *typescore.Approval, - collected map[string]string, -) { - // 🔍 Логирование входа - statusStr := "nil" - if approval.Status != nil { - statusStr = *approval.Status - } - logrus.Infof("📢 NotifyObserversDecision: status=%s, observers=%d, approvalID=%v", - statusStr, len(observers), approval.ID) - - if approval.Status == nil || *approval.Status != "approved" { - logrus.Warnf("⚠️ NotifyObserversDecision: skipped — status is not 'approved' (got: %s)", statusStr) - return - } - - if len(observers) == 0 { - logrus.Warnf("⚠️ NotifyObserversDecision: no observers to notify") - return - } - - ctx := context.Background() - card := n.buildApprovalCard(ctx, approval, initiator, collected) - - approverName := "—" - if approver != nil && approver.FullName != nil { - approverName = *approver.FullName - } - header := fmt.Sprintf( - "✅ %s согласовал(а) заявку\n\n", - approverName, - ) - - text := header + card - - filesCount := len(approval.Files) - if filesCount == 0 { - files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - filesCount = len(files) - } - - status := "" - if approval.Status != nil { - status = *approval.Status - } - - for _, obs := range observers { - if obs.TelegramID == nil { - logrus.Warnf("⚠️ NotifyObserversDecision: observer %v (id=%v) has no TelegramID, skipping", - obs.FullName, obs.ID) - continue - } - - logrus.Infof("📨 NotifyObserversDecision: sending to observer %s (telegramID=%d)", - *obs.FullName, *obs.TelegramID) - - msg := tgbotapi.NewMessage(*obs.TelegramID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverActions(*approval.ID, "", status, filesCount, n.GetCommentsCount(ctx, *approval.ID)) - - if _, err := bot.Send(msg); err != nil { - logrus.Errorf("❌ NotifyObserversDecision: Send to %d err=%v", *obs.TelegramID, err) - } else { - logrus.Infof("✅ NotifyObserversDecision: sent to %s (telegramID=%d)", - *obs.FullName, *obs.TelegramID) - } - } -} - -// sendFilesToRecipient отправляет файлы из approval получателю. -// Текст прикрепляется к первому файлу (caption), клавиатура — к последнему. -// Если файл не декодируется — пропускается с логированием. -func (n *Notifier) sendFilesToRecipient( - bot *tgbotapi.BotAPI, - chatID int64, - approval *typescore.Approval, - text string, - replyMarkup interface{}, -) { - type decodedFile struct { - name string - bytes []byte - } - - var validFiles []decodedFile - 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, decodedFile{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 - } - - const batchSize = 10 - batches := splitIntoBatches(validFiles, batchSize) - - for batchIdx, batch := range batches { - isLastBatch := batchIdx == len(batches)-1 - - if len(batch) == 1 { - // Один файл — отправляем как документ с текстом и кнопками - doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{ - Name: batch[0].name, - Bytes: batch[0].bytes, - }) - doc.ParseMode = "HTML" - if batchIdx == 0 { - doc.Caption = text - } - if isLastBatch && replyMarkup != nil { - doc.ReplyMarkup = replyMarkup - } - if _, err := bot.Send(doc); err != nil { - logrus.Errorf("sendFilesToRecipient: Send doc err=%v", err) - } - continue - } - - var mediaGroup []interface{} - for i, f := range batch { - photo := tgbotapi.NewInputMediaDocument(tgbotapi.FileBytes{ - Name: f.name, - Bytes: f.bytes, - }) - if i == 0 && batchIdx == 0 { - photo.Caption = text - photo.ParseMode = "HTML" - } - mediaGroup = append(mediaGroup, photo) - } - - mg := tgbotapi.NewMediaGroup(chatID, mediaGroup) - if _, err := bot.Request(mg); err != nil { - logrus.Errorf("sendFilesToRecipient: SendMediaGroup batch=%d err=%v", batchIdx, err) - } - - if isLastBatch && replyMarkup != nil { - btnMsg := tgbotapi.NewMessage(chatID, "⬆️ Файлы выше") - btnMsg.ParseMode = "HTML" - btnMsg.ReplyMarkup = replyMarkup - bot.Send(btnMsg) //nolint:errcheck - } - } -} - -// splitIntoBatches делит слайс на батчи размером size -func splitIntoBatches[T any](items []T, size int) [][]T { - if len(items) == 0 { - return nil - } - var batches [][]T - for len(items) > size { - batches = append(batches, items[:size]) - items = items[size:] - } - return append(batches, items) -} - -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 - } - - // Подгружаем актуальные файлы - files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - approval.Files = files - - addedByName := "—" - if additionalApprover.AddedByID != nil { - if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *additionalApprover.AddedByID); u != nil && u.FullName != nil { - addedByName = *u.FullName - } - } - - // Используем единую карточку - card := h.buildApprovalCard(ctx, approval, h.getCollectedFromApproval(ctx, approval)) - - text := fmt.Sprintf("📄 Добавлен пользователем: %s\n\n%s", addedByName, card) - - status := "" - if approval.Status != nil { - status = *approval.Status - } - - if len(files) == 0 { - msg := tgbotapi.NewMessage(chatID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) - bot.Send(msg) //nolint:errcheck - return - } - - categoryCode := h.getTopicCodeByApproval(ctx, approval) - topic, _ := h.Registry.Get(categoryCode) - if topic != nil { - notifier := NewNotifier(h.ipc, topic) - notifier.sendFilesToRecipient(bot, chatID, approval, text, keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID))) - } -} - -// notifyObserversAboutNewFile уведомляет наблюдателей о прикреплённом файле -func (h *Handler) notifyObserversAboutNewFile( - bot *tgbotapi.BotAPI, - approvalID uint64, - attachedBy *typescore.User, - fileName, fileBase64 string, -) { - ctx := context.Background() - - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if err != nil || approval == nil { - logrus.Errorf("notifyObserversAboutNewFile: GetApprovalByIDDB err=%v", err) - return - } - - topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if err != nil || topic == nil || topic.Code == nil { - logrus.Errorf("notifyObserversAboutNewFile: GetApprovalTopicByIDDB err=%v", err) - return - } - - observers, err := h.ipc.Database.User.GetObserversForApprovalDB(ctx, *topic.Code, topic.ID) - if err != nil { - logrus.Warnf("notifyObserversAboutNewFile: GetObserversForCategoryDB err=%v", err) - return - } - - userName := "Пользователь" - if attachedBy.FullName != nil { - userName = *attachedBy.FullName - } - - fileData, decodeErr := base64.StdEncoding.DecodeString(fileBase64) - - for _, obs := range observers { - if obs.TelegramID == nil { - continue - } - - text := fmt.Sprintf( - "📎 К заявке #%d добавлен файл\n\n"+ - "👤 Кем: %s\n"+ - "📄 Файл: %s", - approvalID, userName, fileName, - ) - - if decodeErr != nil { - logrus.Errorf("notifyObserversAboutNewFile: base64 decode err=%v", decodeErr) - msg := tgbotapi.NewMessage(*obs.TelegramID, text) - msg.ParseMode = "HTML" - bot.Send(msg) //nolint:errcheck - continue - } - - doc := tgbotapi.NewDocument(*obs.TelegramID, tgbotapi.FileBytes{ - Name: fileName, - Bytes: fileData, - }) - doc.Caption = text - doc.ParseMode = "HTML" - - if _, err := bot.Send(doc); err != nil { - logrus.Errorf("notifyObserversAboutNewFile: Send document err=%v", err) - } - } -} - -func (h *Handler) notifyAllParticipantsAboutFile( - bot *tgbotapi.BotAPI, - approvalID uint64, - attachedBy *typescore.User, - fileDescription string, -) { - ctx := context.Background() - - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if err != nil || approval == nil { - logrus.Errorf("notifyAllParticipantsAboutFile: GetApprovalByIDDB err=%v", err) - return - } - - files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) - if err != nil { - logrus.Warnf("notifyAllParticipantsAboutFile: GetFilesByApprovalIDDB err=%v", err) - } - approval.Files = files - - senderID := uint64(0) - if attachedBy != nil && attachedBy.ID != nil { - senderID = *attachedBy.ID - } - - senderName := "—" - if attachedBy != nil && attachedBy.FullName != nil { - senderName = *attachedBy.FullName - } - - text := fmt.Sprintf( - "📎 Файлы прикреплены к заявке #%d\n\n"+ - "👤 Кем: %s\n"+ - "📄 Количество: %s", - approvalID, senderName, fileDescription, - ) - - var recipients []*typescore.User - - if approval.InitiatorID != nil { - if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil { - recipients = append(recipients, u) - } - } - - if step, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID); step != nil && step.ApproverID != nil { - if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID); u != nil { - recipients = append(recipients, u) - } - } - - categoryCode := h.getTopicCodeByApproval(ctx, approval) - observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID) - recipients = append(recipients, observers...) - - // Получаем нотифайер для sendFilesToRecipient - topic, err := h.Registry.Get(categoryCode) - if err != nil { - logrus.Errorf("notifyAllParticipantsAboutFile: Registry.Get err=%v", err) - return - } - notifier := NewNotifier(h.ipc, topic) - - seen := make(map[uint64]bool) - for _, r := range recipients { - if r == nil || r.ID == nil || r.TelegramID == nil { - continue - } - if *r.ID == senderID || seen[*r.ID] { - continue - } - seen[*r.ID] = true - - if len(approval.Files) == 0 { - msg := tgbotapi.NewMessage(*r.TelegramID, text) - msg.ParseMode = "HTML" - bot.Send(msg) //nolint:errcheck - } else { - notifier.sendFilesToRecipient(bot, *r.TelegramID, approval, text, nil) - } - } -} - -func (n *Notifier) formatApprovalMessage(initiator *typescore.User, collected map[string]string) string { - return n.topic.FormatApproverMessage(initiator, collected) -} - -func (n *Notifier) buildApprovalCard(ctx context.Context, approval *typescore.Approval, initiator *typescore.User, collected map[string]string) string { - if approval.ID == nil { - return "" - } - approvalID := *approval.ID - - topicInfo := n.topic.FormatApproverMessage(initiator, collected) - - filesCount := len(approval.Files) - if filesCount == 0 { - files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) - filesCount = len(files) - } - - filesLabel := "Без файлов" - if filesCount > 0 { - filesLabel = fmt.Sprintf("📎 %d файл(ов)", filesCount) - } - - status := "⏳ ожидает" - if approval.Status != nil { - switch *approval.Status { - case "approved": - status = "✅ согласована" - case "rejected": - status = "❌ отклонена" - case "revoked": - status = "🔙 отозвана" - } - } - - createdAt := "—" - if approval.CreatedAt != nil { - createdAt = approval.CreatedAt.Format("02.01.2006 15:04") - } - - card := fmt.Sprintf( - "📋 Заявка #%d\n\n"+ - "%s\n\n"+ // 🚀 Сюда вставляется полное тело заявки из topicInfo - "📎 Файлы: %s\n"+ - "📅 Создана: %s\n"+ - "📊 Статус: %s", - approvalID, topicInfo, filesLabel, createdAt, status, - ) - - // Добавляем информацию о текущем согласующем если заявка в процессе - if approval.Status != nil && *approval.Status == "pending" { - activeStep, _ := n.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) - if activeStep != nil && activeStep.ApproverID != nil { - approver, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) - if approver != nil && approver.FullName != nil { - card += fmt.Sprintf("\n🔄 У согласующего: %s", *approver.FullName) - } - } - } - - // Добавляем информацию о дополнительных согласующих - additionalApprovers, _, _ := n.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ - ApprovalID: &approvalID, - }, - }) - if len(additionalApprovers) > 0 { - card += "\n\n👥 Дополнительные согласующие:" - for _, aa := range additionalApprovers { - if aa.ApproverID == nil { - continue - } - approver, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) - if approver == nil || approver.FullName == nil { - continue - } - - statusIcon := "⏳" - if aa.Status != nil { - switch *aa.Status { - case "approved": - statusIcon = "✅" - case "rejected": - statusIcon = "❌" - } - } - card += fmt.Sprintf("\n• %s %s", statusIcon, *approver.FullName) - } - } - - // Добавляем комментарии - commentsSection := n.formatCommentsSection(ctx, approvalID, 4) - card += commentsSection - - return card -} - -func (n *Notifier) formatCommentsSection(ctx context.Context, approvalID uint64, limit int) string { - comments, _, _ := n.ipc.Database.ApprovalComment.GetApprovalCommentsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalComment{ApprovalID: &approvalID}, - }) - if len(comments) == 0 { - return "" - } - - total := len(comments) - if limit > 0 && total > limit { - comments = comments[total-limit:] - } - - section := "\n\n💬 Комментарии:" - if limit > 0 && total > limit { - section = fmt.Sprintf("\n\n💬 Последние %d комментариев (из %d):", limit, total) - } - - for _, c := range comments { - authorName := "—" - if c.UserID != nil { - author, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *c.UserID) - if author != nil && author.FullName != nil { - authorName = *author.FullName - } - } - createdAt := "" - if c.CreatedAt != nil { - createdAt = c.CreatedAt.Format("02.01 15:04") - } - comment := "-" - if c.Comment != nil { - comment = *c.Comment - } - section += fmt.Sprintf("\n• %s (%s): %s", authorName, createdAt, comment) - } - return section -} - -func (n *Notifier) GetCommentsCount(ctx context.Context, approvalID uint64) int { - comments, err := n.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID) - if err != nil { - return 0 - } - return len(comments) -} - -func (h *Handler) notifyControllerAboutCreation( - bot *tgbotapi.BotAPI, - ctx context.Context, - controller *typescore.User, - initiator *typescore.User, - approval *typescore.Approval, - collected map[string]string, -) { - if controller.TelegramID == nil || approval.ID == nil { - return - } - - initiatorName := "—" - if initiator.FullName != nil { - initiatorName = *initiator.FullName - } - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - content := collected["content"] - if content == "" { - content = "—" - } - - text := fmt.Sprintf( - "👁 Создана заявка на согласование #%d\n\n"+ - "👤 Инициатор: %s\n"+ - "📋 Тема: %s\n"+ - "📝 Текст: %s", - *approval.ID, initiatorName, topicFullName, content, - ) - - status := "" - if approval.Status != nil { - status = *approval.Status - } - - msg := tgbotapi.NewMessage(*controller.TelegramID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverActions(*approval.ID, "", status, len(approval.Files), h.GetCommentsCount(ctx, *approval.ID)) - bot.Send(msg) //nolint:errcheck -} - ------END service/telegram_service/handlers/approval/notify.go----- - -File: service/telegram_service/handlers/approval/registry.go -Lines: 117 ------BEGIN service/telegram_service/handlers/approval/registry.go----- -package approval - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "bitrix_balancer_api/telegram_service/types" - "context" - "fmt" - "github.com/sirupsen/logrus" - "sync" -) - -type Registry struct { - ipc *types.InternalProviderControl - topics map[string]approvalflow.Topic - order []string - - topicCodeToCategory map[string]string - - mu sync.RWMutex -} - -func NewRegistry(ipc *types.InternalProviderControl) *Registry { - r := &Registry{ - ipc: ipc, - topics: make(map[string]approvalflow.Topic), - topicCodeToCategory: make(map[string]string), - } - - r.topicCodeToCategory["timeoff"] = "absence" - r.topicCodeToCategory["vacation"] = "absence" - r.topicCodeToCategory["sickleave"] = "absence" - - return r -} - -func (r *Registry) LoadFromDB(ctx context.Context) error { - r.mu.Lock() - defer r.mu.Unlock() - - r.topics = make(map[string]approvalflow.Topic) - r.order = nil - - categories, _, err := r.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTopicCategory{IsActive: boolPtr(true)}, - }) - if err != nil { - return fmt.Errorf("load categories: %w", err) - } - - for _, category := range categories { - if category.ID == nil || category.Code == nil { - continue - } - - nodes, err := r.loadFlowNodes(ctx, *category.ID) - if err != nil { - logrus.Warnf("LoadFromDB: loadFlowNodes categoryID=%d err=%v", *category.ID, err) - continue - } - if len(nodes) == 0 { - // категория ещё не мигрирована / дерево не настроено — пропускаем молча - continue - } - - dynamicTopic := approvalflow.NewDynamicTopic(category, nodes) - code := *category.Code - r.topics[code] = dynamicTopic - r.order = append(r.order, code) - } - - return nil -} - -func (r *Registry) loadFlowNodes(ctx context.Context, categoryID uint64) ([]*typescore.ApprovalFlowNode, error) { - nodes, _, err := r.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID}, - }) - return nodes, err -} - -func (r *Registry) Get(code string) (approvalflow.Topic, error) { - r.mu.RLock() - defer r.mu.RUnlock() - - if t, ok := r.topics[code]; ok { - return t, nil - } - - if categoryCode, mapped := r.topicCodeToCategory[code]; mapped { - if t, ok := r.topics[categoryCode]; ok { - return t, nil - } - } - - return nil, fmt.Errorf("unknown topic code: %s", code) -} - -func (r *Registry) All() []approvalflow.Topic { - r.mu.RLock() - defer r.mu.RUnlock() - - result := make([]approvalflow.Topic, 0, len(r.order)) - for _, code := range r.order { - result = append(result, r.topics[code]) - } - return result -} - -// Reload перезагружает темы из БД -func (r *Registry) Reload(ctx context.Context) error { - return r.LoadFromDB(ctx) -} - -func boolPtr(b bool) *bool { - return &b -} - ------END service/telegram_service/handlers/approval/registry.go----- - -File: service/telegram_service/handlers/approval/reminder.go -Lines: 167 ------BEGIN service/telegram_service/handlers/approval/reminder.go----- -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" -) - -// HandleReminderRevisions показывает список заявок на доработке -func (h *Handler) HandleReminderRevisions(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { - ctx := context.Background() - chatID := cq.Message.Chat.ID - telegramID := cq.From.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - sendText(bot, chatID, "⚠️ Пользователь не найден.") - return - } - - revisions, _, err := h.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Approval{ - InitiatorID: user.ID, - Status: utilscore.PointerToString("revision"), - }, - }) - if err != nil || len(revisions) == 0 { - sendText(bot, chatID, "📭 Нет заявок на доработке.") - return - } - - sendText(bot, chatID, fmt.Sprintf("📝 Заявки на доработке (%d):", len(revisions))) - - for _, approval := range revisions { - if approval.ID == nil { - continue - } - - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - content := "—" - if approval.Content != nil { - content = *approval.Content - } - - text := fmt.Sprintf( - "🔄 Заявка #%d на доработке\n\n"+ - "📋 Тема: %s\n"+ - "📝 Текст: %s", - *approval.ID, topicFullName, content, - ) - - if approval.RevisionComment != nil && *approval.RevisionComment != "" { - text += fmt.Sprintf("\n💬 Причина: %s", *approval.RevisionComment) - } - - msg := tgbotapi.NewMessage(chatID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevisionOptions(*approval.ID, h.GetCommentsCount(ctx, *approval.ID)) - bot.Send(msg) //nolint:errcheck - } -} - -// HandleReminderApprovals показывает список согласований к принятию -func (h *Handler) HandleReminderApprovals(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { - ctx := context.Background() - chatID := cq.Message.Chat.ID - telegramID := cq.From.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - sendText(bot, chatID, "⚠️ Пользователь не найден.") - return - } - - currentUserID := *user.ID - - // Получаем основные шаги согласования - steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ - ApproverID: ¤tUserID, - Status: utilscore.PointerToString("pending"), - }, - }) - if err != nil { - logrus.Errorf("HandleReminderApprovals: GetApprovalStepsListDB err=%v", err) - } - - // Получаем дополнительные согласования - additionalApprovers, _, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ - ApproverID: ¤tUserID, - Status: utilscore.PointerToString("pending"), - }, - }) - if err != nil { - logrus.Errorf("HandleReminderApprovals: GetApprovalAdditionalApproversListDB 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 - } - if approval.Status == nil && *approval.Status != "pending" { - continue - } - h.sendApprovalCardForReminder(bot, chatID, approval) - } - - // Показываем дополнительные согласования - for _, aa := range additionalApprovers { - if aa.ApprovalID == nil { - continue - } - approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *aa.ApprovalID) - if approval == nil { - continue - } - h.sendApprovalCardForReminder(bot, chatID, approval) - } -} - -// sendApprovalCardForReminder отправляет карточку заявки для напоминания -func (h *Handler) sendApprovalCardForReminder(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval) { - ctx := context.Background() - - if approval.ID == nil { - return - } - - files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - filesCount := len(files) - commentsCount := h.GetCommentsCount(ctx, *approval.ID) - - status := "" - if approval.Status != nil { - status = *approval.Status - } - - collected := h.getCollectedFromApproval(ctx, approval) - card := h.buildApprovalCard(ctx, approval, collected) - - msg := tgbotapi.NewMessage(chatID, card) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, filesCount > 0, filesCount, commentsCount) - bot.Send(msg) //nolint:errcheck -} - ------END service/telegram_service/handlers/approval/reminder.go----- - -File: service/telegram_service/handlers/approval/revision.go -Lines: 495 ------BEGIN service/telegram_service/handlers/approval/revision.go----- -package approval - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/keyboard" - "bitrix_balancer_api/telegram_service/state" - "context" - "fmt" - "time" - - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" -) - -// HandleRevisionCallback — согласующий нажал "Вернуть на доработку" -func (h *Handler) HandleRevisionCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { - chatID := cq.Message.Chat.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck - - msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( - "🔄 Заявка #%d — вернуть на доработку\n\n"+ - "Хотите указать причину?", - approvalID, - )) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevisionRejectOptions(approvalID) - bot.Send(msg) //nolint:errcheck -} - -// HandleRevisionCommentStart — согласующий хочет указать причину доработки -func (h *Handler) HandleRevisionCommentStart(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 - - // Сохраняем в Redis ожидание комментария (аналогично reject) - revisionKey := fmt.Sprintf("appr_revision_pending:%d", telegramID) - if err := h.ipc.RedisClient.Set(ctx, revisionKey, fmt.Sprintf("%d", approvalID), 10*time.Minute); err != nil { - logrus.Errorf("HandleRevisionCommentStart: Set err=%v", err) - return - } - - sendText(bot, chatID, "Укажите причину возврата на доработку:") -} - -// HandleRevisionWithComment — основной метод возврата на доработку -func (h *Handler) HandleRevisionWithComment(bot *tgbotapi.BotAPI, approverChatID int64, approverTelegramID int64, approvalID uint64, comment string) { - ctx := context.Background() - - approver, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, approverTelegramID) - if err != nil || approver == nil || approver.ID == nil { - sendText(bot, approverChatID, "⚠️ Пользователь не найден.") - return - } - - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID) - if err != nil || approval == nil { - sendText(bot, approverChatID, "⚠️ Заявка не найдена.") - return - } - - if approval.Status != nil && *approval.Status != "pending" { - sendText(bot, approverChatID, "⚠️ Заявку можно вернуть на доработку только в статусе 'На согласовании'.") - return - } - - now := time.Now() - revisionStatus := "revision" - revisionCount := 1 - if approval.RevisionCount != nil { - revisionCount = *approval.RevisionCount + 1 - } - - approval.Status = &revisionStatus - approval.RevisionComment = &comment - approval.RevisionByID = approver.ID - approval.RevisionAt = &now - approval.RevisionCount = &revisionCount - - if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval); err != nil { - logrus.Errorf("HandleRevisionWithComment: UpdateApprovalDB err=%v", err) - sendText(bot, approverChatID, "Ошибка при возврате заявки.") - return - } - - activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) - if activeStep != nil { - returnedAt := now - activeStep.ReturnedAt = &returnedAt - h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, activeStep) //nolint:errcheck - } - - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - - content := "—" - if approval.Content != nil { - content = *approval.Content - } - - commentText := "" - if comment != "" { - commentText = fmt.Sprintf("\n💬 Причина: %s", comment) - } - - approvalCard := h.buildApprovalCard(ctx, approval, h.getCollectedFromApproval(ctx, approval)) - - sendText(bot, approverChatID, fmt.Sprintf( - "🔄 Заявка #%d возвращена на доработку\n\n%s%s", - approvalID, approvalCard, commentText, - )) - - if approval.InitiatorID != nil { - initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) - if initiator != nil && initiator.TelegramID != nil { - h.notifyInitiatorRevision(bot, initiator, approval, approver, comment, topicFullName, content) - } - } -} - -// notifyInitiatorRevision — сигнатура не меняется, topicFullName теперь содержит "Категория: Тема". -func (h *Handler) notifyInitiatorRevision( - bot *tgbotapi.BotAPI, - initiator *typescore.User, - approval *typescore.Approval, - approver *typescore.User, - comment string, - topicFullName string, - content string, -) { - if initiator.TelegramID == nil || approval.ID == nil { - return - } - - approverName := "—" - if approver != nil && approver.FullName != nil { - approverName = *approver.FullName - } - - commentText := "" - if comment != "" { - commentText = fmt.Sprintf("\n💬 Причина: %s", comment) - } - - revisionCount := 1 - if approval.RevisionCount != nil { - revisionCount = *approval.RevisionCount - } - - text := fmt.Sprintf( - "🔄 Заявка #%d возвращена на доработку\n\n"+ - "📋 Тема: %s\n"+ - "📝 Текущий текст: %s\n"+ - "👤 Вернул: %s%s\n\n"+ - "🔢 Доработка #%d\n\n"+ - "Что хотите сделать?", - *approval.ID, topicFullName, content, approverName, commentText, revisionCount, - ) - - msg := tgbotapi.NewMessage(*initiator.TelegramID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevisionOptions(*approval.ID, h.GetCommentsCount(context.Background(), *approval.ID)) - bot.Send(msg) //nolint:errcheck -} - -// HandleRevisionEditText — инициатор хочет изменить текст -func (h *Handler) HandleRevisionEditText(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 - - // Проверяем что это инициатор - 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 - } - - if approval.InitiatorID == nil || *approval.InitiatorID != *user.ID { - sendText(bot, chatID, "⚠️ Только инициатор может редактировать заявку.") - return - } - - if approval.Status == nil || *approval.Status != "revision" { - sendText(bot, chatID, "⚠️ Редактирование доступно только для заявок на доработке.") - return - } - - // Сохраняем состояние ожидания нового текста - revisionState := &state.RevisionFlowState{ - ApprovalID: approvalID, - Stage: "await_content", - } - h.States.SetRevisionFlow(ctx, telegramID, revisionState) //nolint:errcheck - - currentContent := "—" - if approval.Content != nil { - currentContent = *approval.Content - } - - sendText(bot, chatID, fmt.Sprintf( - "✏️ Редактирование заявки #%d\n\n"+ - "📝 Текущий текст:\n%s\n\n"+ - "Введите новый текст:", - approvalID, currentContent, - )) -} - -// HandleRevisionTextInput — обработка нового текста от инициатора -func (h *Handler) HandleRevisionTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { - ctx := context.Background() - telegramID := msg.From.ID - chatID := msg.Chat.ID - - revisionState, err := h.States.GetRevisionFlow(ctx, telegramID) - if err != nil || revisionState == nil || revisionState.Stage != "await_content" { - return false - } - - h.States.ClearRevisionFlow(ctx, telegramID) //nolint:errcheck - - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, revisionState.ApprovalID) - if err != nil || approval == nil { - sendText(bot, chatID, "⚠️ Заявка не найдена.") - return true - } - - newContent := msg.Text - approval.Content = &newContent - - if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval); err != nil { - logrus.Errorf("HandleRevisionTextInput: UpdateApprovalDB err=%v", err) - sendText(bot, chatID, "Ошибка при сохранении текста.") - return true - } - - sendText(bot, chatID, fmt.Sprintf( - "✅ Текст обновлён\n\n"+ - "📝 Новый текст:\n%s\n\n"+ - "Что ещё хотите сделать?", - newContent, - )) - - // Показываем опции снова - optMsg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Заявка #%d на доработке:", revisionState.ApprovalID)) - optMsg.ParseMode = "HTML" - optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(revisionState.ApprovalID, h.GetCommentsCount(ctx, *approval.ID)) - bot.Send(optMsg) //nolint:errcheck - - return true -} - -// HandleRevisionResubmit — инициатор отправляет заявку на повторное согласование -func (h *Handler) HandleRevisionResubmit(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 - - 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 - } - - if approval.InitiatorID == nil || *approval.InitiatorID != *user.ID { - sendText(bot, chatID, "⚠️ Только инициатор может отправить заявку на повторное согласование.") - return - } - - if approval.Status == nil || *approval.Status != "revision" { - sendText(bot, chatID, "⚠️ Заявка не находится на доработке.") - return - } - - // Возвращаем статус pending - pendingStatus := "pending" - approval.Status = &pendingStatus - approval.RevisionComment = nil - - if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval); err != nil { - logrus.Errorf("HandleRevisionResubmit: UpdateApprovalDB err=%v", err) - sendText(bot, chatID, "Ошибка при отправке заявки.") - return - } - - // Сбрасываем шаг согласования обратно в pending и убираем ReturnedAt - activeStep, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID) - if err != nil || activeStep == nil { - logrus.Warnf("HandleRevisionResubmit: active step not found approvalID=%d", approvalID) - sendText(bot, chatID, "⚠️ Шаг согласования не найден.") - return - } - - pendingStepStatus := "pending" - activeStep.Status = &pendingStepStatus - activeStep.ReturnedAt = nil - h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, activeStep) //nolint:errcheck - - sendText(bot, chatID, fmt.Sprintf( - "✅ Заявка #%d отправлена на повторное согласование\n\n"+ - "Согласующий получил уведомление.", - approvalID, - )) - - // Уведомляем согласующего - if activeStep.ApproverID != nil { - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) - if approver != nil && approver.TelegramID != nil { - topicCode := h.getTopicCodeByApproval(ctx, approval) - topic, _ := h.Registry.Get(topicCode) - - collected := h.getCollectedFromApproval(ctx, approval) - - // Подгружаем актуальные файлы - files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID) - approval.Files = files - - revisionCount := 1 - if approval.RevisionCount != nil { - revisionCount = *approval.RevisionCount - } - - initiatorName := "—" - if user.FullName != nil { - initiatorName = *user.FullName - } - - text := fmt.Sprintf( - "🔄 Заявка #%d возвращена после доработки (доработка #%d)\n\n"+ - "👤 Инициатор: %s\n", - approvalID, revisionCount, initiatorName, - ) - - status := "" - if approval.Status != nil { - status = *approval.Status - } - - if topic != nil { - notifier := NewNotifier(h.ipc, topic) - // Добавляем заголовок о доработке к стандартному сообщению - fullText := text + notifier.formatApprovalMessage(user, collected) - - if len(files) == 0 { - msg := tgbotapi.NewMessage(*approver.TelegramID, fullText) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) - bot.Send(msg) //nolint:errcheck - } else { - notifier.sendFilesToRecipient(bot, *approver.TelegramID, approval, fullText, keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID))) - } - } else { - msg := tgbotapi.NewMessage(*approver.TelegramID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) - bot.Send(msg) //nolint:errcheck - } - } - } -} - -// HandleRevisionAddFiles — инициатор хочет добавить файлы -func (h *Handler) HandleRevisionAddFiles(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 - - 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 || approval.InitiatorID == nil || *approval.InitiatorID != *user.ID { - sendText(bot, chatID, "⚠️ Нет прав или заявка не найдена.") - return - } - - if approval.Status == nil || *approval.Status != "revision" { - sendText(bot, chatID, "⚠️ Добавление файлов доступно только для заявок на доработке.") - return - } - - // Используем существующий механизм через Redis — тот же что HandleAttachFileStart - key := fmt.Sprintf("appr_revision_attach_file:%d", telegramID) - if err := h.ipc.RedisClient.Set(ctx, key, fmt.Sprintf("%d", approvalID), 10*time.Minute); err != nil { - logrus.Errorf("HandleRevisionAddFiles: Redis.Set err=%v", err) - return - } - - msg := tgbotapi.NewMessage(chatID, - fmt.Sprintf("📎 Добавление файла к заявке #%d\n\nОтправьте фото или документ:", approvalID), - ) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevisionAttachCancel(approvalID) - bot.Send(msg) //nolint:errcheck -} - -// HandleRevisionFileInput — обрабатывает файл от инициатора при доработке. -// Вызывается ДО HandleAttachFileInput в update_handler, проверяет свой Redis ключ. -func (h *Handler) HandleRevisionFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { - ctx := context.Background() - telegramID := msg.From.ID - chatID := msg.Chat.ID - - key := fmt.Sprintf("appr_revision_attach_file:%d", telegramID) - val, err := h.ipc.RedisClient.Get(ctx, key) - if err != nil || val == "" { - return false - } - - var approvalID uint64 - fmt.Sscanf(val, "%d", &approvalID) - - 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_%s.jpg", time.Now().Format("20060102_150405")) - case msg.Document != nil: - fileID = msg.Document.FileID - fileName = msg.Document.FileName - default: - sendText(bot, chatID, "⚠️ Пожалуйста, отправьте фото или документ.") - return true - } - - fileURL, err := bot.GetFileDirectURL(fileID) - if err != nil { - logrus.Errorf("HandleRevisionFileInput: GetFileDirectURL err=%v", err) - sendText(bot, chatID, "Ошибка при получении файла.") - return true - } - - base64Data, err := fetchFileAsBase64(fileURL) // используем существующую функцию - if err != nil { - logrus.Errorf("HandleRevisionFileInput: fetchFileAsBase64 err=%v", err) - sendText(bot, chatID, "Ошибка при обработке файла.") - return true - } - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return true - } - - file := &typescore.ApprovalFile{ - ApprovalID: &approvalID, - FileBase64: &base64Data, - FileName: &fileName, - AttachedByID: user.ID, - } - - if _, _, err := h.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, file); err != nil { - logrus.Errorf("HandleRevisionFileInput: CreateApprovalFileDB err=%v", err) - sendText(bot, chatID, "Ошибка при сохранении файла.") - return true - } - - h.ipc.RedisClient.Del(ctx, key) //nolint:errcheck - - sendText(bot, chatID, fmt.Sprintf("✅ Файл %s прикреплён к заявке #%d", fileName, approvalID)) - - // Показываем опции снова - optMsg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Заявка #%d на доработке:", approvalID)) - optMsg.ParseMode = "HTML" - optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(approvalID, h.GetCommentsCount(ctx, approvalID)) - bot.Send(optMsg) //nolint:errcheck - - return true -} - ------END service/telegram_service/handlers/approval/revision.go----- - -File: service/telegram_service/handlers/approval/selection_approver.go -Lines: 509 ------BEGIN service/telegram_service/handlers/approval/selection_approver.go----- -package approval - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/keyboard" - "bitrix_balancer_api/telegram_service/state" - "context" - "fmt" - "strings" - - 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 - } - - flowState, err := h.States.Get(ctx, telegramID) - if err != nil || flowState == nil { - sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.") - return - } - var systems []string - if s := flowState.Collected["systems"]; s != "" { - systems = strings.Split(s, ",") - } - approvers, err := h.getAvailableApproversForTopic(ctx, *user.ID, *user.DepartmentID, approvalTopic, systems) - 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 - } - - if !flowState.AwaitApproverSelection { - logrus.Warnf("HandleApproverSelectionCallback: not awaiting approver selection, userID=%d", telegramID) - return - } - - selected, err := h.ipc.Database.User.GetUserByIDDB(ctx, approverID) - if err != nil || selected == nil { - sendText(bot, chatID, "⚠️ Согласующий не найден.") - return - } - - selectedName := "выбранный согласующий" - if selected.FullName != nil { - selectedName = *selected.FullName - } - - flowState.SelectedApproverID = approverID - flowState.AwaitApproverSelection = false - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - - sendText(bot, chatID, fmt.Sprintf("✅ Выбран согласующий: %s", selectedName)) - - h.continueFlowAfterInput(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 - } - - var systems []string - if s := flowState.Collected["systems"]; s != "" { - systems = strings.Split(s, ",") - } - approvers, err := h.getAvailableApproversForTopic(ctx, *user.ID, *user.DepartmentID, approvalTopic, systems) - 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 -} - -// getAvailableApproversForTopic возвращает кандидатов в согласующие для ручного -// выбора. -// -// ИСПРАВЛЕНО (было 2 самостоятельных бага, из-за которых поведение расходилось -// с SQL-версией GetApproversDB): -// -// 1. Не было приоритета специфичности. Раньше запись, подходящая по topic_id, -// и запись, подходящая только по topic_category_id, учитывались ОДНОВРЕМЕННО. -// В SQL-версии всегда побеждает самый специфичный уровень: topic > category > global. -// Теперь здесь та же логика: сначала вычисляем минимальную специфичность -// среди подходящих записей, затем используем только записи этого уровня. -// -// 2. Полностью игнорировались "глобальные" записи иерархии — те, где -// TopicID и TopicCategoryID оба NULL (уровень specGlobal / specificity=3 -// в SQL). В автоматическом резолве (GetApproversDB) такие записи -// учитываются как fallback, а здесь для ручного выбора — нет, то есть -// в ручном списке мог быть пустой результат там, где автоматика -// нашла бы согласующего. -// -// Также раньше учитывалась только systems[0] — при мультивыборе систем -// (например "okb,1c") override по системе, отличной от первой, никогда не -// применялся. Теперь запись считается override, если её target_system -// совпадает с ЛЮБОЙ из выбранных систем. -func (h *Handler) getAvailableApproversForTopic(ctx context.Context, userID, departmentID uint64, approvalTopic *typescore.ApprovalTopic, systems []string) ([]*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 - } - - const ( - specTopic = iota - specCategory - specGlobal - specNone // не подходит вообще - ) - - type candidate struct { - approverID uint64 - targetSystem string - spec int - } - - var candidates []candidate - minSpec := specNone - for _, hier := range hierarchies { - if hier.ApproverID == nil { - continue - } - - spec := specNone - switch { - case hier.TopicID != nil && *hier.TopicID == *approvalTopic.ID: - spec = specTopic - case hier.TopicCategoryID != nil && *hier.TopicCategoryID == *approvalTopic.CategoryID: - spec = specCategory - case hier.TopicID == nil && hier.TopicCategoryID == nil: - spec = specGlobal - default: - continue - } - - ts := "" - if hier.TargetSystem != nil { - ts = *hier.TargetSystem - } - - candidates = append(candidates, candidate{ - approverID: *hier.ApproverID, - targetSystem: ts, - spec: spec, - }) - if spec < minSpec { - minSpec = spec - } - } - - // Набор выбранных систем — override применяется, если запись целится в - // любую из них (а не только в systems[0], как было раньше). - systemSet := make(map[string]bool, len(systems)) - for _, s := range systems { - s = strings.TrimSpace(s) - if s != "" { - systemSet[s] = true - } - } - - var overrideIDs, commonIDs = make(map[uint64]bool), make(map[uint64]bool) - for _, c := range candidates { - if c.spec != minSpec { - continue // берём только самый специфичный уровень - } - - switch { - case c.targetSystem != "" && c.targetSystem != "all" && systemSet[c.targetSystem]: - overrideIDs[c.approverID] = true - case c.targetSystem == "" || c.targetSystem == "all": - commonIDs[c.approverID] = true - } - } - - // Если для выбранной системы (систем) настроен override — показываем - // только его состав, иначе — общий список (как раньше). - approverIDs := commonIDs - if len(overrideIDs) > 0 { - approverIDs = overrideIDs - } - - 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) { - approvals, err := h.submitApproval(ctx, bot, telegramID, flowState) - if err != nil { - logrus.Errorf("finalizeAndSubmit: submitApproval error: %v", err) - - errMsg := err.Error() - if !strings.HasPrefix(errMsg, "⚠️") { - errMsg = "Произошла ошибка при отправке заявки. Попробуйте позже." - } - - msg := tgbotapi.NewMessage(chatID, errMsg) - msg.ParseMode = "HTML" - bot.Send(msg) //nolint:errcheck - return - } - - if len(approvals) == 0 { - logrus.Error("finalizeAndSubmit: no approvals returned by submitApproval") - bot.Send(tgbotapi.NewMessage(chatID, "📤 Отправлено на согласование")) //nolint:errcheck - return - } - - for _, approval := range approvals { - h.sendConfirmationCard(bot, ctx, chatID, telegramID, flowState, approval) - } -} - -// sendConfirmationCard формирует и отправляет карточку подтверждения для ОДНОЙ -// заявки. Раньше это был "хвост" finalizeAndSubmit — логика не менялась, -// просто вынесена в отдельную функцию, чтобы вызываться в цикле по заявкам. -func (h *Handler) sendConfirmationCard(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, telegramID int64, flowState *state.ApprovalFlowState, approval *typescore.Approval) { - if approval == nil || approval.ID == nil { - return - } - - var approvalTopic *typescore.ApprovalTopic - if approval.TopicID != nil { - approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - } - isAnyOf := approvalTopic != nil && approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of" - - approverLine := "—" - - allSteps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID}, - }) - - if isAnyOf { - var names []string - for _, s := range allSteps { - if s.Status == nil || (*s.Status != "pending" && *s.Status != "waiting") { - continue - } - if s.ApproverID != nil { - if approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID); approver != nil && approver.FullName != nil { - names = append(names, *approver.FullName) - } - } - } - if len(names) > 0 { - approverLine = strings.Join(names, " или ") - } - } else { - if len(allSteps) > 0 { - var firstStep *typescore.ApprovalStep - for _, s := range allSteps { - if s.StepOrder == nil { - continue - } - if firstStep == nil || *s.StepOrder < *firstStep.StepOrder { - firstStep = s - } - } - - if firstStep != nil && firstStep.ApproverID != nil { - if approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *firstStep.ApproverID); approver != nil && approver.FullName != nil { - approverLine = *approver.FullName - } - } - } - } - - topic, err := h.Registry.Get(flowState.TopicCode) - if err != nil || topic == nil { - logrus.Errorf("sendConfirmationCard: Registry.Get(%s) err=%v", flowState.TopicCode, err) - } - - initiator, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, int64(telegramID)) - if err != nil || initiator == nil { - logrus.Errorf("sendConfirmationCard: GetUserByTelegramIDDB err=%v", err) - } - - // Метаданные заявки уже содержат её собственную (единственную) систему — - // восстанавливаем collected именно из meta, а не из flowState.Collected - // (там всё ещё общий "okb,1c" по всем заявкам мультивыбора). - collectedForCard := make(map[string]string, len(flowState.Collected)) - for k, v := range flowState.Collected { - if k == "instructions" { - continue - } - collectedForCard[k] = v - } - if meta, mErr := typescore.ParseApprovalMetadata(approval.Metadata); mErr == nil && meta != nil && len(meta.SelectedSystems) > 0 { - collectedForCard["systems"] = strings.Join(meta.SelectedSystems, ",") - } - - var card string - if topic != nil { - card = topic.FormatApproverMessage(initiator, collectedForCard) - } else { - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) - content := "—" - if approval.Content != nil { - content = *approval.Content - } - card = fmt.Sprintf("📋 Тема: %s\n📝 Текст: %s", topicFullName, content) - } - - var confirmMsg string - if isAnyOf { - confirmMsg = fmt.Sprintf( - "📤 Заявка #%d отправлена на согласование\n"+ - "👤 Согласует один из: %s\n\n%s", - *approval.ID, approverLine, card, - ) - } else { - confirmMsg = fmt.Sprintf( - "📤 Заявка #%d отправлена на согласование\n"+ - "👤 Согласующий: %s\n\n%s", - *approval.ID, approverLine, card, - ) - } - - msgChat := tgbotapi.NewMessage(chatID, confirmMsg) - msgChat.ParseMode = "HTML" - - approvalStatus := "pending" - if approval.Status != nil { - approvalStatus = *approval.Status - } - msgChat.ReplyMarkup = keyboard.BuildInitiatorCard(*approval.ID, approvalStatus, len(approval.Files) > 0, len(approval.Files), h.GetCommentsCount(ctx, *approval.ID)) - - bot.Send(msgChat) //nolint:errcheck -} - -// createTasksForApproval создаёт задачи для исполнителей на основе конфигурации темы -func (h *Handler) createTasksForApproval( - bot *tgbotapi.BotAPI, - ctx context.Context, - approval *typescore.Approval, - initiator *typescore.User, -) { - if approval == nil || approval.TopicID == nil { - return - } - - topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) - if topic == nil { - return - } - - topicExecutors, err := h.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, *approval.TopicID) - if err != nil { - logrus.Errorf("createTasksForApproval: GetExecutorsByTopicIDDB err=%v", err) - return - } - - if len(topicExecutors) == 0 { - logrus.Infof("createTasksForApproval: no executors configured for topicID=%d", *approval.TopicID) - return - } - - meta, _ := typescore.ParseApprovalMetadata(approval.Metadata) - systemsToProcess := meta.SelectedSystems - if len(systemsToProcess) == 0 { - systemsToProcess = []string{"all"} - } - - logrus.Infof("createTasksForApproval: topicID=%d systems=%v executors=%d", - *approval.TopicID, systemsToProcess, len(topicExecutors)) - - taskCounter := 0 - - for _, system := range systemsToProcess { - for _, topicExec := range topicExecutors { - if topicExec.UserID == nil { - continue - } - - if topicExec.TargetSystem != nil && *topicExec.TargetSystem != "all" && *topicExec.TargetSystem != system { - continue - } - - if topicExec.TaskText == nil || *topicExec.TaskText == "" { - continue - } - - executor, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *topicExec.UserID) - if executor == nil || executor.ID == nil { - continue - } - - taskText := *topicExec.TaskText - systemLabel := "" - if system != "all" && system != "" { - switch system { - case "okb": - systemLabel = "[ОКБ] " - case "1c": - systemLabel = "[1С] " - } - taskText = systemLabel + taskText - } - - taskStatus := "waiting" - if taskCounter == 0 { - taskStatus = "pending" - } - - stepOrder := taskCounter - requireFile := false - if topicExec.RequireFile != nil { - requireFile = *topicExec.RequireFile - } - - createdTask, _, err := h.ipc.Database.ApprovalTasks.CreateApprovalTaskDB(ctx, nil, &typescore.ApprovalTask{ - ApprovalID: approval.ID, - ExecutorID: executor.ID, - TaskText: &taskText, - Status: &taskStatus, - StepOrder: &stepOrder, - RequireFile: &requireFile, - TopicExecutorID: topicExec.ID, - }, true) - if err != nil { - logrus.Errorf("createTasksForApproval: CreateApprovalTask system=%s executor=%d err=%v", system, *executor.ID, err) - continue - } - - if createdTask != nil && taskStatus == "pending" && executor.TelegramID != nil { - h.notifyExecutor(bot, ctx, executor, initiator, approval, createdTask) - } - - taskCounter++ - } - } - - logrus.Infof("createTasksForApproval: created %d tasks for approvalID=%d", taskCounter, *approval.ID) -} - ------END service/telegram_service/handlers/approval/selection_approver.go----- - -File: service/telegram_service/handlers/approval/selection_first_approver.go -Lines: 185 ------BEGIN service/telegram_service/handlers/approval/selection_first_approver.go----- -package approval - -import ( - "bitrix_balancer_api/core/typescore" - "context" - "fmt" - - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" - - "bitrix_balancer_api/telegram_service/keyboard" - "bitrix_balancer_api/telegram_service/state" -) - -// showFirstApproverSelection показывает список пользователей с нужной ролью -func (h *Handler) showFirstApproverSelection( - bot *tgbotapi.BotAPI, - ctx context.Context, - chatID int64, - telegramID int64, - roleCode string, - roleLabel string, -) { - users, err := h.ipc.Database.User.GetUsersByRoleCodeDB(ctx, roleCode) - if err != nil { - logrus.Errorf("showFirstApproverSelection: GetUsersByRoleCodeDB roleCode=%s err=%v", roleCode, err) - sendText(bot, chatID, "Ошибка при получении списка пользователей.") - h.States.Clear(ctx, telegramID) //nolint:errcheck - return - } - - if len(users) == 0 { - // Пользователей с такой ролью нет — пропускаем шаг - logrus.Warnf("showFirstApproverSelection: no users with role=%s, skipping", roleCode) - flowState, err := h.States.Get(ctx, telegramID) - if err != nil || flowState == nil { - return - } - flowState.AwaitFirstApproverSelection = false - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) - return - } - - msg := tgbotapi.NewMessage(chatID, fmt.Sprintf( - "👤 Выберите %s\n\n"+ - "Этот пользователь согласует заявку первым.", - roleLabel, - )) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildFirstApproverSelectionMenu(users, 0) - bot.Send(msg) //nolint:errcheck -} - -// getRoleLabelByCode — вспомогательный метод получения названия роли -func (h *Handler) getRoleLabelByCode(ctx context.Context, roleCode string) *typescore.Role { - roleList, _, err := h.ipc.Database.Role.GetRolesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Role{ - Code: &roleCode, - }, - }) - if err != nil || roleList == nil || len(roleList) < 1 || roleList[0] == nil { - return nil - } - return roleList[0] -} - -// HandleFirstApproverSelectCallback — пользователь выбрал первого согласующего -func (h *Handler) HandleFirstApproverSelectCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, userID 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 - } - - if !flowState.AwaitFirstApproverSelection { - logrus.Warnf("HandleFirstApproverSelectCallback: not awaiting first approver, userID=%d", telegramID) - return - } - - selected, err := h.ipc.Database.User.GetUserByIDDB(ctx, userID) - if err != nil || selected == nil { - sendText(bot, chatID, "⚠️ Пользователь не найден.") - return - } - - selectedName := "выбранный пользователь" - if selected.FullName != nil { - selectedName = *selected.FullName - } - - flowState.SelectedFirstApproverID = userID - flowState.AwaitFirstApproverSelection = false - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - - sendText(bot, chatID, fmt.Sprintf("✅ Выбран первый согласующий: %s", selectedName)) - - h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState) -} - -func (h *Handler) HandleFirstApproverPageCallback(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 - - flowState, err := h.States.Get(ctx, telegramID) - if err != nil || flowState == nil || !flowState.AwaitFirstApproverSelection { - 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 || approvalTopic.FirstApproverRoleCode == nil { - return - } - - roleCode := *approvalTopic.FirstApproverRoleCode - users, err := h.ipc.Database.User.GetUsersByRoleCodeDB(ctx, roleCode) - if err != nil { - return - } - - editMsg := tgbotapi.NewEditMessageReplyMarkup( - chatID, - cq.Message.MessageID, - keyboard.BuildFirstApproverSelectionMenu(users, page), - ) - bot.Request(editMsg) //nolint:errcheck -} - -// getFirstApproverRoleForFlow возвращает тему и код роли для первого согласующего -func (h *Handler) getFirstApproverRoleForFlow( - ctx context.Context, - flowState *state.ApprovalFlowState, -) (*typescore.ApprovalTopic, string, string) { - topic, _ := h.Registry.Get(flowState.TopicCode) - if topic == nil { - return nil, "", "" - } - - topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) - approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) - if approvalTopic == nil || approvalTopic.FirstApproverRoleCode == nil { - return nil, "", "" - } - - // Получаем название роли для отображения - roleList, _, err := h.ipc.Database.Role.GetRolesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Role{ - Code: approvalTopic.FirstApproverRoleCode, - }, - }) - if err != nil { - logrus.Errorf("getFirstApproverRoleForFlow err=%v", err) - return nil, "", "" - } - if roleList == nil || len(roleList) == 0 { - logrus.Errorf("getFirstApproverRoleForFlow. Role not found err=%v", err) - return nil, "", "" - } - role := roleList[0] - if role == nil || role.Code == nil { - logrus.Errorf("getFirstApproverRoleForFlow. Role not found err=%v", err) - return nil, "", "" - } - roleLabel := *role.Code - if role.Name != nil { - roleLabel = *role.Name - } - - return approvalTopic, *role.Code, roleLabel -} - ------END service/telegram_service/handlers/approval/selection_first_approver.go----- - -File: service/telegram_service/handlers/approval/selection_observer.go -Lines: 246 ------BEGIN service/telegram_service/handlers/approval/selection_observer.go----- -package approval - -import ( - "bitrix_balancer_api/core/typescore" - "context" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" - - "bitrix_balancer_api/telegram_service/keyboard" - "bitrix_balancer_api/telegram_service/state" -) - -// showObserverSelection показывает экран выбора наблюдателей -func (h *Handler) showObserverSelection( - bot *tgbotapi.BotAPI, - ctx context.Context, - chatID int64, - telegramID int64, - flowState *state.ApprovalFlowState, - approvalTopic *typescore.ApprovalTopic, -) { - observers, err := h.getAvailableObservers(ctx) - if err != nil || len(observers) == 0 { - // Если выбор обязателен, но наблюдателей нет — блокируем создание заявки - isRequired := approvalTopic != nil && - approvalTopic.RequireObserverSelection != nil && - *approvalTopic.RequireObserverSelection - - if isRequired { - sendText(bot, chatID, - "⚠️ Для этой темы обязательно выбрать наблюдателя,\n"+ - "но в системе нет пользователей с ролью наблюдателя.\n\n"+ - "Обратитесь к администратору.") - flowState.AwaitObserverSelection = false - flowState.ObserverSelectionDone = false // не помечаем как выполненное - h.States.Set(ctx, telegramID, flowState) //nolint:errcheck - return - } - - flowState.AwaitObserverSelection = false - flowState.ObserverSelectionDone = true - h.States.Clear(ctx, telegramID) //nolint:errcheck - h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState) - return - } - - isRequired := approvalTopic != nil && - approvalTopic.RequireObserverSelection != nil && - *approvalTopic.RequireObserverSelection - - var text string - if isRequired { - text = "👁 Выберите наблюдателей для заявки\n\n" + - "⚠️ Выберите менеджера, чья это отгрузка." - } else { - text = "👁 Выберите наблюдателей для заявки\n" + - "Они получат уведомления, но не смогут влиять на решение.\n" + - "Можно выбрать несколько или пропустить." - } - - msg := tgbotapi.NewMessage(chatID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, 0, isRequired) - bot.Send(msg) //nolint:errcheck -} - -// HandleObserverToggleCallback — пользователь нажал на наблюдателя (toggle) -func (h *Handler) HandleObserverToggleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, observerID uint64) { - ctx := context.Background() - chatID := cq.Message.Chat.ID - telegramID := cq.From.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - flowState, err := h.States.Get(ctx, telegramID) - if err != nil || flowState == nil || !flowState.AwaitObserverSelection { - return - } - - found := false - newIDs := make([]uint64, 0, len(flowState.SelectedObserverIDs)) - for _, id := range flowState.SelectedObserverIDs { - if id == observerID { - found = true - } else { - newIDs = append(newIDs, id) - } - } - if !found { - newIDs = append(newIDs, observerID) - } - flowState.SelectedObserverIDs = newIDs - - if err := h.States.Set(ctx, telegramID, flowState); err != nil { - logrus.Errorf("HandleObserverToggleCallback: Set state err=%v", err) - return - } - - var approvalTopic *typescore.ApprovalTopic - if flowState.TopicCode != "" { - topic, _ := h.Registry.Get(flowState.TopicCode) - if topic != nil { - topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) - approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) - } - } - isRequired := approvalTopic != nil && - approvalTopic.RequireObserverSelection != nil && - *approvalTopic.RequireObserverSelection - - observers, _ := h.getAvailableObservers(ctx) - editMsg := tgbotapi.NewEditMessageReplyMarkup( - chatID, - cq.Message.MessageID, - keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, 0, isRequired), - ) - bot.Request(editMsg) //nolint:errcheck -} - -func (h *Handler) HandleObserverPageCallback(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 - - flowState, err := h.States.Get(ctx, telegramID) - if err != nil || flowState == nil || !flowState.AwaitObserverSelection { - return - } - - var approvalTopic *typescore.ApprovalTopic - if flowState.TopicCode != "" { - topic, _ := h.Registry.Get(flowState.TopicCode) - if topic != nil { - topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) - approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) - } - } - isRequired := approvalTopic != nil && - approvalTopic.RequireObserverSelection != nil && - *approvalTopic.RequireObserverSelection - - observers, err := h.getAvailableObservers(ctx) - if err != nil { - return - } - - editMsg := tgbotapi.NewEditMessageReplyMarkup( - chatID, - cq.Message.MessageID, - keyboard.BuildObserverSelectionMenu(observers, flowState.SelectedObserverIDs, page, isRequired), - ) - bot.Request(editMsg) //nolint:errcheck -} - -// HandleObserverConfirmCallback — пользователь подтвердил выбор наблюдателей -func (h *Handler) HandleObserverConfirmCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { - ctx := context.Background() - chatID := cq.Message.Chat.ID - telegramID := cq.From.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - flowState, err := h.States.Get(ctx, telegramID) - if err != nil || flowState == nil { - sendText(bot, chatID, "⚠️ Состояние утеряно. Начните заново.") - return - } - - var approvalTopic *typescore.ApprovalTopic - if flowState.TopicCode != "" { - topic, _ := h.Registry.Get(flowState.TopicCode) - if topic != nil { - topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected) - approvalTopic, _ = h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode) - } - } - - isRequired := approvalTopic != nil && - approvalTopic.RequireObserverSelection != nil && - *approvalTopic.RequireObserverSelection - - if isRequired && len(flowState.SelectedObserverIDs) == 0 { - bot.Request(tgbotapi.NewCallback(cq.ID, "⚠️ Выберите хотя бы одного наблюдателя")) //nolint:errcheck - return - } - - bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck - - h.States.Clear(ctx, telegramID) //nolint:errcheck - h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState) -} - -// getAvailableObservers — возвращает всех пользователей с ролью наблюдателя -func (h *Handler) getAvailableObservers(ctx context.Context) ([]*typescore.User, error) { - return h.ipc.Database.User.GetUsersByRoleCodeDB(ctx, "observer") -} - -// saveSelectedObservers сохраняет выбранных наблюдателей после создания заявки -func (h *Handler) saveSelectedObservers( - ctx context.Context, - approvalID uint64, - addedByID uint64, - observerIDs []uint64, -) { - for _, observerID := range observerIDs { - id := observerID // копия для замыкания - addedBy := addedByID - aID := approvalID - - obj := &typescore.ApprovalAdditionalObserver{ - ApprovalID: &aID, - UserID: &id, - AddedByID: &addedBy, - } - if _, _, err := h.ipc.Database.ApprovalAdditionalObserver.CreateApprovalAdditionalObserverDB(ctx, nil, obj); err != nil { - logrus.Errorf("saveSelectedObservers: err observerID=%d err=%v", id, err) - } - } -} - -// getAdditionalObserversForApproval возвращает всех дополнительных наблюдателей заявки -func (h *Handler) getAdditionalObserversForApproval(ctx context.Context, approvalID uint64) []*typescore.User { - records, _, err := h.ipc.Database.ApprovalAdditionalObserver.GetApprovalAdditionalObserversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalObserver{ - ApprovalID: &approvalID, - }, - }) - if err != nil { - logrus.Errorf("failed to get additional observers list. %v", err) - return nil - } - - var users []*typescore.User - for _, r := range records { - if r.UserID == nil { - continue - } - u, err := h.ipc.Database.User.GetUserByIDDB(ctx, *r.UserID) - if err == nil && u != nil { - users = append(users, u) - } - } - return users -} - ------END service/telegram_service/handlers/approval/selection_observer.go----- - -File: service/telegram_service/handlers/approval/topics/absence/topic.go -Lines: 91 ------BEGIN service/telegram_service/handlers/approval/topics/absence/topic.go----- -package absence - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - 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 AbsenceTopic struct { - timeoffTopic *timeoff.TimeOffTopic - vacationTopic *vacation.VacationTopic - sickleaveTopic *sickleave.SickLeaveTopic -} - -func NewAbsenceTopic() *AbsenceTopic { - return &AbsenceTopic{ - timeoffTopic: timeoff.NewTimeOffTopic(), - vacationTopic: vacation.NewVacationTopic(), - sickleaveTopic: sickleave.NewSickLeaveTopic(), - } -} - -func (a *AbsenceTopic) Code() string { return "absence" } -func (a *AbsenceTopic) Name() string { - return "Согласование отпусков/отгулов" -} - -func (a *AbsenceTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "absence", - Label: "Согласование отпусков/отгулов", - Children: []*approvalflow.FlowNode{ - { - Key: "absence_timeoff", - Label: "Отгул", - DataKey: "absence_type", - DataValue: "timeoff", - // Копируем детей из оригинального дерева timeoff - Children: a.timeoffTopic.BuildTree().Children, - }, - { - Key: "absence_vacation", - Label: "Отпуск", - DataKey: "absence_type", - DataValue: "vacation", - Children: a.vacationTopic.BuildTree().Children, - }, - { - Key: "absence_sickleave", - Label: "Официальный больничный", - DataKey: "absence_type", - DataValue: "sickleave", - Children: a.sickleaveTopic.BuildTree().Children, - }, - }, - } -} - -func (a *AbsenceTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - absenceType := collected["absence_type"] - switch absenceType { - case "timeoff": - return a.timeoffTopic.TopicCodeFromCollected(collected) - case "vacation": - return a.vacationTopic.TopicCodeFromCollected(collected) - case "sickleave": - return a.sickleaveTopic.TopicCodeFromCollected(collected) - default: - return "", fmt.Errorf("absence_type не указан в collected: %v", collected) - } -} - -func (a *AbsenceTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - switch collected["absence_type"] { - case "timeoff": - return a.timeoffTopic.FormatApproverMessage(initiator, collected) - case "vacation": - return a.vacationTopic.FormatApproverMessage(initiator, collected) - case "sickleave": - return a.sickleaveTopic.FormatApproverMessage(initiator, collected) - default: - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - return fmt.Sprintf("📋 Согласование отсутствия\n\n%s:\n%s", name, collected["content"]) - } -} - ------END service/telegram_service/handlers/approval/topics/absence/topic.go----- - -File: service/telegram_service/handlers/approval/topics/client_changes/topic.go -Lines: 149 ------BEGIN service/telegram_service/handlers/approval/topics/client_changes/topic.go----- -package clientchanges - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" - "strings" -) - -type ClientChangesTopic struct{} - -func NewClientChangesTopic() *ClientChangesTopic { - return &ClientChangesTopic{} -} - -func (c *ClientChangesTopic) Code() string { return "client_changes" } -func (c *ClientChangesTopic) Name() string { - return "Изменение клиента в ОКБ и 1С" -} - -func (c *ClientChangesTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "client_changes", - Label: "Изменение клиента", - Children: []*approvalflow.FlowNode{ - c.buildChangeType("rename", "Поменять название"), - c.buildChangeType("change_manager", "Сменить менеджера"), - c.buildChangeType("new_client", "Внести нового клиента"), - }, - } -} - -func (c *ClientChangesTopic) buildChangeType(changeKey, changeLabel string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: changeKey, - Label: changeLabel, - DataKey: "change_type", - DataValue: changeKey, - Children: []*approvalflow.FlowNode{ - c.buildRegion(changeKey, "crimea", "Крым"), - c.buildRegion(changeKey, "krasnodar", "Краснодар"), - }, - } -} - -func (c *ClientChangesTopic) buildRegion(changeKey, regionKey, regionLabel string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: changeKey + "_" + regionKey, - Label: regionLabel, - DataKey: "region", - DataValue: regionKey, - Children: []*approvalflow.FlowNode{ - { - Key: changeKey + "_" + regionKey + "_okb", - IsMultiSelect: true, - MultiSelectKey: "systems", - MultiSelectValue: "okb", - Label: "ОКБ", - Children: []*approvalflow.FlowNode{ - { - Key: changeKey + "_" + regionKey + "_okb_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите изменения: текущие данные → новые данные", - }, - }, - }, - { - Key: changeKey + "_" + regionKey + "_1c", - IsMultiSelect: true, - MultiSelectKey: "systems", - MultiSelectValue: "1c", - Label: "1С", - Children: []*approvalflow.FlowNode{ - { - Key: changeKey + "_" + regionKey + "_1c_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите изменения: текущие данные → новые данные", - }, - }, - }, - }, - } -} - -func (c *ClientChangesTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - changeType := collected["change_type"] - region := collected["region"] - - if changeType == "" || region == "" { - return "", fmt.Errorf("неполные данные: change_type=%s, region=%s", changeType, region) - } - - return fmt.Sprintf("client_changes_%s_%s", changeType, region), nil -} - -func (c *ClientChangesTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - - var changeLabel string - switch collected["change_type"] { - case "rename": - changeLabel = "Поменять название" - case "change_manager": - changeLabel = "Сменить менеджера" - case "new_client": - changeLabel = "Внести нового клиента" - default: - changeLabel = "Изменение клиента" - } - - regionLabel := "—" - switch collected["region"] { - case "crimea": - regionLabel = "Крым" - case "krasnodar": - regionLabel = "Краснодар" - } - - var systemLabels []string - systems := collected["systems"] - if systems != "" { - for _, s := range strings.Split(systems, ",") { - switch strings.TrimSpace(s) { - case "okb": - systemLabels = append(systemLabels, "ОКБ") - case "1c": - systemLabels = append(systemLabels, "1С") - } - } - } - - systemsStr := "не указаны" - if len(systemLabels) > 0 { - systemsStr = strings.Join(systemLabels, ", ") - } - - return fmt.Sprintf( - "📋 Изменение клиентов в ОКБ и 1С: – %s\n"+ - "🖥 Системы: %s\n"+ - "📍 Регион: %s\n\n"+ - "%s:\n%s", - changeLabel, systemsStr, regionLabel, name, collected["content"], - ) -} - ------END service/telegram_service/handlers/approval/topics/client_changes/topic.go----- - -File: service/telegram_service/handlers/approval/topics/dealautoapproval/topic.go -Lines: 92 ------BEGIN service/telegram_service/handlers/approval/topics/dealautoapproval/topic.go----- -package dealautoapproval - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type DealAutoApprovalTopic struct{} - -func NewDealAutoApprovalTopic() *DealAutoApprovalTopic { return &DealAutoApprovalTopic{} } - -func (d *DealAutoApprovalTopic) Code() string { return "deal_auto_approval_conditions" } -func (d *DealAutoApprovalTopic) Name() string { - return "Смена условий автосогласования сделок" -} - -func (d *DealAutoApprovalTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "deal_auto_approval_conditions", - Label: "Смена условий автосогласования сделок", - Children: []*approvalflow.FlowNode{ - { - Key: "receivable_limit_vladimir", Label: "📈 Повысить лимит ДЗ (Владимир)", - DataKey: "condition_type", DataValue: "receivable_limit_vladimir", - Children: []*approvalflow.FlowNode{ - { - Key: "receivable_limit_vladimir_input", - IsInput: true, - InputKey: "content", - InputHint: "Прошу повысить лимит дебиторской задолженности клиенту ___ до ___ руб. Основание: ___", - }, - }, - }, - { - Key: "document_limits", Label: "📄 Расширить лимиты по документам", - DataKey: "condition_type", DataValue: "document_limits", - Children: []*approvalflow.FlowNode{ - { - Key: "document_limits_input", - IsInput: true, - InputKey: "content", - InputHint: "Прошу увеличить: кол-во возможных долгов по документам до ___, сумму документов до ___ руб., кол-во дней просрочки оплаты до ___", - }, - }, - }, - }, - } -} - -func (d *DealAutoApprovalTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - conditionType := collected["condition_type"] - if conditionType == "" { - return "", fmt.Errorf("неполные данные: condition_type пуст") - } - - switch conditionType { - case "receivable_limit_vladimir": - return "deal_auto_approval_receivable_limit_vladimir", nil - case "document_limits": - return "deal_auto_approval_document_limits", nil - default: - return "", fmt.Errorf("неизвестный condition_type: %s", conditionType) - } -} - -func (d *DealAutoApprovalTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "—" - if initiator != nil && initiator.FullName != nil { - name = *initiator.FullName - } - - var typeLabel string - switch collected["condition_type"] { - case "receivable_limit_vladimir": - typeLabel = "Повышение лимита ДЗ (от Владимира лично)" - case "document_limits": - typeLabel = "Расширение лимитов по документам и просрочке" - default: - typeLabel = "Смена условий автосогласования сделок" - } - - content := "—" - if collected["content"] != "" { - content = collected["content"] - } - - return fmt.Sprintf( - "📋 Смена условий автосогласования сделок - %s\n\n👤 Инициатор: %s\n📝 Текст:\n%s", - typeLabel, name, content, - ) -} - ------END service/telegram_service/handlers/approval/topics/dealautoapproval/topic.go----- - -File: service/telegram_service/handlers/approval/topics/deliveryclients/topic.go -Lines: 113 ------BEGIN service/telegram_service/handlers/approval/topics/deliveryclients/topic.go----- -package deliveryclients - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type DeliveryClientsTopic struct{} - -func NewDeliveryClientsTopic() *DeliveryClientsTopic { return &DeliveryClientsTopic{} } - -func (d *DeliveryClientsTopic) Code() string { return "delivery_clients" } -func (d *DeliveryClientsTopic) Name() string { - return "Доставка клиентам/на склад" -} - -func (d *DeliveryClientsTopic) BuildTree() *approvalflow.FlowNode { - directHint := "Иванов Иван Иванович\nТел 89781234567\nПаспорт 1234 567890\nДАФ н862нн46 п/п АА8473|46\n\n61 бц с ад - 52 кор\nЧП000001676\n\nЕПР-СтройКрым" - warehouseHint := "Иванов Иван Иванович\nТел 89781234567\nПаспорт 1234 567890\n61 бц с ад - 52 кор\nЧП000001676" - - return &approvalflow.FlowNode{ - Key: "delivery_clients", - Label: "Доставка клиентам/на склад", - Children: []*approvalflow.FlowNode{ - { - Key: "direct", Label: "Напрямую клиенту", - DataKey: "delivery_type", DataValue: "direct", - Children: []*approvalflow.FlowNode{ - { - Key: "direct_input", - IsInput: true, - InputKey: "content", - InputHint: directHint, - }, - }, - }, - { - Key: "warehouse", Label: "На склад", - DataKey: "delivery_type", DataValue: "warehouse", - Children: []*approvalflow.FlowNode{ - d.buildRegion("warehouse", "crimea", "Крым", warehouseHint), - d.buildRegion("warehouse", "krasnodar", "Краснодар", warehouseHint), - }, - }, - }, - } -} - -func (d *DeliveryClientsTopic) buildRegion(parentKey, regionKey, regionLabel, hint string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: parentKey + "_" + regionKey, - Label: regionLabel, - DataKey: "region", - DataValue: regionKey, - Children: []*approvalflow.FlowNode{ - { - Key: parentKey + "_" + regionKey + "_input", - IsInput: true, - InputKey: "content", - InputHint: hint, - }, - }, - } -} - -func (d *DeliveryClientsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - deliveryType := collected["delivery_type"] - if deliveryType == "" { - return "", fmt.Errorf("неполные данные: delivery_type пуст") - } - - if deliveryType == "direct" { - return "delivery_clients_direct", nil - } - - region := collected["region"] - if region == "" { - return "", fmt.Errorf("неполные данные: region пуст") - } - return fmt.Sprintf("delivery_clients_warehouse_%s", region), nil -} - -func (d *DeliveryClientsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "—" - if initiator != nil && initiator.FullName != nil { - name = *initiator.FullName - } - - var label string - if collected["delivery_type"] == "direct" { - label = "Доставка: Напрямую клиенту" - } else { - regionLabel := "—" - switch collected["region"] { - case "crimea": - regionLabel = "Крым" - case "krasnodar": - regionLabel = "Краснодар" - } - label = fmt.Sprintf("Доставка: На склад, %s", regionLabel) - } - - content := "—" - if collected["content"] != "" { - content = collected["content"] - } - - return fmt.Sprintf( - "📋 %s\n\n👤 Инициатор: %s\n📝 Текст:\n%s", - label, name, content, - ) -} - ------END service/telegram_service/handlers/approval/topics/deliveryclients/topic.go----- - -File: service/telegram_service/handlers/approval/topics/free/topic.go -Lines: 75 ------BEGIN service/telegram_service/handlers/approval/topics/free/topic.go----- -package free - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -// FreeTopic — тема с единственным шагом: свободный текстовый ввод. -// Подходит для всех тем без разветвлённой логики. -type FreeTopic struct { - code string - name string - template string -} - -func NewFreeTopic(code, name, template string) *FreeTopic { - return &FreeTopic{ - code: code, - name: name, - template: template, - } -} - -func (o *FreeTopic) Code() string { return o.code } -func (o *FreeTopic) Name() string { return o.name } - -func (o *FreeTopic) BuildTree() *approvalflow.FlowNode { - tmp := "Напишите текст согласования" - if o.template != "" { - tmp = o.template - } - return &approvalflow.FlowNode{ - Key: o.code, - Label: o.name, - Children: []*approvalflow.FlowNode{ - { - Key: o.code + "_input", - IsInput: true, - InputKey: "content", - InputHint: tmp, - }, - }, - } -} - -func (o *FreeTopic) TopicCodeFromCollected(_ map[string]string) (string, error) { - return o.code, nil -} - -func (t *FreeTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - initiatorName := "—" - if initiator != nil && initiator.FullName != nil { - initiatorName = *initiator.FullName - } - - content := collected["content"] - if content == "" { - content = "—" - } - - text := fmt.Sprintf( - "📋 Заявка на согласование\n\n"+ - "👤 От: %s\n"+ - "📂 Тема: %s\n"+ - "📝 Текст:\n%s", - initiatorName, t.Name(), content, - ) - - if instructions, ok := collected["instructions"]; ok && instructions != "" { - text += fmt.Sprintf("\n\n💡 Инструкция:\n%s", instructions) - } - - return text -} - ------END service/telegram_service/handlers/approval/topics/free/topic.go----- - -File: service/telegram_service/handlers/approval/topics/goods_order/topic.go -Lines: 108 ------BEGIN service/telegram_service/handlers/approval/topics/goods_order/topic.go----- -package goodsorder - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type GoodsOrderTopic struct{} - -func NewGoodsOrderTopic() *GoodsOrderTopic { - return &GoodsOrderTopic{} -} - -func (g *GoodsOrderTopic) Code() string { return "goods_order" } -func (g *GoodsOrderTopic) Name() string { return "Заказ товаров" } - -func (g *GoodsOrderTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "goods_order", - Label: "Заказ товаров", - Children: []*approvalflow.FlowNode{ - { - Key: "monthly", - Label: "На месяц", - DataKey: "order_type", - DataValue: "monthly", - Children: g.buildRegions("monthly"), - }, - { - Key: "additional", - Label: "Дополнительный заказ", - DataKey: "order_type", - DataValue: "additional", - Children: g.buildRegions("additional"), - }, - }, - } -} - -func (g *GoodsOrderTopic) buildRegions(orderType string) []*approvalflow.FlowNode { - return []*approvalflow.FlowNode{ - { - Key: orderType + "_crimea", - Label: "Крым", - DataKey: "region", - DataValue: "crimea", - Children: []*approvalflow.FlowNode{{ - Key: orderType + "_crimea_input", - IsInput: true, - InputKey: "content", - InputHint: "Скилур заказ:\n22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.\nф1, на склад Гвардейское, 2я декада.", - }}, - }, - { - Key: orderType + "_krasnodar", - Label: "Краснодар", - DataKey: "region", - DataValue: "krasnodar", - Children: []*approvalflow.FlowNode{{ - Key: orderType + "_krasnodar_input", - IsInput: true, - InputKey: "content", - InputHint: "Скилур заказ:\n22 гр.38 мм бесцветная (10176) ЕПМ - 5кор.\nф1, на склад Гвардейское, 2я декада.", - }}, - }, - } -} - -func (g *GoodsOrderTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - orderType := collected["order_type"] - region := collected["region"] - if orderType == "" { - return "", fmt.Errorf("order_type не указан") - } - // region опционален для обратной совместимости - if region != "" { - return fmt.Sprintf("goods_order_%s_%s", orderType, region), nil - } - return fmt.Sprintf("goods_order_%s", orderType), nil -} - -func (g *GoodsOrderTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - - typeLabel := "На месяц" - if collected["order_type"] == "additional" { - typeLabel = "Дополнительный заказ" - } - - regionLabel := "—" - switch collected["region"] { - case "crimea": - regionLabel = "Крым" - case "krasnodar": - regionLabel = "Краснодар" - } - - return fmt.Sprintf( - "📋 Заказ товаров — %s\n"+ - "📍 Регион: %s\n\n"+ - "%s:\n%s", - typeLabel, regionLabel, name, collected["content"], - ) -} - ------END service/telegram_service/handlers/approval/topics/goods_order/topic.go----- - -File: service/telegram_service/handlers/approval/topics/inventory/topic.go -Lines: 111 ------BEGIN service/telegram_service/handlers/approval/topics/inventory/topic.go----- -package inventory - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type InventoryTopic struct{} - -func NewInventoryTopic() *InventoryTopic { return &InventoryTopic{} } - -func (i *InventoryTopic) Code() string { return "inventory" } -func (i *InventoryTopic) Name() string { return "Инвентаризация" } - -func (i *InventoryTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "inventory", - Label: "Инвентаризация", - Children: []*approvalflow.FlowNode{ - { - Key: "crimea", Label: "Крым", - DataKey: "region", DataValue: "crimea", - Children: []*approvalflow.FlowNode{ - i.buildLocation("crimea", "19l", "19л"), - i.buildLocation("crimea", "gvardeyskoe", "Гвардейское"), - }, - }, - { - // Краснодар без развилки — сразу ввод - Key: "krasnodar", Label: "Краснодар", - DataKey: "region", DataValue: "krasnodar", - Children: []*approvalflow.FlowNode{ - { - Key: "krasnodar_input", - IsInput: true, - InputKey: "content", - InputHint: "Прошу согласовать проведение инвентаризации по складу (Наименование склада\\Филиал склада) 25.06.2026, 27.06.2026. \nШироков Михаил, Жеребцов Виктор", - }, - }, - }, - }, - } -} - -func (i *InventoryTopic) buildLocation(regionKey, locKey, locLabel string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: regionKey + "_" + locKey, - Label: locLabel, - DataKey: "location", - DataValue: locKey, - Children: []*approvalflow.FlowNode{ - { - Key: regionKey + "_" + locKey + "_input", - IsInput: true, - InputKey: "content", - InputHint: "Прошу согласовать проведение инвентаризации по складу (Наименование склада\\Филиал склада) 25.06.2026, 27.06.2026. \nХалилов Дамур, Анисимов Виталий, Романов Александр", - }, - }, - } -} - -func (i *InventoryTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - region := collected["region"] - if region == "" { - return "", fmt.Errorf("неполные данные: region пуст") - } - - if region == "krasnodar" { - return "inventory_krasnodar", nil - } - - location := collected["location"] - if location == "" { - return "", fmt.Errorf("неполные данные: location пуст") - } - return fmt.Sprintf("inventory_%s_%s", region, location), nil -} - -func (i *InventoryTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "—" - if initiator != nil && initiator.FullName != nil { - name = *initiator.FullName - } - - regionLabel := "—" - switch collected["region"] { - case "crimea": - regionLabel = "Крым" - case "krasnodar": - regionLabel = "Краснодар" - } - - locationLabel := "" - switch collected["location"] { - case "19l": - locationLabel = ", 19л" - case "gvardeyskoe": - locationLabel = ", Гвардейское" - } - - content := "—" - if collected["content"] != "" { - content = collected["content"] - } - - return fmt.Sprintf( - "📋 Инвентаризация: %s%s\n\n👤 Инициатор: %s\n📝 Текст:\n%s", - regionLabel, locationLabel, name, content, - ) -} - ------END service/telegram_service/handlers/approval/topics/inventory/topic.go----- - -File: service/telegram_service/handlers/approval/topics/manager_expenses/topic.go -Lines: 70 ------BEGIN service/telegram_service/handlers/approval/topics/manager_expenses/topic.go----- -package managerexpenses - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type ManagerExpensesTopic struct{} - -func NewManagerExpensesTopic() *ManagerExpensesTopic { return &ManagerExpensesTopic{} } - -func (s *ManagerExpensesTopic) Code() string { return "manager_expenses" } -func (s *ManagerExpensesTopic) Name() string { return "Менеджерские расходы" } - -func (s *ManagerExpensesTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "manager_expenses", - Label: "Менеджерские расходы", - Children: []*approvalflow.FlowNode{ - s.buildRegion("crimea", "Крым"), - s.buildRegion("krasnodar", "Краснодар"), - }, - } -} - -func (s *ManagerExpensesTopic) buildRegion(regionKey, regionLabel string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: regionKey, - Label: regionLabel, - DataKey: "region", - DataValue: regionKey, - Children: []*approvalflow.FlowNode{ - { - Key: regionKey + "_input", - IsInput: true, - InputKey: "content", - InputHint: "Оплата платной дороги Краснодар-Темрюк-Краснодар в сумме 1420 руб. (клиент РУСМолоко) (расход Макаренко)", - }, - }, - } -} - -func (s *ManagerExpensesTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - region := collected["region"] - if region == "" { - return "", fmt.Errorf("неполные данные: region пуст") - } - return fmt.Sprintf("manager_expenses_%s", region), nil -} - -func (s *ManagerExpensesTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - - regionLabel := collected["region"] - switch regionLabel { - case "crimea": - regionLabel = "Крым" - case "krasnodar": - regionLabel = "Краснодар" - } - - return fmt.Sprintf( - "📋 Менеджерские расходы — %s\n\n%s:\n%s", - regionLabel, name, collected["content"], - ) -} - ------END service/telegram_service/handlers/approval/topics/manager_expenses/topic.go----- - -File: service/telegram_service/handlers/approval/topics/non_budget_expenses/topic.go -Lines: 125 ------BEGIN service/telegram_service/handlers/approval/topics/non_budget_expenses/topic.go----- -package nonbudgetexpenses - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type NonBudgetExpensesTopic struct{} - -func NewNonBudgetExpensesTopic() *NonBudgetExpensesTopic { - return &NonBudgetExpensesTopic{} -} - -func (n *NonBudgetExpensesTopic) Code() string { return "non_budget_expenses" } -func (n *NonBudgetExpensesTopic) Name() string { return "Внебюджетные расходы" } - -func (n *NonBudgetExpensesTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "non_budget_expenses", - Label: "Внебюджетные расходы", - Children: []*approvalflow.FlowNode{ - { - Key: "f1", Label: "Ф1", - DataKey: "branch", DataValue: "f1", - Children: []*approvalflow.FlowNode{ - // 🚀 Ф1 — с развилкой ПП (разные подтемы) - n.buildExpenseTypeWithPP("f1_tmc", "tmc", "ТМЦ", - "Прошу согласовать и оплатить Счет от ООО Интернет Решения (Озон) за ноутбук и мышь для закупщика в сумме 31 335 руб. С НДС"), - n.buildExpenseTypeWithPP("f1_expense", "expense", "Расход", - "Прошу оплатить счет ИП Гулякина на сумму 3180,00 руб (без НДС) за продление 1С-Отчетность на 1 год"), - }, - }, - { - Key: "f2", Label: "Ф2", - DataKey: "branch", DataValue: "f2", - Children: []*approvalflow.FlowNode{ - // Ф2 — без развилки ПП (одна подтема) - n.buildExpenseTypeSimple("f2_tmc", "tmc", "ТМЦ", - "Прошу согласовать и оплатить Счет от ООО Интернет Решения (Озон) за ноутбук и мышь для закупщика в сумме 31 335 руб. С НДС"), - n.buildExpenseTypeSimple("f2_expense", "expense", "Расход", - "Прошу оплатить счет ИП Гулякина на сумму 3180,00 руб (без НДС) за продление 1С-Отчетность на 1 год"), - }, - }, - }, - } -} - -// buildExpenseTypeWithPP создаёт узел с выбором "Нужна ПП" / "Не нужна ПП" -// Каждый выбор ведёт к СВОЕЙ подтеме -func (n *NonBudgetExpensesTopic) buildExpenseTypeWithPP(key, typeVal, label, hint string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: key, Label: label, - DataKey: "expense_type", DataValue: typeVal, - Children: []*approvalflow.FlowNode{ - { - Key: key + "_pp_yes", Label: "✅ Нужна ПП", - DataKey: "pp_required", DataValue: "yes", - Children: []*approvalflow.FlowNode{{ - Key: key + "_pp_yes_input", IsInput: true, - InputKey: "content", InputHint: hint, - }}, - }, - { - Key: key + "_pp_no", Label: "❌ Не нужна ПП", - DataKey: "pp_required", DataValue: "no", - Children: []*approvalflow.FlowNode{{ - Key: key + "_pp_no_input", IsInput: true, - InputKey: "content", InputHint: hint, - }}, - }, - }, - } -} - -func (n *NonBudgetExpensesTopic) buildExpenseTypeSimple(key, typeVal, label, hint string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: key, Label: label, - DataKey: "expense_type", DataValue: typeVal, - Children: []*approvalflow.FlowNode{{ - Key: key + "_input", IsInput: true, - InputKey: "content", InputHint: hint, - }}, - } -} - -// 🚀 TopicCodeFromCollected теперь включает pp_required в код темы -func (n *NonBudgetExpensesTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - branch := collected["branch"] - expenseType := collected["expense_type"] - ppRequired := collected["pp_required"] - - if branch == "" || expenseType == "" { - return "", fmt.Errorf("неполные данные: branch=%s, expense_type=%s", branch, expenseType) - } - - // 🚀 Если pp_required указан — добавляем его в код темы - if ppRequired != "" { - return fmt.Sprintf("non_budget_expenses_%s_%s_pp_%s", branch, expenseType, ppRequired), nil - } - // Для Ф2 (без ПП) — старый формат - return fmt.Sprintf("non_budget_expenses_%s_%s", branch, expenseType), nil -} - -func (n *NonBudgetExpensesTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - - branchLabel := map[string]string{"f1": "Ф1", "f2": "Ф2"}[collected["branch"]] - typeLabel := map[string]string{"tmc": "ТМЦ", "expense": "Расход"}[collected["expense_type"]] - - // 🚀 Информация о ПП теперь в названии темы, не дублируем - ppLine := "" - if pp := collected["pp_required"]; pp != "" { - ppLabel := map[string]string{"yes": "✅ Нужна ПП", "no": "❌ Не нужна ПП"}[pp] - ppLine = fmt.Sprintf("\n💳 ПП: %s", ppLabel) - } - - return fmt.Sprintf( - "📋 Внебюджетные расходы — %s (%s)%s\n\n%s:\n%s", - branchLabel, typeLabel, ppLine, name, collected["content"], - ) -} - ------END service/telegram_service/handlers/approval/topics/non_budget_expenses/topic.go----- - -File: service/telegram_service/handlers/approval/topics/non_budget_expenses_pet_line/topic.go -Lines: 135 ------BEGIN service/telegram_service/handlers/approval/topics/non_budget_expenses_pet_line/topic.go----- -package nonbudgetexpensespetline - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type NonBudgetExpensesPetLineTopic struct{} - -func NewNonBudgetExpensesPetLineTopic() *NonBudgetExpensesPetLineTopic { - return &NonBudgetExpensesPetLineTopic{} -} - -func (n *NonBudgetExpensesPetLineTopic) Code() string { return "non_budget_expenses_pet_line" } -func (n *NonBudgetExpensesPetLineTopic) Name() string { - return "Внебюджетные расходы ПЭТ Лайн" -} - -func (n *NonBudgetExpensesPetLineTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "non_budget_expenses_pet_line", - Label: "Внебюджетные расходы ПЭТ Лайн", - Children: []*approvalflow.FlowNode{ - { - Key: "f1", - Label: "Ф1", - DataKey: "branch", - DataValue: "f1", - Children: []*approvalflow.FlowNode{ - { - Key: "f1_tmc", - Label: "ТМЦ", - DataKey: "expense_type", - DataValue: "tmc", - Children: []*approvalflow.FlowNode{ - { - Key: "f1_tmc_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите расход ТМЦ ПЭТ Лайн: наименование, количество, сумма", - }, - }, - }, - { - Key: "f1_expense", - Label: "Расход", - DataKey: "expense_type", - DataValue: "expense", - Children: []*approvalflow.FlowNode{ - { - Key: "f1_expense_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите расход ПЭТ Лайн: назначение, сумма, детали", - }, - }, - }, - }, - }, - { - Key: "f2", - Label: "Ф2", - DataKey: "branch", - DataValue: "f2", - Children: []*approvalflow.FlowNode{ - { - Key: "f2_tmc", - Label: "ТМЦ", - DataKey: "expense_type", - DataValue: "tmc", - Children: []*approvalflow.FlowNode{ - { - Key: "f2_tmc_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите расход ТМЦ ПЭТ Лайн: наименование, количество, сумма", - }, - }, - }, - { - Key: "f2_expense", - Label: "Расход", - DataKey: "expense_type", - DataValue: "expense", - Children: []*approvalflow.FlowNode{ - { - Key: "f2_expense_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите расход ПЭТ Лайн: назначение, сумма, детали", - }, - }, - }, - }, - }, - }, - } -} - -func (n *NonBudgetExpensesPetLineTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - branch := collected["branch"] - expenseType := collected["expense_type"] - - if branch == "" || expenseType == "" { - return "", fmt.Errorf("неполные данные: branch=%s, expense_type=%s", branch, expenseType) - } - - return fmt.Sprintf("non_budget_expenses_pet_line_%s_%s", branch, expenseType), nil -} - -func (n *NonBudgetExpensesPetLineTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - - branchLabel := collected["branch"] - if branchLabel == "f1" { - branchLabel = "Ф1" - } else if branchLabel == "f2" { - branchLabel = "Ф2" - } - - typeLabel := "Расход" - if collected["expense_type"] == "tmc" { - typeLabel = "ТМЦ" - } - - return fmt.Sprintf( - "📋 Внебюджетные расходы ПЭТ Лайн — %s (%s)\n\n"+ - "%s:\n%s", - branchLabel, typeLabel, name, collected["content"], - ) -} - ------END service/telegram_service/handlers/approval/topics/non_budget_expenses_pet_line/topic.go----- - -File: service/telegram_service/handlers/approval/topics/nonstandard_contract/topic.go -Lines: 75 ------BEGIN service/telegram_service/handlers/approval/topics/nonstandard_contract/topic.go----- -package nonstandardcontract - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type NonstandardContractTopic struct{} - -func NewNonstandardContractTopic() *NonstandardContractTopic { return &NonstandardContractTopic{} } - -func (s *NonstandardContractTopic) Code() string { return "nonstandard_contract" } -func (s *NonstandardContractTopic) Name() string { - return "Нестандартные условия договора поставки" -} - -func (s *NonstandardContractTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "nonstandard_contract", - Label: "Нестандартные условия договора поставки", - Children: []*approvalflow.FlowNode{ - s.buildRegion("crimea", "Крым"), - s.buildRegion("krasnodar", "Краснодар"), - s.buildRegion("belarus", "Беларусь"), - }, - } -} - -func (s *NonstandardContractTopic) buildRegion(regionKey, regionLabel string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: regionKey, - Label: regionLabel, - DataKey: "region", - DataValue: regionKey, - Children: []*approvalflow.FlowNode{ - { - Key: regionKey + "_input", - IsInput: true, - InputKey: "content", - InputHint: "Прошу согласовать отсрочку 21 день для клиента ООО Роса (другое юрлицо ООО Аквариум) (менеджер Петров)", - }, - }, - } -} - -func (s *NonstandardContractTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - region := collected["region"] - if region == "" { - return "", fmt.Errorf("неполные данные: region пуст") - } - return fmt.Sprintf("nonstandard_contract_%s", region), nil -} - -func (s *NonstandardContractTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - - regionLabel := collected["region"] - switch regionLabel { - case "crimea": - regionLabel = "Крым" - case "krasnodar": - regionLabel = "Краснодар" - case "belarus": - regionLabel = "Беларусь" - } - - return fmt.Sprintf( - "📋 Нестандартные условия договора поставки — %s\n\n%s:\n%s", - regionLabel, name, collected["content"], - ) -} - ------END service/telegram_service/handlers/approval/topics/nonstandard_contract/topic.go----- - -File: service/telegram_service/handlers/approval/topics/otk_conditions/topic.go -Lines: 82 ------BEGIN service/telegram_service/handlers/approval/topics/otk_conditions/topic.go----- -package otkconditions - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type OtkConditionsTopic struct{} - -func NewOtkConditionsTopic() *OtkConditionsTopic { return &OtkConditionsTopic{} } - -func (s *OtkConditionsTopic) Code() string { return "otk_conditions" } -func (s *OtkConditionsTopic) Name() string { return "Долгосрочные условия ОТК" } - -func (s *OtkConditionsTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "otk_conditions", - Label: "Долгосрочные условия ОТК", - Children: []*approvalflow.FlowNode{ - s.buildRegion("crimea", "Крым"), - s.buildRegion("krasnodar", "Краснодар"), - s.buildRegion("belarus", "Беларусь"), - }, - } -} - -func (s *OtkConditionsTopic) buildRegion(regionKey, regionLabel string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: regionKey, - Label: regionLabel, - DataKey: "region", - DataValue: regionKey, - Children: []*approvalflow.FlowNode{ - { - Key: regionKey + "_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите долгосрочные условия ОТК", - }, - }, - } -} - -func (s *OtkConditionsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - region := collected["region"] - if region == "" { - return "", fmt.Errorf("неполные данные: region пуст") - } - return fmt.Sprintf("otk_conditions_%s", region), nil -} - -func (s *OtkConditionsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "—" - if initiator != nil && initiator.FullName != nil { - name = *initiator.FullName - } - - regionLabel := "—" - if collected != nil { - switch collected["region"] { - case "crimea": - regionLabel = "Крым" - case "krasnodar": - regionLabel = "Краснодар" - case "belarus": - regionLabel = "Беларусь" - } - } - - content := "—" - if collected != nil && collected["content"] != "" { - content = collected["content"] - } - - return fmt.Sprintf( - "📋 Долгосрочные условия ОТК — %s\n\n"+ - "👤 Инициатор: %s\n"+ - "📝 Текст:\n%s", - regionLabel, name, content, - ) -} - ------END service/telegram_service/handlers/approval/topics/otk_conditions/topic.go----- - -File: service/telegram_service/handlers/approval/topics/payments_cashless/topic.go -Lines: 90 ------BEGIN service/telegram_service/handlers/approval/topics/payments_cashless/topic.go----- -package paymentscashless - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type PaymentsCashlessTopic struct{} - -func NewPaymentsCashlessTopic() *PaymentsCashlessTopic { return &PaymentsCashlessTopic{} } - -func (p *PaymentsCashlessTopic) Code() string { return "payments_cashless" } -func (p *PaymentsCashlessTopic) Name() string { - return "Утверждение оплат безнал" -} - -func (p *PaymentsCashlessTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "payments_cashless", - Label: "Утверждение оплат безнал", - Children: []*approvalflow.FlowNode{ - p.buildCategoryWithPP("goods", "Товар", - "Счет 2838 от 12.05.2026 от ООО Упаковка на сумму 2 464 700,16 руб."), - p.buildCategoryWithPP("misc", "Разное", - "Счет 2838 от 12.05.2026 от ООО Упаковка на сумму 2 464 700,16 руб."), - }, - } -} - -func (p *PaymentsCashlessTopic) buildCategoryWithPP(key, label, hint string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: key, Label: label, - DataKey: "payment_category", DataValue: key, - Children: []*approvalflow.FlowNode{ - { - Key: key + "_pp_yes", Label: "✅ Нужна ПП", - DataKey: "pp_required", DataValue: "yes", - Children: []*approvalflow.FlowNode{{ - Key: key + "_pp_yes_input", IsInput: true, - InputKey: "content", InputHint: hint, - }}, - }, - { - Key: key + "_pp_no", Label: "❌ Не нужна ПП", - DataKey: "pp_required", DataValue: "no", - Children: []*approvalflow.FlowNode{{ - Key: key + "_pp_no_input", IsInput: true, - InputKey: "content", InputHint: hint, - }}, - }, - }, - } -} - -// 🚀 TopicCodeFromCollected теперь включает pp_required в код темы -func (p *PaymentsCashlessTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - cat := collected["payment_category"] - ppRequired := collected["pp_required"] - - if cat == "" { - return "", fmt.Errorf("payment_category не указан") - } - - // 🚀 Если pp_required указан — добавляем его в код темы - if ppRequired != "" { - return fmt.Sprintf("payments_cashless_%s_pp_%s", cat, ppRequired), nil - } - return fmt.Sprintf("payments_cashless_%s", cat), nil -} - -func (p *PaymentsCashlessTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - - catLabel := map[string]string{"goods": "Товар", "misc": "Разное"}[collected["payment_category"]] - - ppLine := "" - if pp := collected["pp_required"]; pp != "" { - ppLabel := map[string]string{"yes": "✅ Нужна ПП", "no": "❌ Не нужна ПП"}[pp] - ppLine = fmt.Sprintf("\n💳 ПП: %s", ppLabel) - } - - return fmt.Sprintf( - "📋 Утверждение оплат безнал — %s%s\n\n%s:\n%s", - catLabel, ppLine, name, collected["content"], - ) -} - ------END service/telegram_service/handlers/approval/topics/payments_cashless/topic.go----- - -File: service/telegram_service/handlers/approval/topics/rates_logistics/topic.go -Lines: 100 ------BEGIN service/telegram_service/handlers/approval/topics/rates_logistics/topic.go----- -package rateslogistics - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type RatesLogisticsTopic struct{} - -func NewRatesLogisticsTopic() *RatesLogisticsTopic { - return &RatesLogisticsTopic{} -} - -func (r *RatesLogisticsTopic) Code() string { return "rates_logistics" } -func (r *RatesLogisticsTopic) Name() string { - return "Утверждение ставок логистики" -} - -func (r *RatesLogisticsTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "rates_logistics", - Label: "Утверждение ставок логистики", - Children: []*approvalflow.FlowNode{ - { - Key: "once", - Label: "Разово", - DataKey: "rate_type", - DataValue: "once", - Children: []*approvalflow.FlowNode{ - { - Key: "once_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите разовые ставки: маршрут, стоимость, срок", - }, - }, - }, - { - Key: "long_term", - Label: "Надолго", - DataKey: "rate_type", - DataValue: "long_term", - Children: []*approvalflow.FlowNode{ - { - Key: "long_term_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите долгосрочные ставки: маршрут, стоимость, период", - }, - }, - }, - { - Key: "once_head_approval", - Label: "Разово согласовать с рук. отдела логистики", - DataKey: "rate_type", - DataValue: "once_head_approval", - Children: []*approvalflow.FlowNode{ - { - Key: "once_head_approval_input", - IsInput: true, - InputKey: "content", - InputHint: "№ПП из таблицы транспорт и доставка клиенту\nНаправление\nЦена", - }, - }, - }, - }, - } -} - -func (r *RatesLogisticsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - rateType := collected["rate_type"] - if rateType == "" { - return "", fmt.Errorf("rate_type не указан") - } - return fmt.Sprintf("rates_logistics_%s", rateType), nil -} - -func (r *RatesLogisticsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - - var typeLabel string - switch collected["rate_type"] { - case "long_term": - typeLabel = "Надолго" - case "once_head_approval": - typeLabel = "Разово (с рук. отдела логистики)" - default: - typeLabel = "Разово" - } - - return fmt.Sprintf( - "📋 Утверждение ставок логистики — %s\n\n"+ - "%s:\n%s", - typeLabel, name, collected["content"], - ) -} - ------END service/telegram_service/handlers/approval/topics/rates_logistics/topic.go----- - -File: service/telegram_service/handlers/approval/topics/receipts/topic.go -Lines: 81 ------BEGIN service/telegram_service/handlers/approval/topics/receipts/topic.go----- -package receipts - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type ReceiptsTopic struct{} - -func NewReceiptsTopic() *ReceiptsTopic { - return &ReceiptsTopic{} -} - -func (r *ReceiptsTopic) Code() string { return "receipts" } -func (r *ReceiptsTopic) Name() string { - return "Поступления по приходным документам" -} - -func (r *ReceiptsTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "receipts", - Label: "Поступления", - Children: []*approvalflow.FlowNode{ - { - Key: "f1", - Label: "Ф1", - DataKey: "branch", - DataValue: "f1", - Children: []*approvalflow.FlowNode{ - { - Key: "f1_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите поступление по филиалу Ф1: товар, количество, поставщик", - }, - }, - }, - { - Key: "f2", - Label: "Ф2", - DataKey: "branch", - DataValue: "f2", - Children: []*approvalflow.FlowNode{ - { - Key: "f2_input", - IsInput: true, - InputKey: "content", - InputHint: "Опишите поступление по филиалу Ф2: товар, количество, поставщик", - }, - }, - }, - }, - } -} - -func (r *ReceiptsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - branch := collected["branch"] - if branch == "" { - return "", fmt.Errorf("branch не указан") - } - return fmt.Sprintf("receipts_%s", branch), nil -} - -func (r *ReceiptsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - - branchLabel := "Ф1" - if collected["branch"] == "f2" { - branchLabel = "Ф2" - } - - return fmt.Sprintf( - "📋 Поступления — %s\n\n"+ - "%s:\n%s", - branchLabel, name, collected["content"], - ) -} - ------END service/telegram_service/handlers/approval/topics/receipts/topic.go----- - -File: service/telegram_service/handlers/approval/topics/returns/topic.go -Lines: 177 ------BEGIN service/telegram_service/handlers/approval/topics/returns/topic.go----- -package returns - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type ReturnsTopic struct{} - -func NewReturnsTopic() *ReturnsTopic { - return &ReturnsTopic{} -} - -func (r *ReturnsTopic) Code() string { return "returns" } -func (r *ReturnsTopic) Name() string { return "Возвраты" } - -// BuildTree: Тип возврата → Регион → Ввод -// Примечание: "Продажа другим менеджером" требует выбора менеджера - -// это будет реализовано позже через дополнительный флоу -func (r *ReturnsTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "returns", - Label: "Возвраты", - Children: []*approvalflow.FlowNode{ - { - Key: "supplier", - Label: "Возврат поставщику", - DataKey: "return_type", - DataValue: "supplier", - Children: []*approvalflow.FlowNode{ - { - Key: "supplier_crimea", - Label: "Крым", - DataKey: "region", - DataValue: "crimea", - Children: []*approvalflow.FlowNode{ - { - Key: "supplier_crimea_input", - IsInput: true, - InputKey: "content", - InputHint: "Бишули\n28 гр.1881 бесцветная (9504) ПФ - 2 короба\nРеализация товаров и услуг ЧП000001326 от 20.04.2026 8:00:01\nФ1\n\nПричина: Короб приехал с завода и сильно порвался в дороге, клиент не может на свою продукцию использовать его", - }, - }, - }, - { - Key: "supplier_krasnodar", - Label: "Краснодар", - DataKey: "region", - DataValue: "krasnodar", - Children: []*approvalflow.FlowNode{ - { - Key: "supplier_krasnodar_input", - IsInput: true, - InputKey: "content", - InputHint: "Бишули\n28 гр.1881 бесцветная (9504) ПФ - 2 короба\nРеализация товаров и услуг ЧП000001326 от 20.04.2026 8:00:01\nФ1\n\nПричина: Короб приехал с завода и сильно порвался в дороге, клиент не может на свою продукцию использовать его", - }, - }, - }, - }, - }, - { - Key: "other_manager", - Label: "Продажа другим менеджером", - DataKey: "return_type", - DataValue: "other_manager", - Children: []*approvalflow.FlowNode{ - { - Key: "other_manager_crimea", - Label: "Крым", - DataKey: "region", - DataValue: "crimea", - Children: []*approvalflow.FlowNode{ - { - Key: "other_manager_crimea_input", - IsInput: true, - InputKey: "content", - InputHint: "Бишули\n61 гр.38 мм бесцветная (3888) ЕП - 11 коробов\nРеализация товаров и услуг ЧП000000584 от 05.03.2026 8:00:01\nФ1\n\nПричина: Часть заказа отвалилась, будут переходить на эту позицию не раньше, чем через 3 мес\n\nПродаст выбранный менеджер на Бойко", - }, - }, - }, - { - Key: "other_manager_krasnodar", - Label: "Краснодар", - DataKey: "region", - DataValue: "krasnodar", - Children: []*approvalflow.FlowNode{ - { - Key: "other_manager_krasnodar_input", - IsInput: true, - InputKey: "content", - InputHint: "Бишули\n61 гр.38 мм бесцветная (3888) ЕП - 11 коробов\nРеализация товаров и услуг ЧП000000584 от 05.03.2026 8:00:01\nФ1\n\nПричина: Часть заказа отвалилась, будут переходить на эту позицию не раньше, чем через 3 мес\n\nПродаст выбранный менеджер на Бойко", - }, - }, - }, - }, - }, - { - Key: "self_sale", - Label: "Самостоятельная продажа", - DataKey: "return_type", - DataValue: "self_sale", - Children: []*approvalflow.FlowNode{ - { - Key: "self_sale_crimea", - Label: "Крым", - DataKey: "region", - DataValue: "crimea", - Children: []*approvalflow.FlowNode{ - { - Key: "self_sale_crimea_input", - IsInput: true, - InputKey: "content", - InputHint: "ТД Крымэколайф\n40,5 гр.1881 бесцветная (7808) ПФ - 52 короба\nРеализация товаров и услуг ЧП000003123 от 4.08.25\nФ1\n\nПричина: для сокращения долга клиента\n\nДействия: продам ООО Нива", - }, - }, - }, - { - Key: "self_sale_krasnodar", - Label: "Краснодар", - DataKey: "region", - DataValue: "krasnodar", - Children: []*approvalflow.FlowNode{ - { - Key: "self_sale_krasnodar_input", - IsInput: true, - InputKey: "content", - InputHint: "ТД Крымэколайф\n40,5 гр.1881 бесцветная (7808) ПФ - 52 короба\nРеализация товаров и услуг ЧП000003123 от 4.08.25\nФ1\n\nПричина: для сокращения долга клиента\n\nДействия: продам ООО Нива", - }, - }, - }, - }, - }, - }, - } -} - -func (r *ReturnsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - returnType := collected["return_type"] - region := collected["region"] - - if returnType == "" || region == "" { - return "", fmt.Errorf("неполные данные: return_type=%s, region=%s", returnType, region) - } - - return fmt.Sprintf("returns_%s_%s", returnType, region), nil -} - -func (r *ReturnsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - - var typeLabel string - switch collected["return_type"] { - case "supplier": - typeLabel = "Возврат поставщику" - case "other_manager": - typeLabel = "Продажа другим менеджером" - case "self_sale": - typeLabel = "Самостоятельная продажа" - default: - typeLabel = "Возврат" - } - - regionLabel := "Крым" - if collected["region"] == "krasnodar" { - regionLabel = "Краснодар" - } - - return fmt.Sprintf( - "📋 Возвраты: %s — %s\n\n"+ - "%s:\n%s", - typeLabel, regionLabel, name, collected["content"], - ) -} - ------END service/telegram_service/handlers/approval/topics/returns/topic.go----- - -File: service/telegram_service/handlers/approval/topics/shipments_soh/topic.go -Lines: 97 ------BEGIN service/telegram_service/handlers/approval/topics/shipments_soh/topic.go----- -package shipments_soh - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type ShipmentsSOHTopic struct{} - -func NewShipmentsSOHTopic() *ShipmentsSOHTopic { return &ShipmentsSOHTopic{} } - -func (s *ShipmentsSOHTopic) Code() string { return "shipments_soh" } -func (s *ShipmentsSOHTopic) Name() string { return "Отгрузки на СОХ" } - -func (s *ShipmentsSOHTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "shipments_soh", - Label: "Отгрузки на СОХ", - Children: []*approvalflow.FlowNode{ - s.buildRegion("crimea", "Крым"), - s.buildRegion("krasnodar", "Краснодар"), - }, - } -} - -func (s *ShipmentsSOHTopic) buildRegion(regionKey, regionLabel string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: regionKey, - Label: regionLabel, - DataKey: "region", - DataValue: regionKey, - Children: []*approvalflow.FlowNode{ - { - Key: regionKey + "_real", - Label: "Реальная", - DataKey: "shipment_type", - DataValue: "real", - Children: []*approvalflow.FlowNode{{ - Key: regionKey + "_real_input", - IsInput: true, - InputKey: "content", - InputHint: "Прошу согласовать перемещение на СОХ\nНива ООО \n31,6 гр. 1810 бесцветная (8352) АТФ 5 кор. 7,21 руб.\n81 гр.48 мм бесцветная (2464) ОП 10 кор. 18,23 руб.\nна сумму 750 276,8 руб.\nОстаток лимита у клиента с учётом текущей задолженности 2 656 689,12 руб.", - }}, - }, - { - Key: regionKey + "_limit", - Label: "Для лимита", - DataKey: "shipment_type", - DataValue: "limit", - Children: []*approvalflow.FlowNode{{ - Key: regionKey + "_limit_input", - IsInput: true, - InputKey: "content", - InputHint: "ЭКОИЛЬИЧПРОДУКТ ООО\nна сумму 750 276,8 руб\nОстаток лимита у клиента с учётом текущей задолженности 2 656 689,12 руб", - }}, - }, - }, - } -} - -func (s *ShipmentsSOHTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - region := collected["region"] - shipmentType := collected["shipment_type"] - if region == "" || shipmentType == "" { - return "", fmt.Errorf("неполные данные: region=%s, shipment_type=%s", region, shipmentType) - } - return fmt.Sprintf("shipments_soh_%s_%s", region, shipmentType), nil -} - -func (s *ShipmentsSOHTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - - regionLabel := collected["region"] - switch regionLabel { - case "crimea": - regionLabel = "Крым" - case "krasnodar": - regionLabel = "Краснодар" - } - - typeLabel := collected["shipment_type"] - switch typeLabel { - case "real": - typeLabel = "Реальная" - case "limit": - typeLabel = "Для лимита" - } - - return fmt.Sprintf( - "📋 Отгрузки на СОХ — %s (%s)\n\n%s:\n%s", - regionLabel, typeLabel, name, collected["content"], - ) -} - ------END service/telegram_service/handlers/approval/topics/shipments_soh/topic.go----- - -File: service/telegram_service/handlers/approval/topics/sick_leave/topic.go -Lines: 116 ------BEGIN service/telegram_service/handlers/approval/topics/sick_leave/topic.go----- -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 "Официальный больничный" } - -func (o *SickLeaveTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "sickleave", - Label: "Официальный больничный", - Children: []*approvalflow.FlowNode{ - { - // 🚀 Уникальный ключ: sl_open_date - Key: "sl_open_date", - IsInput: true, - InputKey: "open_date", - InputHint: "Введите дату открытия больничного листа (например: 22.02.2022)", - Children: []*approvalflow.FlowNode{ - { - // 🚀 Уникальный ключ: sl_vacation (не конфликтует с vacation-темой) - Key: "sl_vacation", Label: "В счёт отпуска", - DataKey: "payment_type", DataValue: "vacation_account", - Children: []*approvalflow.FlowNode{ - o.buildDuration("sl_single_day", "На один день", "22.02.2022"), - o.buildDuration("sl_date_range", "Диапазон дат", "22.02.2022 - 25.02.2022"), - }, - }, - { - // 🚀 Уникальный ключ: sl_official - Key: "sl_official", Label: "Только оф. больничный", - DataKey: "payment_type", DataValue: "official", - Children: []*approvalflow.FlowNode{ - o.buildDuration("sl_single_day", "На один день", "22.02.2022"), - o.buildDuration("sl_date_range", "Диапазон дат", "22.02.2022 - 25.02.2022"), - }, - }, - }, - }, - }, - } -} - -// 🚀 Все ключи теперь с префиксом sl_ -func (o *SickLeaveTopic) buildDuration(durKey, durLabel, hint string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: durKey, Label: durLabel, - DataKey: "duration_type", DataValue: durKey, // ⚠️ DataValue тоже с префиксом — нужно учесть в TopicCodeFromCollected - Children: []*approvalflow.FlowNode{ - { - Key: durKey + "_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) - } - - // 🚀 Убираем префикс sl_ из duration_type, т.к. код темы в БД без префикса - durClean := dur - if len(durClean) > 3 && durClean[:3] == "sl_" { - durClean = durClean[3:] - } - - return fmt.Sprintf("sickleave_%s_full_day_%s", durClean, 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 = collected["payment_type"] - } - - content := collected["content"] - openDate := collected["open_date"] - if openDate != "" { - content = fmt.Sprintf("Дата открытия больничного листа - %s.\n%s", openDate, content) - } - - msg := fmt.Sprintf( - "📋 Тип: Официальный больничный\n\n"+ - "%s: прошу согласовать больничный\n"+ - "%s\n"+ - "%s", - name, content, paymentLabel, - ) - - return msg -} - ------END service/telegram_service/handlers/approval/topics/sick_leave/topic.go----- - -File: service/telegram_service/handlers/approval/topics/time_off/time_off.go -Lines: 123 ------BEGIN service/telegram_service/handlers/approval/topics/time_off/time_off.go----- -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("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, - ) -} - ------END service/telegram_service/handlers/approval/topics/time_off/time_off.go----- - -File: service/telegram_service/handlers/approval/topics/transaction_passport/topic.go -Lines: 100 ------BEGIN service/telegram_service/handlers/approval/topics/transaction_passport/topic.go----- -package transactionpassport - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type TransactionPassportTopic struct{} - -func NewTransactionPassportTopic() *TransactionPassportTopic { - return &TransactionPassportTopic{} -} - -func (t *TransactionPassportTopic) Code() string { return "transaction_passport" } -func (t *TransactionPassportTopic) Name() string { return "Паспорт сделки" } - -func (t *TransactionPassportTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "transaction_passport", - Label: "Паспорт сделки", - Children: []*approvalflow.FlowNode{ - { - Key: "krasnodar", - Label: "Краснодар", - DataKey: "region", - DataValue: "krasnodar", - Children: []*approvalflow.FlowNode{ - { - Key: "krasnodar_input", - IsInput: true, - InputKey: "content", - InputHint: "Текст для паспорта сделки (Краснодар)", - }, - }, - }, - { - Key: "crimea", - Label: "Крым", - DataKey: "region", - DataValue: "crimea", - Children: []*approvalflow.FlowNode{ - { - Key: "crimea_input", - IsInput: true, - InputKey: "content", - InputHint: "Текст для паспорта сделки (Крым)", - }, - }, - }, - { - Key: "belarus", - Label: "Беларусь", - DataKey: "region", - DataValue: "belarus", - Children: []*approvalflow.FlowNode{ - { - Key: "belarus_input", - IsInput: true, - InputKey: "content", - InputHint: "Текст для паспорта сделки (Беларусь)", - }, - }, - }, - }, - } -} - -func (t *TransactionPassportTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - region := collected["region"] - if region == "" { - return "", fmt.Errorf("region не указан") - } - return fmt.Sprintf("transaction_passport_%s", region), nil -} - -func (t *TransactionPassportTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "" - if initiator.FullName != nil { - name = *initiator.FullName - } - - var regionLabel string - switch collected["region"] { - case "krasnodar": - regionLabel = "Краснодар" - case "crimea": - regionLabel = "Крым" - case "belarus": - regionLabel = "Беларусь" - default: - regionLabel = collected["region"] - } - - return fmt.Sprintf( - "📋 Паспорт сделки — %s\n\n"+ - "%s:\n%s", - regionLabel, name, collected["content"], - ) -} - ------END service/telegram_service/handlers/approval/topics/transaction_passport/topic.go----- - -File: service/telegram_service/handlers/approval/topics/vacation/topic.go -Lines: 89 ------BEGIN service/telegram_service/handlers/approval/topics/vacation/topic.go----- -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 "Отпуск" } - -func (o *VacationTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "vacation", - Label: "Отпуск", - Children: []*approvalflow.FlowNode{ - o.buildDuration("vac_single_day", "На один день", "22.02.2022", "single_day"), - o.buildDuration("vac_date_range", "Диапазон дат", "22.02.2022 - 25.02.2022", "date_range"), - o.buildDuration("vac_multi_day", "Несколько дней", "22.02.2022, 24.02.2022, 26.02.2022", "multi_day"), - }, - } -} - -func (o *VacationTopic) buildDuration(key, durLabel, hint, dataValue string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: key, Label: durLabel, - DataKey: "duration_type", DataValue: dataValue, - Children: []*approvalflow.FlowNode{ - { - Key: key + "_own", Label: "За свой счёт", - DataKey: "payment_type", DataValue: "own_expense", - Children: []*approvalflow.FlowNode{ - { - Key: key + "_own_input", - IsInput: true, - InputKey: "content", - InputHint: hint, - DataKey: "time_type", DataValue: "full_day", - }, - }, - }, - { - Key: key + "_vac", Label: "В счёт отпуска", - DataKey: "payment_type", DataValue: "vacation_account", - Children: []*approvalflow.FlowNode{ - { - Key: key + "_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) - } - // 🚀 DataValue уже без префикса — ничего убирать не нужно - 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, - ) -} - ------END service/telegram_service/handlers/approval/topics/vacation/topic.go----- - -File: service/telegram_service/handlers/approval/topics/vshipments/topic.go -Lines: 127 ------BEGIN service/telegram_service/handlers/approval/topics/vshipments/topic.go----- -package vshipments - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" -) - -type VShipmentsTopic struct{} - -func NewVShipmentsTopic() *VShipmentsTopic { return &VShipmentsTopic{} } - -func (v *VShipmentsTopic) Code() string { return "v_shipments" } -func (v *VShipmentsTopic) Name() string { return "В. Отгрузки" } - -func (v *VShipmentsTopic) BuildTree() *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "v_shipments", - Label: "В. Отгрузки", - Children: []*approvalflow.FlowNode{ - v.buildLeaf("shipment", "В. Отгрузки", - "ООО Аква на сумму 1 000 000 руб. под 15%"), - { - Key: "advance", - Label: "Авансовая отгрузка", - DataKey: "subtype", - DataValue: "advance", - Children: []*approvalflow.FlowNode{ - v.buildAdvanceLeaf("amount", "По сумме", - "ООО Аква на сумму 1 000 000 руб. от 30.06.2026"), - v.buildAdvanceLeaf("goods", "По товару", - "ООО Аква 29,2 гр.1810 бесцветная (8800) ОП - 52 кор - по 5,2 руб. итого на сумму 1 000 000 руб. от 30.06.2026"), - }, - }, - v.buildLeaf("receipt", "В. Поступления", - "ООО Нива на 370 тыс. руб. — поступление под 19%"), - }, - } -} - -func (v *VShipmentsTopic) buildLeaf(key, label, hint string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: key, - Label: label, - DataKey: "subtype", - DataValue: key, - Children: []*approvalflow.FlowNode{ - { - Key: key + "_input", - IsInput: true, - InputKey: "content", - InputHint: hint, - }, - }, - } -} - -// buildAdvanceLeaf — под-развилка внутри "Авансовая отгрузка": по сумме / по товару -func (v *VShipmentsTopic) buildAdvanceLeaf(key, label, hint string) *approvalflow.FlowNode { - return &approvalflow.FlowNode{ - Key: "advance_" + key, - Label: label, - DataKey: "advance_type", - DataValue: key, - Children: []*approvalflow.FlowNode{ - { - Key: "advance_" + key + "_input", - IsInput: true, - InputKey: "content", - InputHint: hint, - }, - }, - } -} - -func (v *VShipmentsTopic) TopicCodeFromCollected(collected map[string]string) (string, error) { - subtype := collected["subtype"] - if subtype == "" { - return "", fmt.Errorf("неполные данные: subtype пуст") - } - - if subtype == "advance" { - advanceType := collected["advance_type"] - if advanceType == "" { - return "", fmt.Errorf("неполные данные: advance_type пуст") - } - return fmt.Sprintf("v_shipments_advance_%s", advanceType), nil - } - - return fmt.Sprintf("v_shipments_%s", subtype), nil -} - -func (v *VShipmentsTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string { - name := "—" - if initiator != nil && initiator.FullName != nil { - name = *initiator.FullName - } - - var label string - switch collected["subtype"] { - case "shipment": - label = "В. Отгрузки" - case "receipt": - label = "В. Поступления" - case "advance": - switch collected["advance_type"] { - case "amount": - label = "Авансовая отгрузка (по сумме)" - case "goods": - label = "Авансовая отгрузка (по товару)" - default: - label = "Авансовая отгрузка" - } - default: - label = "В. Отгрузки" - } - - content := "—" - if collected["content"] != "" { - content = collected["content"] - } - - return fmt.Sprintf( - "📋 В. Отгрузки - %s\n\n👤 Инициатор: %s\n📝 Текст:\n%s", - label, name, content, - ) -} - ------END service/telegram_service/handlers/approval/topics/vshipments/topic.go----- - -File: service/telegram_service/handlers/faq/handler.go -Lines: 97 ------BEGIN service/telegram_service/handlers/faq/handler.go----- -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.BuildMainMenu(keyboard.UserRole{}) - } - - // Получаем все роли пользователя - 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) - isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID) - - return keyboard.BuildMainMenu(keyboard.UserRole{ - IsApprover: isApprover, - IsObserver: isObserver, - IsExecutor: isExecutor, - IsDirector: isDirector, - }) -} - ------END service/telegram_service/handlers/faq/handler.go----- - -File: service/telegram_service/handlers/start/handler.go -Lines: 198 ------BEGIN service/telegram_service/handlers/start/handler.go----- -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) - - defaultRoles, _, err := h.ipc.Database.Role.GetRolesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Role{IsDefault: utilscore.PointerToBool(true)}, - }) - if err != nil { - logrus.Error("start.handleFullNameInput: GetRolesListDB: ", err) - utilscore.SendBotMessage(bot, msg.Chat.ID, "Произошла ошибка при регистрации. Попробуйте ещё раз — /start") - return - } - if len(defaultRoles) > 0 { - for _, role := range defaultRoles { - _, _, err = h.ipc.Database.UserRole.CreateUserRoleDB(ctx, nil, &typescore.UserRole{ - UserID: created.ID, - RoleID: role.ID, - }) - if err != nil { - logrus.Error("start.handleFullNameInput: CreateUserRoleDB: ", err) - } - } - } - 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.BuildMainMenu(keyboard.UserRole{}) - } - - // Получаем все роли пользователя - 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) - isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID) - - return keyboard.BuildMainMenu(keyboard.UserRole{ - IsApprover: isApprover, - IsObserver: isObserver, - IsExecutor: isExecutor, - IsDirector: isDirector, - }) -} - -// 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, - )) -} - ------END service/telegram_service/handlers/start/handler.go----- - -File: service/telegram_service/handlers/start/helpers.go -Lines: 47 ------BEGIN service/telegram_service/handlers/start/helpers.go----- -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 -} - ------END service/telegram_service/handlers/start/helpers.go----- - -File: service/telegram_service/handlers/suggestion/handler.go -Lines: 450 ------BEGIN service/telegram_service/handlers/suggestion/handler.go----- -package suggestion - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/state" - "bitrix_balancer_api/telegram_service/types" - "context" - "encoding/base64" - "fmt" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" -) - -type Handler struct { - ipc *types.InternalProviderControl - States *state.StateManager -} - -func NewHandler(ipc *types.InternalProviderControl) *Handler { - return &Handler{ - ipc: ipc, - States: state.NewStateManager(ipc.RedisClient), - } -} - -func (h *Handler) HandleCreateSuggestion(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 { - sendText(bot, chatID, "⚠️ Пользователь не найден.") - return - } - - // Сохраняем состояние ожидания темы - suggestionState := &state.SuggestionFlowState{ - Stage: "await_subject", - } - h.States.SetSuggestionFlow(ctx, telegramID, suggestionState) //nolint:errcheck - - sendText(bot, chatID, "💡 Новое предложение/пожелание\n\nВведите тему предложения:") -} - -func (h *Handler) HandleSuggestionTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool { - ctx := context.Background() - telegramID := msg.From.ID - chatID := msg.Chat.ID - - suggestionState, err := h.States.GetSuggestionFlow(ctx, telegramID) - if err != nil { - logrus.Errorf("HandleSuggestionTextInput: GetSuggestionFlow err=%v", err) - return false - } - - if suggestionState == nil { - return false - } - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil { - logrus.Errorf("HandleSuggestionTextInput: GetUserByTelegramIDDB err=%v", err) - return false - } - - if user == nil || user.ID == nil { - logrus.Warnf("HandleSuggestionTextInput: user not found telegramID=%d", telegramID) - return false - } - - switch suggestionState.Stage { - case "await_subject": - return h.handleSubjectInput(bot, ctx, chatID, telegramID, user, msg.Text) - - case "await_message": - return h.handleMessageInput(bot, ctx, chatID, telegramID, user, suggestionState, msg.Text, nil, nil) - - default: - logrus.Warnf("HandleSuggestionTextInput: unknown stage=%s", suggestionState.Stage) - return false - } -} - -func (h *Handler) handleSubjectInput(bot *tgbotapi.BotAPI, ctx context.Context, chatID, telegramID int64, user *typescore.User, subject string) bool { - directors, err := h.ipc.Database.User.GetDirectorsDB(ctx) - if err != nil { - logrus.Errorf("handleSubjectInput: GetDirectorsDB err=%v", err) - sendText(bot, chatID, "⚠️ Ошибка при получении списка директоров.") - h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck - return true - } - - if len(directors) == 0 { - sendText(bot, chatID, "⚠️ Директор не найден в системе. Обратитесь к администратору.") - h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck - return true - } - - // Ищем первого директора с заполненным ID - var director *typescore.User - for _, d := range directors { - if d != nil && d.ID != nil { - director = d - break - } - } - - if director == nil { - logrus.Errorf("handleSubjectInput: all directors have nil ID, count=%d", len(directors)) - sendText(bot, chatID, "⚠️ Директор не найден в системе. Обратитесь к администратору.") - h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck - return true - } - - // Создаем предложение - openStatus := "open" - suggestion := &typescore.Suggestion{ - InitiatorID: user.ID, - DirectorID: director.ID, - Subject: &subject, - Status: &openStatus, - } - - created, _, err := h.ipc.Database.Suggestion.CreateSuggestionDB(ctx, nil, suggestion, true) - if err != nil { - logrus.Errorf("handleSubjectInput: CreateSuggestionDB err=%v", err) - sendText(bot, chatID, "Ошибка при создании предложения. Попробуйте позже.") - h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck - return true - } - - if created == nil || created.ID == nil { - logrus.Errorf("handleSubjectInput: created suggestion is nil or has no ID") - sendText(bot, chatID, "Ошибка при создании предложения. Попробуйте позже.") - h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck - return true - } - - // Обновляем state — переходим к вводу текста - suggestionState := &state.SuggestionFlowState{ - SuggestionID: *created.ID, - Stage: "await_message", - } - if err := h.States.SetSuggestionFlow(ctx, telegramID, suggestionState); err != nil { - logrus.Errorf("handleSubjectInput: SetSuggestionFlow err=%v", err) - sendText(bot, chatID, "Ошибка при сохранении состояния. Попробуйте позже.") - return true - } - - directorName := "директору" - if director.FullName != nil { - directorName = *director.FullName - } - - sendText(bot, chatID, fmt.Sprintf( - "✅ Тема сохранена\n\n"+ - "📋 Тема: %s\n"+ - "👤 Получатель: %s\n\n"+ - "Теперь введите текст предложения или прикрепите файл:", - subject, directorName, - )) - - return true -} - -func (h *Handler) handleMessageInput( - bot *tgbotapi.BotAPI, - ctx context.Context, - chatID, telegramID int64, - user *typescore.User, - suggestionState *state.SuggestionFlowState, - messageText string, - fileData, fileName *string, -) bool { - message := &typescore.SuggestionMessage{ - SuggestionID: &suggestionState.SuggestionID, - UserID: user.ID, - Message: &messageText, - FileData: fileData, - FileName: fileName, - } - - _, _, err := h.ipc.Database.SuggestionMessage.CreateSuggestionMessageDB(ctx, nil, message) - if err != nil { - logrus.Errorf("handleMessageInput: CreateSuggestionMessageDB err=%v", err) - sendText(bot, chatID, "Ошибка при отправке сообщения.") - return true - } - - suggestion, err := h.ipc.Database.Suggestion.GetSuggestionByIDDB(ctx, suggestionState.SuggestionID) - if err != nil || suggestion == nil { - logrus.Errorf("handleMessageInput: GetSuggestionByIDDB err=%v", err) - return true - } - - if suggestion.InitiatorID == nil || suggestion.DirectorID == nil || user.ID == nil { - logrus.Errorf("handleMessageInput: suggestion participants are nil") - return true - } - - sendText(bot, chatID, "✅ Ваше сообщение отправлено.") - - var recipientID uint64 - if *user.ID == *suggestion.InitiatorID { - recipientID = *suggestion.DirectorID - } else { - recipientID = *suggestion.InitiatorID - } - - recipient, err := h.ipc.Database.User.GetUserByIDDB(ctx, recipientID) - if err != nil || recipient == nil { - logrus.Errorf("handleMessageInput: GetUserByIDDB recipient err=%v", err) - h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck - return true - } - - if recipient.TelegramID != nil { - isNew := suggestionState.Stage == "await_subject" // первое сообщение - h.notifyAboutMessage(bot, ctx, *recipient.TelegramID, suggestion, user, messageText, fileData, fileName, isNew) - } - - h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck - return true -} - -func (h *Handler) HandleReplyToSuggestion(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, suggestionID uint64) { - ctx := context.Background() - chatID := cq.Message.Chat.ID - telegramID := cq.From.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - sendText(bot, chatID, "⚠️ Пользователь не найден.") - return - } - - suggestion, err := h.ipc.Database.Suggestion.GetSuggestionByIDDB(ctx, suggestionID) - if err != nil || suggestion == nil { - sendText(bot, chatID, "⚠️ Предложение не найдено.") - return - } - - if suggestion.InitiatorID == nil || suggestion.DirectorID == nil { - sendText(bot, chatID, "⚠️ Ошибка данных предложения.") - return - } - - // Проверяем что пользователь - участник диалога - isInitiator := *user.ID == *suggestion.InitiatorID - isDirector := *user.ID == *suggestion.DirectorID - - if !isInitiator && !isDirector { - sendText(bot, chatID, "⚠️ Вы не участник этого диалога.") - return - } - - suggestionState := &state.SuggestionFlowState{ - SuggestionID: suggestionID, - Stage: "await_message", - } - h.States.SetSuggestionFlow(ctx, telegramID, suggestionState) //nolint:errcheck - - // Показываем кому пойдёт ответ - var recipientName string - if isInitiator { - director, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.DirectorID) - if director != nil && director.FullName != nil { - recipientName = *director.FullName - } - } else { - initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.InitiatorID) - if initiator != nil && initiator.FullName != nil { - recipientName = *initiator.FullName - } - } - - subject := "—" - if suggestion.Subject != nil { - subject = *suggestion.Subject - } - - sendText(bot, chatID, fmt.Sprintf( - "💬 Ответить на предложение #%d\n"+ - "📋 Тема: %s\n"+ - "➡️ Получатель: %s\n\n"+ - "Введите текст или прикрепите файл:", - suggestionID, subject, recipientName, - )) -} - -func (h *Handler) HandleViewSuggestion(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, suggestionID uint64) { - ctx := context.Background() - chatID := cq.Message.Chat.ID - telegramID := cq.From.ID - - bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck - - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return - } - - suggestion, err := h.ipc.Database.Suggestion.GetSuggestionByIDDB(ctx, suggestionID) - if err != nil || suggestion == nil { - sendText(bot, chatID, "⚠️ Предложение не найдено.") - return - } - - h.showSuggestionThread(bot, ctx, chatID, suggestion) -} - -func (h *Handler) showSuggestionThread(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, suggestion *typescore.Suggestion) { - if suggestion.ID == nil { - return - } - - messages, _, err := h.ipc.Database.SuggestionMessage.GetSuggestionMessagesListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.SuggestionMessage{ - SuggestionID: suggestion.ID, - }, - }) - if err != nil { - logrus.Errorf("showSuggestionThread: GetMessagesBySuggestionIDDB err=%v", err) - return - } - - subject := "—" - if suggestion.Subject != nil { - subject = *suggestion.Subject - } - - initiatorName := "—" - if suggestion.InitiatorID != nil { - initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.InitiatorID) - if initiator != nil && initiator.FullName != nil { - initiatorName = *initiator.FullName - } - } - - text := fmt.Sprintf( - "💡 Предложение #%d\n\n"+ - "📋 Тема: %s\n"+ - "👤 Автор: %s\n\n"+ - "💬 Переписка:", - *suggestion.ID, subject, initiatorName, - ) - - for _, msg := range messages { - if msg.UserID == nil || msg.Message == nil { - continue - } - - user, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *msg.UserID) - userName := "—" - if user != nil && user.FullName != nil { - userName = *user.FullName - } - - timestamp := "" - if msg.CreatedAt != nil { - timestamp = msg.CreatedAt.Format("02.01.2006 15:04") - } - - text += fmt.Sprintf("\n\n%s (%s):\n%s", userName, timestamp, *msg.Message) - - if msg.FileData != nil && msg.FileName != nil { - text += fmt.Sprintf("\n📎 %s", *msg.FileName) - } - } - - message := tgbotapi.NewMessage(chatID, text) - message.ParseMode = "HTML" - message.ReplyMarkup = buildSuggestionActions(*suggestion.ID) - bot.Send(message) //nolint:errcheck -} - -func (h *Handler) notifyAboutMessage( - bot *tgbotapi.BotAPI, - ctx context.Context, - recipientChatID int64, - suggestion *typescore.Suggestion, - sender *typescore.User, - messageText string, - fileData, fileName *string, - isNew bool, -) { - subject := "—" - if suggestion.Subject != nil { - subject = *suggestion.Subject - } - - senderName := "—" - if sender.FullName != nil { - senderName = *sender.FullName - } - - header := "📬 Новое сообщение" - if isNew { - header = "💡 Новое предложение" - } - - text := fmt.Sprintf( - "%s\n\n"+ - "📋 Тема: %s\n"+ - "👤 От: %s\n"+ - "💬 Сообщение:\n%s", - header, subject, senderName, messageText, - ) - - if fileData != nil && fileName != nil { - // Отправляем файл - decoded, err := base64.StdEncoding.DecodeString(*fileData) - if err != nil { - logrus.Errorf("notifyAboutMessage: base64 decode err=%v", err) - } else { - doc := tgbotapi.NewDocument(recipientChatID, tgbotapi.FileBytes{ - Name: *fileName, - Bytes: decoded, - }) - doc.Caption = text - doc.ParseMode = "HTML" - doc.ReplyMarkup = buildSuggestionActions(*suggestion.ID) - bot.Send(doc) //nolint:errcheck - return - } - } - - msg := tgbotapi.NewMessage(recipientChatID, text) - msg.ParseMode = "HTML" - msg.ReplyMarkup = buildSuggestionActions(*suggestion.ID) - bot.Send(msg) //nolint:errcheck -} - -func buildSuggestionActions(suggestionID uint64) tgbotapi.InlineKeyboardMarkup { - return tgbotapi.NewInlineKeyboardMarkup( - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("↩️ Ответить", fmt.Sprintf("sugg_reply:%d", suggestionID)), - ), - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("👁 Посмотреть всю переписку", fmt.Sprintf("sugg_view:%d", suggestionID)), - ), - ) -} - -func sendText(bot *tgbotapi.BotAPI, chatID int64, text string) { - msg := tgbotapi.NewMessage(chatID, text) - msg.ParseMode = "HTML" - bot.Send(msg) //nolint:errcheck -} - ------END service/telegram_service/handlers/suggestion/handler.go----- - -File: service/telegram_service/keyboard/absense_delegation_keyboard.go -Lines: 60 ------BEGIN service/telegram_service/keyboard/absense_delegation_keyboard.go----- -package keyboard - -import ( - "bitrix_balancer_api/core/typescore" - "fmt" - - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" -) - -// BuildDelegationChoiceMenu — клавиатура Да/Нет для вопроса о делегировании. -func BuildDelegationChoiceMenu() tgbotapi.InlineKeyboardMarkup { - return tgbotapi.NewInlineKeyboardMarkup( - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("✅ Да", "appr_deleg_yes"), - tgbotapi.NewInlineKeyboardButtonData("❌ Нет", "appr_deleg_no"), - ), - ) -} - -const delegateCandidatesPerPage = 8 - -// BuildDelegateSelectionMenu — постраничный список кандидатов на -// делегирование (одиночный выбор, без toggle — в отличие от наблюдателей). -func BuildDelegateSelectionMenu(candidates []*typescore.User, page int) tgbotapi.InlineKeyboardMarkup { - start := page * delegateCandidatesPerPage - if start > len(candidates) { - start = len(candidates) - } - end := start + delegateCandidatesPerPage - if end > len(candidates) { - end = len(candidates) - } - - var rows [][]tgbotapi.InlineKeyboardButton - for _, u := range candidates[start:end] { - if u.ID == nil { - continue - } - name := "Без имени" - if u.FullName != nil { - name = *u.FullName - } - rows = append(rows, tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData(name, fmt.Sprintf("appr_deleg_sel:%d", *u.ID)), - )) - } - - var navRow []tgbotapi.InlineKeyboardButton - if page > 0 { - navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData("⬅️ Назад", fmt.Sprintf("appr_deleg_pg:%d", page-1))) - } - if end < len(candidates) { - navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData("Вперёд ➡️", fmt.Sprintf("appr_deleg_pg:%d", page+1))) - } - if len(navRow) > 0 { - rows = append(rows, navRow) - } - - return tgbotapi.NewInlineKeyboardMarkup(rows...) -} - ------END service/telegram_service/keyboard/absense_delegation_keyboard.go----- - -File: service/telegram_service/keyboard/add_approver.go -Lines: 157 ------BEGIN service/telegram_service/keyboard/add_approver.go----- -package keyboard - -import ( - "bitrix_balancer_api/core/lib/external/tgkit" - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/types" - "context" - "fmt" -) - -func BuildAddApproverMainMenu() interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Добавить согласующего", "add_appr_create")). - Row(tgkit.Btn("📋 Ранее добавленные", "add_appr_list")). - Build() -} - -func BuildAddApproverCategoryMenu(categories []*typescore.ApprovalTopicCategory, page int) interface{} { - const perPage = 6 - total := len(categories) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start, end := page*perPage, page*perPage+perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, c := range categories[start:end] { - if c.ID == nil || c.Name == nil { - continue - } - kb.Row(tgkit.Btn(*c.Name, fmt.Sprintf("add_appr_category:%d", *c.ID))) - } - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "add_appr_category_page", "add_appr_page_noop")) - } - return kb.Build() -} - -func BuildAddApproverApprovalMenu(approvals []*typescore.Approval, categoryID uint64, page int, ctx context.Context, ipc *types.InternalProviderControl) interface{} { - const perPage = 6 - total := len(approvals) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start, end := page*perPage, page*perPage+perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, a := range approvals[start:end] { - if a.ID == nil { - continue - } - topicName := "—" - if a.TopicID != nil { - if t, _ := ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); t != nil && t.Name != nil { - topicName = *t.Name - } - } - kb.Row(tgkit.Btn(fmt.Sprintf("#%d — %s", *a.ID, topicName), fmt.Sprintf("add_appr_approval:%d", *a.ID))) - } - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, - fmt.Sprintf("add_appr_approval_page:%d", categoryID), "add_appr_page_noop")) - } - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К категориям", "add_appr_create")) - return kb.Build() -} - -func BuildAddApproverUserMenu(users []*typescore.User, approvalID, categoryID uint64, page int) interface{} { - const perPage = 8 - total := len(users) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start, end := page*perPage, page*perPage+perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, u := range users[start:end] { - if u.ID == nil || u.FullName == nil { - continue - } - kb.Row(tgkit.Btn(*u.FullName, fmt.Sprintf("add_appr_user:%d", *u.ID))) - } - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, - fmt.Sprintf("add_appr_user_page:%d:%d", approvalID, categoryID), "add_appr_page_noop")) - } - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("add_appr_category:%d", categoryID))) - return kb.Build() -} - -func BuildAddedApproversList(items []*typescore.ApprovalAdditionalApprover, page int, ctx context.Context, ipc *types.InternalProviderControl) interface{} { - const perPage = 6 - total := len(items) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start, end := page*perPage, page*perPage+perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, aa := range items[start:end] { - if aa.ID == nil || aa.ApprovalID == nil { - continue - } - approverName := "—" - if aa.ApproverID != nil { - if u, _ := ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID); u != nil && u.FullName != nil { - approverName = *u.FullName - } - } - kb.Row(tgkit.Btn(fmt.Sprintf("#%d — %s", *aa.ApprovalID, approverName), fmt.Sprintf("add_appr_detail:%d", *aa.ID))) - } - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "add_appr_list_page", "add_appr_page_noop")) - } - return kb.Build() -} - -func BuildAddedApproverDetail() interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", "add_appr_list")). - Build() -} - -// BuildAddApproverToApproval — добавить согласующего прямо из карточки -func BuildAddApproverToApproval(approvalID uint64) interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Добавить согласующего", fmt.Sprintf("add_appr_to_approval:%d", approvalID))). - Build() -} - ------END service/telegram_service/keyboard/add_approver.go----- - -File: service/telegram_service/keyboard/approval.go -Lines: 362 ------BEGIN service/telegram_service/keyboard/approval.go----- -package keyboard - -import ( - "bitrix_balancer_api/core/lib/external/tgkit" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/telegram_service/approvalflow" - "bitrix_balancer_api/telegram_service/state" - "fmt" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" -) - -// BuildApproverDecision — кнопки для согласующего -func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, filesCount int, commentsCount int) tgbotapi.InlineKeyboardMarkup { - kb := tgkit.NewInlineKeyboard() - - if status == "approved" { - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID))) - kb.Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) - kb.Row(buildCommentsButton(approvalID, commentsCount)) - return kb.Build() - } - - if hasFiles { - buttonTitle := fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount) - kb.Row(tgkit.Btn(buttonTitle, fmt.Sprintf("appr_view_files:%d", approvalID))) - } - - kb.Row( - tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Да", fmt.Sprintf("appr_yes:%d", approvalID)), - tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Нет", fmt.Sprintf("appr_no:%d", approvalID)), - ). - Row(tgkit.Btn("🔄 Вернуть на доработку", fmt.Sprintf("appr_revision:%d", approvalID))). - Row( - tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)), - buildCommentsButton(approvalID, commentsCount), - ). - Row( - tgkit.Btn("📎 Прикрепить файл", fmt.Sprintf("appr_attach:%d", approvalID)), - ). - Row( - tgkit.Btn("➕ Добавить согласующего", fmt.Sprintf("add_appr_to_approval:%d", approvalID)), - ). - Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) - - return kb.Build() -} - -// BuildInitiatorCard — кнопки инициатора на карточке заявки -func BuildInitiatorCard(approvalID uint64, status string, hasFiles bool, filesCount int, commentsCount int) interface{} { - kb := tgkit.NewInlineKeyboard() - - if hasFiles { - buttonTitle := fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount) - kb.Row(tgkit.Btn(buttonTitle, fmt.Sprintf("appr_view_files:%d", approvalID))) - } - - if status != "approved" { - kb.Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))) - } - if commentsCount > 0 { - buildCommentsButton(approvalID, commentsCount) - } - - if status == "pending" || status == "revision" || status == "approved" { - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID))) - } - - kb.Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) - return kb.Build() -} - -// BuildRevokeButton — кнопка отзыва (для директора и инициатора) -func BuildRevokeButton(approvalID uint64, status string, filesCount int, commentsCount int) interface{} { - kb := tgkit.NewInlineKeyboard() - - if filesCount > 0 { - kb.Row(tgkit.Btn(fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount), fmt.Sprintf("appr_view_files:%d", approvalID))) - } - - kb.Row( - tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)), - buildCommentsButton(approvalID, commentsCount), - ) - - if status == "pending" || status == "revision" || status == "approved" { - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать заявку", fmt.Sprintf("appr_revoke:%d", approvalID))) - } - - kb.Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) - return kb.Build() -} - -// BuildObserverActions — кнопки наблюдателя -func BuildObserverActions(approvalID uint64, topicCode string, status string, filesCount, commentsCount int) tgbotapi.InlineKeyboardMarkup { - kb := tgkit.NewInlineKeyboard() - - if filesCount > 0 { - kb.Row(tgkit.Btn( - fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount), - fmt.Sprintf("appr_view_files:%d", approvalID), - )) - } - - kb.Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))) - buildCommentsButton(approvalID, commentsCount) - - return kb.Build() -} - -// BuildApprovalMenu — список тем для создания заявки -func BuildApprovalMenu(topics []approvalflow.Topic, page int) interface{} { - const perPage = 6 - total := len(topics) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start := page * perPage - end := start + perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, t := range topics[start:end] { - kb.Row(tgkit.Btn(t.Name(), fmt.Sprintf("appr:%s:%s", t.Code(), t.Code()))) - } - if totalPages > 1 { - pagination := tgkit.PaginationRow( - page, - totalPages, - fmt.Sprintf("appr_page:%d", page-1), - fmt.Sprintf("appr_page:%d", page+1), - "appr_page_noop", - ) - kb.Rows = append(kb.Rows, pagination) - } - return kb.Build() -} - -// BuildApprovalStep — шаг флоу согласования -func BuildApprovalStep(topicCode string, nodes []*approvalflow.FlowNode) interface{} { - kb := tgkit.NewInlineKeyboard() - for _, n := range nodes { - if n == nil { - continue - } - kb.Row(tgkit.Btn(n.Label, fmt.Sprintf("appr:%s:%s", topicCode, n.Key))) - } - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("appr_back:%s", topicCode))) - return kb.Build() -} - -// BuildApprovalInputPrompt — подсказка ввода -func BuildApprovalInputPrompt(topicCode string) interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("appr_back:%s", topicCode))). - Build() -} - -// BuildRejectOptions — варианты при отклонении -func BuildRejectOptions(approvalID uint64) interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("💬 Написать причину", fmt.Sprintf("appr_no_comment:%d", approvalID))). - Row(tgkit.Btn("⏳ Отложить", fmt.Sprintf("appr_no_defer:%d", approvalID))). - Row(tgkit.Btn("Отклонить без комментария", fmt.Sprintf("appr_no_skip:%d", approvalID))). - Build() -} - -// BuildRevokeOptions — варианты при отзыве -func BuildRevokeOptions(approvalID uint64) interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("💬 Написать причину", fmt.Sprintf("appr_revoke_comment:%d", approvalID))). - Row(tgkit.Btn("⏳ Отложить", fmt.Sprintf("appr_revoke_defer:%d", approvalID))). - Row(tgkit.Btn("Отозвать без комментария", fmt.Sprintf("appr_revoke_skip:%d", approvalID))). - Build() -} - -// BuildApprovalRejectComment — кнопка "без комментария" при вводе причины -func BuildApprovalRejectComment(approvalID uint64) interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("Отправить без комментария", fmt.Sprintf("appr_no_skip:%d", approvalID))). - Build() -} - -// BuildApprovalStagesButton — кнопка стадий -func BuildApprovalStagesButton(approvalID uint64) interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))). - Build() -} - -// BuildFileInputKeyboard — управление файлами в процессе флоу -func BuildFileInputKeyboard(topicCode string, files []state.FileAttachment, required bool) 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)), - )) - } - - if len(files) > 0 { - submitLabel := fmt.Sprintf("✅ Отправить (%s)", utilscore.PluralFiles(len(files))) - rows = append(rows, tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData(submitLabel, "appr_file_submit:"+topicCode), - )) - } - - // Кнопка "без файлов" только если прикрепление НЕ обязательно - if !required { - skipLabel := "📤 Отправить без файлов" - if len(files) == 0 { - skipLabel = "✅ Отправить на согласование (без файлов)" - } - rows = append(rows, tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData(skipLabel, "appr_file_skip:"+topicCode), - )) - } - - rows = append(rows, tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("← Назад", "appr_back:"+topicCode), - )) - - return tgbotapi.NewInlineKeyboardMarkup(rows...) -} - -// BuildPendingCommentsList — список отложенных заявок -func BuildPendingCommentsList(items []state.PendingCommentItem, topicNames map[uint64]string) interface{} { - kb := tgkit.NewInlineKeyboard() - 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 - } - kb.Row(tgkit.Btn(label, fmt.Sprintf("pending_item:%d", item.ApprovalID))) - } - return kb.Build() -} - -// BuildPendingItemOptions — действия по отложенной заявке -func BuildPendingItemOptions(approvalID uint64, action string) interface{} { - 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 tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("💬 Написать причину", commentCB)). - Row(tgkit.Btn("Без комментария", skipCB)). - Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", "pending_back")). - Build() -} - -// BuildAttachFileCancel — отмена прикрепления файла -func BuildAttachFileCancel(approvalID uint64) interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отмена", fmt.Sprintf("appr_attach_cancel:%d", approvalID))). - Build() -} - -// BuildMultiSelectStep — мультиселект (например, системы ОКБ/1С/Битрикс) -func BuildMultiSelectStep(topicCode string, nodes []*approvalflow.FlowNode, selectedValues []string, allowedTopicCodes map[string]bool) tgbotapi.InlineKeyboardMarkup { - selectedSet := make(map[string]bool, len(selectedValues)) - for _, v := range selectedValues { - selectedSet[v] = true - } - - kb := tgkit.NewInlineKeyboard() - for _, n := range nodes { - if n == nil { - continue - } - if n.TopicCode != "" && allowedTopicCodes != nil && !allowedTopicCodes[n.TopicCode] { - continue - } - label := n.Label - if selectedSet[n.MultiSelectValue] { - label = "✅ " + label - } - kb.Row(tgkit.Btn(label, fmt.Sprintf("appr_ms_toggle:%s:%s:%s", topicCode, n.Key, n.MultiSelectValue))) - } - - confirmLabel := "✅ Подтвердить" - if len(selectedValues) > 0 { - confirmLabel = fmt.Sprintf("✅ Подтвердить (%d)", len(selectedValues)) - } - kb.Row(tgkit.Btn(confirmLabel, fmt.Sprintf("appr_ms_confirm:%s", topicCode))) - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("appr_back:%s", topicCode))) - return kb.Build() -} - -// вспомогательная функция пагинации -func buildPageRow(page, totalPages int, prefix, noop string) []tgbotapi.InlineKeyboardButton { - var row []tgbotapi.InlineKeyboardButton - if page > 0 { - row = append(row, tgkit.Btn("←", fmt.Sprintf("%s:%d", prefix, page-1)).Build()) - } - if page < totalPages-1 { - row = append(row, tgkit.Btn(fmt.Sprintf("%d/%d →", page+1, totalPages), fmt.Sprintf("%s:%d", prefix, page+1)).Build()) - } else { - row = append(row, tgkit.Btn(fmt.Sprintf("%d/%d", page+1, totalPages), noop).Build()) - } - return row -} - -func BuildAttachSessionKeyboard(approvalID uint64, fileCount int) tgbotapi.InlineKeyboardMarkup { - kb := tgkit.NewInlineKeyboard() - - if fileCount > 0 { - kb.Row(tgkit.Btn( - fmt.Sprintf("✅ Отправить файлы (%d)", fileCount), - fmt.Sprintf("attach_submit:%d", approvalID), - )) - kb.Row(tgkit.Btn( - "🗑 Очистить все", - fmt.Sprintf("attach_clear:%d", approvalID), - )) - } - - kb.Row(tgkit.BtnStyled( - tgkit.ButtonStyleDanger, - "Отмена", - fmt.Sprintf("attach_cancel:%d", approvalID), - )) - - return kb.Build() -} - -// BuildExecutorTaskActions — кнопки исполнителя -func BuildExecutorTaskActions(taskID, approvalID uint64, filesCount int, commentsCount int) interface{} { - kb := tgkit.NewInlineKeyboard() - - if filesCount > 0 { - kb.Row(tgkit.Btn( - fmt.Sprintf("📎 Файлы заявки (%d)", filesCount), - fmt.Sprintf("appr_view_files:%d", approvalID), - )) - } - - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Выполнено", fmt.Sprintf("task_complete:%d", taskID))). - Row(tgkit.Btn("📎 Прикрепить файл к задаче", fmt.Sprintf("executor_attach:%d:%d", taskID, approvalID))). - Row(tgkit.Btn("🔁 Передать задачу", fmt.Sprintf("task_transfer_start:%d", taskID))). // 🆕 - Row( - tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)), - buildCommentsButton(approvalID, commentsCount), - ) - - return kb.Build() -} - ------END service/telegram_service/keyboard/approval.go----- - -File: service/telegram_service/keyboard/builder.go -Lines: 77 ------BEGIN service/telegram_service/keyboard/builder.go----- -package keyboard - -import ( - "bitrix_balancer_api/core/lib/external/tgkit" - "fmt" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" -) - -// 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("← Назад"), - ), - ) -} - -// BuildCommentNotificationKeyboard — для уведомления инициатора о комментарии -func BuildCommentNotificationKeyboard(approvalID uint64, commentsCount int) interface{} { - viewLabel := "💬 Посмотреть все комментарии" - if commentsCount > 0 { - viewLabel = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount) - } - - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("↩️ Ответить на комментарий", fmt.Sprintf("comment_reply:%d", approvalID))). - Row(tgkit.Btn("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID))). - Row(tgkit.Btn(viewLabel, fmt.Sprintf("appr_view_comments:%d", approvalID))). - Build() -} - -// BuildCommentReplyKeyboard — для согласующего/наблюдателя при получении ответа -func BuildCommentReplyKeyboard(approvalID uint64, commentsCount int) interface{} { - viewLabel := "💬 Посмотреть все комментарии" - if commentsCount > 0 { - viewLabel = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount) - } - - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("↩️ Ответить на комментарий", fmt.Sprintf("comment_reply:%d", approvalID))). - Row(tgkit.Btn("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID))). - Row(tgkit.Btn(viewLabel, fmt.Sprintf("appr_view_comments:%d", approvalID))). - Build() -} - ------END service/telegram_service/keyboard/builder.go----- - -File: service/telegram_service/keyboard/delegation.go -Lines: 172 ------BEGIN service/telegram_service/keyboard/delegation.go----- -// telegram_service/keyboard/delegation.go - ПОЛНОСТЬЮ ЗАМЕНИТЬ - -package keyboard - -import ( - "bitrix_balancer_api/core/lib/external/tgkit" - "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 delegationPerPage = 6 - -func BuildDelegationMainMenu() interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Делегировать права", "deleg_create")). - Row(tgkit.Btn("📋 Делегированные права", "deleg_list")). - Build() -} - -func BuildDelegationCategoryMenu(categories []*typescore.ApprovalTopicCategory, page int) interface{} { - total := len(categories) - totalPages := (total + delegationPerPage - 1) / delegationPerPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start, end := page*delegationPerPage, page*delegationPerPage+delegationPerPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, c := range categories[start:end] { - if c.ID == nil || c.Name == nil { - continue - } - kb.Row(tgkit.Btn(*c.Name, fmt.Sprintf("deleg_category:%d", *c.ID))) - } - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "deleg_category_page", "deleg_page_noop")) - } - return kb.Build() -} - -func BuildDelegationTopicMenu(topics []*typescore.ApprovalTopic, categoryID uint64, page int) interface{} { - const perPage = 6 - total := len(topics) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start, end := page*perPage, page*perPage+perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Вся категория", fmt.Sprintf("deleg_all_category:%d", categoryID))) - - for _, t := range topics[start:end] { - if t.ID == nil || t.Name == nil { - continue - } - kb.Row(tgkit.Btn(*t.Name, fmt.Sprintf("deleg_topic:%d", *t.ID))) - } - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, - fmt.Sprintf("deleg_topic_page:%d", categoryID), "deleg_page_noop")) - } - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К категориям", "deleg_back_categories")) - return kb.Build() -} - -func BuildDelegationUserMenu(users []*typescore.User, categoryID, topicID uint64, page int) interface{} { - const perPage = 8 - total := len(users) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start, end := page*perPage, page*perPage+perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, u := range users[start:end] { - if u.ID == nil || u.FullName == nil { - continue - } - kb.Row(tgkit.Btn(*u.FullName, fmt.Sprintf("deleg_user:%d", *u.ID))) - } - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, - fmt.Sprintf("deleg_user_page:%d:%d", categoryID, topicID), "deleg_page_noop")) - } - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("deleg_category:%d", categoryID))) - return kb.Build() -} - -func BuildDelegatedRightsList(delegations []*typescore.ApprovalDelegation, page int, ctx context.Context, ipc *types.InternalProviderControl) interface{} { - const perPage = 6 - total := len(delegations) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start, end := page*perPage, page*perPage+perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, d := range delegations[start:end] { - if d.ID == nil { - continue - } - scopeName := "—" - if d.TopicID != nil { - if t, _ := ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *d.TopicID); t != nil && t.Name != nil { - scopeName = *t.Name - } - } else if d.CategoryID != nil { - if c, _ := ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *d.CategoryID); c != nil && c.Name != nil { - scopeName = *c.Name - } - } - kb.Row(tgkit.Btn(scopeName, fmt.Sprintf("deleg_detail:%d", *d.ID))) - } - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "deleg_list_page", "deleg_page_noop")) - } - return kb.Build() -} - -func BuildDelegationActions(delegationID uint64) interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("📅 Изменить срок", fmt.Sprintf("deleg_extend:%d", delegationID))). - Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отозвать делегирование", fmt.Sprintf("deleg_revoke:%d", delegationID))). - Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", "deleg_list")). - Build() -} - -func BuildDelegationExtendCancel(delegationID uint64) interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", fmt.Sprintf("deleg_detail:%d", delegationID))). - Build() -} - -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 tgkit.NewInlineKeyboard(). - Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", callback)). - Build() -} - ------END service/telegram_service/keyboard/delegation.go----- - -File: service/telegram_service/keyboard/menu.go -Lines: 83 ------BEGIN service/telegram_service/keyboard/menu.go----- -package keyboard - -import ( - "bitrix_balancer_api/core/lib/external/tgkit" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" -) - -// UserRole — набор ролей пользователя для построения меню -type UserRole struct { - IsApprover bool - IsObserver bool - IsExecutor bool - IsDirector bool -} - -// BuildMainMenu — главное меню с разделами по ролям -func BuildMainMenu(roles UserRole) tgbotapi.ReplyKeyboardMarkup { - kb := tgkit.NewReplyKeyboard() - - // Раздел: Инициатор (всегда видим) - kb.Row("👤 Инициатор") - - // Раздел: Согласующий - if roles.IsApprover || roles.IsDirector { - kb.Row("✅ Согласующий") - } - - // Раздел: Наблюдатель - if roles.IsObserver { - kb.Row("👁 Наблюдатель") - } - - if roles.IsDirector { - kb.Row("Директор") - } - - // Раздел: Исполнитель - if roles.IsExecutor { - kb.Row("Задачи к исполнению") - } - - // Общие кнопки — всегда внизу - kb.Row("❓ Как создать согласование?") - kb.Row("💬 Предложения и пожелания") - - return kb.Build() -} - -// BuildInitiatorSubmenu — подменю для инициатора -func BuildInitiatorSubmenu() tgbotapi.ReplyKeyboardMarkup { - return tgkit.NewReplyKeyboard(). - Row("➕ Создать согласование"). - Row("Ранее созданные согласования"). - Row("← Назад"). - Build() -} - -// BuildApproverSubmenu — подменю для согласующего -func BuildApproverSubmenu() tgbotapi.ReplyKeyboardMarkup { - return tgkit.NewReplyKeyboard(). - Row("Принять согласование в работу"). - Row("Список согласований", "Отложенные согласования"). - Row("📊 Сформировать отчёт", "Делегировать права"). - Row("← Назад"). - Build() -} - -// BuildObserverSubmenu — подменю для наблюдателя -func BuildObserverSubmenu() tgbotapi.ReplyKeyboardMarkup { - return tgkit.NewReplyKeyboard(). - Row("Наблюдать за согласованием"). - Row("📊 Сформировать отчёт"). - Row("← Назад"). - Build() -} - -// BuildDirectorSubmenu — подменю для директора -func BuildDirectorSubmenu() tgbotapi.ReplyKeyboardMarkup { - return tgkit.NewReplyKeyboard(). - Row("🔔 Настроить уведомления"). - Row("← Назад"). - Build() -} - ------END service/telegram_service/keyboard/menu.go----- - -File: service/telegram_service/keyboard/misc.go -Lines: 389 ------BEGIN service/telegram_service/keyboard/misc.go----- -package keyboard - -import ( - "bitrix_balancer_api/core/lib/external/tgkit" - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "fmt" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" -) - -// BuildDirectorNotificationCategoriesMenu — мультиселект категорий с галочками. -// subscribedIDs — те category_id, на которые директор уже подписан. -func BuildDirectorNotificationCategoriesMenu(categories []*typescore.ApprovalTopicCategory, subscribedIDs []uint64, page int) tgbotapi.InlineKeyboardMarkup { - const perPage = 8 - - subscribed := make(map[uint64]bool, len(subscribedIDs)) - for _, id := range subscribedIDs { - subscribed[id] = true - } - - total := len(categories) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start := page * perPage - end := start + perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, c := range categories[start:end] { - if c.ID == nil || c.Name == nil { - continue - } - label := *c.Name - if subscribed[*c.ID] { - label = "✅ " + label - } else { - label = "⬜ " + label - } - // page передаём в callback, чтобы после тоггла вернуться на ту же страницу - kb.Row(tgkit.Btn(label, fmt.Sprintf("dir_notif_toggle:%d:%d", *c.ID, page))) - } - - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "dir_notif_page", "dir_notif_page_noop")) - } - - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Готово", "dir_notif_done")) - return kb.Build() -} - -func BuildApproverSelectionMenu(approvers []*typescore.User, page int) interface{} { - const perPage = 8 - total := len(approvers) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start, end := page*perPage, page*perPage+perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, a := range approvers[start:end] { - if a.ID == nil || a.FullName == nil { - continue - } - kb.Row(tgkit.Btn(*a.FullName, fmt.Sprintf("select_approver:%d", *a.ID))) - } - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "select_approver_page", "select_approver_noop")) - } - return kb.Build() -} - -func BuildFirstApproverSelectionMenu(users []*typescore.User, page int) tgbotapi.InlineKeyboardMarkup { - const perPage = 8 - total := len(users) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start := page * perPage - end := start + perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, u := range users[start:end] { - if u.ID == nil || u.FullName == nil { - continue - } - kb.Row(tgkit.Btn(*u.FullName, fmt.Sprintf("first_approver_select:%d", *u.ID))) - } - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "first_approver_page", "first_approver_noop")) - } - return kb.Build() -} - -func BuildObserverSelectionMenu(observers []*typescore.User, selectedIDs []uint64, page int, isRequired bool) tgbotapi.InlineKeyboardMarkup { - const perPage = 8 - - if len(observers) == 0 { - kb := tgkit.NewInlineKeyboard() - if isRequired { - kb.Row(tgkit.Btn("⚠️ Нет доступных наблюдателей", "obs_select_noop")) - } else { - kb.Row(tgkit.Btn("✅ Подтвердить без наблюдателей", "obs_select_confirm")) - } - return kb.Build() - } - - total := len(observers) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages { - page = totalPages - 1 - } - start := page * perPage - end := start + perPage - if end > total { - end = total - } - - selected := make(map[uint64]bool, len(selectedIDs)) - for _, id := range selectedIDs { - selected[id] = true - } - - kb := tgkit.NewInlineKeyboard() - for _, u := range observers[start:end] { - if u.ID == nil || u.FullName == nil { - continue - } - label := *u.FullName - if selected[*u.ID] { - label = "✅ " + label - } - kb.Row(tgkit.Btn(label, fmt.Sprintf("obs_select_toggle:%d", *u.ID))) - } - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "obs_select_page", "obs_select_noop")) - } - - if isRequired { - if len(selectedIDs) == 0 { - kb.Row(tgkit.Btn("⚠️ Выберите хотя бы одного наблюдателя", "obs_select_confirm")) - } else { - kb.Row(tgkit.Btn( - fmt.Sprintf("✅ Подтвердить (%d выбрано)", len(selectedIDs)), - "obs_select_confirm", - )) - } - } else { - confirmLabel := "✅ Подтвердить" - if len(selectedIDs) > 0 { - confirmLabel = fmt.Sprintf("✅ Подтвердить (%d выбрано)", len(selectedIDs)) - } else { - confirmLabel = "✅ Подтвердить без наблюдателей" - } - kb.Row(tgkit.Btn(confirmLabel, "obs_select_confirm")) - } - - return kb.Build() -} - -// BuildObserverTopicMenuFromDB — строит меню тем наблюдения из БД -func BuildObserverTopicMenuFromDB(topics []*typescore.ApprovalTopic, page int) tgbotapi.InlineKeyboardMarkup { - const perPage = 6 - total := len(topics) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start := page * perPage - end := start + perPage - if end > total { - end = total - } - - var rows [][]tgbotapi.InlineKeyboardButton - for _, t := range topics[start:end] { - if t.ID == nil || t.Name == nil || t.Code == nil { - continue - } - rows = append(rows, tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData(*t.Name, fmt.Sprintf("obs_topic:%s", *t.Code)), - )) - } - - if totalPages > 1 { - rows = append(rows, tgkit.PaginationRow( - page, totalPages, - fmt.Sprintf("obs_topic_page:%d", page-1), - fmt.Sprintf("obs_topic_page:%d", page+1), - "obs_topic_noop", - )) - } - - return tgbotapi.NewInlineKeyboardMarkup(rows...) -} - -func BuildObserverTopicMenu(topics []approvalflow.Topic, page int) tgbotapi.InlineKeyboardMarkup { - const perPage = 6 - total := len(topics) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start := page * perPage - end := start + perPage - if end > total { - end = total - } - - var rows [][]tgbotapi.InlineKeyboardButton - for _, t := range topics[start:end] { - rows = append(rows, tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData(t.Name(), fmt.Sprintf("obs_topic:%s", t.Code())), - )) - } - - if totalPages > 1 { - rows = append(rows, tgkit.PaginationRow( - page, totalPages, - fmt.Sprintf("obs_topic_page:%d", page-1), - fmt.Sprintf("obs_topic_page:%d", page+1), - "obs_topic_noop", - )) - } - - return tgbotapi.NewInlineKeyboardMarkup(rows...) -} - -func BuildReportDateToMenu() interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("📤 Выгрузить (по сегодня)", "report_generate")). - Row(tgkit.Btn("Указать даты", "report_set_dates")). - Build() -} - -func BuildRevisionOptions(approvalID uint64, commentsCount int) interface{} { - viewLabel := "💬 Посмотреть все комментарии" - if commentsCount > 0 { - viewLabel = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount) - } - - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("✏️ Изменить текст", fmt.Sprintf("revision_edit_text:%d", approvalID))). - Row(tgkit.Btn("📎 Добавить файлы", fmt.Sprintf("revision_add_files:%d", approvalID))). - Row(tgkit.Btn(viewLabel, fmt.Sprintf("appr_view_comments:%d", approvalID))). - Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Отправить на повторное согласование", fmt.Sprintf("revision_resubmit:%d", approvalID))). - Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отозвать заявку", fmt.Sprintf("appr_revoke:%d", approvalID))). - Build() -} - -func BuildRevisionRejectOptions(approvalID uint64) interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("💬 Указать причину", fmt.Sprintf("appr_revision_comment:%d", approvalID))). - Row(tgkit.Btn("↩️ Вернуть без комментария", fmt.Sprintf("appr_revision_skip:%d", approvalID))). - Build() -} - -func BuildRevisionAttachCancel(approvalID uint64) interface{} { - return tgkit.NewInlineKeyboard(). - Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отмена", fmt.Sprintf("revision_attach_cancel:%d", approvalID))). - Build() -} - -func BuildRevokeTaskConfirmation(taskID uint64, approvalID uint64) tgbotapi.InlineKeyboardMarkup { - return tgbotapi.NewInlineKeyboardMarkup( - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData( - "✅ Нет, изменений не вносил", - fmt.Sprintf("revoke_task_no_changes:%d:%d", taskID, approvalID), - ), - ), - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData( - "⚠️ Да, изменения были", - fmt.Sprintf("revoke_task_has_changes:%d:%d", taskID, approvalID), - ), - ), - ) -} - -func buildCommentsButton(approvalID uint64, commentsCount int) tgkit.InlineButton { - label := "💬 Посмотреть все комментарии" - if commentsCount > 0 { - label = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount) - } - return tgkit.Btn(label, fmt.Sprintf("appr_view_comments:%d", approvalID)) -} - -// BuildTaskTransferUserMenu — список пользователей для передачи задачи -func BuildTaskTransferUserMenu(users []*typescore.User, page int) tgbotapi.InlineKeyboardMarkup { - const perPage = 8 - total := len(users) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start := page * perPage - end := start + perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, u := range users[start:end] { - if u.ID == nil || u.FullName == nil { - continue - } - kb.Row(tgkit.Btn(*u.FullName, fmt.Sprintf("task_transfer_user:%d", *u.ID))) - } - if totalPages > 1 { - kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "task_transfer_page", "task_transfer_noop")) - } - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", "task_transfer_cancel")) - return kb.Build() -} - -// BuildTaskTransferConfirmation — кнопки Принять/Отклонить для получателя запроса -func BuildTaskTransferConfirmation(transferID uint64) tgbotapi.InlineKeyboardMarkup { - return tgkit.NewInlineKeyboard(). - Row( - tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "✅ Принять", fmt.Sprintf("task_transfer_accept:%d", transferID)), - tgkit.BtnStyled(tgkit.ButtonStyleDanger, "❌ Отклонить", fmt.Sprintf("task_transfer_decline:%d", transferID)), - ). - Build() -} - -// BuildRevocationApprovalDecision — Да/Нет для согласующего, дающего согласие на отзыв -func BuildRevocationApprovalDecision(approvalID uint64, requestID uint64, commentsCount int) tgbotapi.InlineKeyboardMarkup { - return tgkit.NewInlineKeyboard(). - Row( - tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "✅ Да", fmt.Sprintf("revoke_appr_yes:%d", requestID)), - tgkit.BtnStyled(tgkit.ButtonStyleDanger, "❌ Нет", fmt.Sprintf("revoke_appr_no:%d", requestID)), - ). - Row( - tgkit.Btn("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID)), - buildCommentsButton(approvalID, commentsCount), - ). - Build() -} - -func BuildDailyReminderKeyboard(hasRevisions, hasTasks, hasApprovals bool) tgbotapi.InlineKeyboardMarkup { - kb := tgkit.NewInlineKeyboard() - - if hasRevisions { - kb.Row(tgkit.Btn("К доработкам", "reminder_revisions")) - } - - if hasTasks { - kb.Row(tgkit.Btn("К задачам", "reminder_tasks")) - } - - if hasApprovals { - kb.Row(tgkit.Btn("К заявкам", "reminder_approvals")) - } - - return kb.Build() -} - ------END service/telegram_service/keyboard/misc.go----- - -File: service/telegram_service/keyboard/observer.go -Lines: 97 ------BEGIN service/telegram_service/keyboard/observer.go----- -package keyboard - -import ( - "bitrix_balancer_api/core/lib/external/tgkit" - "bitrix_balancer_api/core/typescore" - "fmt" - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" -) - -// BuildObserverApprovalDetail — карточка заявки с кнопками наблюдателя. -func BuildObserverApprovalDetail(approvalID uint64, topicCode string, commentsCount int) tgbotapi.InlineKeyboardMarkup { - return tgbotapi.NewInlineKeyboardMarkup( - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("🔔 Напомнить согласующему", fmt.Sprintf("obs_remind:%d", approvalID)), - tgbotapi.NewInlineKeyboardButtonData("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID)), - ), - tgbotapi.NewInlineKeyboardRow( - buildCommentsButtonData(approvalID, commentsCount), - ), - tgbotapi.NewInlineKeyboardRow( - tgbotapi.NewInlineKeyboardButtonData("← К фильтрам", fmt.Sprintf("obs_topic:%s", topicCode)), - ), - ) -} - -func buildCommentsButtonData(approvalID uint64, commentsCount int) tgbotapi.InlineKeyboardButton { - label := "💬 Посмотреть все комментарии" - if commentsCount > 0 { - label = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount) - } - return tgbotapi.NewInlineKeyboardButtonData(label, fmt.Sprintf("appr_view_comments:%d", approvalID)) -} - -// BuildObserverStatusFilterMenu — выбор статуса заявок для просмотра в рамках темы/категории -func BuildObserverStatusFilterMenu(topicCode string) tgbotapi.InlineKeyboardMarkup { - return tgkit.NewInlineKeyboard(). - Row(tgkit.Btn("⏳ На согласовании", fmt.Sprintf("obs_status:pending:%s:0", topicCode))). - Row(tgkit.Btn("✅ Согласованные", fmt.Sprintf("obs_status:approved:%s:0", topicCode))). - Row(tgkit.Btn("📋 Все", fmt.Sprintf("obs_status:all:%s:0", topicCode))). - Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад к темам", "obs_back_topics")). - Build() -} - -// BuildObserverApprovalList — список заявок с пагинацией и учётом текущего фильтра. -// Кнопка "К фильтрам" возвращает на экран выбора статуса, "К темам" — к списку тем. -func BuildObserverApprovalList( - approvals []*typescore.Approval, - initiators map[uint64]*typescore.User, - departments map[uint64]*typescore.Department, - status, topicCode string, - page int, -) tgbotapi.InlineKeyboardMarkup { - const perPage = 8 - - total := len(approvals) - totalPages := (total + perPage - 1) / perPage - if page < 0 { - page = 0 - } - if page >= totalPages && totalPages > 0 { - page = totalPages - 1 - } - start := page * perPage - end := start + perPage - if end > total { - end = total - } - - kb := tgkit.NewInlineKeyboard() - for _, a := range approvals[start:end] { - 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 - } - } - kb.Row(tgkit.Btn(label, fmt.Sprintf("obs_approval:%d", *a.ID))) - } - - if totalPages > 1 { - prevCB := fmt.Sprintf("obs_status:%s:%s:%d", status, topicCode, page-1) - nextCB := fmt.Sprintf("obs_status:%s:%s:%d", status, topicCode, page+1) - kb.Rows = append(kb.Rows, tgkit.PaginationRow(page, totalPages, prevCB, nextCB, "obs_status_noop")) - } - - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К фильтрам", fmt.Sprintf("obs_topic:%s", topicCode))) - kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К темам", "obs_back_topics")) - return kb.Build() -} - ------END service/telegram_service/keyboard/observer.go----- - -File: service/telegram_service/migrate/insert.go -Lines: 379 ------BEGIN service/telegram_service/migrate/insert.go----- -package migrate - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/telegram_service/approvalflow" - "bitrix_balancer_api/telegram_service/handlers/approval/topics/absence" - clientchanges "bitrix_balancer_api/telegram_service/handlers/approval/topics/client_changes" - "bitrix_balancer_api/telegram_service/handlers/approval/topics/dealautoapproval" - "bitrix_balancer_api/telegram_service/handlers/approval/topics/deliveryclients" - "bitrix_balancer_api/telegram_service/handlers/approval/topics/free" - goodsorder "bitrix_balancer_api/telegram_service/handlers/approval/topics/goods_order" - "bitrix_balancer_api/telegram_service/handlers/approval/topics/inventory" - managerexpenses "bitrix_balancer_api/telegram_service/handlers/approval/topics/manager_expenses" - nonbudgetexpenses "bitrix_balancer_api/telegram_service/handlers/approval/topics/non_budget_expenses" - nonbudgetexpensespetline "bitrix_balancer_api/telegram_service/handlers/approval/topics/non_budget_expenses_pet_line" - nonstandardcontract "bitrix_balancer_api/telegram_service/handlers/approval/topics/nonstandard_contract" - otkconditions "bitrix_balancer_api/telegram_service/handlers/approval/topics/otk_conditions" - paymentscashless "bitrix_balancer_api/telegram_service/handlers/approval/topics/payments_cashless" - rateslogistics "bitrix_balancer_api/telegram_service/handlers/approval/topics/rates_logistics" - "bitrix_balancer_api/telegram_service/handlers/approval/topics/receipts" - "bitrix_balancer_api/telegram_service/handlers/approval/topics/returns" - shipmentssoh "bitrix_balancer_api/telegram_service/handlers/approval/topics/shipments_soh" - transactionpassport "bitrix_balancer_api/telegram_service/handlers/approval/topics/transaction_passport" - "bitrix_balancer_api/telegram_service/handlers/approval/topics/vshipments" - "bitrix_balancer_api/telegram_service/types" - "context" - "fmt" -) - -// ===== helpers ===== - -func nilIfEmpty(s string) *string { - if s == "" { - return nil - } - return &s -} - -// insertNode рекурсивно вставляет узел и его детей, сохраняя порядок -// (SortOrder = индекс среди сиблингов). -func insertNode(ctx context.Context, ipc *types.InternalProviderControl, categoryID uint64, parentID *uint64, sortOrder int, n *approvalflow.FlowNode) (*typescore.ApprovalFlowNode, error) { - key, label := n.Key, n.Label - isInput, isMulti := n.IsInput, n.IsMultiSelect - so := sortOrder - - dbNode := &typescore.ApprovalFlowNode{ - CategoryID: &categoryID, - ParentID: parentID, - Key: &key, - Label: &label, - DataKey: nilIfEmpty(n.DataKey), - DataValue: nilIfEmpty(n.DataValue), - IsInput: &isInput, - InputKey: nilIfEmpty(n.InputKey), - InputHint: nilIfEmpty(n.InputHint), - IsMultiSelect: &isMulti, - MultiSelectKey: nilIfEmpty(n.MultiSelectKey), - MultiSelectValue: nilIfEmpty(n.MultiSelectValue), - TopicCode: nilIfEmpty(n.TopicCode), - SortOrder: &so, - } - - // returnObj=false: не полагаемся на встроенный lookup CreateApprovalFlowNodeDB — - // он фильтрует по ВСЕМ полям переданного объекта, а у сиблингов (например - // "✅ Нужна ПП" под разными родителями) совпадают Label/DataKey/DataValue/SortOrder, - // из-за чего lookup либо не находит строку, либо потенциально мог бы найти чужую. - _, _, err := ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, dbNode, false) - if err != nil { - return nil, fmt.Errorf("insert node %s: %w", key, err) - } - - // Ищем свежесозданную запись сами, по минимальному уникальному триплету: - // category_id + parent_id + key. Этого достаточно, т.к. Key уникален в - // пределах дерева категории по построению (см. BuildTree каждой темы). - lookup := &typescore.ApprovalFlowNode{ - CategoryID: &categoryID, - ParentID: parentID, - Key: &key, - } - found, _, err := ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{Filtering: lookup}) - if err != nil { - return nil, fmt.Errorf("insert node %s: lookup after insert: %w", key, err) - } - if len(found) == 0 { - return nil, fmt.Errorf("insert node %s: not found after insert", key) - } - if len(found) > 1 { - return nil, fmt.Errorf("insert node %s: ambiguous lookup after insert (%d matches, category_id+parent_id+key not unique)", key, len(found)) - } - created := found[0] - - for i, child := range n.Children { - if _, err := insertNode(ctx, ipc, categoryID, created.ID, i, child); err != nil { - return nil, err - } - } - return created, nil -} - -// SeedCategoryTree создаёт дерево узлов для категории categoryCode из tree, -// затем проставляет code_template/message_template на корневой узел. -// codeTemplate == "" оставляет дефолтный фолбэк в DynamicTopic.TopicCodeFromCollected -// (baseCode + отсортированные непустые значения collected). -func SeedCategoryTree( - ctx context.Context, - ipc *types.InternalProviderControl, - categoryCode string, - tree *approvalflow.FlowNode, - codeTemplate string, - messageTemplate string, -) error { - category, err := ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByCodeDB(ctx, categoryCode) - if err != nil { - return fmt.Errorf("get category %s: %w", categoryCode, err) - } - if category == nil || category.ID == nil { - return fmt.Errorf("category not found: %s", categoryCode) - } - - root, err := insertNode(ctx, ipc, *category.ID, nil, 0, tree) - if err != nil { - return fmt.Errorf("insert tree for %s: %w", categoryCode, err) - } - - ct, mt := codeTemplate, messageTemplate - root.CodeTemplate = &ct - root.MessageTemplate = &mt - if _, _, err := ipc.Database.ApprovalFlowNode.UpdateApprovalFlowNodeDB(ctx, nil, root); err != nil { - return fmt.Errorf("set templates for %s: %w", categoryCode, err) - } - - return nil -} - -// freeMessageTemplate воспроизводит FreeTopic.FormatApproverMessage дословно, -// включая опциональный блок инструкций (сейчас недостижим в живом флоу, -// т.к. collected["instructions"] не заполняется при подаче заявки, но -// сохраняем на случай если это изменится). -const freeMessageTemplate = `📋 Заявка на согласование - -👤 От: {{.initiator_name}} -📂 Тема: {{.topic_name}} -📝 Текст: -{{if .content}}{{.content}}{{else}}—{{end}}{{if .instructions}} - -💡 Инструкция: -{{.instructions}}{{end}}` - -// ===== entry point ===== - -// SeedAllTopics переносит статические деревья тем в approval_flow_nodes, -// разбитые по approval_topic_categories. Идемпотентности намеренно нет — -// запускать один раз на чистых категориях (без существующих узлов). -// -// approval_topics и approval_topic_categories нигде здесь не изменяются — -// только читаются (Get...ByCodeDB) для получения category_id. -// -// НЕ мигрировано — источника дерева не было прислано: -// - new_clients (category_id=27): в старом Registry вообще не регистрировался. -// -// НЕ создаётся отдельным деревом (сознательно, алиасинг хардкодом в Registry): -// - timeoff (category_id=1), vacation (2), sickleave (3) — их узлы объединены -// в дерево категории "absence" (345) через AbsenceTopic.BuildTree(). -// Registry должен резолвить коды "timeoff"/"vacation"/"sickleave" в topics["absence"]. -func SeedAllTopics(ctx context.Context, ipc *types.InternalProviderControl) error { - type seed struct { - categoryCode string - tree *approvalflow.FlowNode - codeTemplate string - messageTemplate string - } - - seeds := []seed{ - { - "non_budget_expenses", - nonbudgetexpenses.NewNonBudgetExpensesTopic().BuildTree(), - `non_budget_expenses_{{.branch}}_{{.expense_type}}{{if .pp_required}}_pp_{{.pp_required}}{{end}}`, - `📋 Внебюджетные расходы — {{.branch_label}} ({{.expense_type_label}}){{if .pp_required}} -💳 ПП: {{.pp_required_label}}{{end}} - -{{.initiator_name}}: -{{.content}}`, - }, - { - "client_changes", - clientchanges.NewClientChangesTopic().BuildTree(), - `client_changes_{{.change_type}}_{{.region}}`, - `📋 Изменение клиентов в ОКБ и 1С: – {{.change_type_label}} -🖥 Системы: {{.systems_label}} -📍 Регион: {{.region_label}} - -{{.initiator_name}}: -{{.content}}`, - }, - { - "deal_auto_approval_conditions", - dealautoapproval.NewDealAutoApprovalTopic().BuildTree(), - `deal_auto_approval_{{.condition_type}}`, - `📋 Смена условий автосогласования сделок - {{if eq .condition_type "receivable_limit_vladimir"}}Повышение лимита ДЗ (от Владимира лично){{else if eq .condition_type "document_limits"}}Расширение лимитов по документам и просрочке{{else}}Смена условий автосогласования сделок{{end}} - -👤 Инициатор: {{.initiator_name}} -📝 Текст: -{{if .content}}{{.content}}{{else}}—{{end}}`, - }, - { - "delivery_clients", - deliveryclients.NewDeliveryClientsTopic().BuildTree(), - `delivery_clients_{{.delivery_type}}{{if eq .delivery_type "warehouse"}}_{{.region}}{{end}}`, - `📋 {{if eq .delivery_type "direct"}}Доставка: Напрямую клиенту{{else}}Доставка: На склад, {{.region_label}}{{end}} - -👤 Инициатор: {{.initiator_name}} -📝 Текст: -{{if .content}}{{.content}}{{else}}—{{end}}`, - }, - { - "goods_order", - goodsorder.NewGoodsOrderTopic().BuildTree(), - `goods_order_{{.order_type}}{{if .region}}_{{.region}}{{end}}`, - `📋 Заказ товаров — {{.order_type_label}} -📍 Регион: {{if .region}}{{.region_label}}{{else}}—{{end}} - -{{.initiator_name}}: -{{.content}}`, - }, - { - "inventory", - inventory.NewInventoryTopic().BuildTree(), - `inventory_{{.region}}{{if ne .region "krasnodar"}}_{{.location}}{{end}}`, - `📋 Инвентаризация: {{.region_label}}{{if eq .location "19l"}}, 19л{{else if eq .location "gvardeyskoe"}}, Гвардейское{{end}} - -👤 Инициатор: {{.initiator_name}} -📝 Текст: -{{if .content}}{{.content}}{{else}}—{{end}}`, - }, - { - // Единственное дерево на всю категорию absence (345). - // timeoff/vacation/sickleave как категории (1/2/3) своих узлов не получают. - "absence", - absence.NewAbsenceTopic().BuildTree(), - `{{.absence_type}}_{{trimPrefix .duration_type "sl_"}}_{{.time_type}}_{{.payment_type}}`, - `📋 {{if eq .absence_type "timeoff"}}Тип: Отгул{{else if eq .absence_type "vacation"}}Тип: Отпуск{{else}}Тип: Официальный больничный{{end}} - -{{.initiator_name}}: прошу согласовать {{if eq .absence_type "timeoff"}}отгул{{else if eq .absence_type "vacation"}}отпуск{{else}}больничный{{end}} -{{if .open_date}}Дата открытия больничного листа - {{.open_date}}. -{{end}}{{.content}} -{{.payment_type_label}}`, - }, - { - "returns", - returns.NewReturnsTopic().BuildTree(), - `returns_{{.return_type}}_{{.region}}`, - `📋 Возвраты: {{.return_type_label}} — {{.region_label}} - -{{.initiator_name}}: -{{.content}}`, - }, - { - "manager_expenses", - managerexpenses.NewManagerExpensesTopic().BuildTree(), - `manager_expenses_{{.region}}`, - `📋 Менеджерские расходы — {{.region_label}} - -{{.initiator_name}}: -{{.content}}`, - }, - { - "non_budget_expenses_pet_line", - nonbudgetexpensespetline.NewNonBudgetExpensesPetLineTopic().BuildTree(), - `non_budget_expenses_pet_line_{{.branch}}_{{.expense_type}}`, - `📋 Внебюджетные расходы ПЭТ Лайн — {{.branch_label}} ({{.expense_type_label}}) - -{{.initiator_name}}: -{{.content}}`, - }, - { - "nonstandard_contract", - nonstandardcontract.NewNonstandardContractTopic().BuildTree(), - `nonstandard_contract_{{.region}}`, - `📋 Нестандартные условия договора поставки — {{.region_label}} - -{{.initiator_name}}: -{{.content}}`, - }, - { - "otk_conditions", - otkconditions.NewOtkConditionsTopic().BuildTree(), - `otk_conditions_{{.region}}`, - `📋 Долгосрочные условия ОТК — {{.region_label}} - -👤 Инициатор: {{.initiator_name}} -📝 Текст: -{{if .content}}{{.content}}{{else}}—{{end}}`, - }, - { - "payments_cashless", - paymentscashless.NewPaymentsCashlessTopic().BuildTree(), - `payments_cashless_{{.payment_category}}{{if .pp_required}}_pp_{{.pp_required}}{{end}}`, - `📋 Утверждение оплат безнал — {{.payment_category_label}}{{if .pp_required}} -💳 ПП: {{.pp_required_label}}{{end}} - -{{.initiator_name}}: -{{.content}}`, - }, - { - "rates_logistics", - rateslogistics.NewRatesLogisticsTopic().BuildTree(), - `rates_logistics_{{.rate_type}}`, - `📋 Утверждение ставок логистики — {{if eq .rate_type "long_term"}}Надолго{{else if eq .rate_type "once_head_approval"}}Разово (с рук. отдела логистики){{else}}Разово{{end}} - -{{.initiator_name}}: -{{.content}}`, - }, - { - "receipts", - receipts.NewReceiptsTopic().BuildTree(), - `receipts_{{.branch}}`, - `📋 Поступления — {{.branch_label}} - -{{.initiator_name}}: -{{.content}}`, - }, - { - "shipments_soh", - shipmentssoh.NewShipmentsSOHTopic().BuildTree(), - `shipments_soh_{{.region}}_{{.shipment_type}}`, - `📋 Отгрузки на СОХ — {{.region_label}} ({{.shipment_type_label}}) - -{{.initiator_name}}: -{{.content}}`, - }, - { - "transaction_passport", - transactionpassport.NewTransactionPassportTopic().BuildTree(), - `transaction_passport_{{.region}}`, - `📋 Паспорт сделки — {{.region_label}} - -{{.initiator_name}}: -{{.content}}`, - }, - { - "v_shipments", - vshipments.NewVShipmentsTopic().BuildTree(), - `v_shipments_{{.subtype}}{{if eq .subtype "advance"}}_{{.advance_type}}{{end}}`, - `📋 В. Отгрузки - {{if eq .subtype "shipment"}}В. Отгрузки{{else if eq .subtype "receipt"}}В. Поступления{{else if eq .subtype "advance"}}{{if eq .advance_type "amount"}}Авансовая отгрузка (по сумме){{else if eq .advance_type "goods"}}Авансовая отгрузка (по товару){{else}}Авансовая отгрузка{{end}}{{else}}В. Отгрузки{{end}} - -👤 Инициатор: {{.initiator_name}} -📝 Текст: -{{if .content}}{{.content}}{{else}}—{{end}}`, - }, - } - - // 10 тем без развилок (один шаг: свободный текстовый ввод). - // codeTemplate == "" -> дефолтный фолбэк в DynamicTopic даёт ровно Code() - // категории, как и раньше отдавал FreeTopic.TopicCodeFromCollected. - freeTopics := []struct{ code, name, template string }{ - {"shipments", "Отгрузки", ""}, - {"vacancies", "Вакансии", ""}, - {"delivery_rates_ap", "Ставки доставки АП", "Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб."}, - {"freelancers_approval", "Утверждение фрилансеров", "Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день"}, - {"non_working_day", "Выход в нерабочий день", "Прошу вывести склад для учета c 25.04 по 26.04"}, - {"suggestions", "Предложения и пожелания", ""}, - {"cash_balance", "Остаток в кассах", ""}, - {"client_sales", "Продажи по клиенту", ""}, - {"manager_expenses_report", "Проведенные расходы по менеджеру", ""}, - {"remote_access", "Согласование удаленной работы", "Прошу согласовать удалённый выход на работу 06.06.2026"}, - } - for _, t := range freeTopics { - topic := free.NewFreeTopic(t.code, t.name, t.template) - seeds = append(seeds, seed{t.code, topic.BuildTree(), "", freeMessageTemplate}) - } - - for _, s := range seeds { - if err := SeedCategoryTree(ctx, ipc, s.categoryCode, s.tree, s.codeTemplate, s.messageTemplate); err != nil { - return fmt.Errorf("seed %s: %w", s.categoryCode, err) - } - } - - return nil -} - ------END service/telegram_service/migrate/insert.go----- - -File: service/telegram_service/scheduler/daily_reminder.go -Lines: 490 ------BEGIN service/telegram_service/scheduler/daily_reminder.go----- -package scheduler - -import ( - "bitrix_balancer_api/core/typescore" - "bitrix_balancer_api/core/utilscore" - "bitrix_balancer_api/telegram_service/keyboard" - "bitrix_balancer_api/telegram_service/types" - "context" - "encoding/json" - "fmt" - "regexp" - "strconv" - "strings" - "time" - - tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" - "github.com/sirupsen/logrus" -) - -type DailyReminder struct { - ipc *types.InternalProviderControl -} - -func NewDailyReminder(ipc *types.InternalProviderControl) *DailyReminder { - return &DailyReminder{ipc: ipc} -} - -// Start запускает планировщик ежедневных напоминаний -func (dr *DailyReminder) Start() { - logrus.Infof("DailyReminder: Start() вызван — планировщик запускается") - - go dr.scheduleLoop() -} - -// scheduleLoop бесконечный цикл, который ждет 9:00 МСК каждый день -func (dr *DailyReminder) scheduleLoop() { - mskLocation, err := time.LoadLocation("Europe/Moscow") - if err != nil { - logrus.Errorf("DailyReminder: не удалось загрузить часовой пояс МСК: %v", err) - mskLocation = time.FixedZone("MSK", 3*3600) // Fallback: UTC+3 - } - - for { - now := time.Now().In(mskLocation) - - // Вычисляем следующее 9:00 МСК - next := time.Date(now.Year(), now.Month(), now.Day(), 9, 0, 0, 0, mskLocation) - - // Если сегодня уже прошло 9:00, планируем на завтра - if now.After(next) { - next = next.AddDate(0, 0, 1) - } - - next = dr.skipWeekends(next) - - duration := time.Until(next) - logrus.Infof("DailyReminder: следующее напоминание запланировано на %s (через %v)", - next.Format("02.01.2006 15:04 MSK"), duration.Round(time.Second)) - - // Ждем до следующего 9:00 - time.Sleep(duration) - - // Отправляем напоминания - dr.sendReminders() - } -} - -// skipWeekends переносит дату на ближайший будний день, -// если она выпадает на субботу или воскресенье -func (dr *DailyReminder) skipWeekends(t time.Time) time.Time { - switch t.Weekday() { - case time.Saturday: - return t.AddDate(0, 0, 2) - case time.Sunday: - // Воскресенье → понедельник (+1 день) - return t.AddDate(0, 0, 1) - } - return t -} - -// sendReminders отправляет напоминания всем пользователям -func (dr *DailyReminder) sendReminders() { - logrus.Infof("DailyReminder: sendReminders() запущен") - - ctx := context.Background() - bot := dr.ipc.TGBotClient.Bot() - - mskLocation, err := time.LoadLocation("Europe/Moscow") - if err != nil { - logrus.Errorf("DailyReminder: не удалось загрузить часовой пояс МСК: %v", err) - mskLocation = time.FixedZone("MSK", 3*3600) - } - logrus.Infof("DailyReminder: сегодняшняя дата (МСК) = %s", time.Now().In(mskLocation).Format("02.01.2006")) - - // Получаем всех активных пользователей - users, _, err := dr.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{}) - if err != nil { - logrus.Errorf("DailyReminder: GetUsersListDB err=%v", err) - return - } - logrus.Infof("DailyReminder: получено пользователей из БД: %d", len(users)) - - absentToday := dr.getAbsentEmployeesToday(ctx, mskLocation) - - logrus.Infof("DailyReminder: начинаем отправку напоминаний для %d пользователей (отсутствующих сегодня: %d)", - len(users), len(absentToday)) - - sentCount := 0 - for _, user := range users { - if user.TelegramID == nil || user.ID == nil { - logrus.Debugf("DailyReminder: пропуск пользователя без TelegramID/ID (user=%+v)", user) - continue - } - - sent := dr.sendReminderToUser(bot, ctx, user, absentToday) - if sent { - sentCount++ - } - - time.Sleep(100 * time.Millisecond) - } - - logrus.Infof("DailyReminder: отправлено напоминаний: %d из %d", sentCount, len(users)) -} - -// sendReminderToUser отправляет напоминание конкретному пользователю -// Возвращает true, если сообщение было отправлено -func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Context, user *typescore.User, absentToday []AbsentEmployeeInfo) bool { - userID := *user.ID - telegramID := *user.TelegramID - - revisions, _, err := dr.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Approval{ - InitiatorID: &userID, - Status: utilscore.PointerToString("revision"), - }, - }) - if err != nil { - logrus.Errorf("DailyReminder: GetApprovalsListDB (revisions) for user=%d err=%v", userID, err) - } - revisionsCount := len(revisions) - - myPendingApprovals, _, err := dr.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Approval{ - InitiatorID: &userID, - Status: utilscore.PointerToString("pending"), - }, - }) - if err != nil { - logrus.Errorf("DailyReminder: GetApprovalsListDB (my pending) for user=%d err=%v", userID, err) - } - myPendingCount := len(myPendingApprovals) - - tasks, _, err := dr.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalTask{ - ExecutorID: &userID, - Status: utilscore.PointerToString("pending"), - }, - }) - if err != nil { - logrus.Errorf("DailyReminder: GetApprovalTasksListDB for user=%d err=%v", userID, err) - } - tasksCount := len(tasks) - - steps, _, err := dr.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalStep{ - ApproverID: &userID, - Status: utilscore.PointerToString("pending"), - }, - }) - if err != nil { - logrus.Errorf("DailyReminder: GetApprovalStepsListDB for user=%d err=%v", userID, err) - } - - // Также проверяем дополнительные согласования - additionalApprovers, _, err := dr.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ - ApproverID: &userID, - Status: utilscore.PointerToString("pending"), - }, - }) - if err != nil { - logrus.Errorf("DailyReminder: GetApprovalAdditionalApproversListDB for user=%d err=%v", userID, err) - } - - approvalsCount := dr.countPendingApprovals(ctx, steps, additionalApprovers) - - hasPersonalItems := revisionsCount > 0 || tasksCount > 0 || approvalsCount > 0 || myPendingCount > 0 - - logrus.Infof("DailyReminder: userID=%d telegramID=%d — revisions=%d tasks=%d approvals=%d hasPersonalItems=%v absentTodayCount=%d", - userID, telegramID, revisionsCount, tasksCount, approvalsCount, hasPersonalItems, len(absentToday)) - - if !hasPersonalItems && len(absentToday) == 0 { - logrus.Infof("DailyReminder: userID=%d telegramID=%d — нечего сообщить (нет личных пунктов и список отсутствующих пуст), сообщение НЕ отправляется", userID, telegramID) - return false - } - - text := "☀️ Доброе утро! Ежедневная сводка\n\n" - - if myPendingCount > 0 { - text += fmt.Sprintf("Ваших заявок на согласовании: %d\n", myPendingCount) - } - if revisionsCount > 0 { - text += fmt.Sprintf("Заявок на доработке: %d\n", revisionsCount) - } - - if tasksCount > 0 { - text += fmt.Sprintf("Задач к исполнению: %d\n", tasksCount) - } - - if approvalsCount > 0 { - text += fmt.Sprintf("Согласований к принятию: %d\n", approvalsCount) - } - - if hasPersonalItems { - text += "\nНажмите на кнопку для перехода к нужному разделу" - } - - if len(absentToday) > 0 { - if hasPersonalItems { - text += "\n\n" - } - text += "👥 Сотрудники в отгуле/больничном/отпуске:\n" - for _, a := range absentToday { - text += fmt.Sprintf("%s - %s - по срочным вопросам обращаться: %s\n", a.Name, a.TimeDescription, a.Contact) - } - } - - msg := tgbotapi.NewMessage(telegramID, text) - msg.ParseMode = "HTML" - if hasPersonalItems { - msg.ReplyMarkup = keyboard.BuildDailyReminderKeyboard( - revisionsCount > 0, - tasksCount > 0, - approvalsCount > 0, - ) - } - - if _, err := bot.Send(msg); err != nil { - logrus.Errorf("DailyReminder: не удалось отправить сообщение пользователю %d: %v", telegramID, err) - return false - } - - logrus.Infof("DailyReminder: сообщение успешно отправлено telegramID=%d (длина текста=%d символов)", telegramID, len(text)) - - return true -} - -// countPendingApprovals считает количество заявок со статусом "pending" -// из списка шагов и дополнительных согласующих -func (dr *DailyReminder) countPendingApprovals( - ctx context.Context, - steps []*typescore.ApprovalStep, - additionalApprovers []*typescore.ApprovalAdditionalApprover, -) int { - // Собираем уникальные approvalID - approvalIDs := make(map[uint64]bool) - - for _, step := range steps { - if step.ApprovalID != nil { - approvalIDs[*step.ApprovalID] = true - } - } - for _, aa := range additionalApprovers { - if aa.ApprovalID != nil { - approvalIDs[*aa.ApprovalID] = true - } - } - - if len(approvalIDs) == 0 { - return 0 - } - - // Получаем все заявки одним запросом и фильтруем по статусу pending - count := 0 - for approvalID := range approvalIDs { - id := approvalID - approval, err := dr.ipc.Database.Approval.GetApprovalByIDDB(ctx, id) - if err != nil || approval == nil { - continue - } - if approval.Status != nil && *approval.Status == "pending" { - count++ - } - } - - return count -} - -type absenceMetadata struct { - Extra struct { - TimeType string `json:"time_type"` - AbsenceType string `json:"absence_type"` - } `json:"extra"` -} - -type AbsentEmployeeInfo struct { - Name string - TimeDescription string - Contact string -} - -var absenceDateRe = regexp.MustCompile(`(\d{1,2})[.,](\d{1,2})\.(\d{4})`) - -var absenceTimeRe = regexp.MustCompile(`(?:с|от)\s*(\d{1,2})[:\.](\d{2})\s*(?:до|по|-|—|–)\s*(\d{1,2})[:\.](\d{2})`) - -func (dr *DailyReminder) getAbsentEmployeesToday(ctx context.Context, mskLocation *time.Location) []AbsentEmployeeInfo { - today := time.Now().In(mskLocation) - todayY, todayM, todayD := today.Date() - - approvals, _, err := dr.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.Approval{ - Status: utilscore.PointerToString("approved"), - }, - }) - if err != nil { - logrus.Errorf("DailyReminder: getAbsentEmployeesToday: GetApprovalsListDB err=%v", err) - return nil - } - logrus.Infof("DailyReminder: getAbsentEmployeesToday: заявок со статусом approved найдено: %d (сегодня %04d-%02d-%02d)", - len(approvals), todayY, todayM, todayD) - - seenUsers := make(map[uint64]bool) - var result []AbsentEmployeeInfo - - for _, approval := range approvals { - approvalID := derefApprovalID(approval) - - if approval.Metadata == nil || *approval.Metadata == "" || approval.Content == nil { - logrus.Infof("DailyReminder: заявка #%d пропущена — нет Metadata или Content", approvalID) - continue - } - - var meta absenceMetadata - if err := json.Unmarshal([]byte(*approval.Metadata), &meta); err != nil { - logrus.Warnf("DailyReminder: заявка #%d — не удалось распарсить Metadata как JSON: %v (metadata=%q)", - approvalID, err, *approval.Metadata) - continue - } - if meta.Extra.AbsenceType == "" { - logrus.Infof("DailyReminder: заявка #%d пропущена — metadata.extra.absence_type пустой (не тема отсутствия), metadata=%q", - approvalID, *approval.Metadata) - continue - } - logrus.Infof("DailyReminder: заявка #%d — absence_type=%q time_type=%q content=%q", - approvalID, meta.Extra.AbsenceType, meta.Extra.TimeType, *approval.Content) - - if approval.InitiatorID == nil { - logrus.Warnf("DailyReminder: заявка #%d пропущена — InitiatorID nil", approvalID) - continue - } - if seenUsers[*approval.InitiatorID] { - logrus.Infof("DailyReminder: заявка #%d пропущена — по этому инициатору (userID=%d) уже есть запись в сводке", approvalID, *approval.InitiatorID) - continue - } - - dates := parseAbsenceDates(*approval.Content) - if len(dates) == 0 { - logrus.Warnf("DailyReminder: заявка #%d — не удалось разобрать даты в content: %q", - approvalID, *approval.Content) - continue - } - logrus.Infof("DailyReminder: заявка #%d — распознанные даты: %v", approvalID, dates) - - if !absenceCoversDate(dates, *approval.Content, todayY, todayM, todayD) { - logrus.Infof("DailyReminder: заявка #%d пропущена — распознанные даты не покрывают сегодня (%04d-%02d-%02d)", - approvalID, todayY, todayM, todayD) - continue - } - logrus.Infof("DailyReminder: заявка #%d — покрывает сегодня, добавляем в сводку", approvalID) - - name := "—" - if approval.Initiator != nil && approval.Initiator.FullName != nil { - name = *approval.Initiator.FullName - } else { - user, uErr := dr.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) - if uErr == nil && user != nil && user.FullName != nil { - name = *user.FullName - } - } - - var timeDescription string - switch meta.Extra.AbsenceType { - case "timeoff": - if meta.Extra.TimeType == "partial" { - if m := absenceTimeRe.FindStringSubmatch(*approval.Content); m != nil { - timeDescription = fmt.Sprintf("отгул с %s:%s до %s:%s", m[1], m[2], m[3], m[4]) - } else { - timeDescription = "отгул весь день" - } - } else { - timeDescription = "отгул весь день" - } - case "vacation": - timeDescription = fmt.Sprintf("отпуск до %s", maxDate(dates).Format("02.01.2006")) - case "sickleave": - timeDescription = fmt.Sprintf("больничный до %s", maxDate(dates).Format("02.01.2006")) - default: - timeDescription = "отсутствует" - } - - contact := name - if delegations, _, dErr := dr.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalDelegation{ - DelegatorID: approval.InitiatorID, - IsActive: utilscore.PointerToBool(true), - }, - }); dErr == nil { - now := time.Now() - for _, d := range delegations { - if d.DelegateID == nil { - continue - } - if d.ValidUntil != nil && d.ValidUntil.Before(now) { - continue - } - delegate, uErr := dr.ipc.Database.User.GetUserByIDDB(ctx, *d.DelegateID) - if uErr == nil && delegate != nil && delegate.FullName != nil { - contact = *delegate.FullName - } - break - } - } - - seenUsers[*approval.InitiatorID] = true - result = append(result, AbsentEmployeeInfo{ - Name: name, - TimeDescription: timeDescription, - Contact: contact, - }) - } - - logrus.Infof("DailyReminder: getAbsentEmployeesToday: итоговый список отсутствующих сегодня (%d): %+v", len(result), result) - - return result -} - -func derefApprovalID(a *typescore.Approval) uint64 { - if a == nil || a.ID == nil { - return 0 - } - return *a.ID -} - -func parseAbsenceDates(content string) []time.Time { - matches := absenceDateRe.FindAllStringSubmatch(content, -1) - var dates []time.Time - for _, m := range matches { - day, errD := strconv.Atoi(m[1]) - month, errM := strconv.Atoi(m[2]) - year, errY := strconv.Atoi(m[3]) - if errD != nil || errM != nil || errY != nil { - continue - } - if month < 1 || month > 12 || day < 1 || day > 31 { - continue - } - dates = append(dates, time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)) - } - return dates -} - -func maxDate(dates []time.Time) time.Time { - max := dates[0] - for _, d := range dates[1:] { - if d.After(max) { - max = d - } - } - return max -} - -func absenceCoversDate(dates []time.Time, content string, y int, m time.Month, d int) bool { - target := time.Date(y, m, d, 0, 0, 0, 0, time.UTC) - - if len(dates) == 2 && strings.Contains(content, "-") { - start, end := dates[0], dates[1] - if end.Before(start) { - start, end = end, start - } - return !target.Before(start) && !target.After(end) - } - - for _, dt := range dates { - if dt.Equal(target) { - return true - } - } - return false -} - ------END service/telegram_service/scheduler/daily_reminder.go----- - -File: service/telegram_service/scheduler/delegation_checker.go -Lines: 139 ------BEGIN service/telegram_service/scheduler/delegation_checker.go----- -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.Bot() - - 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 - } -} - ------END service/telegram_service/scheduler/delegation_checker.go----- - -File: service/telegram_service/state/add_approver.go -Lines: 42 ------BEGIN service/telegram_service/state/add_approver.go----- -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)) -} - ------END service/telegram_service/state/add_approver.go----- - -File: service/telegram_service/state/attachment.go -Lines: 46 ------BEGIN service/telegram_service/state/attachment.go----- -package state - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "github.com/redis/go-redis/v9" - "time" -) - -type AttachmentSession struct { - ApprovalID uint64 `json:"approval_id"` - TaskID uint64 `json:"task_id,omitempty"` - Files []FileAttachment `json:"files"` // накапливаем - Stage string `json:"stage"` // "collecting" -} - -func (s *StateManager) SetAttachmentSession(ctx context.Context, telegramID int64, session *AttachmentSession) error { - key := fmt.Sprintf("attach_session:%d", telegramID) - data, err := json.Marshal(session) - if err != nil { - return err - } - return s.redis.Set(ctx, key, data, 30*time.Minute) -} - -func (s *StateManager) GetAttachmentSession(ctx context.Context, telegramID int64) (*AttachmentSession, error) { - key := fmt.Sprintf("attach_session:%d", telegramID) - data, err := s.redis.Get(ctx, key) - if errors.Is(err, redis.Nil) { - return nil, nil - } - if err != nil { - return nil, err - } - var session AttachmentSession - if err := json.Unmarshal([]byte(data), &session); err != nil { - return nil, err - } - return &session, nil -} - -func (s *StateManager) ClearAttachmentSession(ctx context.Context, telegramID int64) error { - return s.redis.Del(ctx, fmt.Sprintf("attach_session:%d", telegramID)) -} - ------END service/telegram_service/state/attachment.go----- - -File: service/telegram_service/state/comment.go -Lines: 76 ------BEGIN service/telegram_service/state/comment.go----- -package state - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "time" - - "github.com/redis/go-redis/v9" -) - -type CommentFlowState struct { - ApprovalID uint64 `json:"approval_id"` - Stage string `json:"stage"` // "await_text" -} - -type CommentReplyState struct { - ApprovalID uint64 `json:"approval_id"` - Stage string `json:"stage"` // "await_text" -} - -func (s *StateManager) SetCommentFlow(ctx context.Context, telegramID int64, state *CommentFlowState) error { - key := fmt.Sprintf("comment_flow:%d", telegramID) - data, err := json.Marshal(state) - if err != nil { - return err - } - return s.redis.Set(ctx, key, data, 30*time.Minute) -} - -func (s *StateManager) GetCommentFlow(ctx context.Context, telegramID int64) (*CommentFlowState, error) { - key := fmt.Sprintf("comment_flow:%d", telegramID) - data, err := s.redis.Get(ctx, key) - if errors.Is(err, redis.Nil) { - return nil, nil - } - if err != nil { - return nil, err - } - - var state CommentFlowState - if err := json.Unmarshal([]byte(data), &state); err != nil { - return nil, err - } - return &state, nil -} - -func (s *StateManager) ClearCommentFlow(ctx context.Context, telegramID int64) error { - key := fmt.Sprintf("comment_flow:%d", telegramID) - return s.redis.Del(ctx, key) -} - -func (s *StateManager) SetCommentReply(ctx context.Context, telegramID int64, state *CommentReplyState) error { - key := fmt.Sprintf("comment_reply:%d", telegramID) - data, _ := json.Marshal(state) - return s.redis.Set(ctx, key, data, 30*time.Minute) -} - -func (s *StateManager) GetCommentReply(ctx context.Context, telegramID int64) (*CommentReplyState, error) { - key := fmt.Sprintf("comment_reply:%d", telegramID) - data, err := s.redis.Get(ctx, key) - if errors.Is(err, redis.Nil) { - return nil, nil - } - if err != nil { - return nil, err - } - var state CommentReplyState - json.Unmarshal([]byte(data), &state) - return &state, nil -} - -func (s *StateManager) ClearCommentReply(ctx context.Context, telegramID int64) error { - return s.redis.Del(ctx, fmt.Sprintf("comment_reply:%d", telegramID)) -} - ------END service/telegram_service/state/comment.go----- - -File: service/telegram_service/state/delegation.go -Lines: 45 ------BEGIN service/telegram_service/state/delegation.go----- -// telegram_service/state/handler_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)) -} - ------END service/telegram_service/state/delegation.go----- - -File: service/telegram_service/state/pending_state.go -Lines: 67 ------BEGIN service/telegram_service/state/pending_state.go----- -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)) -} - ------END service/telegram_service/state/pending_state.go----- - -File: service/telegram_service/state/report_state.go -Lines: 44 ------BEGIN service/telegram_service/state/report_state.go----- -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)) -} - ------END service/telegram_service/state/report_state.go----- - -File: service/telegram_service/state/revision.go -Lines: 47 ------BEGIN service/telegram_service/state/revision.go----- -package state - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "time" - - "github.com/redis/go-redis/v9" -) - -type RevisionFlowState struct { - ApprovalID uint64 `json:"approval_id"` - Stage string `json:"stage"` // "await_action" | "await_content" | "await_files" -} - -func (s *StateManager) SetRevisionFlow(ctx context.Context, telegramID int64, state *RevisionFlowState) error { - key := fmt.Sprintf("revision_flow:%d", telegramID) - data, err := json.Marshal(state) - if err != nil { - return err - } - return s.redis.Set(ctx, key, data, 30*time.Minute) -} - -func (s *StateManager) GetRevisionFlow(ctx context.Context, telegramID int64) (*RevisionFlowState, error) { - key := fmt.Sprintf("revision_flow:%d", telegramID) - data, err := s.redis.Get(ctx, key) - if errors.Is(err, redis.Nil) { - return nil, nil - } - if err != nil { - return nil, err - } - - var state RevisionFlowState - if err := json.Unmarshal([]byte(data), &state); err != nil { - return nil, err - } - return &state, nil -} - -func (s *StateManager) ClearRevisionFlow(ctx context.Context, telegramID int64) error { - key := fmt.Sprintf("revision_flow:%d", telegramID) - return s.redis.Del(ctx, key) -} - ------END service/telegram_service/state/revision.go----- - -File: service/telegram_service/state/state.go -Lines: 93 ------BEGIN service/telegram_service/state/state.go----- -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 - MessageID int -} - -// 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"` - FilesStepCompleted bool `json:"files_step_completed"` - MultiSelected map[string][]string `json:"multi_selected,omitempty"` - AwaitMultiSelectConfirm bool `json:"await_multi_select_confirm,omitempty"` - MultiSelectNodeKey string `json:"multi_select_node_key,omitempty"` - - // Выбор первого согласующего по роли - AwaitFirstApproverSelection bool `json:"await_first_approver_selection"` - SelectedFirstApproverID uint64 `json:"selected_first_approver_id,omitempty"` - - // Выбор основного согласующего - AwaitApproverSelection bool `json:"await_approver_selection"` - SelectedApproverID uint64 `json:"selected_approver_id,omitempty"` - - // Выбор наблюдателей (мультиселект) - AwaitObserverSelection bool `json:"await_observer_selection"` - ObserverSelectionDone bool `json:"observer_selection_done"` - SelectedObserverIDs []uint64 `json:"selected_observer_ids,omitempty"` - - // 🆕 Делегирование обязанностей на время отсутствия (отгул/отпуск/ - // больничный) — см. handlers/approval/delegation.go. Тот же паттерн, - // что у наблюдателей: Await*/ *Done флаги + выбранное значение. - AwaitDelegationChoice bool `json:"await_delegation_choice,omitempty"` - AwaitDelegateSelection bool `json:"await_delegate_selection,omitempty"` - DelegationSelectionDone bool `json:"delegation_selection_done,omitempty"` - SelectedDelegateID uint64 `json:"selected_delegate_id,omitempty"` -} - -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)) -} - ------END service/telegram_service/state/state.go----- - -File: service/telegram_service/state/suggesttion.go -Lines: 47 ------BEGIN service/telegram_service/state/suggesttion.go----- -package state - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "time" - - "github.com/redis/go-redis/v9" -) - -type SuggestionFlowState struct { - SuggestionID uint64 `json:"suggestion_id,omitempty"` - Stage string `json:"stage"` // "await_subject", "await_message", "await_file" -} - -func (s *StateManager) SetSuggestionFlow(ctx context.Context, telegramID int64, state *SuggestionFlowState) error { - key := fmt.Sprintf("suggestion_flow:%d", telegramID) - data, err := json.Marshal(state) - if err != nil { - return err - } - return s.redis.Set(ctx, key, data, 30*time.Minute) -} - -func (s *StateManager) GetSuggestionFlow(ctx context.Context, telegramID int64) (*SuggestionFlowState, error) { - key := fmt.Sprintf("suggestion_flow:%d", telegramID) - data, err := s.redis.Get(ctx, key) - if errors.Is(err, redis.Nil) { - return nil, nil - } - if err != nil { - return nil, err - } - - var state SuggestionFlowState - if err := json.Unmarshal([]byte(data), &state); err != nil { - return nil, err - } - return &state, nil -} - -func (s *StateManager) ClearSuggestionFlow(ctx context.Context, telegramID int64) error { - key := fmt.Sprintf("suggestion_flow:%d", telegramID) - return s.redis.Del(ctx, key) -} - ------END service/telegram_service/state/suggesttion.go----- - -File: service/telegram_service/types/types.go -Lines: 16 ------BEGIN service/telegram_service/types/types.go----- -package types - -import ( - configcore "bitrix_balancer_api/core/config" - database "bitrix_balancer_api/core/db" - "bitrix_balancer_api/core/lib/external/tgkit" - - redismodule "bitrix_balancer_api/core/lib/internally/redis" -) - -type InternalProviderControl struct { - Config *configcore.Config - RedisClient *redismodule.ModuleRedis - TGBotClient *tgkit.Client - Database *database.ModuleDB -} - ------END service/telegram_service/types/types.go----- - diff --git a/service/telegram_service/scheduler/monthly_order_checker.go b/service/telegram_service/scheduler/monthly_order_checker.go index 03194e5..2178bff 100644 --- a/service/telegram_service/scheduler/monthly_order_checker.go +++ b/service/telegram_service/scheduler/monthly_order_checker.go @@ -24,7 +24,12 @@ func (c *MonthlyOrderChecker) Start() { func (c *MonthlyOrderChecker) loop() { logrus.Info("🚀 [MonthlyOrderChecker] Воркер автоотправки заказов запущен. Интервал проверки: 15 минут") - for { + // Используем Ticker вместо time.Sleep + ticker := time.NewTicker(15 * time.Minute) + defer ticker.Stop() + + // Бесконечный цикл, который блокируется до следующего тика + for range ticker.C { now := time.Now() month, year := int(now.Month()), now.Year() ctx := context.Background() @@ -34,6 +39,7 @@ func (c *MonthlyOrderChecker) loop() { settings, err := c.ipc.Database.MonthlyOrders.GetCurrentSettings(ctx, month, year) if err != nil || settings == nil || settings.DeadlineDate == nil { logrus.Debugf("⚠️ [MonthlyOrderChecker] Настройки дедлайна на %02d.%d не заданы. Пропуск.", month, year) + // Теперь continue безопасно вернет нас к ожиданию следующего тика таймера continue } @@ -46,14 +52,12 @@ func (c *MonthlyOrderChecker) loop() { for _, managerID := range managers { logrus.Infof("🔄 [MonthlyOrderChecker] Обработка менеджера ID: %d", managerID) - err := c.service.SubmitOrdersToTelegram(ctx, managerID) - if err != nil { + if err := c.service.SubmitOrdersToTelegram(ctx, managerID); err != nil { logrus.Errorf("❌ [MonthlyOrderChecker] Ошибка отправки для менеджера %d: %v", managerID, err) } } } else { logrus.Debugf("⏳ [MonthlyOrderChecker] Дедлайн (%s) еще не наступил. Спим дальше.", settings.DeadlineDate.Format("02.01.2006 15:04")) } - time.Sleep(15 * time.Minute) } }