Added admin actions logs #87

Merged
romanskijdev merged 1 commits from fix-permissions into main 2026-07-28 11:33:50 +03:00
23 changed files with 2360 additions and 209 deletions

View File

@ -39,6 +39,7 @@ type ModuleDB struct {
ApprovalTaskTransfer *dbcore.ApprovalTaskTransferDB
ApprovalRevocation *dbcore.ApprovalRevocationDB
ApprovalFlowNode *dbcore.ApprovalFlowNodeDB
AdminActionLogs *dbcore.AdminActionLogDB
}
func NewModuleDB(
@ -94,6 +95,7 @@ func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *Mod
modules.ApprovalTaskTransfer = dbcore.NewApprovalTaskTransferDB(modules.Pool)
modules.ApprovalRevocation = dbcore.NewApprovalRevocationDB(modules.Pool)
modules.ApprovalFlowNode = dbcore.NewApprovalFlowNodeDB(modules.Pool)
modules.AdminActionLogs = dbcore.NewAdminActionLogDB(modules.Pool)
return modules
}

View File

@ -44,6 +44,7 @@ func (m *MigrationFunctions) migrateTables() error {
tablesmigration.ApprovalTaskTransfersTableMigrate,
tablesmigration.ApprovalRevocationTablesMigrate,
tablesmigration.ApprovalFlowNodesTableMigrate,
tablesmigration.AdminActionLogsTableMigrate,
}
for _, migrate := range migrations {

View File

@ -0,0 +1,36 @@
package tablesmigration
import (
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
"bitrix_balancer_api/core/typescore"
"gorm.io/gorm"
"time"
)
// LocalAdminProvider - локальная структура для миграции
type LocalAdminActionProvider typescore.AdminActionLog
func (LocalAdminActionProvider) TableName() string {
return dbcoretablenames.TableNameAdminActionLogs.ToString()
}
// AdminsTableMigrate - миграция таблицы Admins
func AdminActionLogsTableMigrate(db *gorm.DB) error {
hasTable := db.Migrator().HasTable(&LocalAdminActionProvider{})
// Выполняем автосоздание таблицы
err := db.AutoMigrate(&LocalAdminActionProvider{})
if err != nil {
return err
}
if !hasTable {
time.Sleep(5 * time.Second) // Добавляем задержку
// Add comments to table and columns
db.Exec(`
COMMENT ON TABLE admin_action_logs IS 'Таблица для хранения данных о действиях администратора';
`)
}
return nil
}

View File

@ -0,0 +1,192 @@
package dbcore
import (
dbcoretablenames "bitrix_balancer_api/core/db/table_names"
"bitrix_balancer_api/core/typescore"
dbutils "bitrix_balancer_api/core/utilscore/db"
"context"
"errors"
"github.com/Masterminds/squirrel"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/sirupsen/logrus"
)
type AdminActionLogDB struct {
pool *pgxpool.Pool
}
func NewAdminActionLogDB(pool *pgxpool.Pool) *AdminActionLogDB {
return &AdminActionLogDB{pool: pool}
}
type AdminActionLogDBI interface {
GetAdminActionLogsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.AdminActionLog, uint64, error)
CreateAdminActionLogDB(ctx context.Context, tx pgx.Tx, obj *typescore.AdminActionLog, returnObj ...bool) (*typescore.AdminActionLog, pgx.Tx, error)
DeleteAdminActionLogDB(ctx context.Context, params *typescore.AdminActionLog) error
GetAdminActionLogByIDDB(ctx context.Context, id uint64) (*typescore.AdminActionLog, error)
GetAdminActionLogsFilteredDB(ctx context.Context, filter typescore.AdminActionLogFilter, offset, limit *uint64) ([]*typescore.AdminActionLog, uint64, error)
}
func (u *AdminActionLogDB) GetAdminActionLogsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.AdminActionLog, uint64, error) {
fields := dbutils.GetStructFieldsDB(&typescore.AdminActionLog{}, dbcoretablenames.TableNameAdminActionLogs.ToString())
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
options, filter, err := dbutils.GetOptionsDB[typescore.AdminActionLog](opts...)
if err != nil {
return nil, 0, err
}
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameAdminActionLogs.ToString(), selectFields)
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
query = dbutils.ApplyFilters(query, filter, options.LikeFields, dbcoretablenames.TableNameAdminActionLogs.ToString())
query = query.OrderBy("created_at DESC") // самые свежие действия первыми
sql, args, err := query.ToSql()
if err != nil {
return nil, 0, err
}
rows, err := u.pool.Query(ctx, sql, args...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
var logs []*typescore.AdminActionLog
var totalCount uint64
for rows.Next() {
entry := &typescore.AdminActionLog{}
if err := dbutils.ScanRowsToStructRows(rows, entry, &totalCount); err != nil {
logrus.Warn("GetAdminActionLogsListDB:ScanRowsToStructRows", err)
continue
}
logs = append(logs, entry)
}
return logs, totalCount, nil
}
func (u *AdminActionLogDB) GetAdminActionLogsFilteredDB(ctx context.Context, filter typescore.AdminActionLogFilter, offset, limit *uint64) ([]*typescore.AdminActionLog, uint64, error) {
fields := dbutils.GetStructFieldsDB(&typescore.AdminActionLog{}, dbcoretablenames.TableNameAdminActionLogs.ToString())
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
query := dbutils.BuildSelectQuery(dbcoretablenames.TableNameAdminActionLogs.ToString(), selectFields)
if filter.AdminID != nil {
query = query.Where(squirrel.Eq{"admin_id": *filter.AdminID})
}
if filter.AdminLogin != nil && *filter.AdminLogin != "" {
query = query.Where(squirrel.ILike{"admin_login": "%" + *filter.AdminLogin + "%"})
}
if filter.Action != nil {
query = query.Where(squirrel.Eq{"action": *filter.Action})
}
if filter.EntityType != nil {
query = query.Where(squirrel.Eq{"entity_type": *filter.EntityType})
}
if filter.EntityID != nil {
query = query.Where(squirrel.Eq{"entity_id": *filter.EntityID})
}
if filter.DateFrom != nil {
query = query.Where(squirrel.GtOrEq{"created_at": *filter.DateFrom})
}
if filter.DateTo != nil {
query = query.Where(squirrel.LtOrEq{"created_at": *filter.DateTo})
}
if filter.Search != nil && *filter.Search != "" {
query = query.Where(squirrel.ILike{"description": "%" + *filter.Search + "%"})
}
query = dbutils.SetterLimitAndOffsetQuery(query, offset, limit)
query = query.OrderBy("created_at DESC")
sql, args, err := query.ToSql()
if err != nil {
return nil, 0, err
}
rows, err := u.pool.Query(ctx, sql, args...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
var logs []*typescore.AdminActionLog
var totalCount uint64
for rows.Next() {
entry := &typescore.AdminActionLog{}
if err := dbutils.ScanRowsToStructRows(rows, entry, &totalCount); err != nil {
logrus.Warn("GetAdminActionLogsFilteredDB:ScanRowsToStructRows", err)
continue
}
logs = append(logs, entry)
}
return logs, totalCount, nil
}
func (u *AdminActionLogDB) CreateAdminActionLogDB(ctx context.Context, tx pgx.Tx, obj *typescore.AdminActionLog, returnObj ...bool) (*typescore.AdminActionLog, pgx.Tx, error) {
if obj == nil {
return nil, nil, errors.New("AdminActionLog obj is nil")
}
var insertedID uint64
err := dbutils.ExecuteTx(ctx, u.pool, tx, func(tx pgx.Tx) error {
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
Insert(dbcoretablenames.TableNameAdminActionLogs.ToString())
sqlV, args, err := dbutils.GenerateInsertRequest(query, obj)
if err != nil {
return err
}
*sqlV = *sqlV + " RETURNING id"
return tx.QueryRow(ctx, *sqlV, args...).Scan(&insertedID)
})
if err != nil {
return nil, tx, err
}
returnObjBool := len(returnObj) > 0 && returnObj[0]
if returnObjBool && insertedID > 0 {
created, err := u.GetAdminActionLogByIDDB(ctx, insertedID)
return created, tx, err
}
return nil, tx, nil
}
func (u *AdminActionLogDB) DeleteAdminActionLogDB(ctx context.Context, params *typescore.AdminActionLog) error {
if params == nil || params.ID == nil {
return errors.New("AdminActionLog obj is nil")
}
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
Delete(dbcoretablenames.TableNameAdminActionLogs.ToString()).
Where(squirrel.Eq{"id": *params.ID}).
ToSql()
if err != nil {
return err
}
rows, err := u.pool.Query(ctx, query, args...)
if err != nil {
return err
}
defer rows.Close()
return nil
}
func (u *AdminActionLogDB) GetAdminActionLogByIDDB(ctx context.Context, id uint64) (*typescore.AdminActionLog, error) {
logs, _, err := u.GetAdminActionLogsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.AdminActionLog{ID: &id},
})
if err != nil {
return nil, err
}
if len(logs) == 0 {
return nil, nil
}
return logs[0], nil
}

