Update directors role. Added pagination of categories #60

Merged
romanskijdev merged 1 commits from fix-permissions into main 2026-07-12 20:46:33 +03:00
3 changed files with 84 additions and 31 deletions

View File

@ -297,8 +297,22 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
// ── УВЕДОМЛЕНИЯ ДИРЕКТОРА ─────────────────────────────────────
case strings.HasPrefix(data, "dir_notif_toggle:"):
categoryID := parseID(data, "dir_notif_toggle:")
s.approvalHandler.HandleDirectorNotificationToggle(bot, cq, categoryID)
parts := strings.Split(strings.TrimPrefix(data, "dir_notif_toggle:"), ":")
if len(parts) == 2 {
var categoryID uint64
var page int
fmt.Sscanf(parts[0], "%d", &categoryID)
fmt.Sscanf(parts[1], "%d", &page)
s.approvalHandler.HandleDirectorNotificationToggle(bot, cq, categoryID, page)
}
case strings.HasPrefix(data, "dir_notif_page:"):
page := 0
fmt.Sscanf(strings.TrimPrefix(data, "dir_notif_page:"), "%d", &page)
s.approvalHandler.HandleDirectorNotificationPage(bot, cq, page)
case data == "dir_notif_page_noop":
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
case data == "dir_notif_done":
s.approvalHandler.HandleDirectorNotificationDone(bot, cq)

View File

@ -2,24 +2,22 @@ package approval
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
"bitrix_balancer_api/telegram_service/keyboard"
"context"
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
"sort"
)
// HandleDirectorSubmenu — подменю директора
func (h *Handler) HandleDirectorSubmenu(bot *tgbotapi.BotAPI, chatID int64) {
msg := tgbotapi.NewMessage(chatID, "<b>Директор</b>\n\nВыберите действие:")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildDirectorSubmenu()
bot.Send(msg) //nolint:errcheck
// HandleDirectorNotificationSettings — показывает мультиселект категорий уведомлений (страница 0)
func (h *Handler) HandleDirectorNotificationSettings(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
h.showDirectorNotificationPage(bot, chatID, 0, telegramID, 0)
}
// HandleDirectorNotificationSettings — показывает мультиселект категорий уведомлений
func (h *Handler) HandleDirectorNotificationSettings(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
// showDirectorNotificationPage — общая логика показа/перерисовки страницы категорий.
// prevMessageID != 0 — редактируем существующее сообщение вместо отправки нового.
func (h *Handler) showDirectorNotificationPage(bot *tgbotapi.BotAPI, chatID int64, page int, telegramID int64, prevMessageID int) {
ctx := context.Background()
director, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
@ -34,28 +32,44 @@ func (h *Handler) HandleDirectorNotificationSettings(bot *tgbotapi.BotAPI, chatI
return
}
isActive := true
categories, _, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopicCategory{IsActive: utilscore.PointerToBool(true)},
Filtering: &typescore.ApprovalTopicCategory{IsActive: &isActive},
})
if err != nil {
logrus.Errorf("HandleDirectorNotificationSettings: GetApprovalTopicCategoriesListDB err=%v", err)
logrus.Errorf("showDirectorNotificationPage: GetApprovalTopicCategoryListDB err=%v", err)
sendText(bot, chatID, "⚠️ Ошибка загрузки категорий.")
return
}
sort.Slice(categories, func(i, j int) bool {
if categories[i].Name == nil || categories[j].Name == nil {
return false
}
return *categories[i].Name < *categories[j].Name
})
subscribedIDs, err := h.ipc.Database.DirectorNotifications.GetSubscribedCategoryIDsDB(ctx, *director.ID)
if err != nil {
logrus.Errorf("HandleDirectorNotificationSettings: GetSubscribedCategoryIDsDB err=%v", err)
logrus.Errorf("showDirectorNotificationPage: GetSubscribedCategoryIDsDB err=%v", err)
}
markup := keyboard.BuildDirectorNotificationCategoriesMenu(categories, subscribedIDs, page)
if prevMessageID != 0 {
edit := tgbotapi.NewEditMessageReplyMarkup(chatID, prevMessageID, markup)
bot.Request(edit) //nolint:errcheck
return
}
msg := tgbotapi.NewMessage(chatID, "🔔 <b>Уведомления по категориям</b>\n\nВыберите категории, по которым хотите получать уведомления о финально согласованных заявках. По умолчанию все выключены.")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildDirectorNotificationCategoriesMenu(categories, subscribedIDs)
msg.ReplyMarkup = markup
bot.Send(msg) //nolint:errcheck
}
// HandleDirectorNotificationToggle — обрабатывает нажатие на категорию (callback dir_notif_toggle:{categoryID})
func (h *Handler) HandleDirectorNotificationToggle(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64) {
// HandleDirectorNotificationToggle — обрабатывает нажатие на категорию (callback dir_notif_toggle:{categoryID}:{page})
func (h *Handler) HandleDirectorNotificationToggle(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, categoryID uint64, page int) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
telegramID := cq.From.ID
@ -79,18 +93,14 @@ func (h *Handler) HandleDirectorNotificationToggle(bot *tgbotapi.BotAPI, cq *tgb
}
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)
// Перерисовываем ту же страницу, где был клик
h.showDirectorNotificationPage(bot, chatID, page, telegramID, cq.Message.MessageID)
}
edit := tgbotapi.NewEditMessageReplyMarkup(chatID, cq.Message.MessageID,
keyboard.BuildDirectorNotificationCategoriesMenu(categories, subscribedIDs))
bot.Request(edit) //nolint:errcheck
// HandleDirectorNotificationPage — переключение страниц пагинации
func (h *Handler) HandleDirectorNotificationPage(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
h.showDirectorNotificationPage(bot, cq.Message.Chat.ID, page, cq.From.ID, cq.Message.MessageID)
}
// HandleDirectorNotificationDone — закрывает меню настройки уведомлений
@ -98,3 +108,11 @@ func (h *Handler) HandleDirectorNotificationDone(bot *tgbotapi.BotAPI, cq *tgbot
bot.Request(tgbotapi.NewCallback(cq.ID, "Настройки сохранены")) //nolint:errcheck
bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck
}
// HandleDirectorSubmenu — подменю директора
func (h *Handler) HandleDirectorSubmenu(bot *tgbotapi.BotAPI, chatID int64) {
msg := tgbotapi.NewMessage(chatID, "<b>Директор</b>\n\nВыберите действие:")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildDirectorSubmenu()
bot.Send(msg) //nolint:errcheck
}

