diff --git a/core/db/db.go b/core/db/db.go index 2362085..d327d1b 100644 --- a/core/db/db.go +++ b/core/db/db.go @@ -35,6 +35,7 @@ type ModuleDB struct { ApprovalTopicExecutor *dbcore.ApprovalTopicExecutorDB Admin *dbcore.AdminDB Notification *dbcore.NotificationDB + DirectorNotifications *dbcore.DirectorNotificationDB } func NewModuleDB( @@ -86,6 +87,7 @@ func initDBModules(modules *ModuleDB, redisClient *redismodule.ModuleRedis) *Mod modules.ApprovalTopicExecutor = dbcore.NewApprovalTopicExecutorDB(modules.Pool) modules.Admin = dbcore.NewAdminDB(modules.Pool) modules.Notification = dbcore.NewNotificationDB(modules.Pool) + modules.DirectorNotifications = dbcore.NewDirectorNotificationDB(modules.Pool) return modules } diff --git a/core/db/db_migration/tables.go b/core/db/db_migration/tables.go index 5b0438f..d2d3534 100644 --- a/core/db/db_migration/tables.go +++ b/core/db/db_migration/tables.go @@ -40,6 +40,7 @@ func (m *MigrationFunctions) migrateTables() error { tablesmigration.AdminsTableMigrate, tablesmigration.NotificationsTableMigrate, + tablesmigration.DirectorNotificationSubscriptionsTableMigrate, } for _, migrate := range migrations { diff --git a/core/db/db_migration/tables/directors_category_subscription.go b/core/db/db_migration/tables/directors_category_subscription.go new file mode 100644 index 0000000..ccae5a9 --- /dev/null +++ b/core/db/db_migration/tables/directors_category_subscription.go @@ -0,0 +1,33 @@ +package tablesmigration + +import ( + "gorm.io/gorm" + "time" +) + +func DirectorNotificationSubscriptionsTableMigrate(db *gorm.DB) error { + hasTable := db.Migrator().HasTable(&LocalDirectorNotificationSubscriptionProvider{}) + + if err := db.AutoMigrate(&LocalDirectorNotificationSubscriptionProvider{}); err != nil { + return err + } + + if !hasTable { + time.Sleep(5 * time.Second) + + db.Exec(`ALTER TABLE director_notification_subscriptions ADD CONSTRAINT fk_dns_director_id FOREIGN KEY (director_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE director_notification_subscriptions ADD CONSTRAINT fk_dns_category_id FOREIGN KEY (category_id) REFERENCES approval_topic_categories(id) ON DELETE CASCADE ON UPDATE CASCADE`) + db.Exec(`ALTER TABLE director_notification_subscriptions ADD CONSTRAINT uq_dns_director_category UNIQUE (director_id, category_id)`) + + execComments(db, ` + COMMENT ON TABLE "director_notification_subscriptions" IS 'Подписки директоров на уведомления по категориям тем согласования. Наличие строки = подписка включена, по умолчанию для всех категорий выключено'; + COMMENT ON COLUMN "director_notification_subscriptions".director_id IS 'Директор, оформивший подписку'; + COMMENT ON COLUMN "director_notification_subscriptions".category_id IS 'Категория тем, на которую подписан директор'; + `) + } + + db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_dns_director_id ON director_notification_subscriptions (director_id)`) + db.Exec(`CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_dns_category_id ON director_notification_subscriptions (category_id)`) + + return nil +} diff --git a/core/db/db_migration/tables/providers.go b/core/db/db_migration/tables/providers.go index 28e4243..ff7e314 100644 --- a/core/db/db_migration/tables/providers.go +++ b/core/db/db_migration/tables/providers.go @@ -26,7 +26,11 @@ type LocalSuggestionMessagesProvider typescore.SuggestionMessage type LocalApprovalTopicExecutorProvider typescore.ApprovalTopicExecutor type LocalNotificationProvider typescore.Notification type LocalNotificationRecipientProvider typescore.NotificationRecipient +type LocalDirectorNotificationSubscriptionProvider typescore.DirectorNotificationSubscription +func (LocalDirectorNotificationSubscriptionProvider) TableName() string { + return dbcoretablenames.TableNameDirectorNotificationSubscriptions.ToString() +} func (LocalUserProvider) TableName() string { return dbcoretablenames.TableNameUsers.ToString() } @@ -84,11 +88,9 @@ func (ApprovalAdditionalObserver) TableName() string { func (LocalApprovalTopicExecutorProvider) TableName() string { return dbcoretablenames.TableNameApprovalTopicExecutor.ToString() } - func (LocalNotificationProvider) TableName() string { return dbcoretablenames.TableNameNotifications.ToString() } - func (LocalNotificationRecipientProvider) TableName() string { return dbcoretablenames.TableNameNotificationsRecipients.ToString() } diff --git a/core/db/methods/director_notification.go b/core/db/methods/director_notification.go new file mode 100644 index 0000000..c1286ed --- /dev/null +++ b/core/db/methods/director_notification.go @@ -0,0 +1,126 @@ +package dbcore + +import ( + dbcoretablenames "bitrix_balancer_api/core/db/table_names" + "bitrix_balancer_api/core/typescore" + dbutils "bitrix_balancer_api/core/utilscore/db" + "context" + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5/pgxpool" +) + +type DirectorNotificationDB struct { + pool *pgxpool.Pool +} + +func NewDirectorNotificationDB(pool *pgxpool.Pool) *DirectorNotificationDB { + return &DirectorNotificationDB{pool: pool} +} + +type DirectorNotificationDBI interface { + GetSubscribedCategoryIDsDB(ctx context.Context, directorID uint64) ([]uint64, error) + ToggleSubscriptionDB(ctx context.Context, directorID, categoryID uint64) (enabled bool, err error) + GetDirectorsSubscribedToCategoryDB(ctx context.Context, categoryID uint64) ([]*typescore.User, error) +} + +// GetSubscribedCategoryIDsDB — список ID категорий, на которые подписан директор +func (d *DirectorNotificationDB) GetSubscribedCategoryIDsDB(ctx context.Context, directorID uint64) ([]uint64, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("category_id"). + From("director_notification_subscriptions"). + Where(squirrel.Eq{"director_id": directorID}). + ToSql() + if err != nil { + return nil, err + } + + rows, err := d.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var ids []uint64 + for rows.Next() { + var id uint64 + if err := rows.Scan(&id); err != nil { + continue + } + ids = append(ids, id) + } + return ids, nil +} + +// ToggleSubscriptionDB — переключает подписку директора на категорию. +// Если подписки не было — создаёт (enabled=true). Если была — удаляет (enabled=false). +func (d *DirectorNotificationDB) ToggleSubscriptionDB(ctx context.Context, directorID, categoryID uint64) (bool, error) { + checkSQL, checkArgs, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("id"). + From("director_notification_subscriptions"). + Where(squirrel.Eq{"director_id": directorID, "category_id": categoryID}). + ToSql() + if err != nil { + return false, err + } + + var existingID uint64 + err = d.pool.QueryRow(ctx, checkSQL, checkArgs...).Scan(&existingID) + + if err == nil { + // Подписка есть — удаляем (выключаем) + delSQL, delArgs, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Delete("director_notification_subscriptions"). + Where(squirrel.Eq{"id": existingID}). + ToSql() + if err != nil { + return false, err + } + _, err = d.pool.Exec(ctx, delSQL, delArgs...) + return false, err + } + + // Подписки нет — создаём (включаем) + insSQL, insArgs, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Insert("director_notification_subscriptions"). + Columns("director_id", "category_id"). + Values(directorID, categoryID). + ToSql() + if err != nil { + return false, err + } + _, err = d.pool.Exec(ctx, insSQL, insArgs...) + return true, err +} + +// GetDirectorsSubscribedToCategoryDB — все директора, подписанные на указанную категорию +func (d *DirectorNotificationDB) GetDirectorsSubscribedToCategoryDB(ctx context.Context, categoryID uint64) ([]*typescore.User, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT u.*"). + From(dbcoretablenames.TableNameUsers.ToString() + " u"). + Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id"). + Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id"). + Join("director_notification_subscriptions dns ON dns.director_id = u.id"). + Where(squirrel.Eq{"r.is_director": true}). + Where(squirrel.Eq{"u.is_blocked": false}). + Where(squirrel.Eq{"dns.category_id": categoryID}). + ToSql() + if err != nil { + return nil, err + } + + rows, err := d.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var users []*typescore.User + for rows.Next() { + user := &typescore.User{} + if err := dbutils.ScanRowsToStructRows(rows, user, nil); err != nil { + continue + } + users = append(users, user) + } + return users, nil +} diff --git a/core/db/table_names/table_names.go b/core/db/table_names/table_names.go index f7cf2f6..402e6dd 100644 --- a/core/db/table_names/table_names.go +++ b/core/db/table_names/table_names.go @@ -3,28 +3,29 @@ package dbcoretablenames type TableName string const ( - TableNameApprovals TableName = "approvals" - TableNameApprovalSteps TableName = "approval_steps" - TableNameApprovalTopics TableName = "approval_topics" - TableNameApprovalTopicCategories TableName = "approval_topic_categories" - TableNameDepartments TableName = "departments" - TableNamePermissions TableName = "permissions" - TableNameRoles TableName = "roles" - TableNameUsers TableName = "users" - TableNameUserHierarchy TableName = "user_hierarchy" - TableNameUserRoles TableName = "user_roles" - TableNameApprovalFiles TableName = "approval_files" - TableNameApprovalDelegations TableName = "approval_delegations" - TableNameApprovalAdditionalApprovers TableName = "approval_additional_approvers" - TableNameApprovalAdditionalObservers TableName = "approval_additional_observers" - TableNameApprovalTasks TableName = "approval_tasks" - TableNameApprovalComments TableName = "approval_comments" - TableNameSuggestions TableName = "suggestions" - TableNameSuggestionMessages TableName = "suggestion_messages" - TableNameApprovalTopicExecutor TableName = "approval_topic_executor" - TableNameAdmin TableName = "admin" - TableNameNotifications TableName = "notifications" - TableNameNotificationsRecipients TableName = "notification_recipients" + TableNameApprovals TableName = "approvals" + TableNameApprovalSteps TableName = "approval_steps" + TableNameApprovalTopics TableName = "approval_topics" + TableNameApprovalTopicCategories TableName = "approval_topic_categories" + TableNameDepartments TableName = "departments" + TableNamePermissions TableName = "permissions" + TableNameRoles TableName = "roles" + TableNameUsers TableName = "users" + TableNameUserHierarchy TableName = "user_hierarchy" + TableNameUserRoles TableName = "user_roles" + TableNameApprovalFiles TableName = "approval_files" + TableNameApprovalDelegations TableName = "approval_delegations" + TableNameApprovalAdditionalApprovers TableName = "approval_additional_approvers" + TableNameApprovalAdditionalObservers TableName = "approval_additional_observers" + TableNameApprovalTasks TableName = "approval_tasks" + TableNameApprovalComments TableName = "approval_comments" + TableNameSuggestions TableName = "suggestions" + TableNameSuggestionMessages TableName = "suggestion_messages" + TableNameApprovalTopicExecutor TableName = "approval_topic_executor" + TableNameAdmin TableName = "admin" + TableNameNotifications TableName = "notifications" + TableNameNotificationsRecipients TableName = "notification_recipients" + TableNameDirectorNotificationSubscriptions TableName = "director_notification_subscriptions" ) func (t TableName) ToString() string { diff --git a/core/typescore/director_notification.go b/core/typescore/director_notification.go new file mode 100644 index 0000000..b14a712 --- /dev/null +++ b/core/typescore/director_notification.go @@ -0,0 +1,10 @@ +package typescore + +import "time" + +type DirectorNotificationSubscription struct { + ID *uint64 `gorm:"column:id" json:"id" db:"id"` + DirectorID *uint64 `gorm:"column:director_id" json:"director_id" db:"director_id"` + CategoryID *uint64 `gorm:"column:category_id" json:"category_id" db:"category_id"` + CreatedAt *time.Time `gorm:"column:created_at" json:"created_at" db:"created_at"` +} diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go index 862c4eb..7b8c1e8 100644 --- a/service/telegram_service/common/update/callback.go +++ b/service/telegram_service/common/update/callback.go @@ -295,6 +295,14 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba case data == "deleg_page_noop": bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + // ── УВЕДОМЛЕНИЯ ДИРЕКТОРА ───────────────────────────────────── + case strings.HasPrefix(data, "dir_notif_toggle:"): + categoryID := parseID(data, "dir_notif_toggle:") + s.approvalHandler.HandleDirectorNotificationToggle(bot, cq, categoryID) + + case data == "dir_notif_done": + s.approvalHandler.HandleDirectorNotificationDone(bot, cq) + // ── ДОБАВЛЕНИЕ СОГЛАСУЮЩЕГО ─────────────────────────────────────────────────── case strings.HasPrefix(data, "add_appr_category_page:"): page := 0 diff --git a/service/telegram_service/common/update/update.go b/service/telegram_service/common/update/update.go index 0148d32..0abb484 100644 --- a/service/telegram_service/common/update/update.go +++ b/service/telegram_service/common/update/update.go @@ -68,6 +68,27 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag }) return + case "Директор": + s.withDepartmentCheck(bot, msg, func() { + ctx := context.Background() + user, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID) + if err != nil || user == nil || user.ID == nil { + return + } + isDirector, _ := s.ipc.Database.User.IsDirectorDB(ctx, *user.ID) + if !isDirector { + return + } + s.approvalHandler.HandleDirectorSubmenu(bot, msg.Chat.ID) + }) + return + + case "🔔 Настроить уведомления": + s.withDepartmentCheck(bot, msg, func() { + s.approvalHandler.HandleDirectorNotificationSettings(bot, msg.Chat.ID, msg.From.ID) + }) + return + case "👁 Наблюдатель": s.withDepartmentCheck(bot, msg, func() { ctx := context.Background() diff --git a/service/telegram_service/handlers/approval/director_notification_settings.go b/service/telegram_service/handlers/approval/director_notification_settings.go new file mode 100644 index 0000000..3b8060d --- /dev/null +++ b/service/telegram_service/handlers/approval/director_notification_settings.go @@ -0,0 +1,100 @@ +package approval + +import ( + "bitrix_balancer_api/core/typescore" + "bitrix_balancer_api/core/utilscore" + "bitrix_balancer_api/telegram_service/keyboard" + "context" + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +// HandleDirectorSubmenu — подменю директора +func (h *Handler) HandleDirectorSubmenu(bot *tgbotapi.BotAPI, chatID int64) { + msg := tgbotapi.NewMessage(chatID, "Директор\n\nВыберите действие:") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildDirectorSubmenu() + bot.Send(msg) //nolint:errcheck +} + +// HandleDirectorNotificationSettings — показывает мультиселект категорий уведомлений +func (h *Handler) HandleDirectorNotificationSettings(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) { + ctx := context.Background() + + director, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || director == nil || director.ID == nil { + sendText(bot, chatID, "⚠️ Пользователь не найден.") + return + } + + isDirector, err := h.ipc.Database.User.IsDirectorDB(ctx, *director.ID) + if err != nil || !isDirector { + sendText(bot, chatID, "⚠️ У вас нет прав директора.") + return + } + + categories, _, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopicCategory{IsActive: utilscore.PointerToBool(true)}, + }) + if err != nil { + logrus.Errorf("HandleDirectorNotificationSettings: GetApprovalTopicCategoriesListDB err=%v", err) + sendText(bot, chatID, "⚠️ Ошибка загрузки категорий.") + return + } + + subscribedIDs, err := h.ipc.Database.DirectorNotifications.GetSubscribedCategoryIDsDB(ctx, *director.ID) + if err != nil { + logrus.Errorf("HandleDirectorNotificationSettings: GetSubscribedCategoryIDsDB err=%v", err) + } + + msg := tgbotapi.NewMessage(chatID, "🔔 Уведомления по категориям\n\nВыберите категории, по которым хотите получать уведомления о финально согласованных заявках. По умолчанию все выключены.") + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildDirectorNotificationCategoriesMenu(categories, subscribedIDs) + bot.Send(msg) //nolint:errcheck +} + +// HandleDirectorNotificationToggle — обрабатывает нажатие на категорию (callback dir_notif_toggle:{categoryID}) +func (h *Handler) HandleDirectorNotificationToggle(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + telegramID := cq.From.ID + + director, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + if err != nil || director == nil || director.ID == nil { + bot.Request(tgbotapi.NewCallback(cq.ID, "Пользователь не найден")) //nolint:errcheck + return + } + + enabled, err := h.ipc.Database.DirectorNotifications.ToggleSubscriptionDB(ctx, *director.ID, categoryID) + if err != nil { + logrus.Errorf("HandleDirectorNotificationToggle: ToggleSubscriptionDB err=%v", err) + bot.Request(tgbotapi.NewCallback(cq.ID, "Ошибка сохранения")) //nolint:errcheck + return + } + + statusText := "выключены" + if enabled { + statusText = "включены" + } + bot.Request(tgbotapi.NewCallback(cq.ID, fmt.Sprintf("Уведомления %s", statusText))) //nolint:errcheck + + // Перерисовываем клавиатуру с актуальными галочками + categories, _, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTopicCategory{IsActive: utilscore.PointerToBool(true)}, + }) + if err != nil { + return + } + subscribedIDs, _ := h.ipc.Database.DirectorNotifications.GetSubscribedCategoryIDsDB(ctx, *director.ID) + + edit := tgbotapi.NewEditMessageReplyMarkup(chatID, cq.Message.MessageID, + keyboard.BuildDirectorNotificationCategoriesMenu(categories, subscribedIDs)) + bot.Request(edit) //nolint:errcheck +} + +// HandleDirectorNotificationDone — закрывает меню настройки уведомлений +func (h *Handler) HandleDirectorNotificationDone(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + bot.Request(tgbotapi.NewCallback(cq.ID, "Настройки сохранены")) //nolint:errcheck + bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck +} diff --git a/service/telegram_service/handlers/approval/handler_decision.go b/service/telegram_service/handlers/approval/handler_decision.go index a126014..3a013dc 100644 --- a/service/telegram_service/handlers/approval/handler_decision.go +++ b/service/telegram_service/handlers/approval/handler_decision.go @@ -268,8 +268,18 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co } } - directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx) - for _, director := range directors { + var subscribedDirectors []*typescore.User + if approval.TopicID != nil { + topicForCategory, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) + if err == nil && topicForCategory != nil && topicForCategory.CategoryID != nil { + subscribedDirectors, err = h.ipc.Database.DirectorNotifications.GetDirectorsSubscribedToCategoryDB(ctx, *topicForCategory.CategoryID) + if err != nil { + logrus.Warnf("processNextStepOrComplete: GetDirectorsSubscribedToCategoryDB err=%v", err) + } + } + } + + for _, director := range subscribedDirectors { if director.TelegramID != nil { notifier.NotifyDirector(bot, director, initiator, approval, collected) } diff --git a/service/telegram_service/keyboard/menu.go b/service/telegram_service/keyboard/menu.go index df8dffd..b0f4a28 100644 --- a/service/telegram_service/keyboard/menu.go +++ b/service/telegram_service/keyboard/menu.go @@ -30,6 +30,10 @@ func BuildMainMenu(roles UserRole) tgbotapi.ReplyKeyboardMarkup { kb.Row("👁 Наблюдатель") } + if roles.IsDirector { + kb.Row("Директор") + } + // Раздел: Исполнитель if roles.IsExecutor { kb.Row("Задачи к исполнению") @@ -69,3 +73,11 @@ func BuildObserverSubmenu() tgbotapi.ReplyKeyboardMarkup { Row("← Назад"). Build() } + +// BuildDirectorSubmenu — подменю для директора +func BuildDirectorSubmenu() tgbotapi.ReplyKeyboardMarkup { + return tgkit.NewReplyKeyboard(). + Row("🔔 Настроить уведомления"). + Row("← Назад"). + Build() +} diff --git a/service/telegram_service/keyboard/misc.go b/service/telegram_service/keyboard/misc.go index 8896419..e062edc 100644 --- a/service/telegram_service/keyboard/misc.go +++ b/service/telegram_service/keyboard/misc.go @@ -8,6 +8,32 @@ import ( tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) +// BuildDirectorNotificationCategoriesMenu — мультиселект категорий с галочками. +// subscribedIDs — те category_id, на которые директор уже подписан. +func BuildDirectorNotificationCategoriesMenu(categories []*typescore.ApprovalTopicCategory, subscribedIDs []uint64) tgbotapi.InlineKeyboardMarkup { + subscribed := make(map[uint64]bool, len(subscribedIDs)) + for _, id := range subscribedIDs { + subscribed[id] = true + } + + kb := tgkit.NewInlineKeyboard() + for _, c := range categories { + if c.ID == nil || c.Name == nil { + continue + } + label := *c.Name + if subscribed[*c.ID] { + label = "✅ " + label + } else { + label = "⬜ " + label + } + kb.Row(tgkit.Btn(label, fmt.Sprintf("dir_notif_toggle:%d", *c.ID))) + } + + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Готово", "dir_notif_done")) + return kb.Build() +} + func BuildApproverSelectionMenu(approvers []*typescore.User, page int) interface{} { const perPage = 8 total := len(approvers)