View File

@ -30,6 +30,7 @@ const (
TableNameApprovalRevocationRequests TableName = "approval_revocation_requests"
TableNameApprovalRevocationApprovers TableName = "approval_revocation_approvers"
TableNameApprovalFlowNodes TableName = "approval_flow_nodes"
TableNameAdminActionLogs TableName = "admin_action_logs"
)
func (t TableName) ToString() string {

View File

@ -0,0 +1,28 @@
package typescore
import "time"
type AdminActionLog struct {
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
AdminID *uint64 `gorm:"type:bigint;not null;index;column:admin_id" json:"admin_id" db:"admin_id"`
AdminLogin *string `gorm:"type:text;not null;column:admin_login" json:"admin_login" db:"admin_login"`
Action *string `gorm:"type:text;not null;column:action" json:"action" db:"action"`
EntityType *string `gorm:"type:text;not null;column:entity_type" json:"entity_type" db:"entity_type"`
EntityID *uint64 `gorm:"type:bigint;column:entity_id" json:"entity_id,omitempty" db:"entity_id"`
Description *string `gorm:"type:text;not null;column:description" json:"description" db:"description"`
Metadata *string `gorm:"type:jsonb;column:metadata" json:"metadata,omitempty" db:"metadata"`
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
Admin *Admin `gorm:"-" json:"admin,omitempty"`
}
type AdminActionLogFilter struct {
AdminID *uint64
AdminLogin *string // ILIKE-подстрока
Action *string
EntityType *string
EntityID *uint64
DateFrom *time.Time
DateTo *time.Time
Search *string // ILIKE-подстрока по Description
}

62
core/utilscore/eq.go Normal file
View File

@ -0,0 +1,62 @@
package utilscore
func DerefStr(s *string) string {
if s == nil {
return ""
}
return *s
}
func DerefBool(b *bool) bool {
if b == nil {
return false
}
return *b
}
func StrEq(a, b *string) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
return *a == *b
}
func BoolEq(a, b *bool) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
return *a == *b
}
func Uint64Eq(a, b *uint64) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
return *a == *b
}
func IntEq(a, b *int) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
return *a == *b
}
func DerefInt(i *int) int {
if i == nil {
return 0
}
return *i
}

View File

@ -5,6 +5,7 @@ import (
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"
@ -225,6 +226,7 @@ func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) erro
{"notifications", notificationshandler.RegisterNotificationRoutes},
{"flownodes", nodeshandler.RegisterFlowNodesRoutes},
{"approvalextras", approvalextrashandler.RegisterApprovalExtrasRoutes},
{"adminlog", adminloghandler.RegisterAdminLogRoutes},
}
// Регистрация всех маршрутов

View File

@ -5,10 +5,14 @@ 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"
"encoding/json"
"errors"
"fmt"
"github.com/sirupsen/logrus"
"io"
"net/http"
"strings"
)
// GetAdminsListHandler Получение списка администраторов
@ -96,12 +100,10 @@ func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (
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")
}
// Проверяем, что пользователь с таким telegram_id существует
telegramUser, err := s.ipc.Database.User.GetUserByTelegramIDDB(r.Context(), *req.TelegramID)
if err != nil || telegramUser == nil {
return nil, errors.New("telegram_user_not_found")
@ -144,6 +146,40 @@ func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (
}
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
}
@ -243,6 +279,51 @@ func (s *AdminsReg) UpdateAdminHandler(w http.ResponseWriter, r *http.Request) (
}
}
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,
@ -268,6 +349,20 @@ func (s *AdminsReg) UpdateAdminHandler(w http.ResponseWriter, r *http.Request) (
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
}
@ -317,10 +412,91 @@ func (s *AdminsReg) DeleteAdminHandler(w http.ResponseWriter, r *http.Request) (
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
}

View File

@ -0,0 +1,210 @@
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
}

View File

