updated core methods, updated table migrations, improove optimization, updated rest api requests #48
|
|
@ -36,5 +36,20 @@ func ApprovalsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approvals".updated_at IS 'Дата последнего изменения заявки';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Индексы: покрывают фильтры GetApprovalsListHandler, JOIN'ы enrichApprovalsBatch и сортировку
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_initiator_id ON approvals (initiator_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_topic_id ON approvals (topic_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_department_id ON approvals (department_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_revoked_by_id ON approvals (revoked_by_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_status ON approvals (status)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_created_at ON approvals (created_at DESC)`)
|
||||
// Композитный индекс под самый частый сценарий: список заявок конкретного статуса, отсортированный по дате
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_status_created_at ON approvals (status, created_at DESC)`)
|
||||
// Под фильтр report по инициатору + период
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_initiator_created_at ON approvals (initiator_id, created_at DESC)`)
|
||||
// Под DeleteTopicHandler / проверку "есть ли заявки по теме"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approvals_topic_status ON approvals (topic_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,12 +15,10 @@ func ApprovalAdditionalApproverTableMigrate(db *gorm.DB) error {
|
|||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Foreign key constraints
|
||||
db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_approver_id FOREIGN KEY (approver_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_additional_approvers ADD CONSTRAINT fk_approval_additional_approvers_added_by_id FOREIGN KEY (added_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
// Comments
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_additional_approvers" IS 'Дополнительные согласующие заявки: кто добавлен для согласования конкретной заявки';
|
||||
COMMENT ON COLUMN "approval_additional_approvers".id IS 'Внутренний уникальный идентификатор записи';
|
||||
|
|
@ -34,5 +32,13 @@ func ApprovalAdditionalApproverTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_additional_approvers".updated_at IS 'Дата и время последнего изменения записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 approval_id — джойн при обогащении заявки; approver_id — "мои задачи на согласование";
|
||||
// композит approval_id+status — фильтр pending-согласующих конкретной заявки
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_approval_id ON approval_additional_approvers (approval_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_approver_id ON approval_additional_approvers (approver_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_added_by_id ON approval_additional_approvers (added_by_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_approvers_approval_status ON approval_additional_approvers (approval_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,12 +15,10 @@ func ApprovalAdditionalObserverTableMigrate(db *gorm.DB) error {
|
|||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Foreign key constraints
|
||||
db.Exec(`ALTER TABLE approval_additional_observers ADD CONSTRAINT fk_approval_additional_approvers_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_additional_observers ADD CONSTRAINT fk_approval_additional_approvers_observer_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_additional_observers ADD CONSTRAINT fk_approval_additional_approvers_added_by_id FOREIGN KEY (added_by_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
|
||||
// Comments
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_additional_observers" IS 'Дополнительные наблюдатели заявки: кто добавлен для согласования конкретной заявки';
|
||||
COMMENT ON COLUMN "approval_additional_observers".id IS 'Внутренний уникальный идентификатор записи';
|
||||
|
|
@ -30,5 +28,10 @@ func ApprovalAdditionalObserverTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_additional_observers".created_at IS 'Дата и время создания записи';
|
||||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_observers_approval_id ON approval_additional_observers (approval_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_observers_user_id ON approval_additional_observers (user_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_add_observers_added_by_id ON approval_additional_observers (added_by_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,5 +28,10 @@ func ApprovalCommentsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_comments".updated_at IS 'Дата последнего изменения комментария';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композит покрывает типичный запрос "комментарии заявки в хронологическом порядке"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_comments_approval_id_created_at ON approval_comments (approval_id, created_at)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_comments_user_id ON approval_comments (user_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,12 +15,10 @@ func ApprovalDelegationTableMigrate(db *gorm.DB) error {
|
|||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Foreign key constraints
|
||||
db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_delegator_id FOREIGN KEY (delegator_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_delegate_id FOREIGN KEY (delegate_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_delegations ADD CONSTRAINT fk_approval_delegations_topic_id FOREIGN KEY (topic_id) REFERENCES approval_topics(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
|
||||
|
||||
// Comments
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_delegations" IS 'Делегирование прав согласования: кто кому может согласовывать заявки по определённым темам';
|
||||
COMMENT ON COLUMN "approval_delegations".id IS 'Внутренний уникальный идентификатор записи делегирования';
|
||||
|
|
@ -35,5 +33,13 @@ func ApprovalDelegationTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_delegations".updated_at IS 'Дата и время последнего изменения записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композит под самый вероятный запрос: "активные делегирования делегата по теме, ещё не истёкшие"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_delegator_id ON approval_delegations (delegator_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_delegate_id ON approval_delegations (delegate_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_topic_id ON approval_delegations (topic_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_active_valid_until ON approval_delegations (is_active, valid_until) WHERE is_active = true`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_appr_delegations_delegator_topic_active ON approval_delegations (delegator_id, topic_id) WHERE is_active = true`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,5 +26,9 @@ func ApprovalsFilesTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_files".created_at IS 'Дата создания файла';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Ключевой индекс под GetFilesByApprovalIDsDB (батч IN по approval_id)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_files_approval_id ON approval_files (approval_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,5 +33,12 @@ func ApprovalStepsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_steps".updated_at IS 'Дата последнего обновления шага';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композит покрывает GetApprovalStepsByApprovalIDsDB (IN approval_id + ORDER BY step_order)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_steps_approval_id_step_order ON approval_steps (approval_id, step_order)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_steps_approver_id ON approval_steps (approver_id)`)
|
||||
// Под "мои pending-согласования"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_steps_approver_status ON approval_steps (approver_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,11 +15,9 @@ func ApprovalTasksTableMigrate(db *gorm.DB) error {
|
|||
if !hasTable {
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
// Внешние ключи
|
||||
db.Exec(`ALTER TABLE approval_tasks ADD CONSTRAINT fk_approval_tasks_approval_id FOREIGN KEY (approval_id) REFERENCES approvals(id) ON DELETE CASCADE ON UPDATE CASCADE`)
|
||||
db.Exec(`ALTER TABLE approval_tasks ADD CONSTRAINT fk_approval_tasks_executor_id FOREIGN KEY (executor_id) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE`)
|
||||
|
||||
// Комментарии к таблице и колонкам
|
||||
execComments(db, `
|
||||
COMMENT ON TABLE "approval_tasks" IS 'Задачи согласования, назначенные исполнителям';
|
||||
COMMENT ON COLUMN "approval_tasks".id IS 'Внутренний ID задачи';
|
||||
|
|
@ -33,5 +31,9 @@ func ApprovalTasksTableMigrate(db *gorm.DB) error {
|
|||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_tasks_approval_id ON approval_tasks (approval_id)`)
|
||||
// Под "мои задачи исполнителя, отфильтрованные по статусу"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_tasks_executor_status ON approval_tasks (executor_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,5 +33,12 @@ func ApprovalTopicsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_topics".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 code — уникальность/поиск при создании темы; category_id — под GetTopicsListHandler фильтр и enrich;
|
||||
// композит category_id+is_active — под список активных тем категории (частый сценарий в боте)
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_approval_topics_code ON approval_topics (code)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topics_category_id ON approval_topics (category_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topics_category_active ON approval_topics (category_id, is_active)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,5 +28,10 @@ func ApprovalTopicCategoriesTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_topic_categories".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 code используется в GetApprovalTopicCategoryByCodeDB и в JOIN'ах GetObserversForApprovalDB/GetUserPermissionsDB
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_approval_topic_categories_code ON approval_topic_categories (code)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_categories_active ON approval_topic_categories (is_active)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,5 +31,14 @@ func ApprovalTopicExecutorsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "approval_topic_executor".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композит покрывает GetExecutorsByTopicIDDB (topic_id + is_active + ORDER BY step_order)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_executor_topic_active_step ON approval_topic_executor (topic_id, is_active, step_order)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_executor_user_id ON approval_topic_executor (user_id)`)
|
||||
// Уникальность под проверку "исполнитель уже назначен на этот шаг" в CreateTopicExecutorHandler
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_approval_topic_executor_topic_user_step ON approval_topic_executor (topic_id, user_id, step_order)`)
|
||||
// Под фильтрацию GetApprovalTopicExecutorListByCategoryDB (JOIN approval_topics ON t.category_id)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_approval_topic_executor_id_step ON approval_topic_executor (id, step_order)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,5 +26,9 @@ func DepartmentsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "departments".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_departments_code ON departments (code)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_departments_active ON departments (is_active)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,5 +31,16 @@ func PermissionsTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "permissions".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 role_id — под GetUserPermissionsDB JOIN с user_roles; композит role_id+action — под UserCanCreateTopicDB;
|
||||
// topic_id/topic_category_id — под enrichPermissionsBatch и JOIN'ы наблюдателей
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_role_id ON permissions (role_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_role_id_action ON permissions (role_id, action)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_topic_id ON permissions (topic_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_topic_category_id ON permissions (topic_category_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_action ON permissions (action)`)
|
||||
// Под GetObserversForCategoryDB / GetObserversForApprovalDB: action='observe' + topic_category_id
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_permissions_action_category ON permissions (action, topic_category_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,5 +28,15 @@ func RolesTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "roles".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 code — под GetUsersByRoleCodeDB; флаги is_director/is_approver/is_observer используются
|
||||
// как условия в JOIN'ах GetDirectorsDB/IsDirectorDB/IsApproverDB/IsObserverDB/GetObserversForCategoryDB —
|
||||
// частичные индексы дают максимальную выборочность, т.к. флаг true встречается редко
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_roles_code ON roles (code)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_director ON roles (id) WHERE is_director = true`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_approver ON roles (id) WHERE is_approver = true`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_observer ON roles (id) WHERE is_observer = true`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_roles_is_default ON roles (id) WHERE is_default = true`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,5 +30,9 @@ func SuggestionMessagesTableMigrate(db *gorm.DB) error {
|
|||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композит покрывает "переписка по предложению в хронологическом порядке"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestion_messages_suggestion_id_created_at ON suggestion_messages (suggestion_id, created_at)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestion_messages_user_id ON suggestion_messages (user_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,5 +30,9 @@ func SuggestionsTableMigrate(db *gorm.DB) error {
|
|||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композиты под "мои открытые предложения" / "предложения, адресованные директору"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestions_initiator_status ON suggestions (initiator_id, status)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_suggestions_director_status ON suggestions (director_id, status)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,5 +31,20 @@ func UsersTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "users".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 telegram_id — под GetUserByTelegramIDDB (уникальный лукап при каждом сообщении в бота);
|
||||
// department_id — под фильтр users и JOIN'ы в enrichUsersBatch;
|
||||
// pg_trgm-индекс под LIKE-поиск по full_name (GetUserListHandler search)
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_users_telegram_id ON users (telegram_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_department_id ON users (department_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_is_blocked ON users (is_blocked)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_is_fired ON users (is_fired)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_created_at ON users (created_at DESC)`)
|
||||
// Композит под самый частый вызов фильтра списка: не заблокирован + не уволен
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_blocked_fired ON users (is_blocked, is_fired)`)
|
||||
// Требует расширения pg_trgm: CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||
db.Exec(`CREATE EXTENSION IF NOT EXISTS pg_trgm`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_users_full_name_trgm ON users USING gin (full_name gin_trgm_ops)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,5 +30,11 @@ func UserHierarchyTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "user_hierarchy".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Композит покрывает основной сценарий: "цепочка согласующих подчинённого в отделе по приоритету"
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_hierarchy_subordinate_dept_priority ON user_hierarchy (subordinate_id, department_id, priority)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_hierarchy_approver_id ON user_hierarchy (approver_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_hierarchy_department_id ON user_hierarchy (department_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,5 +27,13 @@ func UserRolesTableMigrate(db *gorm.DB) error {
|
|||
COMMENT ON COLUMN "user_roles".updated_at IS 'Дата последнего обновления записи';
|
||||
`)
|
||||
}
|
||||
|
||||
// 🚀 Индексы: user_id — под GetUserRolesByUserIDsDB/DeleteUserRolesByUserIDDB,
|
||||
// role_id — под GetPermissionsByRoleIDHandler JOIN'ы,
|
||||
// уникальный композит — защита от дублей роли у пользователя + быстрый lookup в AssignUserRoleHandler
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_roles_user_id ON user_roles (user_id)`)
|
||||
db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_user_roles_role_id ON user_roles (role_id)`)
|
||||
db.Exec(`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_user_roles_user_role ON user_roles (user_id, role_id)`)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ type ApprovalFileDBI interface {
|
|||
GetFilesByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalFile, error)
|
||||
GetApprovalFileByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFile, error)
|
||||
GetFilesByTaskIDDB(ctx context.Context, taskID uint64) ([]*typescore.ApprovalFile, error)
|
||||
GetFilesByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*typescore.ApprovalFile, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalFileDB) GetApprovalFilesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFile, uint64, error) {
|
||||
|
|
@ -226,3 +227,42 @@ func (u *ApprovalFileDB) GetFilesByTaskIDDB(ctx context.Context, taskID uint64)
|
|||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
// GetFilesByApprovalIDsDB — пакетное получение файлов сразу для нескольких заявок (устраняет N+1)
|
||||
func (a *ApprovalFileDB) GetFilesByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*typescore.ApprovalFile, error) {
|
||||
if len(approvalIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalFile{}, dbcoretablenames.TableNameApprovalFiles.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameApprovalFiles.ToString()).
|
||||
Where(squirrel.Eq{"approval_id": approvalIDs}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := a.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var files []*typescore.ApprovalFile
|
||||
for rows.Next() {
|
||||
f := &typescore.ApprovalFile{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, f, nil); err != nil {
|
||||
logrus.Warn("GetFilesByApprovalIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
files = append(files, f)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return files, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ type ApprovalStepDBI interface {
|
|||
|
||||
GetActiveStepDB(ctx context.Context, approvalID uint64) (*typescore.ApprovalStep, error)
|
||||
GetNextStepDB(ctx context.Context, approvalID uint64, currentOrder int) (*typescore.ApprovalStep, error)
|
||||
GetApprovalStepsByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*typescore.ApprovalStep, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalStepDB) GetApprovalStepsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalStep, uint64, error) {
|
||||
|
|
@ -232,3 +233,43 @@ func (u *ApprovalStepDB) GetNextStepDB(ctx context.Context, approvalID uint64, c
|
|||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// GetApprovalStepsByApprovalIDsDB — пакетное получение шагов сразу для нескольких заявок (устраняет N+1)
|
||||
func (a *ApprovalStepDB) GetApprovalStepsByApprovalIDsDB(ctx context.Context, approvalIDs []uint64) ([]*typescore.ApprovalStep, error) {
|
||||
if len(approvalIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalStep{}, dbcoretablenames.TableNameApprovalSteps.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameApprovalSteps.ToString()).
|
||||
Where(squirrel.Eq{"approval_id": approvalIDs}).
|
||||
OrderBy("step_order ASC").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := a.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var steps []*typescore.ApprovalStep
|
||||
for rows.Next() {
|
||||
st := &typescore.ApprovalStep{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, st, nil); err != nil {
|
||||
logrus.Warn("GetApprovalStepsByApprovalIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
steps = append(steps, st)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return steps, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ type ApprovalTopicDBI interface {
|
|||
|
||||
GetApprovalTopicByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalTopic, error)
|
||||
GetApprovalTopicByCodeDB(ctx context.Context, code string) (*typescore.ApprovalTopic, error)
|
||||
GetApprovalTopicsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopic, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalTopicDB) GetApprovalTopicsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalTopic, uint64, error) {
|
||||
|
|
@ -208,3 +209,42 @@ func (u *ApprovalTopicDB) GetApprovalTopicByCodeDB(ctx context.Context, code str
|
|||
}
|
||||
return topics[0], nil
|
||||
}
|
||||
|
||||
// GetApprovalTopicsByIDsDB — пакетное получение тем по списку ID (устраняет N+1)
|
||||
func (u *ApprovalTopicDB) GetApprovalTopicsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopic, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopic{}, dbcoretablenames.TableNameApprovalTopics.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameApprovalTopics.ToString()).
|
||||
Where(squirrel.Eq{"id": ids}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var topics []*typescore.ApprovalTopic
|
||||
for rows.Next() {
|
||||
topic := &typescore.ApprovalTopic{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, topic, nil); err != nil {
|
||||
logrus.Warn("GetApprovalTopicsByIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
topics = append(topics, topic)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return topics, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ type ApprovalTopicCategoryDBI interface {
|
|||
initiatorID uint64,
|
||||
) ([]*typescore.ApprovalTopicCategory, error)
|
||||
GetCategoriesWithApprovalsByApproverDB(ctx context.Context, approverID uint64) ([]*typescore.ApprovalTopicCategory, error)
|
||||
GetApprovalTopicCategoriesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopicCategory, error)
|
||||
}
|
||||
|
||||
// GetCategoriesWithApprovalsByInitiatorDB — категории тем, по которым у инициатора есть заявки
|
||||
|
|
@ -286,3 +287,42 @@ func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoryByCodeDB(ctx context.C
|
|||
}
|
||||
return categories[0], nil
|
||||
}
|
||||
|
||||
// GetApprovalTopicCategoriesByIDsDB — пакетное получение категорий по списку ID (устраняет N+1)
|
||||
func (u *ApprovalTopicCategoryDB) GetApprovalTopicCategoriesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.ApprovalTopicCategory, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.ApprovalTopicCategory{}, dbcoretablenames.TableNameApprovalTopicCategories.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameApprovalTopicCategories.ToString()).
|
||||
Where(squirrel.Eq{"id": ids}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var categories []*typescore.ApprovalTopicCategory
|
||||
for rows.Next() {
|
||||
category := &typescore.ApprovalTopicCategory{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, category, nil); err != nil {
|
||||
logrus.Warn("GetApprovalTopicCategoriesByIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
categories = append(categories, category)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return categories, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ type DepartmentDBI interface {
|
|||
UpdateDepartmentDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Department, returnObj ...bool) (*typescore.Department, pgx.Tx, error)
|
||||
DeleteDepartmentDB(ctx context.Context, params *typescore.Department) error
|
||||
GetDepartmentByIDDB(ctx context.Context, id uint64) (*typescore.Department, error)
|
||||
GetDepartmentsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Department, error)
|
||||
}
|
||||
|
||||
func (u *DepartmentDB) GetDepartmentsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Department, uint64, error) {
|
||||
|
|
@ -189,3 +190,42 @@ func (u *DepartmentDB) GetDepartmentByIDDB(ctx context.Context, id uint64) (*typ
|
|||
}
|
||||
return deps[0], nil
|
||||
}
|
||||
|
||||
// GetDepartmentsByIDsDB — пакетное получение отделов по списку ID (устраняет N+1)
|
||||
func (d *DepartmentDB) GetDepartmentsByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Department, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Department{}, dbcoretablenames.TableNameDepartments.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameDepartments.ToString()).
|
||||
Where(squirrel.Eq{"id": ids}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := d.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var departments []*typescore.Department
|
||||
for rows.Next() {
|
||||
dep := &typescore.Department{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, dep, nil); err != nil {
|
||||
logrus.Warn("GetDepartmentsByIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
departments = append(departments, dep)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return departments, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ type RoleDBI interface {
|
|||
UpdateRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.Role, returnObj ...bool) (*typescore.Role, pgx.Tx, error)
|
||||
DeleteRoleDB(ctx context.Context, params *typescore.Role) error
|
||||
GetRoleByIDDB(ctx context.Context, id uint64) (*typescore.Role, error)
|
||||
GetRolesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Role, error)
|
||||
}
|
||||
|
||||
func (u *RoleDB) GetRolesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Role, uint64, error) {
|
||||
|
|
@ -189,3 +190,42 @@ func (u *RoleDB) GetRoleByIDDB(ctx context.Context, id uint64) (*typescore.Role,
|
|||
}
|
||||
return roles[0], nil
|
||||
}
|
||||
|
||||
// GetRolesByIDsDB — пакетное получение ролей по списку ID (устраняет N+1)
|
||||
func (u *RoleDB) GetRolesByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.Role, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Role{}, dbcoretablenames.TableNameRoles.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameRoles.ToString()).
|
||||
Where(squirrel.Eq{"id": ids}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var roles []*typescore.Role
|
||||
for rows.Next() {
|
||||
role := &typescore.Role{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, role, nil); err != nil {
|
||||
logrus.Warn("GetRolesByIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
roles = append(roles, role)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return roles, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ type UserDBI interface {
|
|||
GetUsersByRoleCodeDB(ctx context.Context, roleCode string) ([]*typescore.User, error)
|
||||
GetObserversForApprovalDB(ctx context.Context, categoryCode string, topicID *uint64) ([]*typescore.User, error)
|
||||
GetUsersListByRoleIDsDB(ctx context.Context, opts typescore.ListDbOptions, roleIDs []uint64) ([]*typescore.User, uint64, error)
|
||||
GetUsersByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.User, error)
|
||||
}
|
||||
|
||||
func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.User, uint64, error) {
|
||||
|
|
@ -569,3 +570,42 @@ func (u *UserDB) GetUsersListByRoleIDsDB(ctx context.Context, opts typescore.Lis
|
|||
|
||||
return users, totalCount, nil
|
||||
}
|
||||
|
||||
// GetUsersByIDsDB — пакетное получение пользователей по списку ID (устраняет N+1)
|
||||
func (u *UserDB) GetUsersByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.User, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.User{}, dbcoretablenames.TableNameUsers.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameUsers.ToString()).
|
||||
Where(squirrel.Eq{"id": ids}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []*typescore.User
|
||||
for rows.Next() {
|
||||
user := &typescore.User{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, user, nil); err != nil {
|
||||
logrus.Warn("GetUsersByIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ type UserRoleDBI interface {
|
|||
CreateUserRoleDB(ctx context.Context, tx pgx.Tx, UserRoleObj *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error)
|
||||
UpdateUserRoleDB(ctx context.Context, tx pgx.Tx, paramsUpdate *typescore.UserRole, returnObj ...bool) (*typescore.UserRole, pgx.Tx, error)
|
||||
DeleteUserRoleDB(ctx context.Context, params *typescore.UserRole) error
|
||||
CreateUserRolesBulkDB(ctx context.Context, tx pgx.Tx, userID uint64, roleIDs []uint64) ([]*typescore.UserRole, error)
|
||||
}
|
||||
|
||||
func (u *UserRoleDB) GetUserRolesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.UserRole, uint64, error) {
|
||||
|
|
@ -178,3 +179,86 @@ func (u *UserRoleDB) DeleteUserRoleDB(ctx context.Context, params *typescore.Use
|
|||
return errors.New("userRole obj is nil")
|
||||
}
|
||||
}
|
||||
|
||||
// GetUserRolesByUserIDsDB — пакетное получение ролей сразу для нескольких пользователей (устраняет N+1)
|
||||
func (ur *UserRoleDB) GetUserRolesByUserIDsDB(ctx context.Context, userIDs []uint64) ([]*typescore.UserRole, error) {
|
||||
if len(userIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.UserRole{}, dbcoretablenames.TableNameUserRoles.ToString())
|
||||
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select(fields...).
|
||||
From(dbcoretablenames.TableNameUserRoles.ToString()).
|
||||
Where(squirrel.Eq{"user_id": userIDs}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := ur.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.UserRole
|
||||
for rows.Next() {
|
||||
item := &typescore.UserRole{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, item, nil); err != nil {
|
||||
logrus.Warn("GetUserRolesByUserIDsDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// DeleteUserRolesByUserIDDB — удаляет все роли пользователя одним запросом вместо цикла DELETE
|
||||
func (ur *UserRoleDB) DeleteUserRolesByUserIDDB(ctx context.Context, userID uint64) error {
|
||||
sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameUserRoles.ToString()).
|
||||
Where(squirrel.Eq{"user_id": userID}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = ur.pool.Exec(ctx, sql, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
// CreateUserRolesBulkDB — вставляет сразу несколько ролей одним multi-row INSERT вместо цикла
|
||||
func (ur *UserRoleDB) CreateUserRolesBulkDB(ctx context.Context, tx pgx.Tx, userID uint64, roleIDs []uint64) ([]*typescore.UserRole, error) {
|
||||
if len(roleIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
err := dbutils.ExecuteTx(ctx, ur.pool, tx, func(tx pgx.Tx) error {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Insert(dbcoretablenames.TableNameUserRoles.ToString()).
|
||||
Columns("user_id", "role_id")
|
||||
|
||||
for _, roleID := range roleIDs {
|
||||
query = query.Values(userID, roleID)
|
||||
}
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, sql, args...)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ur.GetUserRolesByUserIDsDB(ctx, []uint64{userID})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
|
@ -41,7 +42,6 @@ func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Re
|
|||
|
||||
filter := typescore.ApprovalFilter{}
|
||||
|
||||
// Базовые параметры
|
||||
if status := queryParams.Get("status"); status != "" {
|
||||
filter.Status = &status
|
||||
}
|
||||
|
|
@ -60,7 +60,6 @@ func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Re
|
|||
filter.DepartmentID = &id
|
||||
}
|
||||
|
||||
// Поиск по тексту
|
||||
contentSearch := queryParams.Get("content")
|
||||
if contentSearch != "" {
|
||||
if len(contentSearch) < 2 {
|
||||
|
|
@ -69,7 +68,6 @@ func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Re
|
|||
filter.Content = &contentSearch
|
||||
}
|
||||
|
||||
// 🆕 Множественный выбор тем (поддерживаем оба варианта: topic_id и topic_ids)
|
||||
if topicIDsStr := queryParams.Get("topic_ids"); topicIDsStr != "" {
|
||||
ids, err := parseUint64Array(topicIDsStr)
|
||||
if err != nil {
|
||||
|
|
@ -84,7 +82,6 @@ func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Re
|
|||
filter.TopicIDs = []uint64{id}
|
||||
}
|
||||
|
||||
// 🆕 Множественный выбор категорий
|
||||
if categoryIDsStr := queryParams.Get("category_ids"); categoryIDsStr != "" {
|
||||
ids, err := parseUint64Array(categoryIDsStr)
|
||||
if err != nil {
|
||||
|
|
@ -93,7 +90,6 @@ func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Re
|
|||
filter.CategoryIDs = ids
|
||||
}
|
||||
|
||||
// 🆕 Период дат
|
||||
if dateFromStr := queryParams.Get("date_from"); dateFromStr != "" {
|
||||
dateFrom, err := time.Parse("2006-01-02", dateFromStr)
|
||||
if err != nil {
|
||||
|
|
@ -109,7 +105,6 @@ func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Re
|
|||
filter.DateTo = &dateTo
|
||||
}
|
||||
|
||||
// Пагинация
|
||||
offset := uint64(0)
|
||||
limit := uint64(100)
|
||||
if offsetStr := queryParams.Get("offset"); offsetStr != "" {
|
||||
|
|
@ -135,9 +130,7 @@ func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Re
|
|||
approvalsDbLst = []*typescore.Approval{}
|
||||
}
|
||||
|
||||
for _, approval := range approvalsDbLst {
|
||||
s.enrichApproval(ctx, approval, false)
|
||||
}
|
||||
s.enrichApprovalsBatch(ctx, approvalsDbLst, false)
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: total,
|
||||
|
|
@ -333,7 +326,6 @@ func (s *ApprovalsReg) GetApprovalsForReportHandler(w http.ResponseWriter, r *ht
|
|||
|
||||
filter := typescore.ReportFilter{}
|
||||
|
||||
// Парсим user_id
|
||||
if userIDStr := queryParams.Get("user_id"); userIDStr != "" {
|
||||
userID, err := strconv.ParseUint(userIDStr, 10, 64)
|
||||
if err != nil {
|
||||
|
|
@ -342,7 +334,6 @@ func (s *ApprovalsReg) GetApprovalsForReportHandler(w http.ResponseWriter, r *ht
|
|||
filter.UserID = &userID
|
||||
}
|
||||
|
||||
// Парсим даты
|
||||
if dateFromStr := queryParams.Get("date_from"); dateFromStr != "" {
|
||||
dateFrom, err := time.Parse("2006-01-02", dateFromStr)
|
||||
if err != nil {
|
||||
|
|
@ -359,7 +350,6 @@ func (s *ApprovalsReg) GetApprovalsForReportHandler(w http.ResponseWriter, r *ht
|
|||
filter.DateTo = &dateTo
|
||||
}
|
||||
|
||||
// Парсим all_access
|
||||
if allAccessStr := queryParams.Get("all_access"); allAccessStr == "true" {
|
||||
filter.AllAccess = true
|
||||
}
|
||||
|
|
@ -370,10 +360,7 @@ func (s *ApprovalsReg) GetApprovalsForReportHandler(w http.ResponseWriter, r *ht
|
|||
return nil, err
|
||||
}
|
||||
|
||||
// Подгружаем связанные данные
|
||||
for _, approval := range approvals {
|
||||
s.enrichApproval(ctx, approval, false)
|
||||
}
|
||||
s.enrichApprovalsBatch(ctx, approvals, false)
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: uint64(len(approvals)),
|
||||
|
|
@ -382,74 +369,115 @@ func (s *ApprovalsReg) GetApprovalsForReportHandler(w http.ResponseWriter, r *ht
|
|||
}
|
||||
|
||||
// enrichApproval подгружает связанные данные для заявки
|
||||
// enrichApproval подгружает связанные данные для ОДНОЙ заявки.
|
||||
// Независимые запросы выполняются параллельно, чтобы сократить суммарную задержку.
|
||||
func (s *ApprovalsReg) enrichApproval(ctx context.Context, approval *typescore.Approval, loadSteps bool) {
|
||||
if approval == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Подгружаем инициатора
|
||||
var wg sync.WaitGroup
|
||||
|
||||
if approval.InitiatorID != nil {
|
||||
initiator, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
|
||||
if err == nil && initiator != nil {
|
||||
approval.Initiator = initiator
|
||||
}
|
||||
}
|
||||
|
||||
// Подгружаем тему
|
||||
if approval.TopicID != nil {
|
||||
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
|
||||
if err == nil && topic != nil {
|
||||
approval.Topic = topic
|
||||
|
||||
// 🆕 Подгружаем категорию темы
|
||||
if topic.CategoryID != nil {
|
||||
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
|
||||
if err == nil && category != nil {
|
||||
topic.Category = category
|
||||
}
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if initiator, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); err == nil && initiator != nil {
|
||||
approval.Initiator = initiator
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Подгружаем отдел
|
||||
if approval.DepartmentID != nil {
|
||||
department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID)
|
||||
if err == nil && department != nil {
|
||||
approval.Department = department
|
||||
}
|
||||
}
|
||||
|
||||
// Подгружаем того, кто отозвал
|
||||
if approval.RevokedByID != nil {
|
||||
revokedBy, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.RevokedByID)
|
||||
if err == nil && revokedBy != nil {
|
||||
approval.RevokedBy = revokedBy
|
||||
}
|
||||
}
|
||||
|
||||
// Подгружаем файлы
|
||||
files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
|
||||
if err == nil {
|
||||
approval.Files = files
|
||||
}
|
||||
|
||||
// Подгружаем шаги согласования (только для детального просмотра)
|
||||
if loadSteps {
|
||||
steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID},
|
||||
})
|
||||
if err == nil {
|
||||
for _, step := range steps {
|
||||
if step.ApproverID != nil {
|
||||
approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
|
||||
if err == nil && approver != nil {
|
||||
step.Approver = approver
|
||||
if approval.TopicID != nil {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
|
||||
if err == nil && topic != nil {
|
||||
approval.Topic = topic
|
||||
if topic.CategoryID != nil {
|
||||
if category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID); err == nil && category != nil {
|
||||
topic.Category = category
|
||||
}
|
||||
}
|
||||
}
|
||||
approval.Steps = steps
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
if approval.DepartmentID != nil {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID); err == nil && department != nil {
|
||||
approval.Department = department
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
if approval.RevokedByID != nil {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if revokedBy, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.RevokedByID); err == nil && revokedBy != nil {
|
||||
approval.RevokedBy = revokedBy
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
if approval.ID != nil {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID); err == nil {
|
||||
approval.Files = files
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
if loadSteps && approval.ID != nil {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID},
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Согласующие подгружаются одним батч-запросом, а не по одному на шаг
|
||||
approverIDsSet := make(map[uint64]struct{})
|
||||
for _, step := range steps {
|
||||
if step.ApproverID != nil {
|
||||
approverIDsSet[*step.ApproverID] = struct{}{}
|
||||
}
|
||||
}
|
||||
approverIDs := make([]uint64, 0, len(approverIDsSet))
|
||||
for id := range approverIDsSet {
|
||||
approverIDs = append(approverIDs, id)
|
||||
}
|
||||
|
||||
if approvers, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, approverIDs); err == nil {
|
||||
approversMap := make(map[uint64]*typescore.User, len(approvers))
|
||||
for _, u := range approvers {
|
||||
if u.ID != nil {
|
||||
approversMap[*u.ID] = u
|
||||
}
|
||||
}
|
||||
for _, step := range steps {
|
||||
if step.ApproverID != nil {
|
||||
if approver, ok := approversMap[*step.ApproverID]; ok {
|
||||
step.Approver = approver
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
approval.Steps = steps
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// isValidStatusTransition проверяет валидность перехода между статусами
|
||||
|
|
@ -476,3 +504,175 @@ func isValidStatusTransition(from, to string) bool {
|
|||
|
||||
return false
|
||||
}
|
||||
|
||||
// enrichApprovalsBatch выполняет пакетную подгрузку связанных данных для СПИСКА заявок,
|
||||
// заменяя N+1 отдельных запросов (было: enrichApproval в цикле) несколькими батч-запросами.
|
||||
func (s *ApprovalsReg) enrichApprovalsBatch(ctx context.Context, approvals []*typescore.Approval, loadSteps bool) {
|
||||
if len(approvals) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
userIDsSet := make(map[uint64]struct{})
|
||||
topicIDsSet := make(map[uint64]struct{})
|
||||
departmentIDsSet := make(map[uint64]struct{})
|
||||
approvalIDs := make([]uint64, 0, len(approvals))
|
||||
|
||||
for _, a := range approvals {
|
||||
if a.InitiatorID != nil {
|
||||
userIDsSet[*a.InitiatorID] = struct{}{}
|
||||
}
|
||||
if a.RevokedByID != nil {
|
||||
userIDsSet[*a.RevokedByID] = struct{}{}
|
||||
}
|
||||
if a.TopicID != nil {
|
||||
topicIDsSet[*a.TopicID] = struct{}{}
|
||||
}
|
||||
if a.DepartmentID != nil {
|
||||
departmentIDsSet[*a.DepartmentID] = struct{}{}
|
||||
}
|
||||
if a.ID != nil {
|
||||
approvalIDs = append(approvalIDs, *a.ID)
|
||||
}
|
||||
}
|
||||
|
||||
userIDs := make([]uint64, 0, len(userIDsSet))
|
||||
for id := range userIDsSet {
|
||||
userIDs = append(userIDs, id)
|
||||
}
|
||||
topicIDs := make([]uint64, 0, len(topicIDsSet))
|
||||
for id := range topicIDsSet {
|
||||
topicIDs = append(topicIDs, id)
|
||||
}
|
||||
departmentIDs := make([]uint64, 0, len(departmentIDsSet))
|
||||
for id := range departmentIDsSet {
|
||||
departmentIDs = append(departmentIDs, id)
|
||||
}
|
||||
|
||||
usersMap := make(map[uint64]*typescore.User)
|
||||
if users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, userIDs); err == nil {
|
||||
for _, u := range users {
|
||||
if u.ID != nil {
|
||||
usersMap[*u.ID] = u
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
topicsMap := make(map[uint64]*typescore.ApprovalTopic)
|
||||
categoryIDsSet := make(map[uint64]struct{})
|
||||
if topics, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsByIDsDB(ctx, topicIDs); err == nil {
|
||||
for _, t := range topics {
|
||||
if t.ID != nil {
|
||||
topicsMap[*t.ID] = t
|
||||
}
|
||||
if t.CategoryID != nil {
|
||||
categoryIDsSet[*t.CategoryID] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
categoryIDs := make([]uint64, 0, len(categoryIDsSet))
|
||||
for id := range categoryIDsSet {
|
||||
categoryIDs = append(categoryIDs, id)
|
||||
}
|
||||
categoriesMap := make(map[uint64]*typescore.ApprovalTopicCategory)
|
||||
if categories, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoriesByIDsDB(ctx, categoryIDs); err == nil {
|
||||
for _, c := range categories {
|
||||
if c.ID != nil {
|
||||
categoriesMap[*c.ID] = c
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, t := range topicsMap {
|
||||
if t.CategoryID != nil {
|
||||
if cat, ok := categoriesMap[*t.CategoryID]; ok {
|
||||
t.Category = cat
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
departmentsMap := make(map[uint64]*typescore.Department)
|
||||
if departments, err := s.ipc.Database.Department.GetDepartmentsByIDsDB(ctx, departmentIDs); err == nil {
|
||||
for _, d := range departments {
|
||||
if d.ID != nil {
|
||||
departmentsMap[*d.ID] = d
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
filesMap := make(map[uint64][]*typescore.ApprovalFile)
|
||||
if files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDsDB(ctx, approvalIDs); err == nil {
|
||||
for _, f := range files {
|
||||
if f.ApprovalID != nil {
|
||||
filesMap[*f.ApprovalID] = append(filesMap[*f.ApprovalID], f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var stepsMap map[uint64][]*typescore.ApprovalStep
|
||||
if loadSteps {
|
||||
stepsMap = make(map[uint64][]*typescore.ApprovalStep)
|
||||
steps, err := s.ipc.Database.ApprovalStep.GetApprovalStepsByApprovalIDsDB(ctx, approvalIDs)
|
||||
if err == nil {
|
||||
approverIDsSet := make(map[uint64]struct{})
|
||||
for _, st := range steps {
|
||||
if st.ApprovalID != nil {
|
||||
stepsMap[*st.ApprovalID] = append(stepsMap[*st.ApprovalID], st)
|
||||
}
|
||||
if st.ApproverID != nil {
|
||||
approverIDsSet[*st.ApproverID] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
approverIDs := make([]uint64, 0, len(approverIDsSet))
|
||||
for id := range approverIDsSet {
|
||||
approverIDs = append(approverIDs, id)
|
||||
}
|
||||
approversMap := make(map[uint64]*typescore.User)
|
||||
if approvers, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, approverIDs); err == nil {
|
||||
for _, u := range approvers {
|
||||
if u.ID != nil {
|
||||
approversMap[*u.ID] = u
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, stepsForApproval := range stepsMap {
|
||||
for _, st := range stepsForApproval {
|
||||
if st.ApproverID != nil {
|
||||
if approver, ok := approversMap[*st.ApproverID]; ok {
|
||||
st.Approver = approver
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, a := range approvals {
|
||||
if a.InitiatorID != nil {
|
||||
if u, ok := usersMap[*a.InitiatorID]; ok {
|
||||
a.Initiator = u
|
||||
}
|
||||
}
|
||||
if a.RevokedByID != nil {
|
||||
if u, ok := usersMap[*a.RevokedByID]; ok {
|
||||
a.RevokedBy = u
|
||||
}
|
||||
}
|
||||
if a.TopicID != nil {
|
||||
if t, ok := topicsMap[*a.TopicID]; ok {
|
||||
a.Topic = t
|
||||
}
|
||||
}
|
||||
if a.DepartmentID != nil {
|
||||
if d, ok := departmentsMap[*a.DepartmentID]; ok {
|
||||
a.Department = d
|
||||
}
|
||||
}
|
||||
if a.ID != nil {
|
||||
a.Files = filesMap[*a.ID]
|
||||
if loadSteps {
|
||||
a.Steps = stepsMap[*a.ID]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -52,10 +52,8 @@ func (s *PermissionsReg) GetPermissionsListHandler(w http.ResponseWriter, r *htt
|
|||
return nil, errW
|
||||
}
|
||||
|
||||
// 🚀 Подгружаем связанные данные
|
||||
for _, perm := range permissionsDbLst {
|
||||
s.enrichPermission(ctx, perm)
|
||||
}
|
||||
// 🚀 Батч-подгрузка вместо N+1
|
||||
s.enrichPermissionsBatch(ctx, permissionsDbLst)
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: total,
|
||||
|
|
@ -63,6 +61,136 @@ func (s *PermissionsReg) GetPermissionsListHandler(w http.ResponseWriter, r *htt
|
|||
}, nil
|
||||
}
|
||||
|
||||
// GetPermissionsByRoleIDHandler Получение всех прав для роли
|
||||
// @Summary Получение прав по роли
|
||||
// @Description Получение списка всех прав для указанной роли
|
||||
// @Tags permissions
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param role_id path integer true "ID роли"
|
||||
// @Success 200 {object} typescore.ApiResponseBase "Успех"
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 404 {object} handlers.ErrorResponse "Роль не найдена"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/permissions/by-role/{role_id} [get]
|
||||
func (s *PermissionsReg) GetPermissionsByRoleIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
roleIDStr := chi.URLParam(r, "role_id")
|
||||
if roleIDStr == "" {
|
||||
return nil, errors.New("role_id is required")
|
||||
}
|
||||
|
||||
roleID, err := strconv.ParseUint(roleIDStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid role_id")
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, roleID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if role == nil {
|
||||
return nil, errors.New("role not found")
|
||||
}
|
||||
|
||||
permissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.Permission{RoleID: &roleID},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 🚀 Батч-подгрузка вместо N+1
|
||||
s.enrichPermissionsBatch(ctx, permissions)
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: uint64(len(permissions)),
|
||||
Data: permissions,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// enrichPermissionsBatch пакетно подгружает роли, категории и темы для списка прав
|
||||
func (s *PermissionsReg) enrichPermissionsBatch(ctx context.Context, permissions []*typescore.Permission) {
|
||||
if len(permissions) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
roleIDsSet := make(map[uint64]struct{})
|
||||
categoryIDsSet := make(map[uint64]struct{})
|
||||
topicIDsSet := make(map[uint64]struct{})
|
||||
|
||||
for _, p := range permissions {
|
||||
if p.RoleID != nil {
|
||||
roleIDsSet[*p.RoleID] = struct{}{}
|
||||
}
|
||||
if p.TopicCategoryID != nil {
|
||||
categoryIDsSet[*p.TopicCategoryID] = struct{}{}
|
||||
}
|
||||
if p.TopicID != nil {
|
||||
topicIDsSet[*p.TopicID] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
roleIDs := make([]uint64, 0, len(roleIDsSet))
|
||||
for id := range roleIDsSet {
|
||||
roleIDs = append(roleIDs, id)
|
||||
}
|
||||
categoryIDs := make([]uint64, 0, len(categoryIDsSet))
|
||||
for id := range categoryIDsSet {
|
||||
categoryIDs = append(categoryIDs, id)
|
||||
}
|
||||
topicIDs := make([]uint64, 0, len(topicIDsSet))
|
||||
for id := range topicIDsSet {
|
||||
topicIDs = append(topicIDs, id)
|
||||
}
|
||||
|
||||
rolesMap := make(map[uint64]*typescore.Role)
|
||||
if roles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs); err == nil {
|
||||
for _, role := range roles {
|
||||
if role.ID != nil {
|
||||
rolesMap[*role.ID] = role
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
categoriesMap := make(map[uint64]*typescore.ApprovalTopicCategory)
|
||||
if categories, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoriesByIDsDB(ctx, categoryIDs); err == nil {
|
||||
for _, c := range categories {
|
||||
if c.ID != nil {
|
||||
categoriesMap[*c.ID] = c
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
topicsMap := make(map[uint64]*typescore.ApprovalTopic)
|
||||
if topics, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsByIDsDB(ctx, topicIDs); err == nil {
|
||||
for _, t := range topics {
|
||||
if t.ID != nil {
|
||||
topicsMap[*t.ID] = t
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, p := range permissions {
|
||||
if p.RoleID != nil {
|
||||
if role, ok := rolesMap[*p.RoleID]; ok {
|
||||
p.Role = role
|
||||
}
|
||||
}
|
||||
if p.TopicCategoryID != nil {
|
||||
if cat, ok := categoriesMap[*p.TopicCategoryID]; ok {
|
||||
p.TopicCategory = cat
|
||||
}
|
||||
}
|
||||
if p.TopicID != nil {
|
||||
if topic, ok := topicsMap[*p.TopicID]; ok {
|
||||
p.Topic = topic
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetPermissionByIDHandler Получение права по ID
|
||||
// @Summary Получение права по ID
|
||||
// @Description Получение детальной информации о праве по его ID
|
||||
|
|
@ -103,58 +231,6 @@ func (s *PermissionsReg) GetPermissionByIDHandler(w http.ResponseWriter, r *http
|
|||
return permission, nil
|
||||
}
|
||||
|
||||
// GetPermissionsByRoleIDHandler Получение всех прав для роли
|
||||
// @Summary Получение прав по роли
|
||||
// @Description Получение списка всех прав для указанной роли
|
||||
// @Tags permissions
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param role_id path integer true "ID роли"
|
||||
// @Success 200 {object} typescore.ApiResponseBase "Успех"
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 404 {object} handlers.ErrorResponse "Роль не найдена"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/permissions/by-role/{role_id} [get]
|
||||
func (s *PermissionsReg) GetPermissionsByRoleIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
roleIDStr := chi.URLParam(r, "role_id")
|
||||
if roleIDStr == "" {
|
||||
return nil, errors.New("role_id is required")
|
||||
}
|
||||
|
||||
roleID, err := strconv.ParseUint(roleIDStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid role_id")
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
// Проверяем, что роль существует
|
||||
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, roleID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if role == nil {
|
||||
return nil, errors.New("role not found")
|
||||
}
|
||||
|
||||
permissions, _, err := s.ipc.Database.Permission.GetPermissionsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.Permission{RoleID: &roleID},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Подгружаем связанные данные
|
||||
for _, perm := range permissions {
|
||||
s.enrichPermission(ctx, perm)
|
||||
}
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: uint64(len(permissions)),
|
||||
Data: permissions,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreatePermissionHandler Создание права
|
||||
// @Summary Создание права
|
||||
// @Description Назначение права на действие для роли
|
||||
|
|
|
|||
|
|
@ -38,7 +38,6 @@ func (s *TopicExecutorsReg) GetTopicExecutorsListHandler(w http.ResponseWriter,
|
|||
return nil, errW
|
||||
}
|
||||
|
||||
// ✅ Добавляем поддержку category_id
|
||||
var categoryID *uint64
|
||||
if categoryIDStr := queryParams.Get("category_id"); categoryIDStr != "" {
|
||||
if id, err := strconv.ParseUint(categoryIDStr, 10, 64); err == nil {
|
||||
|
|
@ -69,9 +68,8 @@ func (s *TopicExecutorsReg) GetTopicExecutorsListHandler(w http.ResponseWriter,
|
|||
return nil, err
|
||||
}
|
||||
|
||||
for _, exec := range executorsDbLst {
|
||||
s.enrichExecutor(ctx, exec)
|
||||
}
|
||||
// 🚀 Батч-подгрузка вместо N+1
|
||||
s.enrichExecutorsBatch(ctx, executorsDbLst)
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: total,
|
||||
|
|
@ -79,6 +77,111 @@ func (s *TopicExecutorsReg) GetTopicExecutorsListHandler(w http.ResponseWriter,
|
|||
}, nil
|
||||
}
|
||||
|
||||
// GetExecutorsByTopicIDHandler Получение всех исполнителей для темы
|
||||
// @Summary Получение исполнителей по теме
|
||||
// @Description Получение списка всех активных исполнителей для указанной темы, отсортированных по step_order
|
||||
// @Tags topic-executors
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param topic_id path integer true "ID темы"
|
||||
// @Success 200 {object} typescore.ApiResponseBase "Успех"
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 404 {object} handlers.ErrorResponse "Тема не найдена"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/topic-executors/by-topic/{topic_id} [get]
|
||||
func (s *TopicExecutorsReg) GetExecutorsByTopicIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
topicIDStr := chi.URLParam(r, "topic_id")
|
||||
if topicIDStr == "" {
|
||||
return nil, errors.New("topic_id is required")
|
||||
}
|
||||
|
||||
topicID, err := strconv.ParseUint(topicIDStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid topic_id")
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if topic == nil {
|
||||
return nil, errors.New("topic not found")
|
||||
}
|
||||
|
||||
executors, err := s.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, topicID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 🚀 Батч-подгрузка вместо N+1
|
||||
s.enrichExecutorsBatch(ctx, executors)
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: uint64(len(executors)),
|
||||
Data: executors,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// enrichExecutorsBatch пакетно подгружает темы и пользователей для списка исполнителей
|
||||
func (s *TopicExecutorsReg) enrichExecutorsBatch(ctx context.Context, executors []*typescore.ApprovalTopicExecutor) {
|
||||
if len(executors) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
topicIDsSet := make(map[uint64]struct{})
|
||||
userIDsSet := make(map[uint64]struct{})
|
||||
for _, e := range executors {
|
||||
if e.TopicID != nil {
|
||||
topicIDsSet[*e.TopicID] = struct{}{}
|
||||
}
|
||||
if e.UserID != nil {
|
||||
userIDsSet[*e.UserID] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
topicIDs := make([]uint64, 0, len(topicIDsSet))
|
||||
for id := range topicIDsSet {
|
||||
topicIDs = append(topicIDs, id)
|
||||
}
|
||||
userIDs := make([]uint64, 0, len(userIDsSet))
|
||||
for id := range userIDsSet {
|
||||
userIDs = append(userIDs, id)
|
||||
}
|
||||
|
||||
topicsMap := make(map[uint64]*typescore.ApprovalTopic)
|
||||
if topics, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsByIDsDB(ctx, topicIDs); err == nil {
|
||||
for _, t := range topics {
|
||||
if t.ID != nil {
|
||||
topicsMap[*t.ID] = t
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
usersMap := make(map[uint64]*typescore.User)
|
||||
if users, err := s.ipc.Database.User.GetUsersByIDsDB(ctx, userIDs); err == nil {
|
||||
for _, u := range users {
|
||||
if u.ID != nil {
|
||||
usersMap[*u.ID] = u
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, e := range executors {
|
||||
if e.TopicID != nil {
|
||||
if t, ok := topicsMap[*e.TopicID]; ok {
|
||||
e.Topic = t
|
||||
}
|
||||
}
|
||||
if e.UserID != nil {
|
||||
if u, ok := usersMap[*e.UserID]; ok {
|
||||
e.User = u
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetTopicExecutorByIDHandler Получение исполнителя по ID
|
||||
// @Summary Получение исполнителя по ID
|
||||
// @Description Получение детальной информации об исполнителе по его ID
|
||||
|
|
@ -119,56 +222,6 @@ func (s *TopicExecutorsReg) GetTopicExecutorByIDHandler(w http.ResponseWriter, r
|
|||
return executor, nil
|
||||
}
|
||||
|
||||
// GetExecutorsByTopicIDHandler Получение всех исполнителей для темы
|
||||
// @Summary Получение исполнителей по теме
|
||||
// @Description Получение списка всех активных исполнителей для указанной темы, отсортированных по step_order
|
||||
// @Tags topic-executors
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param topic_id path integer true "ID темы"
|
||||
// @Success 200 {object} typescore.ApiResponseBase "Успех"
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 404 {object} handlers.ErrorResponse "Тема не найдена"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/topic-executors/by-topic/{topic_id} [get]
|
||||
func (s *TopicExecutorsReg) GetExecutorsByTopicIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
topicIDStr := chi.URLParam(r, "topic_id")
|
||||
if topicIDStr == "" {
|
||||
return nil, errors.New("topic_id is required")
|
||||
}
|
||||
|
||||
topicID, err := strconv.ParseUint(topicIDStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid topic_id")
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
// Проверяем, что тема существует
|
||||
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, topicID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if topic == nil {
|
||||
return nil, errors.New("topic not found")
|
||||
}
|
||||
|
||||
executors, err := s.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, topicID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Подгружаем связанные данные
|
||||
for _, exec := range executors {
|
||||
s.enrichExecutor(ctx, exec)
|
||||
}
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: uint64(len(executors)),
|
||||
Data: executors,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreateTopicExecutorHandler Создание исполнителя для темы
|
||||
// @Summary Создание исполнителя
|
||||
// @Description Назначение исполнителя для конкретной темы согласования
|
||||
|
|
|
|||
|
|
@ -49,12 +49,30 @@ func (s *TopicsReg) GetTopicsListHandler(w http.ResponseWriter, r *http.Request)
|
|||
return nil, errW
|
||||
}
|
||||
|
||||
// Подгружаем информацию о категории для каждой темы
|
||||
categoryIDsSet := make(map[uint64]struct{})
|
||||
for _, topic := range topicsDbLst {
|
||||
if topic.CategoryID != nil {
|
||||
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
|
||||
if err == nil && category != nil {
|
||||
topic.Category = category
|
||||
categoryIDsSet[*topic.CategoryID] = struct{}{}
|
||||
}
|
||||
}
|
||||
categoryIDs := make([]uint64, 0, len(categoryIDsSet))
|
||||
for id := range categoryIDsSet {
|
||||
categoryIDs = append(categoryIDs, id)
|
||||
}
|
||||
|
||||
categoriesMap := make(map[uint64]*typescore.ApprovalTopicCategory)
|
||||
if categories, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoriesByIDsDB(ctx, categoryIDs); err == nil {
|
||||
for _, c := range categories {
|
||||
if c.ID != nil {
|
||||
categoriesMap[*c.ID] = c
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, topic := range topicsDbLst {
|
||||
if topic.CategoryID != nil {
|
||||
if cat, ok := categoriesMap[*topic.CategoryID]; ok {
|
||||
topic.Category = cat
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package userroleshandler
|
|||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/core/utilscore"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
|
@ -45,7 +46,6 @@ func (s *UserRolesReg) GetUserRolesListHandler(w http.ResponseWriter, r *http.Re
|
|||
return nil, errW
|
||||
}
|
||||
|
||||
// user_id обязателен для этого эндпоинта
|
||||
if roleParams.UserID == nil {
|
||||
return nil, errors.New("user_id is required")
|
||||
}
|
||||
|
|
@ -63,15 +63,8 @@ func (s *UserRolesReg) GetUserRolesListHandler(w http.ResponseWriter, r *http.Re
|
|||
return nil, errW
|
||||
}
|
||||
|
||||
// 🚀 Подгружаем информацию о ролях
|
||||
for _, ur := range userRolesDbLst {
|
||||
if ur.RoleID != nil {
|
||||
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *ur.RoleID)
|
||||
if err == nil && role != nil {
|
||||
ur.Role = role
|
||||
}
|
||||
}
|
||||
}
|
||||
// 🚀 Батч-подгрузка ролей одним запросом вместо N+1
|
||||
s.enrichUserRolesBatch(ctx, userRolesDbLst)
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: total,
|
||||
|
|
@ -104,7 +97,6 @@ func (s *UserRolesReg) GetUserRolesByUserIDHandler(w http.ResponseWriter, r *htt
|
|||
|
||||
ctx := r.Context()
|
||||
|
||||
// Проверяем, что пользователь существует
|
||||
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
@ -120,15 +112,8 @@ func (s *UserRolesReg) GetUserRolesByUserIDHandler(w http.ResponseWriter, r *htt
|
|||
return nil, errW
|
||||
}
|
||||
|
||||
// 🚀 Подгружаем информацию о ролях
|
||||
for _, ur := range userRolesDbLst {
|
||||
if ur.RoleID != nil {
|
||||
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *ur.RoleID)
|
||||
if err == nil && role != nil {
|
||||
ur.Role = role
|
||||
}
|
||||
}
|
||||
}
|
||||
// 🚀 Батч-подгрузка ролей одним запросом вместо N+1
|
||||
s.enrichUserRolesBatch(ctx, userRolesDbLst)
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: uint64(len(userRolesDbLst)),
|
||||
|
|
@ -136,6 +121,135 @@ func (s *UserRolesReg) GetUserRolesByUserIDHandler(w http.ResponseWriter, r *htt
|
|||
}, nil
|
||||
}
|
||||
|
||||
// enrichUserRolesBatch пакетно подгружает роли для списка user_role
|
||||
func (s *UserRolesReg) enrichUserRolesBatch(ctx context.Context, userRoles []*typescore.UserRole) {
|
||||
if len(userRoles) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
roleIDsSet := make(map[uint64]struct{})
|
||||
for _, ur := range userRoles {
|
||||
if ur.RoleID != nil {
|
||||
roleIDsSet[*ur.RoleID] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
roleIDs := make([]uint64, 0, len(roleIDsSet))
|
||||
for id := range roleIDsSet {
|
||||
roleIDs = append(roleIDs, id)
|
||||
}
|
||||
|
||||
rolesMap := make(map[uint64]*typescore.Role)
|
||||
if roles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs); err == nil {
|
||||
for _, role := range roles {
|
||||
if role.ID != nil {
|
||||
rolesMap[*role.ID] = role
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, ur := range userRoles {
|
||||
if ur.RoleID != nil {
|
||||
if role, ok := rolesMap[*ur.RoleID]; ok {
|
||||
ur.Role = role
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// BulkAssignRolesHandler Массовое назначение ролей пользователю
|
||||
// @Summary Массовое назначение ролей
|
||||
// @Description Полная замена ролей пользователя: удаляет все текущие роли и назначает новые
|
||||
// @Tags user-roles
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body BulkAssignRolesRequest true "user_id и список role_ids"
|
||||
// @Success 200 {object} typescore.ApiResponseBase "Успех"
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 404 {object} handlers.ErrorResponse "Пользователь не найден"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/user-roles/bulk [post]
|
||||
func (s *UserRolesReg) BulkAssignRolesHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
logrus.Error("🛑 BulkAssignRolesHandler: ReadAll error:", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var req BulkAssignRolesRequest
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return nil, errors.New("invalid request body")
|
||||
}
|
||||
|
||||
if req.UserID == nil {
|
||||
return nil, errors.New("user_id is required")
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if user == nil {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
|
||||
roleIDsSet := make(map[uint64]struct{})
|
||||
roleIDs := make([]uint64, 0, len(req.RoleIDs))
|
||||
for _, roleID := range req.RoleIDs {
|
||||
if roleID == nil {
|
||||
continue
|
||||
}
|
||||
if _, exists := roleIDsSet[*roleID]; exists {
|
||||
continue
|
||||
}
|
||||
roleIDsSet[*roleID] = struct{}{}
|
||||
roleIDs = append(roleIDs, *roleID)
|
||||
}
|
||||
|
||||
// 🚀 Проверяем существование всех ролей ОДНИМ запросом вместо N
|
||||
if len(roleIDs) > 0 {
|
||||
existingRoles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
foundIDs := make(map[uint64]struct{}, len(existingRoles))
|
||||
for _, role := range existingRoles {
|
||||
if role.ID != nil {
|
||||
foundIDs[*role.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
for _, roleID := range roleIDs {
|
||||
if _, ok := foundIDs[roleID]; !ok {
|
||||
return nil, errors.New("role not found: " + strconv.FormatUint(roleID, 10))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 🗑 Удаляем все текущие роли ОДНИМ запросом вместо цикла
|
||||
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)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.enrichUserRolesBatch(ctx, createdRoles)
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: uint64(len(createdRoles)),
|
||||
Data: createdRoles,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// AssignUserRoleHandler Назначение роли пользователю
|
||||
// @Summary Назначение роли пользователю
|
||||
// @Description Назначение роли пользователю (создание связи user_id + role_id)
|
||||
|
|
@ -225,106 +339,6 @@ func (s *UserRolesReg) AssignUserRoleHandler(w http.ResponseWriter, r *http.Requ
|
|||
return createdUserRole, nil
|
||||
}
|
||||
|
||||
// BulkAssignRolesHandler Массовое назначение ролей пользователю
|
||||
// @Summary Массовое назначение ролей
|
||||
// @Description Полная замена ролей пользователя: удаляет все текущие роли и назначает новые
|
||||
// @Tags user-roles
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body BulkAssignRolesRequest true "user_id и список role_ids"
|
||||
// @Success 200 {object} typescore.ApiResponseBase "Успех"
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 404 {object} handlers.ErrorResponse "Пользователь не найден"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/user-roles/bulk [post]
|
||||
func (s *UserRolesReg) BulkAssignRolesHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
logrus.Error("🛑 BulkAssignRolesHandler: ReadAll error:", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var req BulkAssignRolesRequest
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return nil, errors.New("invalid request body")
|
||||
}
|
||||
|
||||
if req.UserID == nil {
|
||||
return nil, errors.New("user_id is required")
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
// Проверяем, что пользователь существует
|
||||
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.UserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if user == nil {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
|
||||
// 🗑 Удаляем все текущие роли пользователя
|
||||
existingRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.UserRole{UserID: req.UserID},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, existingRole := range existingRoles {
|
||||
if err := s.ipc.Database.UserRole.DeleteUserRoleDB(ctx, existingRole); err != nil {
|
||||
logrus.Errorf("BulkAssignRolesHandler: failed to delete user_role id=%d: %v", *existingRole.ID, err)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// 🆕 Назначаем новые роли
|
||||
var createdRoles []*typescore.UserRole
|
||||
for _, roleID := range req.RoleIDs {
|
||||
if roleID == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Проверяем, что роль существует
|
||||
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *roleID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if role == nil {
|
||||
return nil, errors.New("role not found: " + strconv.FormatUint(*roleID, 10))
|
||||
}
|
||||
|
||||
userRoleObj := &typescore.UserRole{
|
||||
UserID: req.UserID,
|
||||
RoleID: roleID,
|
||||
}
|
||||
|
||||
createdUserRole, _, err := s.ipc.Database.UserRole.CreateUserRoleDB(ctx, nil, userRoleObj, true)
|
||||
if err != nil {
|
||||
logrus.Errorf("BulkAssignRolesHandler: failed to create user_role: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Подгружаем информацию о роли
|
||||
if createdUserRole != nil && createdUserRole.RoleID != nil {
|
||||
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *createdUserRole.RoleID)
|
||||
if err == nil && role != nil {
|
||||
createdUserRole.Role = role
|
||||
}
|
||||
}
|
||||
|
||||
createdRoles = append(createdRoles, createdUserRole)
|
||||
}
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: uint64(len(createdRoles)),
|
||||
Data: createdRoles,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RemoveUserRoleHandler Удаление роли у пользователя
|
||||
// @Summary Удаление роли у пользователя
|
||||
// @Description Удаление связи user_id + role_id по ID записи
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package usershandler
|
|||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/core/utilscore"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
|
@ -37,12 +38,7 @@ func (s *UserReg) GetUserListHandler(w http.ResponseWriter, r *http.Request) (in
|
|||
return nil, errW
|
||||
}
|
||||
|
||||
logrus.Infof("🔍 После ParseParamsGetRequest: offset=%d, limit=%d, likeFields=%v, userParams.FullName=%v",
|
||||
offset, limit, likeFields, userParams.FullName)
|
||||
|
||||
search := queryParams.Get("full_name")
|
||||
logrus.Infof("🔍 search из queryParams.Get('full_name'): '%s'", search)
|
||||
|
||||
if search != "" {
|
||||
if likeFields == nil {
|
||||
likeFields = make(map[string]string)
|
||||
|
|
@ -83,29 +79,9 @@ func (s *UserReg) GetUserListHandler(w http.ResponseWriter, r *http.Request) (in
|
|||
return nil, err
|
||||
}
|
||||
|
||||
for _, user := range userDbLst {
|
||||
if user.DepartmentID != nil {
|
||||
department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *user.DepartmentID)
|
||||
if err == nil && department != nil {
|
||||
user.Department = department
|
||||
}
|
||||
}
|
||||
|
||||
userRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.UserRole{UserID: user.ID},
|
||||
})
|
||||
if err == nil && len(userRoles) > 0 {
|
||||
for _, ur := range userRoles {
|
||||
if ur.RoleID != nil {
|
||||
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *ur.RoleID)
|
||||
if err == nil && role != nil {
|
||||
ur.Role = role
|
||||
}
|
||||
}
|
||||
}
|
||||
user.UserRoles = userRoles
|
||||
}
|
||||
}
|
||||
// 🚀 Батч-подгрузка отделов и ролей: было до 2N+1 запросов (department + roles + role-на-каждую-роль),
|
||||
// стало 3 запроса суммарно независимо от количества пользователей
|
||||
s.enrichUsersBatch(ctx, userDbLst)
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: total,
|
||||
|
|
@ -113,6 +89,154 @@ func (s *UserReg) GetUserListHandler(w http.ResponseWriter, r *http.Request) (in
|
|||
}, nil
|
||||
}
|
||||
|
||||
// UpdateUserHandler Обновление пользователя
|
||||
// @Summary Обновление пользователя
|
||||
// @Description Обновление данных существующего пользователя
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body typescore.UpdateUserReqAdmin true "Данные пользователя"
|
||||
// @Success 200 {object} typescore.User "Успех"
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 404 {object} handlers.ErrorResponse "Пользователь не найден"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/users [put]
|
||||
func (s *UserReg) UpdateUserHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
logrus.Error("🛑 UpdateUserHandler: ReadAll error:", err)
|
||||
return nil, err
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var req typescore.UpdateUserReqAdmin
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return nil, errors.New("invalid request body")
|
||||
}
|
||||
|
||||
if req.ID == nil {
|
||||
return nil, errors.New("user id is required")
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
existingUser, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existingUser == nil {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
|
||||
if req.DepartmentID != nil {
|
||||
if existingUser.DepartmentID == nil || *existingUser.DepartmentID != *req.DepartmentID {
|
||||
department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.DepartmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if department == nil {
|
||||
return nil, errors.New("department not found")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
upUserObj := &typescore.User{
|
||||
ID: req.ID,
|
||||
DepartmentID: req.DepartmentID,
|
||||
IsBlocked: req.IsBlocked,
|
||||
IsFired: req.IsFired,
|
||||
}
|
||||
|
||||
upUser, _, errW := s.ipc.Database.User.UpdateUserDB(ctx, nil, upUserObj, true)
|
||||
if errW != nil {
|
||||
return nil, errW
|
||||
}
|
||||
|
||||
s.enrichUsersBatch(ctx, []*typescore.User{upUser})
|
||||
|
||||
return upUser, nil
|
||||
}
|
||||
|
||||
// enrichUsersBatch пакетно подгружает отделы и роли для списка пользователей
|
||||
func (s *UserReg) enrichUsersBatch(ctx context.Context, users []*typescore.User) {
|
||||
if len(users) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
departmentIDsSet := make(map[uint64]struct{})
|
||||
userIDs := make([]uint64, 0, len(users))
|
||||
for _, u := range users {
|
||||
if u.ID != nil {
|
||||
userIDs = append(userIDs, *u.ID)
|
||||
}
|
||||
if u.DepartmentID != nil {
|
||||
departmentIDsSet[*u.DepartmentID] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
departmentIDs := make([]uint64, 0, len(departmentIDsSet))
|
||||
for id := range departmentIDsSet {
|
||||
departmentIDs = append(departmentIDs, id)
|
||||
}
|
||||
|
||||
departmentsMap := make(map[uint64]*typescore.Department)
|
||||
if departments, err := s.ipc.Database.Department.GetDepartmentsByIDsDB(ctx, departmentIDs); err == nil {
|
||||
for _, d := range departments {
|
||||
if d.ID != nil {
|
||||
departmentsMap[*d.ID] = d
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
userRoles, err := s.ipc.Database.UserRole.GetUserRolesByUserIDsDB(ctx, userIDs)
|
||||
roleIDsSet := make(map[uint64]struct{})
|
||||
userRolesByUser := make(map[uint64][]*typescore.UserRole)
|
||||
if err == nil {
|
||||
for _, ur := range userRoles {
|
||||
if ur.UserID != nil {
|
||||
userRolesByUser[*ur.UserID] = append(userRolesByUser[*ur.UserID], ur)
|
||||
}
|
||||
if ur.RoleID != nil {
|
||||
roleIDsSet[*ur.RoleID] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
roleIDs := make([]uint64, 0, len(roleIDsSet))
|
||||
for id := range roleIDsSet {
|
||||
roleIDs = append(roleIDs, id)
|
||||
}
|
||||
rolesMap := make(map[uint64]*typescore.Role)
|
||||
if roles, err := s.ipc.Database.Role.GetRolesByIDsDB(ctx, roleIDs); err == nil {
|
||||
for _, role := range roles {
|
||||
if role.ID != nil {
|
||||
rolesMap[*role.ID] = role
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, u := range users {
|
||||
if u.DepartmentID != nil {
|
||||
if d, ok := departmentsMap[*u.DepartmentID]; ok {
|
||||
u.Department = d
|
||||
}
|
||||
}
|
||||
if u.ID == nil {
|
||||
continue
|
||||
}
|
||||
userRolesForUser := userRolesByUser[*u.ID]
|
||||
for _, ur := range userRolesForUser {
|
||||
if ur.RoleID != nil {
|
||||
if role, ok := rolesMap[*ur.RoleID]; ok {
|
||||
ur.Role = role
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(userRolesForUser) > 0 {
|
||||
u.UserRoles = userRolesForUser
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetUserByIDHandler Получение пользователя по ID
|
||||
// @Summary Получение пользователя по ID
|
||||
// @Description Получение детальной информации о пользователе по его ID с подгрузкой связанных данных
|
||||
|
|
@ -174,96 +298,6 @@ func (s *UserReg) GetUserByIDHandler(w http.ResponseWriter, r *http.Request) (in
|
|||
return user, nil
|
||||
}
|
||||
|
||||
// UpdateUserHandler Обновление пользователя
|
||||
// @Summary Обновление пользователя
|
||||
// @Description Обновление данных существующего пользователя
|
||||
// @Tags users
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body typescore.UpdateUserReqAdmin true "Данные пользователя"
|
||||
// @Success 200 {object} typescore.User "Успех"
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 404 {object} handlers.ErrorResponse "Пользователь не найден"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/users [put]
|
||||
func (s *UserReg) UpdateUserHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
logrus.Error("🛑 UpdateUserHandler: ReadAll error:", err)
|
||||
return nil, err
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var req typescore.UpdateUserReqAdmin
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return nil, errors.New("invalid request body")
|
||||
}
|
||||
|
||||
if req.ID == nil {
|
||||
return nil, errors.New("user id is required")
|
||||
}
|
||||
|
||||
// Проверяем, что пользователь существует
|
||||
ctx := r.Context()
|
||||
existingUser, err := s.ipc.Database.User.GetUserByIDDB(ctx, *req.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existingUser == nil {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
|
||||
// Если обновляется department_id, проверяем, что отдел существует
|
||||
if req.DepartmentID != nil {
|
||||
if existingUser.DepartmentID == nil || *existingUser.DepartmentID != *req.DepartmentID {
|
||||
department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *req.DepartmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if department == nil {
|
||||
return nil, errors.New("department not found")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
upUserObj := &typescore.User{
|
||||
ID: req.ID,
|
||||
DepartmentID: req.DepartmentID,
|
||||
IsBlocked: req.IsBlocked,
|
||||
IsFired: req.IsFired,
|
||||
}
|
||||
|
||||
upUser, _, errW := s.ipc.Database.User.UpdateUserDB(ctx, nil, upUserObj, true)
|
||||
if errW != nil {
|
||||
return nil, errW
|
||||
}
|
||||
|
||||
// Подгружаем связанные данные
|
||||
if upUser.DepartmentID != nil {
|
||||
department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *upUser.DepartmentID)
|
||||
if err == nil && department != nil {
|
||||
upUser.Department = department
|
||||
}
|
||||
}
|
||||
|
||||
userRoles, _, err := s.ipc.Database.UserRole.GetUserRolesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.UserRole{UserID: upUser.ID},
|
||||
})
|
||||
if err == nil && len(userRoles) > 0 {
|
||||
for _, ur := range userRoles {
|
||||
if ur.RoleID != nil {
|
||||
role, err := s.ipc.Database.Role.GetRoleByIDDB(ctx, *ur.RoleID)
|
||||
if err == nil && role != nil {
|
||||
ur.Role = role
|
||||
}
|
||||
}
|
||||
}
|
||||
upUser.UserRoles = userRoles
|
||||
}
|
||||
|
||||
return upUser, nil
|
||||
}
|
||||
|
||||
func (s *UserReg) DeleteUserHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
idStr := chi.URLParam(r, "id")
|
||||
if idStr == "" {
|
||||
|
|
|
|||
Loading…
Reference in New Issue