View File

@ -10,14 +10,30 @@ import (
// BuildDirectorNotificationCategoriesMenu — мультиселект категорий с галочками.
// subscribedIDs — те category_id, на которые директор уже подписан.
func BuildDirectorNotificationCategoriesMenu(categories []*typescore.ApprovalTopicCategory, subscribedIDs []uint64) tgbotapi.InlineKeyboardMarkup {
func BuildDirectorNotificationCategoriesMenu(categories []*typescore.ApprovalTopicCategory, subscribedIDs []uint64, page int) tgbotapi.InlineKeyboardMarkup {
const perPage = 8
subscribed := make(map[uint64]bool, len(subscribedIDs))
for _, id := range subscribedIDs {
subscribed[id] = true
}
total := len(categories)
totalPages := (total + perPage - 1) / perPage
if page < 0 {
page = 0
}
if page >= totalPages && totalPages > 0 {
page = totalPages - 1
}
start := page * perPage
end := start + perPage
if end > total {
end = total
}
kb := tgkit.NewInlineKeyboard()
for _, c := range categories {
for _, c := range categories[start:end] {
if c.ID == nil || c.Name == nil {
continue
}
@ -27,7 +43,12 @@ func BuildDirectorNotificationCategoriesMenu(categories []*typescore.ApprovalTop
} else {
label = "⬜ " + label
}
kb.Row(tgkit.Btn(label, fmt.Sprintf("dir_notif_toggle:%d", *c.ID)))
// page передаём в callback, чтобы после тоггла вернуться на ту же страницу
kb.Row(tgkit.Btn(label, fmt.Sprintf("dir_notif_toggle:%d:%d", *c.ID, page)))
}
if totalPages > 1 {
kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "dir_notif_page", "dir_notif_page_noop"))
}
kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Готово", "dir_notif_done"))