@ -3,6 +3,8 @@ 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"
@ -41,7 +43,6 @@ func (s *ApprovalTasksReg) GetApprovalTasksListHandler(w http.ResponseWriter, r
return nil, errW
}
// 🆕 Обогащаем данные
for _, task := range tasks {
s.enrichTask(ctx, task)
}
@ -105,7 +106,6 @@ func (s *ApprovalTasksReg) UpdateApprovalTaskHandler(w http.ResponseWriter, r *h
return nil, errors.New("task not found")
}
// 🆕 Валидация статуса
if req.Status != nil {
validStatuses := map[string]bool{
"pending": true,
@ -118,6 +118,47 @@ func (s *ApprovalTasksReg) UpdateApprovalTaskHandler(w http.ResponseWriter, r *h
}
}
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
@ -125,6 +166,23 @@ func (s *ApprovalTasksReg) UpdateApprovalTaskHandler(w http.ResponseWriter, r *h
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
}
@ -147,14 +205,66 @@ func (s *ApprovalTasksReg) DeleteApprovalTaskHandler(w http.ResponseWriter, r *h
}
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 {
@ -239,6 +349,11 @@ func (s *ApprovalTasksReg) enrichApproval(ctx context.Context, approval *typesco
}
// GetApprovalTaskFileHandler Получение файла задачи (для предпросмотра)
//
// 🆕 Не логирую просмотр/скачивание файлов — журнал задуман под
// create/update/delete-действия, а не под чтение. Если захотите отслеживать
// ещё и скачивания (например, для файлов с чувствительными данными) — это
// отдельное решение, скажите, добавлю action="download" по тому же паттерну.
func (s *ApprovalTasksReg) GetApprovalTaskFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
ctx := r.Context()

View File

@ -3,12 +3,17 @@ 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"
)
@ -115,7 +120,6 @@ func (s *DepartmentsReg) CreateDepartmentHandler(w http.ResponseWriter, r *http.
return nil, errors.New("invalid request body")
}
// Валидация обязательных полей
if req.Name == nil || *req.Name == "" {
return nil, errors.New("department name is required")
}
@ -123,7 +127,6 @@ func (s *DepartmentsReg) CreateDepartmentHandler(w http.ResponseWriter, r *http.
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},
@ -135,7 +138,6 @@ func (s *DepartmentsReg) CreateDepartmentHandler(w http.ResponseWriter, r *http.
return nil, errors.New("department code already exists")
}
// Устанавливаем is_active по умолчанию, если не указано
if req.IsActive == nil {
isActive := true
req.IsActive = &isActive
@ -146,6 +148,21 @@ func (s *DepartmentsReg) CreateDepartmentHandler(w http.ResponseWriter, r *http.
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
}
@ -179,7 +196,6 @@ func (s *DepartmentsReg) UpdateDepartmentHandler(w http.ResponseWriter, r *http.
return nil, errors.New("department id is required")
}
// Проверяем, что отдел существует
ctx := r.Context()
existingDept, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.ID)
if err != nil {
@ -189,7 +205,6 @@ func (s *DepartmentsReg) UpdateDepartmentHandler(w http.ResponseWriter, r *http.
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{
@ -204,11 +219,49 @@ func (s *DepartmentsReg) UpdateDepartmentHandler(w http.ResponseWriter, r *http.
}
}
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
}
@ -242,7 +295,6 @@ func (s *DepartmentsReg) DeleteDepartmentHandler(w http.ResponseWriter, r *http.
return nil, errors.New("department id is required")
}
// Проверяем, что отдел существует
ctx := r.Context()
existingDept, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.ID)
if err != nil {
@ -257,5 +309,36 @@ func (s *DepartmentsReg) DeleteDepartmentHandler(w http.ResponseWriter, r *http.
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
}

View File

@ -2,6 +2,9 @@ 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"
@ -13,10 +16,6 @@ import (
"github.com/go-chi/chi/v5"
)
// ============================================================
// GET /category/{category_id} — Получить дерево узлов категории
// ============================================================
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)
@ -26,7 +25,6 @@ func (s *FlowNodesReg) GetFlowNodesByCategoryIDHandler(w http.ResponseWriter, r
ctx := r.Context()
// Проверяем, что категория существует
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
if err != nil {
return nil, err
@ -35,7 +33,6 @@ func (s *FlowNodesReg) GetFlowNodesByCategoryIDHandler(w http.ResponseWriter, r
return nil, errors.New("category not found")
}
// Получаем все узлы для этой категории
nodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalFlowNode{CategoryID: &categoryID},
})
@ -43,7 +40,6 @@ func (s *FlowNodesReg) GetFlowNodesByCategoryIDHandler(w http.ResponseWriter, r
return nil, err
}
// Строим дерево для ответа
tree := s.buildTreeFromNodes(nodes)
return &typescore.ApiResponseBase{
@ -52,10 +48,6 @@ func (s *FlowNodesReg) GetFlowNodesByCategoryIDHandler(w http.ResponseWriter, r
}, nil
}
// ============================================================
// GET /{id} — Получить узел по ID
// ============================================================
func (s *FlowNodesReg) GetFlowNodeByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
idStr := chi.URLParam(r, "id")
if idStr == "" {
@ -79,10 +71,6 @@ func (s *FlowNodesReg) GetFlowNodeByIDHandler(w http.ResponseWriter, r *http.Req
return node, nil
}
// ============================================================
// POST / — Создать узел
// ============================================================
func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
@ -95,7 +83,6 @@ func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
return nil, errors.New("invalid request body")
}
// Валидация обязательных полей
if req.CategoryID == nil {
return nil, errors.New("category_id is required")
}
@ -108,7 +95,6 @@ func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
ctx := r.Context()
// Проверяем, что категория существует
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.CategoryID)
if err != nil {
return nil, err
@ -117,7 +103,6 @@ func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
return nil, errors.New("category not found")
}
// Проверяем, что родительский узел существует (если задан)
if req.ParentID != nil {
parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ParentID)
if err != nil {
@ -126,13 +111,11 @@ func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
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,
@ -146,7 +129,6 @@ func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
return nil, fmt.Errorf("node with key '%s' already exists in this category", *req.Key)
}
// Устанавливаем значения по умолчанию
if req.IsInput == nil {
v := false
req.IsInput = &v
@ -160,11 +142,6 @@ func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
req.SortOrder = &v
}
// Примечание: req.MessageTemplate / req.CodeTemplate, если переданы,
// сохранятся автоматически — они являются обычными полями структуры
// ApprovalFlowNode и не требуют отдельной обработки. Задаются, как правило,
// на терминальных узлах, где также заполнен TopicCode.
created, _, err := s.ipc.Database.ApprovalFlowNode.CreateApprovalFlowNodeDB(ctx, nil, &req, true)
if err != nil {
return nil, err
@ -172,13 +149,27 @@ func (s *FlowNodesReg) CreateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
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
}
// ============================================================
// PUT / — Обновить узел
// ============================================================
func (s *FlowNodesReg) UpdateFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
@ -197,7 +188,6 @@ func (s *FlowNodesReg) UpdateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
ctx := r.Context()
// Проверяем, что узел существует
existing, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ID)
if err != nil {
return nil, err
@ -206,7 +196,6 @@ func (s *FlowNodesReg) UpdateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
return nil, errors.New("node not found")
}
// Если меняется parent_id — проверяем корректность
if req.ParentID != nil && (existing.ParentID == nil || *existing.ParentID != *req.ParentID) {
parent, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ParentID)
if err != nil {
@ -215,17 +204,14 @@ func (s *FlowNodesReg) UpdateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
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
}
}
// Если меняется key — проверяем уникальность в рамках категории
if req.Key != nil && *req.Key != "" {
if existing.Key == nil || *existing.Key != *req.Key {
categoryID := existing.CategoryID
@ -247,6 +233,46 @@ func (s *FlowNodesReg) UpdateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
}
}
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
@ -254,13 +280,21 @@ func (s *FlowNodesReg) UpdateFlowNodeHandler(w http.ResponseWriter, r *http.Requ
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
}
// ============================================================
// DELETE / — Удалить узел (и всех детей каскадно через FK)
// ============================================================
func (s *FlowNodesReg) DeleteFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
@ -279,7 +313,6 @@ func (s *FlowNodesReg) DeleteFlowNodeHandler(w http.ResponseWriter, r *http.Requ
ctx := r.Context()
// Проверяем, что узел существует
existing, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, *req.ID)
if err != nil {
return nil, err
@ -288,6 +321,10 @@ func (s *FlowNodesReg) DeleteFlowNodeHandler(w http.ResponseWriter, r *http.Requ
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
@ -295,13 +332,27 @@ func (s *FlowNodesReg) DeleteFlowNodeHandler(w http.ResponseWriter, r *http.Requ
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
}
// ============================================================
// POST /category/{category_id}/tree — Сохранить всё дерево целиком
// ============================================================
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)
@ -324,7 +375,6 @@ func (s *FlowNodesReg) SaveEntireTreeHandler(w http.ResponseWriter, r *http.Requ
ctx := r.Context()
// Проверяем, что категория существует
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, categoryID)
if err != nil {
return nil, err
@ -333,25 +383,38 @@ func (s *FlowNodesReg) SaveEntireTreeHandler(w http.ResponseWriter, r *http.Requ
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
}
// ============================================================
// POST /{id}/move — Переместить узел (изменить родителя и/или порядок)
// ============================================================
func (s *FlowNodesReg) MoveFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
idStr := chi.URLParam(r, "id")
id, err := strconv.ParseUint(idStr, 10, 64)
@ -366,8 +429,8 @@ func (s *FlowNodesReg) MoveFlowNodeHandler(w http.ResponseWriter, r *http.Reques
}
var req struct {
NewParentID *uint64 `json:"new_parent_id"` // nil — не менять родителя
NewSortOrder *int `json:"new_sort_order"` // nil — не менять порядок
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")
@ -375,7 +438,6 @@ func (s *FlowNodesReg) MoveFlowNodeHandler(w http.ResponseWriter, r *http.Reques
ctx := r.Context()
// Получаем текущий узел
node, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id)
if err != nil {
return nil, err
@ -384,9 +446,7 @@ func (s *FlowNodesReg) MoveFlowNodeHandler(w http.ResponseWriter, r *http.Reques
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")
}
@ -399,18 +459,15 @@ func (s *FlowNodesReg) MoveFlowNodeHandler(w http.ResponseWriter, r *http.Reques
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
@ -426,13 +483,28 @@ func (s *FlowNodesReg) MoveFlowNodeHandler(w http.ResponseWriter, r *http.Reques
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
}
// ============================================================
// POST /{id}/duplicate — Дублировать узел со всеми детьми
// ============================================================
func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
idStr := chi.URLParam(r, "id")
id, err := strconv.ParseUint(idStr, 10, 64)
@ -442,7 +514,6 @@ func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.R
ctx := r.Context()
// Получаем исходный узел
original, err := s.ipc.Database.ApprovalFlowNode.GetFlowNodeByIDDB(ctx, id)
if err != nil {
return nil, err
@ -451,7 +522,6 @@ func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("node not found")
}
// Получаем все узлы категории исходного узла (для рекурсивного дублирования)
allNodes, _, err := s.ipc.Database.ApprovalFlowNode.GetApprovalFlowNodesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalFlowNode{CategoryID: original.CategoryID},
})
@ -459,20 +529,16 @@ func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.R
return nil, err
}
// Находим всех потомков (BFS)
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, // остаётся на том же уровне
ParentID: original.ParentID,
Key: &newKey,
Label: &newLabel,
DataKey: original.DataKey,
@ -494,14 +560,11 @@ func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.R
return nil, err
}
// Дублируем потомков рекурсивно
if len(descendants) > 0 {
// Строим маппинг старых ID → новые ID
idMapping := map[uint64]uint64{
id: *createdCopy.ID,
}
// Сортируем потомков по уровню вложенности (чтобы родители создавались раньше детей)
sortedDescendants := s.sortByDepth(id, descendants, allNodes)
for _, desc := range sortedDescendants {
@ -525,7 +588,6 @@ func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.R
CodeTemplate: desc.CodeTemplate,
}
// Устанавливаем новый parent_id
if desc.ParentID != nil {
if newParentID, ok := idMapping[*desc.ParentID]; ok {
descCopy.ParentID = &newParentID
@ -544,14 +606,22 @@ func (s *FlowNodesReg) DuplicateFlowNodeHandler(w http.ResponseWriter, r *http.R
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
}
// ============================================================
// Вспомогательные методы
// ============================================================
// buildTreeFromNodes строит иерархическое дерево из плоского списка узлов
func (s *FlowNodesReg) buildTreeFromNodes(nodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode {
nodeMap := make(map[uint64]*typescore.ApprovalFlowNode)
var roots []*typescore.ApprovalFlowNode
@ -573,7 +643,6 @@ func (s *FlowNodesReg) buildTreeFromNodes(nodes []*typescore.ApprovalFlowNode) [
return roots
}
// saveNodesRecursive рекурсивно сохраняет узлы дерева в БД
func (s *FlowNodesReg) saveNodesRecursive(ctx context.Context, nodes []*typescore.ApprovalFlowNode, categoryID uint64, parentID *uint64) error {
for i, node := range nodes {
node.CategoryID = &categoryID
@ -596,16 +665,15 @@ func (s *FlowNodesReg) saveNodesRecursive(ctx context.Context, nodes []*typescor
return nil
}
// checkNoCyclicReference проверяет, что при перемещении узла не создаётся цикл
// (т.е. узел не становится своим же потомком)
// checkNoCyclicReference идёт вверх по родителям от newParentID — если
// встретит nodeID, значит перемещение создаёт цикл.
func (s *FlowNodesReg) checkNoCyclicReference(ctx context.Context, nodeID, newParentID uint64) error {
// Идём вверх по родителям от newParentID — если встретим nodeID, значит цикл
currentID := newParentID
visited := make(map[uint64]bool)
for currentID != 0 {
if visited[currentID] {
break // защита от уже существующих циклов
break
}
visited[currentID] = true
@ -626,9 +694,7 @@ func (s *FlowNodesReg) checkNoCyclicReference(ctx context.Context, nodeID, newPa
return nil
}
// collectDescendants собирает всех потомков узла (BFS)
func (s *FlowNodesReg) collectDescendants(rootID uint64, allNodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode {
// Строим map parent_id → children
childrenMap := make(map[uint64][]*typescore.ApprovalFlowNode)
for _, n := range allNodes {
if n.ParentID != nil {
@ -654,13 +720,10 @@ func (s *FlowNodesReg) collectDescendants(rootID uint64, allNodes []*typescore.A
return result
}
// sortByDepth сортирует потомков по глубине вложенности (ближайшие к корню — первые)
func (s *FlowNodesReg) sortByDepth(rootID uint64, descendants, allNodes []*typescore.ApprovalFlowNode) []*typescore.ApprovalFlowNode {
// Считаем глубину каждого узла
depthMap := make(map[uint64]int)
depthMap[rootID] = 0
// Строим map id → node
nodeMap := make(map[uint64]*typescore.ApprovalFlowNode)
for _, n := range allNodes {
if n.ID != nil {
@ -668,7 +731,6 @@ func (s *FlowNodesReg) sortByDepth(rootID uint64, descendants, allNodes []*types
}
}
// Для каждого потомка считаем глубину
for _, d := range descendants {
if d.ID == nil {
continue
@ -689,7 +751,6 @@ func (s *FlowNodesReg) sortByDepth(rootID uint64, descendants, allNodes []*types
depthMap[*d.ID] = depth
}
// Простая сортировка по глубине (bubble sort для небольшого N)
sorted := make([]*typescore.ApprovalFlowNode, len(descendants))
copy(sorted, descendants)
for i := 0; i < len(sorted); i++ {
@ -711,13 +772,11 @@ func (s *FlowNodesReg) sortByDepth(rootID uint64, descendants, allNodes []*types
return sorted
}
// generateCopySuffix генерирует уникальный суффикс для дублированного ключа
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},
})
@ -733,12 +792,11 @@ func (s *FlowNodesReg) generateCopySuffix(ctx context.Context, original *typesco
continue
}
key := *n.Key
// Проверяем паттерн baseKey_copy_N
if len(key) > len(baseKey) && key[:len(baseKey)] == baseKey {
suffix := key[len(baseKey):]
if len(suffix) >= 6 && suffix[:5] == "_copy" {
if len(suffix) > 5 {
numStr := suffix[6:] // после "_copy_"
numStr := suffix[6:]
if num, err := strconv.Atoi(numStr); err == nil && num > maxNum {
maxNum = num
}
@ -753,3 +811,27 @@ func (s *FlowNodesReg) generateCopySuffix(ctx context.Context, original *typesco
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
}

View File

@ -3,10 +3,13 @@ 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"
@ -35,7 +38,6 @@ func (s *NotificationReg) CreateNotificationHandler(w http.ResponseWriter, r *ht
ctx := r.Context()
// 1. Резолвим получателей по всем критериям, объединяем через map по user.ID (дедупликация)
recipients, err := s.resolveRecipients(ctx, req.Targets)
if err != nil {
return nil, err
@ -67,7 +69,6 @@ func (s *NotificationReg) CreateNotificationHandler(w http.ResponseWriter, r *ht
return nil, err
}
// 2. Создаём строки истории со статусом pending для каждого получателя
pendingStatus := "pending"
recipientRows := make([]*typescore.NotificationRecipient, 0, len(recipients))
for _, u := range recipients {
@ -81,7 +82,6 @@ func (s *NotificationReg) CreateNotificationHandler(w http.ResponseWriter, r *ht
return nil, err
}
// 3. Отправляем синхронно (для больших рассылок стоит вынести в очередь/горутину с ограничением по rate)
sentCount, failedCount := s.sendToRecipients(ctx, notification, recipients)
finalStatus := "completed"
@ -92,6 +92,23 @@ func (s *NotificationReg) CreateNotificationHandler(w http.ResponseWriter, r *ht
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
}
@ -107,7 +124,6 @@ func (s *NotificationReg) resolveRecipients(ctx context.Context, filters typesco
}
}
// 1. Конкретные пользователи
if len(filters.UserIDs) > 0 {
users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, filters.UserIDs)
if err != nil {
@ -116,7 +132,6 @@ func (s *NotificationReg) resolveRecipients(ctx context.Context, filters typesco
addUsers(users)
}
// 2. По ролям (id)
if len(filters.RoleIDs) > 0 {
users, _, err := s.ipc.Database.User.GetUsersListByRoleIDsDB(ctx, typescore.ListDbOptions{}, filters.RoleIDs)
if err != nil {
@ -125,7 +140,6 @@ func (s *NotificationReg) resolveRecipients(ctx context.Context, filters typesco
addUsers(users)
}
// 3. По типу роли (флаги)
if len(filters.RoleTypeFlags) > 0 {
users, err := s.ipc.Database.User.GetUsersByRoleFlagsDB(ctx, filters.RoleTypeFlags)
if err != nil {
@ -134,7 +148,6 @@ func (s *NotificationReg) resolveRecipients(ctx context.Context, filters typesco
addUsers(users)
}
// 4. По отделу
if len(filters.DepartmentIDs) > 0 {
users, err := s.ipc.Database.User.GetUsersByDepartmentIDsDB(ctx, filters.DepartmentIDs)
if err != nil {
@ -145,7 +158,6 @@ func (s *NotificationReg) resolveRecipients(ctx context.Context, filters typesco
result := make([]*typescore.User, 0, len(usersMap))
for _, u := range usersMap {
// не шлём заблокированным/уволенным, даже если попали через явный user_id
if u.IsBlocked != nil && *u.IsBlocked {
continue
}
@ -195,7 +207,7 @@ func (s *NotificationReg) sendToRecipients(ctx context.Context, n *typescore.Not
} else {
msgID = sentMsg.MessageID
}
_ = fileName // caption уже ушёл через SendPhoto
_ = fileName
} else {
sentMsg, err := s.ipc.TGBotClient.Send(*u.TelegramID, *n.MessageHTML)
if err != nil {
@ -276,3 +288,19 @@ func (s *NotificationReg) GetNotificationByIDHandler(w http.ResponseWriter, r *h
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
}

View File

@ -3,9 +3,12 @@ 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"
@ -52,7 +55,6 @@ func (s *PermissionsReg) GetPermissionsListHandler(w http.ResponseWriter, r *htt
return nil, errW
}
// 🚀 Батч-подгрузка вместо N+1
s.enrichPermissionsBatch(ctx, permissionsDbLst)
return &typescore.ApiResponseBase{
@ -101,7 +103,6 @@ func (s *PermissionsReg) GetPermissionsByRoleIDHandler(w http.ResponseWriter, r
return nil, err
}
// 🚀 Батч-подгрузка вместо N+1
s.enrichPermissionsBatch(ctx, permissions)
return &typescore.ApiResponseBase{
@ -258,7 +259,6 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
return nil, errors.New("invalid request body")
}
// Валидация обязательных полей
if req.RoleID == nil {
return nil, errors.New("role_id is required")
}
@ -266,14 +266,12 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
return nil, errors.New("action is required")
}
// 🛡 Проверяем валидность action
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
@ -282,7 +280,6 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
return nil, errors.New("role not found")
}
// Если указана категория — проверяем её существование
if req.TopicCategoryID != nil {
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID)
if err != nil {
@ -293,7 +290,6 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
}
}
// Если указана тема — проверяем её существование
if req.TopicID != nil {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
if err != nil {
@ -303,7 +299,6 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
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")
@ -311,7 +306,6 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
}
}
// 🛡 Проверяем, что такое право ещё не существует
existingPermissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.Permission{
RoleID: req.RoleID,
@ -334,6 +328,26 @@ func (s *PermissionsReg) CreatePermissionHandler(w http.ResponseWriter, r *http.
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
}
@ -369,7 +383,6 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
ctx := r.Context()
// Проверяем, что право существует
existingPermissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.Permission{ID: req.ID},
})
@ -381,14 +394,12 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
}
existing := existingPermissions[0]
// Если обновляется action — проверяем валидность
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")
}
}
// Если обновляется role_id — проверяем существование
if req.RoleID != nil {
if existing.RoleID == nil || *existing.RoleID != *req.RoleID {
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.RoleID)
@ -401,7 +412,6 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
}
}
// Если обновляется topic_category_id — проверяем существование
if req.TopicCategoryID != nil {
if existing.TopicCategoryID == nil || *existing.TopicCategoryID != *req.TopicCategoryID {
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID)
@ -414,7 +424,6 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
}
}
// Если обновляется topic_id — проверяем существование и принадлежность категории
if req.TopicID != nil {
if existing.TopicID == nil || *existing.TopicID != *req.TopicID {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
@ -425,7 +434,6 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
return nil, errors.New("topic not found")
}
// Проверяем соответствие категории
categoryIDToCheck := req.TopicCategoryID
if categoryIDToCheck == nil {
categoryIDToCheck = existing.TopicCategoryID
@ -436,6 +444,38 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
}
}
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
@ -443,6 +483,18 @@ func (s *PermissionsReg) UpdatePermissionHandler(w http.ResponseWriter, r *http.
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
}
@ -478,7 +530,6 @@ func (s *PermissionsReg) DeletePermissionHandler(w http.ResponseWriter, r *http.
ctx := r.Context()
// Проверяем, что право существует
existingPermissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.Permission{ID: req.ID},
})
@ -488,12 +539,36 @@ func (s *PermissionsReg) DeletePermissionHandler(w http.ResponseWriter, r *http.
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
}
@ -503,7 +578,6 @@ func (s *PermissionsReg) enrichPermission(ctx context.Context, perm *typescore.P
return
}
// Подгружаем роль
if perm.RoleID != nil {
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *perm.RoleID)
if err == nil && role != nil {
@ -511,7 +585,6 @@ func (s *PermissionsReg) enrichPermission(ctx context.Context, perm *typescore.P
}
}
// Подгружаем категорию тем
if perm.TopicCategoryID != nil {
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *perm.TopicCategoryID)
if err == nil && category != nil {
@ -519,7 +592,6 @@ func (s *PermissionsReg) enrichPermission(ctx context.Context, perm *typescore.P
}
}
// Подгружаем тему
if perm.TopicID != nil {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *perm.TopicID)
if err == nil && topic != nil {
@ -541,3 +613,36 @@ func isValidAction(action string) bool {
}
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
}

View File

@ -3,12 +3,17 @@ 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"
)
@ -114,7 +119,6 @@ func (s *RolesReg) CreateRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, errors.New("invalid request body")
}
// Валидация обязательных полей
if req.Name == nil || *req.Name == "" {
return nil, errors.New("role name is required")
}
@ -122,7 +126,6 @@ func (s *RolesReg) CreateRoleHandler(w http.ResponseWriter, r *http.Request) (in
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},
@ -134,7 +137,6 @@ func (s *RolesReg) CreateRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, errors.New("role code already exists")
}
// Устанавливаем значения по умолчанию для булевых флагов
if req.IsDefault == nil {
v := false
req.IsDefault = &v
@ -161,6 +163,25 @@ func (s *RolesReg) CreateRoleHandler(w http.ResponseWriter, r *http.Request) (in
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
}
@ -194,7 +215,6 @@ func (s *RolesReg) UpdateRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, errors.New("role id is required")
}
// Проверяем, что роль существует
ctx := r.Context()
existingRole, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.ID)
if err != nil {
@ -204,7 +224,6 @@ func (s *RolesReg) UpdateRoleHandler(w http.ResponseWriter, r *http.Request) (in
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{
@ -219,11 +238,64 @@ func (s *RolesReg) UpdateRoleHandler(w http.ResponseWriter, r *http.Request) (in
}
}
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
}
@ -257,7 +329,6 @@ func (s *RolesReg) DeleteRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, errors.New("role id is required")
}
// Проверяем, что роль существует
ctx := r.Context()
existingRole, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.ID)
if err != nil {
@ -267,7 +338,6 @@ func (s *RolesReg) DeleteRoleHandler(w http.ResponseWriter, r *http.Request) (in
return nil, errors.New("role not found")
}
// 🛡 Защита от удаления дефолтной роли
if existingRole.IsDefault != nil && *existingRole.IsDefault {
return nil, errors.New("cannot delete default role")
}
@ -277,5 +347,39 @@ func (s *RolesReg) DeleteRoleHandler(w http.ResponseWriter, r *http.Request) (in
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
}

View File

@ -0,0 +1,259 @@
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
}

View File

@ -3,12 +3,17 @@ 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"
)
@ -87,7 +92,6 @@ func (s *CategoriesReg) GetCategoryByIDHandler(w http.ResponseWriter, r *http.Re
return nil, errors.New("category not found")
}
// Подгружаем темы этой категории
topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopic{CategoryID: &id},
})
@ -123,7 +127,6 @@ func (s *CategoriesReg) CreateCategoryHandler(w http.ResponseWriter, r *http.Req
return nil, errors.New("invalid request body")
}
// Валидация обязательных полей
if req.Name == nil || *req.Name == "" {
return nil, errors.New("category name is required")
}
@ -131,7 +134,6 @@ func (s *CategoriesReg) CreateCategoryHandler(w http.ResponseWriter, r *http.Req
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},
@ -143,7 +145,6 @@ func (s *CategoriesReg) CreateCategoryHandler(w http.ResponseWriter, r *http.Req
return nil, errors.New("category code already exists")
}
// Устанавливаем is_active по умолчанию
if req.IsActive == nil {
isActive := true
req.IsActive = &isActive
@ -154,6 +155,21 @@ func (s *CategoriesReg) CreateCategoryHandler(w http.ResponseWriter, r *http.Req
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
}
@ -187,7 +203,6 @@ func (s *CategoriesReg) UpdateCategoryHandler(w http.ResponseWriter, r *http.Req
return nil, errors.New("category id is required")
}
// Проверяем, что категория существует
ctx := r.Context()
existingCategory, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.ID)
if err != nil {
@ -197,7 +212,6 @@ func (s *CategoriesReg) UpdateCategoryHandler(w http.ResponseWriter, r *http.Req
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{
@ -212,11 +226,49 @@ func (s *CategoriesReg) UpdateCategoryHandler(w http.ResponseWriter, r *http.Req
}
}
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
}
@ -251,7 +303,6 @@ func (s *CategoriesReg) DeleteCategoryHandler(w http.ResponseWriter, r *http.Req
return nil, errors.New("category id is required")
}
// Проверяем, что категория существует
ctx := r.Context()
existingCategory, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.ID)
if err != nil {
@ -276,5 +327,35 @@ func (s *CategoriesReg) DeleteCategoryHandler(w http.ResponseWriter, r *http.Req
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
}

View File

@ -3,14 +3,18 @@ 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 Получение списка исполнителей тем
@ -68,7 +72,6 @@ func (s *TopicExecutorsReg) GetTopicExecutorsListHandler(w http.ResponseWriter,
return nil, err
}
// 🚀 Батч-подгрузка вместо N+1
s.enrichExecutorsBatch(ctx, executorsDbLst)
return &typescore.ApiResponseBase{
@ -115,7 +118,6 @@ func (s *TopicExecutorsReg) GetExecutorsByTopicIDHandler(w http.ResponseWriter,
return nil, err
}
// 🚀 Батч-подгрузка вместо N+1
s.enrichExecutorsBatch(ctx, executors)
return &typescore.ApiResponseBase{
@ -249,7 +251,6 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
return nil, errors.New("invalid request body")
}
// Валидация обязательных полей
if req.TopicID == nil {
return nil, errors.New("topic_id is required")
}
@ -259,7 +260,6 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
ctx := r.Context()
// Проверяем существование темы
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
if err != nil {
return nil, err
@ -268,7 +268,6 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
return nil, errors.New("topic not found")
}
// Проверяем существование пользователя
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID)
if err != nil {
return nil, err
@ -277,7 +276,6 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
return nil, errors.New("user not found")
}
// Проверяем, что пользователь не заблокирован и не уволен
if user.IsBlocked != nil && *user.IsBlocked {
return nil, errors.New("user is blocked")
}
@ -285,7 +283,6 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
return nil, errors.New("user is fired")
}
// 🛡 Проверяем, что такой исполнитель на этом шаге ещё не существует
stepOrder := 0
if req.StepOrder != nil {
stepOrder = *req.StepOrder
@ -304,7 +301,6 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
return nil, errors.New("this executor is already assigned to this step for the topic")
}
// Устанавливаем значения по умолчанию
if req.StepOrder == nil {
defaultStep := 0
req.StepOrder = &defaultStep
@ -325,6 +321,23 @@ func (s *TopicExecutorsReg) CreateTopicExecutorHandler(w http.ResponseWriter, r
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
}
@ -360,7 +373,6 @@ func (s *TopicExecutorsReg) UpdateTopicExecutorHandler(w http.ResponseWriter, r
ctx := r.Context()
// Проверяем, что запись существует
existingExecutors, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopicExecutor{ID: req.ID},
})
@ -371,8 +383,8 @@ func (s *TopicExecutorsReg) UpdateTopicExecutorHandler(w http.ResponseWriter, r
return nil, errors.New("topic executor not found")
}
existing := existingExecutors[0]
s.enrichExecutor(ctx, existing)
// Если обновляется topic_id — проверяем существование
if req.TopicID != nil {
if existing.TopicID == nil || *existing.TopicID != *req.TopicID {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
@ -385,7 +397,6 @@ func (s *TopicExecutorsReg) UpdateTopicExecutorHandler(w http.ResponseWriter, r
}
}
// Если обновляется user_id — проверяем существование и статус
if req.UserID != nil {
if existing.UserID == nil || *existing.UserID != *req.UserID {
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID)
@ -404,6 +415,47 @@ func (s *TopicExecutorsReg) UpdateTopicExecutorHandler(w http.ResponseWriter, r
}
}
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
@ -411,6 +463,19 @@ func (s *TopicExecutorsReg) UpdateTopicExecutorHandler(w http.ResponseWriter, r
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
}
@ -446,11 +511,43 @@ func (s *TopicExecutorsReg) DeleteTopicExecutorHandler(w http.ResponseWriter, r
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
}
@ -460,7 +557,6 @@ func (s *TopicExecutorsReg) enrichExecutor(ctx context.Context, exec *typescore.
return
}
// Подгружаем тему
if exec.TopicID != nil {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *exec.TopicID)
if err == nil && topic != nil {
@ -468,7 +564,6 @@ func (s *TopicExecutorsReg) enrichExecutor(ctx context.Context, exec *typescore.
}
}
// Подгружаем пользователя
if exec.UserID != nil {
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *exec.UserID)
if err == nil && user != nil {
@ -476,3 +571,33 @@ func (s *TopicExecutorsReg) enrichExecutor(ctx context.Context, exec *typescore.
}
}
}
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
}

View File

@ -3,12 +3,17 @@ 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"
)
@ -116,7 +121,6 @@ func (s *TopicsReg) GetTopicByIDHandler(w http.ResponseWriter, r *http.Request)
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 {
@ -152,7 +156,6 @@ func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("invalid request body")
}
// Валидация обязательных полей
if req.Name == nil || *req.Name == "" {
return nil, errors.New("topic name is required")
}
@ -163,7 +166,6 @@ func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("category_id is required")
}
// Проверяем, что категория существует
ctx := r.Context()
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.CategoryID)
if err != nil {
@ -173,7 +175,6 @@ func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("category not found")
}
// Проверяем, что код уникален
existingTopics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopic{Code: req.Code},
})
@ -184,7 +185,6 @@ func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("topic code already exists")
}
// Устанавливаем значения по умолчанию
if req.IsActive == nil {
isActive := true
req.IsActive = &isActive
@ -223,7 +223,6 @@ func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, err
}
// Подгружаем информацию о категории
if createdTopic.CategoryID != nil {
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *createdTopic.CategoryID)
if err == nil && category != nil {
@ -231,6 +230,29 @@ func (s *TopicsReg) CreateTopicHandler(w http.ResponseWriter, r *http.Request) (
}
}
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
}
@ -264,7 +286,6 @@ func (s *TopicsReg) UpdateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("topic id is required")
}
// Проверяем, что тема существует
ctx := r.Context()
existingTopic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.ID)
if err != nil {
@ -274,7 +295,6 @@ func (s *TopicsReg) UpdateTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("topic not found")
}
// Если обновляется category_id, проверяем, что категория существует
if req.CategoryID != nil {
if existingTopic.CategoryID == nil || *existingTopic.CategoryID != *req.CategoryID {
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.CategoryID)
@ -287,7 +307,6 @@ func (s *TopicsReg) UpdateTopicHandler(w http.ResponseWriter, r *http.Request) (
}
}
// Если обновляется код, проверяем уникальность
if req.Code != nil && *req.Code != "" {
if existingTopic.Code == nil || *existingTopic.Code != *req.Code {
existingTopics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
@ -302,12 +321,75 @@ func (s *TopicsReg) UpdateTopicHandler(w http.ResponseWriter, r *http.Request) (
}
}
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 {
@ -315,6 +397,19 @@ func (s *TopicsReg) UpdateTopicHandler(w http.ResponseWriter, r *http.Request) (
}
}
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
}
@ -349,7 +444,6 @@ func (s *TopicsReg) DeleteTopicHandler(w http.ResponseWriter, r *http.Request) (
return nil, errors.New("topic id is required")
}
// Проверяем, что тема существует
ctx := r.Context()
existingTopic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.ID)
if err != nil {
@ -369,10 +463,57 @@ func (s *TopicsReg) DeleteTopicHandler(w http.ResponseWriter, r *http.Request) (
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
}

View File

@ -3,12 +3,17 @@ 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"
)
@ -120,7 +125,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("invalid request body")
}
// Валидация обязательных полей
if req.SubordinateID == nil {
return nil, errors.New("subordinate_id is required")
}
@ -133,7 +137,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
ctx := r.Context()
// Проверяем существование подчинённого
subordinate, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.SubordinateID)
if err != nil {
return nil, err
@ -142,7 +145,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("subordinate user not found")
}
// Проверяем существование согласующего
approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ApproverID)
if err != nil {
return nil, err
@ -151,7 +153,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("approver user not found")
}
// Проверяем существование отдела
department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.DepartmentID)
if err != nil {
return nil, err
@ -160,7 +161,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("department not found")
}
// Если указана категория — проверяем её существование
if req.TopicCategoryID != nil {
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID)
if err != nil {
@ -171,7 +171,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
}
}
// Если указана тема — проверяем её существование
if req.TopicID != nil {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
if err != nil {
@ -181,7 +180,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
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")
@ -205,7 +203,6 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("this hierarchy relation already exists")
}
// Устанавливаем priority по умолчанию
if req.Priority == nil {
defaultPriority := 1
req.Priority = &defaultPriority
@ -216,6 +213,28 @@ func (s *HierarchiesReg) CreateHierarchyHandler(w http.ResponseWriter, r *http.R
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
}
@ -251,8 +270,7 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
ctx := r.Context()
// Проверяем, что запись существует
existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{
existingHierarchies, _, err := s.ipc.Database.UserHierarchy.GetHierarchiesWithRelations(ctx, typescore.ListDbOptions{
Filtering: &typescore.UserHierarchy{ID: req.ID},
})
if err != nil {
@ -263,7 +281,6 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
}
existing := existingHierarchies[0]
// Если обновляется subordinate_id — проверяем существование
if req.SubordinateID != nil {
if existing.SubordinateID == nil || *existing.SubordinateID != *req.SubordinateID {
subordinate, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.SubordinateID)
@ -276,7 +293,6 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
}
}
// Если обновляется approver_id — проверяем существование
if req.ApproverID != nil {
if existing.ApproverID == nil || *existing.ApproverID != *req.ApproverID {
approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ApproverID)
@ -289,7 +305,6 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
}
}
// Если обновляется department_id — проверяем существование
if req.DepartmentID != nil {
if existing.DepartmentID == nil || *existing.DepartmentID != *req.DepartmentID {
department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.DepartmentID)
@ -302,7 +317,6 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
}
}
// Если обновляется topic_category_id — проверяем существование
if req.TopicCategoryID != nil {
if existing.TopicCategoryID == nil || *existing.TopicCategoryID != *req.TopicCategoryID {
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *req.TopicCategoryID)
@ -315,7 +329,6 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
}
}
// Если обновляется topic_id — проверяем существование и принадлежность категории
if req.TopicID != nil {
if existing.TopicID == nil || *existing.TopicID != *req.TopicID {
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *req.TopicID)
@ -326,7 +339,6 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
return nil, errors.New("topic not found")
}
// Проверяем соответствие категории
categoryIDToCheck := req.TopicCategoryID
if categoryIDToCheck == nil {
categoryIDToCheck = existing.TopicCategoryID
@ -337,11 +349,81 @@ func (s *HierarchiesReg) UpdateHierarchyHandler(w http.ResponseWriter, r *http.R
}
}
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
}
@ -376,10 +458,73 @@ func (s *HierarchiesReg) DeleteHierarchyHandler(w http.ResponseWriter, r *http.R
}
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
}

