├── .gitignore
├── .golangci.yml
├── README.MD
├── 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.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
File: cmd/app.go
Lines: 256
-----BEGIN 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_TOKEN>` — JWT токен администратора
// @description - `ApiKey: <HMAC_SIGNATURE>` — HMAC подпись для верификации клиента
// @description - `X-Timestamp: <UNIX_TIMESTAMP>` — Unix timestamp (не старше 3 минут)
// @description - `x-device-id: <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 cmd/app.go-----

File: docs/docs.go
Lines: 3990
-----BEGIN 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_TOKEN>` — JWT токен администратора\n- `ApiKey: <HMAC_SIGNATURE>` — HMAC подпись для верификации клиента\n- `X-Timestamp: <UNIX_TIMESTAMP>` — Unix timestamp (не старше 3 минут)\n- `x-device-id: <DEVICE_ID>` — ID устройства",
	InfoInstanceName: "swagger",
	SwaggerTemplate:  docTemplate,
	LeftDelim:        "{{",
	RightDelim:       "}}",
}

func init() {
	swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
}

-----END docs/docs.go-----

File: handlers/admin/handlers.go
Lines: 502
-----BEGIN 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: &currentUserID},
	})
	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: &currentUserID},
	})
	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: &currentUserID},
	})
	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 handlers/admin/handlers.go-----

File: handlers/admin/routes.go
Lines: 38
-----BEGIN 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 handlers/admin/routes.go-----

File: handlers/admin_actions/handlers.go
Lines: 210
-----BEGIN 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: &currentUserID},
	})
	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 handlers/admin_actions/handlers.go-----

File: handlers/approval_steps/handlers.go
Lines: 442
-----BEGIN 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 handlers/approval_steps/handlers.go-----

File: handlers/approval_steps/routes.go
Lines: 43
-----BEGIN 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 handlers/approval_steps/routes.go-----

File: handlers/approval_tasks/handlers.go
Lines: 518
-----BEGIN handlers/approval_tasks/handlers.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
	}

	options := typescore.ListDbOptions{
		Filtering:  taskParams,
		Offset:     offset,
		Limit:      limit,
		LikeFields: likeFields,
	}

	ctx := r.Context()
	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: &currentUserID},
	})
	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 handlers/approval_tasks/handlers.go-----

File: handlers/approval_tasks/routes.go
Lines: 44
-----BEGIN 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 handlers/approval_tasks/routes.go-----

File: handlers/approvalextras/handler.go
Lines: 422
-----BEGIN 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 handlers/approvalextras/handler.go-----

File: handlers/approvals/files.go
Lines: 278
-----BEGIN 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 handlers/approvals/files.go-----

File: handlers/approvals/handlers.go
Lines: 678
-----BEGIN handlers/approvals/handlers.go-----
package approvalshandler

import (
	"bitrix_balancer_api/core/typescore"
	"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
	}

	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()

	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]
			}
		}
	}
}

-----END handlers/approvals/handlers.go-----

File: handlers/approvals/reports.go
Lines: 73
-----BEGIN 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 handlers/approvals/reports.go-----

File: handlers/approvals/routes.go
Lines: 48
-----BEGIN 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 handlers/approvals/routes.go-----

File: handlers/auth/handlers.go
Lines: 204
-----BEGIN 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 handlers/auth/handlers.go-----

File: handlers/auth/routes.go
Lines: 40
-----BEGIN 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 handlers/auth/routes.go-----

File: handlers/dashboard/handlers.go
Lines: 908
-----BEGIN 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(`(\d{1,2}):(\d{2}).*?(\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 handlers/dashboard/handlers.go-----

File: handlers/dashboard/routes.go
Lines: 33
-----BEGIN 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 handlers/dashboard/routes.go-----

File: handlers/departments/handlers.go
Lines: 344
-----BEGIN 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: &currentUserID},
	})
	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 handlers/departments/handlers.go-----

File: handlers/departments/routes.go
Lines: 47
-----BEGIN 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 handlers/departments/routes.go-----

File: handlers/flow_nodes/handler.go
Lines: 837
-----BEGIN 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: &currentUserID},
	})
	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 handlers/flow_nodes/handler.go-----

File: handlers/flow_nodes/preview.go
Lines: 111
-----BEGIN 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 handlers/flow_nodes/preview.go-----

File: handlers/flow_nodes/router.go
Lines: 61
-----BEGIN 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 handlers/flow_nodes/router.go-----

File: handlers/flow_nodes/utils.go
Lines: 20
-----BEGIN 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 handlers/flow_nodes/utils.go-----

File: handlers/middleware.go
Lines: 328
-----BEGIN 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 handlers/middleware.go-----

File: handlers/notification/handlers.go
Lines: 306
-----BEGIN 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: &currentUserID},
	})
	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 handlers/notification/handlers.go-----

File: handlers/notification/routes.go
Lines: 26
-----BEGIN 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 handlers/notification/routes.go-----

File: handlers/permission/handlers.go
Lines: 648
-----BEGIN 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: &currentUserID},
	})
	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 handlers/permission/handlers.go-----

File: handlers/permission/routes.go
Lines: 43
-----BEGIN 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 handlers/permission/routes.go-----

File: handlers/profile/handlers.go
Lines: 102
-----BEGIN 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 handlers/profile/handlers.go-----

File: handlers/profile/routes.go
Lines: 36
-----BEGIN 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 handlers/profile/routes.go-----

File: handlers/register.go
Lines: 162
-----BEGIN 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 handlers/register.go-----

File: handlers/roles/handlers.go
Lines: 385
-----BEGIN 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: &currentUserID},
	})
	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 handlers/roles/handlers.go-----

File: handlers/roles/routes.go
Lines: 39
-----BEGIN 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 handlers/roles/routes.go-----

File: handlers/system_monitoring/handlers.go
Lines: 259
-----BEGIN 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 handlers/system_monitoring/handlers.go-----

File: handlers/topic_categories/handlers.go
Lines: 361
-----BEGIN 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: &currentUserID},
	})
	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 handlers/topic_categories/handlers.go-----

File: handlers/topic_categories/routes.go
Lines: 39
-----BEGIN 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 handlers/topic_categories/routes.go-----

File: handlers/topic_executors/handlers.go
Lines: 603
-----BEGIN 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: &currentUserID},
	})
	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 handlers/topic_executors/handlers.go-----

File: handlers/topic_executors/routes.go
Lines: 43
-----BEGIN 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 handlers/topic_executors/routes.go-----

File: handlers/topics/handlers.go
Lines: 519
-----BEGIN 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: &currentUserID},
	})
	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 handlers/topics/handlers.go-----

File: handlers/topics/routes.go
Lines: 39
-----BEGIN 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 handlers/topics/routes.go-----

File: handlers/user_hierarchy/handlers.go
Lines: 531
-----BEGIN 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: &currentUserID},
	})
	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 handlers/user_hierarchy/handlers.go-----

File: handlers/user_hierarchy/routes.go
Lines: 39
-----BEGIN 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 handlers/user_hierarchy/routes.go-----

File: handlers/user_roles/handlers.go
Lines: 477
-----BEGIN 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: &currentUserID},
	})
	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 handlers/user_roles/handlers.go-----

File: handlers/user_roles/routes.go
Lines: 53
-----BEGIN 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 handlers/user_roles/routes.go-----

File: handlers/users/handlers.go
Lines: 417
-----BEGIN 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: &currentUserID},
	})
	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 handlers/users/handlers.go-----

File: handlers/users/routes.go
Lines: 39
-----BEGIN 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 handlers/users/routes.go-----

File: types/module.go
Lines: 15
-----BEGIN 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 types/module.go-----

File: types/req.go
Lines: 13
-----BEGIN 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 types/req.go-----