View File

@ -3,13 +3,17 @@ 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"
)
@ -63,7 +67,6 @@ func (s *UserRolesReg) GetUserRolesListHandler(w http.ResponseWriter, r *http.Re
return nil, errW
}
// 🚀 Батч-подгрузка ролей одним запросом вместо N+1
s.enrichUserRolesBatch(ctx, userRolesDbLst)
return &typescore.ApiResponseBase{
@ -112,7 +115,6 @@ func (s *UserRolesReg) GetUserRolesByUserIDHandler(w http.ResponseWriter, r *htt
return nil, errW
}
// 🚀 Батч-подгрузка ролей одним запросом вместо N+1
s.enrichUserRolesBatch(ctx, userRolesDbLst)
return &typescore.ApiResponseBase{
@ -210,7 +212,6 @@ func (s *UserRolesReg) BulkAssignRolesHandler(w http.ResponseWriter, r *http.Req
roleIDs = append(roleIDs, *roleID)
}
// 🚀 Проверяем существование всех ролей ОДНИМ запросом вместо N
if len(roleIDs) > 0 {
existingRoles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs)
if err != nil {
@ -229,13 +230,17 @@ func (s *UserRolesReg) BulkAssignRolesHandler(w http.ResponseWriter, r *http.Req
}
}
// 🗑 Удаляем все текущие роли ОДНИМ запросом вместо цикла
// снимаем "было" до удаления — иначе после 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
}
// 🆕 Назначаем новые роли ОДНИМ batch-INSERT вместо цикла
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)
@ -244,6 +249,22 @@ func (s *UserRolesReg) BulkAssignRolesHandler(w http.ResponseWriter, r *http.Req
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,
@ -286,7 +307,6 @@ func (s *UserRolesReg) AssignUserRoleHandler(w http.ResponseWriter, r *http.Requ
ctx := r.Context()
// Проверяем, что пользователь существует
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID)
if err != nil {
return nil, err
@ -295,7 +315,6 @@ func (s *UserRolesReg) AssignUserRoleHandler(w http.ResponseWriter, r *http.Requ
return nil, errors.New("user not found")
}
// Проверяем, что роль существует
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *req.RoleID)
if err != nil {
return nil, err
@ -304,7 +323,6 @@ func (s *UserRolesReg) AssignUserRoleHandler(w http.ResponseWriter, r *http.Requ
return nil, errors.New("role not found")
}
// 🛡 Проверяем, что такая связь ещё не существует
existingRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.UserRole{
UserID: req.UserID,
@ -328,12 +346,19 @@ func (s *UserRolesReg) AssignUserRoleHandler(w http.ResponseWriter, r *http.Requ
return nil, err
}
// Подгружаем информацию о роли
if createdUserRole.RoleID != nil {
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *createdUserRole.RoleID)
if err == nil && role != nil {
createdUserRole.Role = role
}
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
@ -371,7 +396,6 @@ func (s *UserRolesReg) RemoveUserRoleHandler(w http.ResponseWriter, r *http.Requ
ctx := r.Context()
// Проверяем, что запись существует
existingRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.UserRole{ID: req.ID},
})
@ -381,11 +405,73 @@ func (s *UserRolesReg) RemoveUserRoleHandler(w http.ResponseWriter, r *http.Requ
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
}

View File

@ -3,13 +3,17 @@ 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"
)
@ -79,8 +83,6 @@ func (s *UserReg) GetUserListHandler(w http.ResponseWriter, r *http.Request) (in
return nil, err
}
// 🚀 Батч-подгрузка отделов и ролей: было до 2N+1 запросов (department + roles + role-на-каждую-роль),
// стало 3 запроса суммарно независимо от количества пользователей
s.enrichUsersBatch(ctx, userDbLst)
return &typescore.ApiResponseBase{
@ -139,6 +141,39 @@ func (s *UserReg) UpdateUserHandler(w http.ResponseWriter, r *http.Request) (int
}
}
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,
@ -153,6 +188,19 @@ func (s *UserReg) UpdateUserHandler(w http.ResponseWriter, r *http.Request) (int
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
}
@ -270,7 +318,6 @@ func (s *UserReg) GetUserByIDHandler(w http.ResponseWriter, r *http.Request) (in
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 {
@ -278,12 +325,10 @@ func (s *UserReg) GetUserByIDHandler(w http.ResponseWriter, r *http.Request) (in
}
}
// 🚀 Подгружаем роли пользователя
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)
@ -311,7 +356,6 @@ func (s *UserReg) DeleteUserHandler(w http.ResponseWriter, r *http.Request) (int
ctx := r.Context()
// Проверяем, что пользователь существует
existingUser, err := s.ipc.Database.User.GetUserByIDDB(ctx, id)
if err != nil {
return nil, err
@ -320,11 +364,54 @@ func (s *UserReg) DeleteUserHandler(w http.ResponseWriter, r *http.Request) (int
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
}