diff --git a/core/lib/external/tgkit/keyboard.go b/core/lib/external/tgkit/keyboard.go
index 84d0503..38327f4 100644
--- a/core/lib/external/tgkit/keyboard.go
+++ b/core/lib/external/tgkit/keyboard.go
@@ -11,7 +11,7 @@ import (
// InlineKeyboard — построитель inline-клавиатуры
type InlineKeyboard struct {
- rows [][]tgbotapi.InlineKeyboardButton
+ Rows [][]tgbotapi.InlineKeyboardButton
}
// NewInlineKeyboard создаёт пустой построитель
@@ -23,15 +23,15 @@ func NewInlineKeyboard() *InlineKeyboard {
func (kb *InlineKeyboard) Row(buttons ...InlineButton) *InlineKeyboard {
var row []tgbotapi.InlineKeyboardButton
for _, btn := range buttons {
- row = append(row, btn.build())
+ row = append(row, btn.Build())
}
- kb.rows = append(kb.rows, row)
+ kb.Rows = append(kb.Rows, row)
return kb
}
// Build возвращает готовую клавиатуру
func (kb *InlineKeyboard) Build() tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(kb.rows...)
+ return tgbotapi.NewInlineKeyboardMarkup(kb.Rows...)
}
// InlineButton — кнопка inline-клавиатуры
@@ -63,7 +63,7 @@ func (b InlineButton) WithStyle(style ButtonStyle) InlineButton {
return b
}
-func (b InlineButton) build() tgbotapi.InlineKeyboardButton {
+func (b InlineButton) Build() tgbotapi.InlineKeyboardButton {
text := string(b.style) + b.label
if b.url != "" {
return tgbotapi.NewInlineKeyboardButtonURL(text, b.url)
@@ -148,7 +148,7 @@ func PaginationRow(page, totalPages int, prevCallback, nextCallback, noopCallbac
var row []tgbotapi.InlineKeyboardButton
if page > 0 {
- row = append(row, Btn("←", prevCallback).build())
+ row = append(row, Btn("←", prevCallback).Build())
}
row = append(row, tgbotapi.NewInlineKeyboardButtonData(
@@ -156,7 +156,7 @@ func PaginationRow(page, totalPages int, prevCallback, nextCallback, noopCallbac
))
if page < totalPages-1 {
- row = append(row, Btn("→", nextCallback).build())
+ row = append(row, Btn("→", nextCallback).Build())
}
return row
diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go
index 025a9a8..2579004 100644
--- a/service/telegram_service/common/update/callback.go
+++ b/service/telegram_service/common/update/callback.go
@@ -306,6 +306,19 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
categoryID := parseID(data, "add_appr_category:")
s.approvalHandler.HandleAddApproverCategoryCallback(bot, cq, categoryID)
+ case strings.HasPrefix(data, "add_appr_to_approval:"):
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ approvalIDStr := strings.TrimPrefix(data, "add_appr_to_approval:")
+ approvalID, err := strconv.ParseUint(approvalIDStr, 10, 64)
+ if err != nil {
+ logrus.Errorf("handleCallback: invalid approvalID=%s err=%v", approvalIDStr, err)
+ return
+ }
+
+ s.approvalHandler.HandleAddApproverFromApproval(bot, cq.Message.Chat.ID, cq.From.ID, approvalID)
+ return
+
case strings.HasPrefix(data, "add_appr_approval_page:"):
parts := strings.Split(strings.TrimPrefix(data, "add_appr_approval_page:"), ":")
if len(parts) == 2 {
@@ -442,7 +455,9 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
})
default:
- logrus.Warnf("handleCallback: unknown callback: %s", data)
+ logrus.Warnf("handleCallback: unknown callback: %s (from user=%d, chat=%d, msgID=%d)",
+ data, cq.From.ID, cq.Message.Chat.ID, cq.Message.MessageID)
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
}
}
diff --git a/service/telegram_service/common/update/update.go b/service/telegram_service/common/update/update.go
index 4fc995c..73c32be 100644
--- a/service/telegram_service/common/update/update.go
+++ b/service/telegram_service/common/update/update.go
@@ -1,9 +1,11 @@
package tgupdatehandler
import (
+ "bitrix_balancer_api/telegram_service/keyboard"
"context"
"fmt"
"strings"
+ "time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
@@ -50,20 +52,13 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag
// ═══════════════════════════════════════════════════════════
// ГЛАВНОЕ МЕНЮ
// ═══════════════════════════════════════════════════════════
- case "Согласование":
+ case "👤 Инициатор":
s.withDepartmentCheck(bot, msg, func() {
- // Открываем подменю согласований
- s.approvalHandler.HandleApprovalsSubmenu(bot, msg.Chat.ID, msg.From.ID)
+ s.approvalHandler.HandleInitiatorSubmenu(bot, msg.Chat.ID)
})
return
- case "Мои заявки":
- s.withDepartmentCheck(bot, msg, func() {
- s.approvalHandler.HandleMyApprovals(bot, msg.Chat.ID, msg.From.ID)
- })
- return
-
- case "Согласовать":
+ case "✅ Согласующий":
s.withDepartmentCheck(bot, msg, func() {
ctx := context.Background()
user, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID)
@@ -71,106 +66,137 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag
return
}
isApprover, _ := s.ipc.Database.User.IsApproverDB(ctx, *user.ID)
- if !isApprover {
- return // молчим — кнопки нет в его клавиатуре
+ isDirector, _ := s.ipc.Database.User.IsDirectorDB(ctx, *user.ID)
+ if !isApprover && !isDirector {
+ return
}
+ s.approvalHandler.HandleApproverSubmenu(bot, msg.Chat.ID)
+ })
+ 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
+ }
+ isObserver, _ := s.ipc.Database.User.IsObserverDB(ctx, *user.ID)
+ if !isObserver {
+ return
+ }
+ s.approvalHandler.HandleObserverSubmenu(bot, msg.Chat.ID)
+ })
+ return
+
+ // ═══════════════════════════════════════════════════════════
+ // ПОДМЕНЮ ИНИЦИАТОРА
+ // ═══════════════════════════════════════════════════════════
+ case "➕ Создать согласование":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.approvalHandler.HandleMenu(bot, msg.Chat.ID, msg.From.ID) // показ тем
+ })
+ return
+
+ case "Ранее созданные согласования":
+ s.withDepartmentCheck(bot, msg, func() {
+ // Сохраняем контекст: фильтр для инициатора (без "Добавить согласующего")
+ ctx := context.Background()
+ filterKey := fmt.Sprintf("filter_context:%d", msg.From.ID)
+ s.ipc.RedisClient.Set(ctx, filterKey, "initiator", 5*time.Minute) //nolint:errcheck
+ // Показываем подменю фильтров
+ menuMsg := tgbotapi.NewMessage(msg.Chat.ID, "🔍 Выберите статус заявок:")
+ menuMsg.ReplyMarkup = keyboard.BuildFilterSubmenu(false) // withoutAddApprover
+ bot.Send(menuMsg) //nolint:errcheck
+ })
+ return
+
+ // ═══════════════════════════════════════════════════════════
+ // ПОДМЕНЮ СОГЛАСУЮЩЕГО
+ // ═══════════════════════════════════════════════════════════
+ case "Принять согласование в работу":
+ s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleIncomingApprovals(bot, msg.Chat.ID, msg.From.ID)
})
return
- case "Отложенные":
+ case "Отложенные согласования":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandlePendingCommentsList(bot, msg.Chat.ID, msg.From.ID)
})
return
- case "❓ Как создать согласование":
+ case "Список согласований":
s.withDepartmentCheck(bot, msg, func() {
- s.faqHandler.Handle(bot, msg)
+ // Сохраняем контекст: фильтр для согласующего (с "Добавить согласующего")
+ ctx := context.Background()
+ filterKey := fmt.Sprintf("filter_context:%d", msg.From.ID)
+ s.ipc.RedisClient.Set(ctx, filterKey, "approver", 5*time.Minute) //nolint:errcheck
+ // Показываем подменю фильтров
+ menuMsg := tgbotapi.NewMessage(msg.Chat.ID, "🔍 Выберите статус заявок:")
+ menuMsg.ReplyMarkup = keyboard.BuildFilterSubmenu(true) // withAddApprover
+ bot.Send(menuMsg) //nolint:errcheck
})
return
- // ═══════════════════════════════════════════════════════════
- // ПОДМЕНЮ "СОГЛАСОВАНИЯ"
- // ═══════════════════════════════════════════════════════════
- case "Согласования":
- s.withDepartmentCheck(bot, msg, func() {
- s.approvalHandler.HandleApprovalsListSubmenu(bot, msg.Chat.ID, msg.From.ID)
- })
- return
-
- case "Создать согласование":
- s.withDepartmentCheck(bot, msg, func() {
- // Это старый функционал "Согласования" - показываем темы
- s.approvalHandler.HandleMenu(bot, msg.Chat.ID, msg.From.ID)
- })
- return
-
- case "Сформировать отчёт":
+ case "📊 Сформировать отчёт":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleReportMenu(bot, msg.Chat.ID, msg.From.ID)
})
return
- case "Делегирование прав":
+ case "Делегировать права":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleDelegationMainMenu(bot, msg.Chat.ID, msg.From.ID)
})
return
- case "Наблюдаемые":
+ // ═══════════════════════════════════════════════════════════
+ // ПОДМЕНЮ НАБЛЮДАТЕЛЯ
+ // ═══════════════════════════════════════════════════════════
+ case "Наблюдать за согласованием":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleObservedApprovals(bot, msg.Chat.ID, msg.From.ID)
})
return
- case "Добавить согласующего":
- s.withDepartmentCheck(bot, msg, func() {
- s.approvalHandler.HandleAddApproverMainMenu(bot, msg.Chat.ID, msg.From.ID)
- })
- return
-
- case "Мои задачи":
+ // ═══════════════════════════════════════════════════════════
+ // ПОДМЕНЮ ИСПОЛНИТЕЛЯ
+ // ═══════════════════════════════════════════════════════════
+ case "Задачи к исполнению":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleMyTasks(bot, msg.Chat.ID, msg.From.ID)
})
return
- // ═══════════════════════════════════════════════════════════
- // ПОДМЕНЮ "СПИСОК СОГЛАСОВАНИЙ"
- // ═══════════════════════════════════════════════════════════
- case "Все":
+ // ═══════════════════════════════════════════════════════════
+ // ФИЛЬТРЫ (универсальная обработка с контекстом)
+ // ═══════════════════════════════════════════════════════════
+ case "Все", "Согласованные", "Не согласованные", "Ожидают согласования":
+ statusMap := map[string]string{
+ "Все": "all", "Согласованные": "approved",
+ "Не согласованные": "rejected", "Ожидают согласования": "pending",
+ }
+ s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, statusMap[msg.Text])
+
+ // ═══════════════════════════════════════════════════════════
+ // ОБЩИЕ КНОПКИ (всегда доступны)
+ // ═══════════════════════════════════════════════════════════
+ case "❓ Как создать согласование?":
s.withDepartmentCheck(bot, msg, func() {
- s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, "all")
+ s.faqHandler.Handle(bot, msg)
})
return
- case "Принятые":
- s.withDepartmentCheck(bot, msg, func() {
- s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, "approved")
- })
- return
-
- case "Отклонённые":
- s.withDepartmentCheck(bot, msg, func() {
- s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, "rejected")
- })
- return
-
- case "На согласовании":
- s.withDepartmentCheck(bot, msg, func() {
- s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, "pending")
- })
- return
-
- case "Предложения и пожелания":
+ case "💬 Предложения и пожелания":
s.withDepartmentCheck(bot, msg, func() {
s.suggestionHandler.HandleCreateSuggestion(bot, msg.Chat.ID, msg.From.ID)
})
return
- // ═══════════════════════════════════════════════════════════
- // НАВИГАЦИЯ "НАЗАД"
- // ═══════════════════════════════════════════════════════════
+
+ // ═══════════════════════════════════════════════════════════
+ // НАВИГАЦИЯ "НАЗАД"
+ // ═══════════════════════════════════════════════════════════
case "← Назад":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleBackNavigation(bot, msg.Chat.ID, msg.From.ID)
diff --git a/service/telegram_service/handlers/approval/handle_files.go b/service/telegram_service/handlers/approval/handle_files.go
index d6bfdab..6a7622f 100644
--- a/service/telegram_service/handlers/approval/handle_files.go
+++ b/service/telegram_service/handlers/approval/handle_files.go
@@ -108,8 +108,6 @@ func (h *Handler) HandleFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) b
case msg.Photo != nil && len(msg.Photo) > 0:
best := msg.Photo[len(msg.Photo)-1]
fileID = best.FileID
- // Используем timestamp вместо счётчика
- fileName = fmt.Sprintf("photo_%s.jpg", time.Now().Format("20060102_150405"))
case msg.Document != nil:
fileID = msg.Document.FileID
diff --git a/service/telegram_service/handlers/approval/handler.go b/service/telegram_service/handlers/approval/handler.go
index c6e8863..2ae3ba7 100644
--- a/service/telegram_service/handlers/approval/handler.go
+++ b/service/telegram_service/handlers/approval/handler.go
@@ -32,6 +32,29 @@ func (h *Handler) HandleMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int6
h.HandleMenuPage(bot, chatID, telegramID, 0, 0)
}
+func (h *Handler) HandleInitiatorSubmenu(bot *tgbotapi.BotAPI, chatID int64) {
+ msg := tgbotapi.NewMessage(chatID, "👤 Инициатор\n\nВыберите действие:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildInitiatorSubmenu()
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleApproverSubmenu — подменю для согласующего
+func (h *Handler) HandleApproverSubmenu(bot *tgbotapi.BotAPI, chatID int64) {
+ msg := tgbotapi.NewMessage(chatID, "✅ Согласующий\n\nВыберите действие:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildApproverSubmenu()
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleObserverSubmenu — подменю для наблюдателя
+func (h *Handler) HandleObserverSubmenu(bot *tgbotapi.BotAPI, chatID int64) {
+ msg := tgbotapi.NewMessage(chatID, "✅ Наблюдатель\n\nВыберите действие:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildObserverSubmenu()
+ bot.Send(msg) //nolint:errcheck
+}
+
// HandleMenuPage — показывает меню на нужной странице.
// prevMessageID != 0 — удаляем старое сообщение с пагинацией.
func (h *Handler) HandleMenuPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) {
diff --git a/service/telegram_service/handlers/approval/handler_add_approver.go b/service/telegram_service/handlers/approval/handler_add_approver.go
index fda94c0..c3dba91 100644
--- a/service/telegram_service/handlers/approval/handler_add_approver.go
+++ b/service/telegram_service/handlers/approval/handler_add_approver.go
@@ -12,6 +12,83 @@ import (
"github.com/sirupsen/logrus"
)
+// HandleAddApproverFromApproval — добавление согласующего к конкретной заявке (прямой вход)
+func (h *Handler) HandleAddApproverFromApproval(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, approvalID uint64) {
+ ctx := context.Background()
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ sendText(bot, chatID, "⚠️ Пользователь не найден.")
+ return
+ }
+ isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID)
+ isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID)
+ if !isApprover && !isDirector {
+ sendText(bot, chatID, "У вас нет прав для добавления согласующих.")
+ return
+ }
+
+ approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
+ if err != nil || approval == nil {
+ sendText(bot, chatID, "⚠️ Заявка не найдена.")
+ return
+ }
+
+ users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.User{IsBlocked: utilscore.PointerToBool(false)},
+ })
+ if err != nil {
+ logrus.Errorf("HandleAddApproverFromApproval: GetUsersListDB err=%v", err)
+ sendText(bot, chatID, "Ошибка при получении списка пользователей.")
+ return
+ }
+
+ // Исключаем текущего и уже добавленных
+ alreadyAdded, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID},
+ })
+ addedIDs := make(map[uint64]bool)
+ for _, aa := range alreadyAdded {
+ if aa.ApproverID != nil {
+ addedIDs[*aa.ApproverID] = true
+ }
+ }
+
+ var availableUsers []*typescore.User
+ for _, u := range users {
+ if u.ID != nil && *u.ID != *user.ID && !addedIDs[*u.ID] && u.TelegramID != nil {
+ availableUsers = append(availableUsers, u)
+ }
+ }
+
+ if len(availableUsers) == 0 {
+ sendText(bot, chatID, "Нет доступных пользователей для добавления.")
+ return
+ }
+
+ h.States.SetAddApprover(ctx, telegramID, &state.AddApproverFlowState{
+ ApprovalID: approvalID,
+ CategoryID: 0, // не нужно, т.к. заявка уже известна
+ Stage: "select_user",
+ }) //nolint:errcheck
+
+ topicName := "—"
+ if approval.TopicID != nil {
+ topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
+ if topic != nil && topic.Name != nil {
+ topicName = *topic.Name
+ }
+ }
+
+ msg := tgbotapi.NewMessage(chatID, fmt.Sprintf(
+ "➕ Добавить согласующего к заявке #%d\n\n📋 Тема: %s\n\n👇 Выберите пользователя:",
+ approvalID, topicName,
+ ))
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildAddApproverUserMenu(availableUsers, approvalID, 0, 0) // page=0, categoryID=0
+ bot.Send(msg) //nolint:errcheck
+}
+
func (h *Handler) HandleAddApproverMainMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
ctx := context.Background()
diff --git a/service/telegram_service/handlers/approval/handler_comment.go b/service/telegram_service/handlers/approval/handler_comment.go
index 763c41f..057f603 100644
--- a/service/telegram_service/handlers/approval/handler_comment.go
+++ b/service/telegram_service/handlers/approval/handler_comment.go
@@ -140,6 +140,10 @@ func (h *Handler) canUserCommentApproval(ctx context.Context, userID uint64, app
return false, fmt.Errorf("approval or approval ID is nil")
}
+ if approval.InitiatorID != nil && *approval.InitiatorID == userID {
+ return true, nil
+ }
+
// Проверяем, является ли пользователь текущим согласующим
activeStep, err := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, *approval.ID)
if err == nil && activeStep != nil && activeStep.ApproverID != nil && *activeStep.ApproverID == userID {
@@ -189,7 +193,8 @@ func (h *Handler) canUserCommentApproval(ctx context.Context, userID uint64, app
}
}
- return false, nil
+ isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, userID)
+ return isDirector, nil
}
func (h *Handler) notifyInitiatorAboutComment(
diff --git a/service/telegram_service/handlers/approval/handler_observer.go b/service/telegram_service/handlers/approval/handler_observer.go
index ea440bf..f420e8a 100644
--- a/service/telegram_service/handlers/approval/handler_observer.go
+++ b/service/telegram_service/handlers/approval/handler_observer.go
@@ -241,7 +241,7 @@ func (h *Handler) sendObserverTopicApprovals(bot *tgbotapi.BotAPI, ctx context.C
if len(pending) == 0 {
msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("👁 %s\n\nНет заявок, ожидающих согласования.", topicName))
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildObserverApprovalList(nil, nil, nil, topicCode)
+ msg.ReplyMarkup = keyboard.BuildObserverApprovalList(nil, nil, nil)
bot.Send(msg) //nolint:errcheck
return
}
@@ -266,7 +266,7 @@ func (h *Handler) sendObserverTopicApprovals(bot *tgbotapi.BotAPI, ctx context.C
"👁 %s\n\nОжидают согласования: %d", topicName, len(pending),
))
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildObserverApprovalList(pending, initiators, departments, topicCode)
+ msg.ReplyMarkup = keyboard.BuildObserverApprovalList(pending, initiators, departments)
bot.Send(msg) //nolint:errcheck
}
diff --git a/service/telegram_service/handlers/approval/handler_pending_comments.go b/service/telegram_service/handlers/approval/handler_pending_comments.go
index 3183ce1..fc626ee 100644
--- a/service/telegram_service/handlers/approval/handler_pending_comments.go
+++ b/service/telegram_service/handlers/approval/handler_pending_comments.go
@@ -181,7 +181,7 @@ func (h *Handler) HandlePendingDeferCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.
items, _ := h.States.GetPendingComments(ctx, telegramID)
reply := tgbotapi.NewMessage(chatID, fmt.Sprintf(
"⏳ Заявка #%d отложена. В очереди: %d.\n\n"+
- "Обработайте их через кнопку 📝 Ожидают комментария.",
+ "Обработайте их через кнопку Отложенные.",
approvalID, len(items),
))
reply.ParseMode = "HTML"
diff --git a/service/telegram_service/handlers/approval/list.go b/service/telegram_service/handlers/approval/list.go
index 5abc0f3..f365a57 100644
--- a/service/telegram_service/handlers/approval/list.go
+++ b/service/telegram_service/handlers/approval/list.go
@@ -35,7 +35,7 @@ func (h *Handler) HandleMyApprovals(bot *tgbotapi.BotAPI, chatID int64, telegram
sendText(bot, chatID, fmt.Sprintf("📂 Ваши активные заявки (%d):", len(approvals)))
for _, a := range approvals {
- h.sendApprovalCard(bot, chatID, a, false)
+ h.sendApprovalCard(bot, chatID, a, false, false)
}
}
@@ -95,7 +95,7 @@ func (h *Handler) HandleIncomingApprovals(bot *tgbotapi.BotAPI, chatID int64, te
ApprovalID: step.ApprovalID,
},
})
- h.sendApprovalCard(bot, chatID, approval, true, addedApprovers)
+ h.sendApprovalCard(bot, chatID, approval, true, true, addedApprovers)
}
// Отправляем дополнительные согласования
@@ -113,7 +113,7 @@ func (h *Handler) HandleIncomingApprovals(bot *tgbotapi.BotAPI, chatID int64, te
// sendApprovalCard отправляет карточку одной заявки.
// withDecision=true — добавляет кнопки Да/Нет для согласующего.
-func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval, withButtons bool, addedApprovers ...[]*typescore.ApprovalAdditionalApprover) {
+func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval, withButtons, showAddApprover bool, addedApprovers ...[]*typescore.ApprovalAdditionalApprover) {
ctx := context.Background()
if approval.ID == nil {
@@ -181,9 +181,22 @@ func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval
msg.ParseMode = "HTML"
if withButtons && approval.Status != nil && *approval.Status == "pending" {
- msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID)
+ markup := keyboard.BuildApproverDecision(*approval.ID)
+
+ //if showAddApprover {
+ // addBtn := tgbotapi.NewInlineKeyboardButtonData(
+ // "➕ Добавить согласующего",
+ // fmt.Sprintf("appr:add_approver:%d", *approval.ID),
+ // )
+ // markup.InlineKeyboard = append(markup.InlineKeyboard, []tgbotapi.InlineKeyboardButton{addBtn})
+ //}
+
+ msg.ReplyMarkup = markup
+
} else if approval.Status != nil && (*approval.Status == "pending" || *approval.Status == "approved") {
- msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID)
+ markup := keyboard.BuildInitiatorCard(*approval.ID)
+
+ msg.ReplyMarkup = markup
}
bot.Send(msg) //nolint:errcheck
diff --git a/service/telegram_service/handlers/approval/navigation.go b/service/telegram_service/handlers/approval/navigation.go
index 7c76950..19d25be 100644
--- a/service/telegram_service/handlers/approval/navigation.go
+++ b/service/telegram_service/handlers/approval/navigation.go
@@ -93,7 +93,7 @@ func (h *Handler) HandleMyApprovalsByStatus(bot *tgbotapi.BotAPI, chatID int64,
sendText(bot, chatID, fmt.Sprintf("📂 %s (%d):", statusText, len(approvals)))
for _, a := range approvals {
- h.sendApprovalCard(bot, chatID, a, false)
+ h.sendApprovalCard(bot, chatID, a, false, false)
}
}
@@ -143,31 +143,24 @@ func (h *Handler) sendMainMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID in
ctx := context.Background()
user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+
isExecutor := false
if user != nil && user.ID != nil {
isExecutor, _ = h.ipc.Database.User.IsExecutorDB(ctx, *user.ID)
}
- var replyMarkup tgbotapi.ReplyKeyboardMarkup
-
- if isApprover && isObserver && isExecutor {
- replyMarkup = keyboard.ApproverObserverExecutorMenuKeyboard()
- } else if isApprover && isExecutor {
- replyMarkup = keyboard.ApproverExecutorMenuKeyboard()
- } else if isObserver && isExecutor {
- replyMarkup = keyboard.ObserverExecutorMenuKeyboard()
- } else if isApprover && isObserver {
- replyMarkup = keyboard.ApproverObserverMenuKeyboard()
- } else if isApprover {
- replyMarkup = keyboard.ApproverMenuKeyboard()
- } else if isObserver {
- replyMarkup = keyboard.ObserverMenuKeyboard()
- } else if isExecutor {
- replyMarkup = keyboard.ExecutorMenuKeyboard()
- } else {
- replyMarkup = keyboard.MainMenuKeyboard()
+ isDirector := false
+ if user != nil && user.ID != nil {
+ isDirector, _ = h.ipc.Database.User.IsDirectorDB(ctx, *user.ID)
}
+ replyMarkup := keyboard.BuildMainMenu(keyboard.UserRole{
+ IsApprover: isApprover,
+ IsObserver: isObserver,
+ IsExecutor: isExecutor,
+ IsDirector: isDirector,
+ })
+
msg := tgbotapi.NewMessage(chatID, "🏠 Главное меню")
msg.ParseMode = "HTML"
msg.ReplyMarkup = replyMarkup
diff --git a/service/telegram_service/handlers/approval/registry.go b/service/telegram_service/handlers/approval/registry.go
index 270bed9..4c554ac 100644
--- a/service/telegram_service/handlers/approval/registry.go
+++ b/service/telegram_service/handlers/approval/registry.go
@@ -2,6 +2,7 @@ package approval
import (
"bitrix_balancer_api/telegram_service/approvalflow"
+ "bitrix_balancer_api/telegram_service/handlers/approval/topics/absence"
clientchanges "bitrix_balancer_api/telegram_service/handlers/approval/topics/client_changes"
"bitrix_balancer_api/telegram_service/handlers/approval/topics/free"
goodsorder "bitrix_balancer_api/telegram_service/handlers/approval/topics/goods_order"
@@ -11,10 +12,7 @@ import (
"bitrix_balancer_api/telegram_service/handlers/approval/topics/receipts"
"bitrix_balancer_api/telegram_service/handlers/approval/topics/returns"
shipmentssoh "bitrix_balancer_api/telegram_service/handlers/approval/topics/shipments_soh"
- sickleave "bitrix_balancer_api/telegram_service/handlers/approval/topics/sick_leave"
- timeoff "bitrix_balancer_api/telegram_service/handlers/approval/topics/time_off"
transactionpassport "bitrix_balancer_api/telegram_service/handlers/approval/topics/transaction_passport"
- "bitrix_balancer_api/telegram_service/handlers/approval/topics/vacation"
"fmt"
)
@@ -30,12 +28,7 @@ func NewRegistry() *Registry {
}
func (r *Registry) registerAll() {
- // Структурированные темы (уже реализованные)
- r.register(timeoff.NewTimeOffTopic())
- r.register(vacation.NewVacationTopic())
- r.register(sickleave.NewSickLeaveTopic())
-
- // Новые темы с подтемами
+ r.register(absence.NewAbsenceTopic())
r.register(nonbudgetexpenses.NewNonBudgetExpensesTopic())
r.register(nonbudgetexpensespetline.NewNonBudgetExpensesPetLineTopic())
r.register(returns.NewReturnsTopic())
diff --git a/service/telegram_service/handlers/approval/selection_first_approver.go b/service/telegram_service/handlers/approval/selection_first_approver.go
index cd46b1e..3d81420 100644
--- a/service/telegram_service/handlers/approval/selection_first_approver.go
+++ b/service/telegram_service/handlers/approval/selection_first_approver.go
@@ -48,7 +48,7 @@ func (h *Handler) showFirstApproverSelection(
roleLabel,
))
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildFirstApproverSelectionMenu(users, roleLabel, 0)
+ msg.ReplyMarkup = keyboard.BuildFirstApproverSelectionMenu(users, 0)
bot.Send(msg) //nolint:errcheck
}
@@ -128,11 +128,6 @@ func (h *Handler) HandleFirstApproverPageCallback(bot *tgbotapi.BotAPI, cq *tgbo
}
roleCode := *approvalTopic.FirstApproverRoleCode
- role := h.getRoleLabelByCode(ctx, roleCode)
- roleLabel := roleCode
- if role != nil && role.Name != nil {
- roleLabel = *role.Name
- }
users, err := h.ipc.Database.User.GetUsersByRoleCodeDB(ctx, roleCode)
if err != nil {
return
@@ -141,7 +136,7 @@ func (h *Handler) HandleFirstApproverPageCallback(bot *tgbotapi.BotAPI, cq *tgbo
editMsg := tgbotapi.NewEditMessageReplyMarkup(
chatID,
cq.Message.MessageID,
- keyboard.BuildFirstApproverSelectionMenu(users, roleLabel, page),
+ keyboard.BuildFirstApproverSelectionMenu(users, page),
)
bot.Request(editMsg) //nolint:errcheck
}
diff --git a/service/telegram_service/handlers/approval/topics/absence/topic.go b/service/telegram_service/handlers/approval/topics/absence/topic.go
new file mode 100644
index 0000000..2699ba2
--- /dev/null
+++ b/service/telegram_service/handlers/approval/topics/absence/topic.go
@@ -0,0 +1,93 @@
+// telegram_service/handlers/approval/topics/absence/topic.go - НОВЫЙ ФАЙЛ
+
+package absence
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ sickleave "bitrix_balancer_api/telegram_service/handlers/approval/topics/sick_leave"
+ timeoff "bitrix_balancer_api/telegram_service/handlers/approval/topics/time_off"
+ "bitrix_balancer_api/telegram_service/handlers/approval/topics/vacation"
+ "fmt"
+)
+
+// AbsenceTopic — объединяет отгул, отпуск и больничный в одну кнопку
+type AbsenceTopic struct {
+ timeoff *timeoff.TimeOffTopic
+ vacation *vacation.VacationTopic
+ sickleave *sickleave.SickLeaveTopic
+}
+
+func NewAbsenceTopic() *AbsenceTopic {
+ return &AbsenceTopic{
+ timeoff: timeoff.NewTimeOffTopic(),
+ vacation: vacation.NewVacationTopic(),
+ sickleave: sickleave.NewSickLeaveTopic(),
+ }
+}
+
+func (a *AbsenceTopic) Code() string { return "absence" }
+func (a *AbsenceTopic) Name() string {
+ return "Согласование отпусков/отгулов"
+}
+
+func (a *AbsenceTopic) BuildTree() *approvalflow.FlowNode {
+ return &approvalflow.FlowNode{
+ Key: "absence",
+ Label: "Согласование отпусков/отгулов",
+ Children: []*approvalflow.FlowNode{
+ {
+ Key: "absence_timeoff",
+ Label: "Отгул",
+ DataKey: "absence_type",
+ DataValue: "timeoff",
+ Children: a.timeoff.BuildTree().Children,
+ },
+ {
+ Key: "absence_vacation",
+ Label: "Отпуск",
+ DataKey: "absence_type",
+ DataValue: "vacation",
+ Children: a.vacation.BuildTree().Children,
+ },
+ {
+ Key: "absence_sickleave",
+ Label: "Больничный",
+ DataKey: "absence_type",
+ DataValue: "sickleave",
+ Children: a.sickleave.BuildTree().Children,
+ },
+ },
+ }
+}
+
+func (a *AbsenceTopic) TopicCodeFromCollected(collected map[string]string) (string, error) {
+ absenceType := collected["absence_type"]
+ switch absenceType {
+ case "timeoff":
+ return a.timeoff.TopicCodeFromCollected(collected)
+ case "vacation":
+ return a.vacation.TopicCodeFromCollected(collected)
+ case "sickleave":
+ return a.sickleave.TopicCodeFromCollected(collected)
+ default:
+ return "", fmt.Errorf("absence_type не указан: %v", collected)
+ }
+}
+
+func (a *AbsenceTopic) FormatApproverMessage(initiator *typescore.User, collected map[string]string) string {
+ switch collected["absence_type"] {
+ case "timeoff":
+ return a.timeoff.FormatApproverMessage(initiator, collected)
+ case "vacation":
+ return a.vacation.FormatApproverMessage(initiator, collected)
+ case "sickleave":
+ return a.sickleave.FormatApproverMessage(initiator, collected)
+ default:
+ name := ""
+ if initiator.FullName != nil {
+ name = *initiator.FullName
+ }
+ return fmt.Sprintf("📋 Согласование отсутствия\n\n%s:\n%s", name, collected["content"])
+ }
+}
diff --git a/service/telegram_service/handlers/faq/handler.go b/service/telegram_service/handlers/faq/handler.go
index 7b4b082..cf1b7f5 100644
--- a/service/telegram_service/handlers/faq/handler.go
+++ b/service/telegram_service/handlers/faq/handler.go
@@ -79,20 +79,19 @@ func (h *HandlerFAQ) sendHowToCreate(bot *tgbotapi.BotAPI, chatID int64, telegra
// buildMenuKeyboard возвращает клавиатуру в зависимости от роли пользователя
func (h *HandlerFAQ) buildMenuKeyboard(ctx context.Context, user *typescore.User) tgbotapi.ReplyKeyboardMarkup {
if user.ID == nil {
- return keyboard.MainMenuKeyboard()
+ return keyboard.BuildMainMenu(keyboard.UserRole{})
}
+ // Получаем все роли пользователя
isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID)
isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID)
+ isExecutor, _ := h.ipc.Database.User.IsExecutorDB(ctx, *user.ID)
+ isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID)
- switch {
- case isApprover && isObserver:
- return keyboard.ApproverObserverMenuKeyboard()
- case isApprover:
- return keyboard.ApproverMenuKeyboard()
- case isObserver:
- return keyboard.ObserverMenuKeyboard()
- default:
- return keyboard.MainMenuKeyboard()
- }
+ return keyboard.BuildMainMenu(keyboard.UserRole{
+ IsApprover: isApprover,
+ IsObserver: isObserver,
+ IsExecutor: isExecutor,
+ IsDirector: isDirector,
+ })
}
diff --git a/service/telegram_service/handlers/start/handler.go b/service/telegram_service/handlers/start/handler.go
index 5ee613e..e6eeb51 100644
--- a/service/telegram_service/handlers/start/handler.go
+++ b/service/telegram_service/handlers/start/handler.go
@@ -146,35 +146,21 @@ func (h *Handler) sendWelcomeBack(bot *tgbotapi.BotAPI, chatID int64, telegramID
// buildMenuKeyboard возвращает клавиатуру в зависимости от роли пользователя
func (h *Handler) buildMenuKeyboard(ctx context.Context, user *typescore.User) tgbotapi.ReplyKeyboardMarkup {
if user.ID == nil {
- return keyboard.MainMenuKeyboard()
+ return keyboard.BuildMainMenu(keyboard.UserRole{})
}
+ // Получаем все роли пользователя
isApprover, _ := h.ipc.Database.User.IsApproverDB(ctx, *user.ID)
isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, *user.ID)
isExecutor, _ := h.ipc.Database.User.IsExecutorDB(ctx, *user.ID)
+ isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *user.ID)
- var replyMarkup tgbotapi.ReplyKeyboardMarkup
-
- // Все комбинации ролей
- if isApprover && isObserver && isExecutor {
- replyMarkup = keyboard.ApproverObserverExecutorMenuKeyboard()
- } else if isApprover && isExecutor {
- replyMarkup = keyboard.ApproverExecutorMenuKeyboard()
- } else if isObserver && isExecutor {
- replyMarkup = keyboard.ObserverExecutorMenuKeyboard()
- } else if isApprover && isObserver {
- replyMarkup = keyboard.ApproverObserverMenuKeyboard()
- } else if isApprover {
- replyMarkup = keyboard.ApproverMenuKeyboard()
- } else if isObserver {
- replyMarkup = keyboard.ObserverMenuKeyboard()
- } else if isExecutor {
- replyMarkup = keyboard.ExecutorMenuKeyboard()
- } else {
- replyMarkup = keyboard.MainMenuKeyboard()
- }
-
- return replyMarkup
+ return keyboard.BuildMainMenu(keyboard.UserRole{
+ IsApprover: isApprover,
+ IsObserver: isObserver,
+ IsExecutor: isExecutor,
+ IsDirector: isDirector,
+ })
}
// sendRegistrationDone — подтверждение успешной регистрации.
diff --git a/service/telegram_service/handlers/suggestion/handler.go b/service/telegram_service/handlers/suggestion/handler.go
index d2a7ae9..2e04109 100644
--- a/service/telegram_service/handlers/suggestion/handler.go
+++ b/service/telegram_service/handlers/suggestion/handler.go
@@ -120,7 +120,7 @@ func (h *Handler) handleSubjectInput(bot *tgbotapi.BotAPI, ctx context.Context,
Status: &openStatus,
}
- created, _, err := h.ipc.Database.Suggestion.CreateSuggestionDB(ctx, nil, suggestion)
+ created, _, err := h.ipc.Database.Suggestion.CreateSuggestionDB(ctx, nil, suggestion, true)
if err != nil {
logrus.Errorf("handleSubjectInput: CreateSuggestionDB err=%v", err)
sendText(bot, chatID, "Ошибка при создании предложения. Попробуйте позже.")
diff --git a/service/telegram_service/keyboard/add_approver.go b/service/telegram_service/keyboard/add_approver.go
index b79bff9..2ae5a3e 100644
--- a/service/telegram_service/keyboard/add_approver.go
+++ b/service/telegram_service/keyboard/add_approver.go
@@ -1,281 +1,159 @@
+// telegram_service/keyboard/add_approver.go - ПОЛНОСТЬЮ ЗАМЕНИТЬ
+
package keyboard
import (
+ "bitrix_balancer_api/core/lib/external/tgkit"
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/telegram_service/types"
"context"
"fmt"
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
-const addApproverCategoriesPerPage = 6
-const addApproverApprovalsPerPage = 6
-const addApproverUsersPerPage = 8
-const addedApproversListPerPage = 6
-
-func BuildAddApproverMainMenu() tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("➕ Добавить", "add_appr_create"),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("📋 Ранее добавленные", "add_appr_list"),
- ),
- )
+func BuildAddApproverMainMenu() interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Добавить согласующего", "add_appr_create")).
+ Row(tgkit.Btn("📋 Ранее добавленные", "add_appr_list")).
+ Build()
}
-func BuildAddApproverCategoryMenu(categories []*typescore.ApprovalTopicCategory, page int) tgbotapi.InlineKeyboardMarkup {
+func BuildAddApproverCategoryMenu(categories []*typescore.ApprovalTopicCategory, page int) interface{} {
+ const perPage = 6
total := len(categories)
- totalPages := (total + addApproverCategoriesPerPage - 1) / addApproverCategoriesPerPage
-
+ totalPages := (total + perPage - 1) / perPage
if page < 0 {
page = 0
}
if page >= totalPages && totalPages > 0 {
page = totalPages - 1
}
-
- start := page * addApproverCategoriesPerPage
- end := start + addApproverCategoriesPerPage
+ start, end := page*perPage, page*perPage+perPage
if end > total {
end = total
}
- var rows [][]tgbotapi.InlineKeyboardButton
-
+ kb := tgkit.NewInlineKeyboard()
for _, c := range categories[start:end] {
if c.ID == nil || c.Name == nil {
continue
}
- btn := tgbotapi.NewInlineKeyboardButtonData(
- *c.Name,
- fmt.Sprintf("add_appr_category:%d", *c.ID),
- )
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ kb.Row(tgkit.Btn(*c.Name, fmt.Sprintf("add_appr_category:%d", *c.ID)))
}
-
if totalPages > 1 {
- var navRow []tgbotapi.InlineKeyboardButton
- if page > 0 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "← Назад",
- fmt.Sprintf("add_appr_category_page:%d", page-1),
- ))
- }
- if page < totalPages-1 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d →", page+1, totalPages),
- fmt.Sprintf("add_appr_category_page:%d", page+1),
- ))
- } else {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d", page+1, totalPages),
- "add_appr_page_noop",
- ))
- }
- rows = append(rows, navRow)
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "add_appr_category_page", "add_appr_page_noop"))
}
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
+ return kb.Build()
}
-func BuildAddApproverApprovalMenu(approvals []*typescore.Approval, categoryID uint64, page int, ctx context.Context, ipc *types.InternalProviderControl) tgbotapi.InlineKeyboardMarkup {
+func BuildAddApproverApprovalMenu(approvals []*typescore.Approval, categoryID uint64, page int, ctx context.Context, ipc *types.InternalProviderControl) interface{} {
+ const perPage = 6
total := len(approvals)
- totalPages := (total + addApproverApprovalsPerPage - 1) / addApproverApprovalsPerPage
-
+ totalPages := (total + perPage - 1) / perPage
if page < 0 {
page = 0
}
if page >= totalPages && totalPages > 0 {
page = totalPages - 1
}
-
- start := page * addApproverApprovalsPerPage
- end := start + addApproverApprovalsPerPage
+ start, end := page*perPage, page*perPage+perPage
if end > total {
end = total
}
- var rows [][]tgbotapi.InlineKeyboardButton
-
+ kb := tgkit.NewInlineKeyboard()
for _, a := range approvals[start:end] {
if a.ID == nil {
continue
}
-
topicName := "—"
if a.TopicID != nil {
- topic, _ := ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID)
- if topic != nil && topic.Name != nil {
- topicName = *topic.Name
+ if t, _ := ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); t != nil && t.Name != nil {
+ topicName = *t.Name
}
}
-
- label := fmt.Sprintf("#%d — %s", *a.ID, topicName)
- btn := tgbotapi.NewInlineKeyboardButtonData(
- label,
- fmt.Sprintf("add_appr_approval:%d", *a.ID),
- )
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ kb.Row(tgkit.Btn(fmt.Sprintf("#%d — %s", *a.ID, topicName), fmt.Sprintf("add_appr_approval:%d", *a.ID)))
}
-
if totalPages > 1 {
- var navRow []tgbotapi.InlineKeyboardButton
- if page > 0 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "← Назад",
- fmt.Sprintf("add_appr_approval_page:%d:%d", categoryID, page-1),
- ))
- }
- if page < totalPages-1 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d →", page+1, totalPages),
- fmt.Sprintf("add_appr_approval_page:%d:%d", categoryID, page+1),
- ))
- } else {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d", page+1, totalPages),
- "add_appr_page_noop",
- ))
- }
- rows = append(rows, navRow)
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages,
+ fmt.Sprintf("add_appr_approval_page:%d", categoryID), "add_appr_page_noop"))
}
-
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← К категориям", "add_appr_create"),
- ))
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К категориям", "add_appr_create"))
+ return kb.Build()
}
-func BuildAddApproverUserMenu(users []*typescore.User, approvalID, categoryID uint64, page int) tgbotapi.InlineKeyboardMarkup {
+func BuildAddApproverUserMenu(users []*typescore.User, approvalID, categoryID uint64, page int) interface{} {
+ const perPage = 8
total := len(users)
- totalPages := (total + addApproverUsersPerPage - 1) / addApproverUsersPerPage
-
+ totalPages := (total + perPage - 1) / perPage
if page < 0 {
page = 0
}
if page >= totalPages && totalPages > 0 {
page = totalPages - 1
}
-
- start := page * addApproverUsersPerPage
- end := start + addApproverUsersPerPage
+ start, end := page*perPage, page*perPage+perPage
if end > total {
end = total
}
- var rows [][]tgbotapi.InlineKeyboardButton
-
+ kb := tgkit.NewInlineKeyboard()
for _, u := range users[start:end] {
if u.ID == nil || u.FullName == nil {
continue
}
- btn := tgbotapi.NewInlineKeyboardButtonData(
- *u.FullName,
- fmt.Sprintf("add_appr_user:%d", *u.ID),
- )
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ kb.Row(tgkit.Btn(*u.FullName, fmt.Sprintf("add_appr_user:%d", *u.ID)))
}
-
if totalPages > 1 {
- var navRow []tgbotapi.InlineKeyboardButton
- if page > 0 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "← Назад",
- fmt.Sprintf("add_appr_user_page:%d:%d:%d", approvalID, categoryID, page-1),
- ))
- }
- if page < totalPages-1 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d →", page+1, totalPages),
- fmt.Sprintf("add_appr_user_page:%d:%d:%d", approvalID, categoryID, page+1),
- ))
- } else {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d", page+1, totalPages),
- "add_appr_page_noop",
- ))
- }
- rows = append(rows, navRow)
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages,
+ fmt.Sprintf("add_appr_user_page:%d:%d", approvalID, categoryID), "add_appr_page_noop"))
}
-
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← Назад", fmt.Sprintf("add_appr_category:%d", categoryID)),
- ))
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("add_appr_category:%d", categoryID)))
+ return kb.Build()
}
-func BuildAddedApproversList(addedApprovers []*typescore.ApprovalAdditionalApprover, page int, ctx context.Context, ipc *types.InternalProviderControl) tgbotapi.InlineKeyboardMarkup {
- total := len(addedApprovers)
- totalPages := (total + addedApproversListPerPage - 1) / addedApproversListPerPage
-
+func BuildAddedApproversList(items []*typescore.ApprovalAdditionalApprover, page int, ctx context.Context, ipc *types.InternalProviderControl) interface{} {
+ const perPage = 6
+ total := len(items)
+ totalPages := (total + perPage - 1) / perPage
if page < 0 {
page = 0
}
if page >= totalPages && totalPages > 0 {
page = totalPages - 1
}
-
- start := page * addedApproversListPerPage
- end := start + addedApproversListPerPage
+ start, end := page*perPage, page*perPage+perPage
if end > total {
end = total
}
- var rows [][]tgbotapi.InlineKeyboardButton
-
- for _, aa := range addedApprovers[start:end] {
+ kb := tgkit.NewInlineKeyboard()
+ for _, aa := range items[start:end] {
if aa.ID == nil || aa.ApprovalID == nil {
continue
}
-
approverName := "—"
if aa.ApproverID != nil {
- approver, _ := ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID)
- if approver != nil && approver.FullName != nil {
- approverName = *approver.FullName
+ if u, _ := ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID); u != nil && u.FullName != nil {
+ approverName = *u.FullName
}
}
-
- label := fmt.Sprintf("#%d — %s", *aa.ApprovalID, approverName)
- btn := tgbotapi.NewInlineKeyboardButtonData(
- label,
- fmt.Sprintf("add_appr_detail:%d", *aa.ID),
- )
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ kb.Row(tgkit.Btn(fmt.Sprintf("#%d — %s", *aa.ApprovalID, approverName), fmt.Sprintf("add_appr_detail:%d", *aa.ID)))
}
-
if totalPages > 1 {
- var navRow []tgbotapi.InlineKeyboardButton
- if page > 0 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "← Назад",
- fmt.Sprintf("add_appr_list_page:%d", page-1),
- ))
- }
- if page < totalPages-1 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d →", page+1, totalPages),
- fmt.Sprintf("add_appr_list_page:%d", page+1),
- ))
- } else {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d", page+1, totalPages),
- "add_appr_page_noop",
- ))
- }
- rows = append(rows, navRow)
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "add_appr_list_page", "add_appr_page_noop"))
}
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
+ return kb.Build()
}
-func BuildAddedApproverDetail() tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← К списку", "add_appr_list"),
- ),
- )
+func BuildAddedApproverDetail() interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", "add_appr_list")).
+ Build()
+}
+
+// BuildAddApproverToApproval — добавить согласующего прямо из карточки
+func BuildAddApproverToApproval(approvalID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Добавить согласующего", fmt.Sprintf("add_appr_to_approval:%d", approvalID))).
+ Build()
}
diff --git a/service/telegram_service/keyboard/approval.go b/service/telegram_service/keyboard/approval.go
index fb33271..e52dcc3 100644
--- a/service/telegram_service/keyboard/approval.go
+++ b/service/telegram_service/keyboard/approval.go
@@ -1,203 +1,190 @@
+// telegram_service/keyboard/approval.go - ПОЛНОСТЬЮ ЗАМЕНИТЬ
+
package keyboard
import (
+ "bitrix_balancer_api/core/lib/external/tgkit"
+ "bitrix_balancer_api/core/utilscore"
"bitrix_balancer_api/telegram_service/approvalflow"
"bitrix_balancer_api/telegram_service/state"
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
-// Формат callback-data для всех кнопок согласования:
-// appr:{topic_code}:{node_key} — навигация по флоу
-// appr_yes:{approval_id} — одобрить
-// appr_no:{approval_id} — отклонить
-// appr_revoke:{approval_id} — отозвать
-
-func BuildApprovalRejectComment(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "Отправить без комментария",
- fmt.Sprintf("appr_no_skip:%d", approvalID),
- ),
- ),
- )
+// BuildApproverDecision — кнопки для согласующего
+func BuildApproverDecision(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
+ return tgkit.NewInlineKeyboard().
+ Row(
+ tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Согласовать", fmt.Sprintf("appr_yes:%d", approvalID)),
+ tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отклонить", fmt.Sprintf("appr_no:%d", approvalID)),
+ ).
+ Row(tgkit.Btn("🔄 Вернуть на доработку", fmt.Sprintf("appr_revision:%d", approvalID))).
+ Row(
+ tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)),
+ tgkit.Btn("📎 Прикрепить файл", fmt.Sprintf("appr_attach:%d", approvalID)),
+ ).
+ Row(
+ tgkit.Btn("➕ Добавить согласующего", fmt.Sprintf("add_appr_to_approval:%d", approvalID)),
+ ).
+ Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))).
+ Build()
}
-const topicsPerPage = 6
+// BuildInitiatorCard — кнопки инициатора на карточке заявки
+func BuildInitiatorCard(approvalID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(
+ tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)),
+ tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID)),
+ ).
+ Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))).
+ Build()
+}
-// BuildApprovalMenu строит меню тем с пагинацией.
-// page — 0-индексированная страница.
-func BuildApprovalMenu(topics []approvalflow.Topic, page int) tgbotapi.InlineKeyboardMarkup {
+// BuildRevokeButton — кнопка отзыва (для директора и инициатора)
+func BuildRevokeButton(approvalID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отозвать заявку", fmt.Sprintf("appr_revoke:%d", approvalID))).
+ Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))).
+ Build()
+}
+
+// BuildObserverActions — кнопки наблюдателя
+func BuildObserverActions(approvalID uint64, topicCode string) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(
+ tgkit.Btn("🔔 Напомнить согласующему", fmt.Sprintf("obs_remind:%d", approvalID)),
+ ).
+ Row(
+ tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)),
+ ).
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", fmt.Sprintf("obs_back:%s", topicCode))).
+ Build()
+}
+
+// BuildExecutorTaskActions — кнопки исполнителя
+func BuildExecutorTaskActions(taskID, approvalID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Выполнено", fmt.Sprintf("task_complete:%d", taskID))).
+ Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))).
+ Build()
+}
+
+// BuildApprovalMenu — список тем для создания заявки
+func BuildApprovalMenu(topics []approvalflow.Topic, page int) interface{} {
+ const perPage = 6
total := len(topics)
- totalPages := (total + topicsPerPage - 1) / topicsPerPage
-
- // Ограничиваем page
+ totalPages := (total + perPage - 1) / perPage
if page < 0 {
page = 0
}
if page >= totalPages && totalPages > 0 {
page = totalPages - 1
}
-
- start := page * topicsPerPage
- end := start + topicsPerPage
+ start := page * perPage
+ end := start + perPage
if end > total {
end = total
}
- var rows [][]tgbotapi.InlineKeyboardButton
-
+ kb := tgkit.NewInlineKeyboard()
for _, t := range topics[start:end] {
- btn := tgbotapi.NewInlineKeyboardButtonData(
- t.Name(),
- fmt.Sprintf("appr:%s:%s", t.Code(), t.Code()),
- )
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ kb.Row(tgkit.Btn(t.Name(), fmt.Sprintf("appr:%s:%s", t.Code(), t.Code())))
}
-
if totalPages > 1 {
- var navRow []tgbotapi.InlineKeyboardButton
- if page > 0 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "← Назад",
- fmt.Sprintf("appr_page:%d", page-1),
- ))
- }
- if page < totalPages-1 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d →", page+1, totalPages),
- fmt.Sprintf("appr_page:%d", page+1),
- ))
- } else {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d", page+1, totalPages),
- "appr_page_noop",
- ))
- }
- rows = append(rows, navRow)
+ pagination := tgkit.PaginationRow(
+ page,
+ totalPages,
+ fmt.Sprintf("appr_page:%d", page-1),
+ fmt.Sprintf("appr_page:%d", page+1),
+ "appr_page_noop",
+ )
+ kb.Rows = append(kb.Rows, pagination)
}
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
+ return kb.Build()
}
-// BuildApprovalStep строит клавиатуру для текущего шага флоу.
-func BuildApprovalStep(
- topicCode string,
- nodes []*approvalflow.FlowNode,
-) tgbotapi.InlineKeyboardMarkup {
- var rows [][]tgbotapi.InlineKeyboardButton
-
+// BuildApprovalStep — шаг флоу согласования
+func BuildApprovalStep(topicCode string, nodes []*approvalflow.FlowNode) interface{} {
+ kb := tgkit.NewInlineKeyboard()
for _, n := range nodes {
if n == nil {
continue
}
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- n.Label,
- fmt.Sprintf("appr:%s:%s", topicCode, n.Key),
- ),
- ))
+ kb.Row(tgkit.Btn(n.Label, fmt.Sprintf("appr:%s:%s", topicCode, n.Key)))
+ }
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("appr_back:%s", topicCode)))
+ return kb.Build()
+}
+
+// BuildApprovalInputPrompt — подсказка ввода
+func BuildApprovalInputPrompt(topicCode string) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("appr_back:%s", topicCode))).
+ Build()
+}
+
+// BuildRejectOptions — варианты при отклонении
+func BuildRejectOptions(approvalID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("💬 Написать причину", fmt.Sprintf("appr_no_comment:%d", approvalID))).
+ Row(tgkit.Btn("⏳ Отложить", fmt.Sprintf("appr_no_defer:%d", approvalID))).
+ Row(tgkit.Btn("Отклонить без комментария", fmt.Sprintf("appr_no_skip:%d", approvalID))).
+ Build()
+}
+
+// BuildRevokeOptions — варианты при отзыве
+func BuildRevokeOptions(approvalID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("💬 Написать причину", fmt.Sprintf("appr_revoke_comment:%d", approvalID))).
+ Row(tgkit.Btn("⏳ Отложить", fmt.Sprintf("appr_revoke_defer:%d", approvalID))).
+ Row(tgkit.Btn("Отозвать без комментария", fmt.Sprintf("appr_revoke_skip:%d", approvalID))).
+ Build()
+}
+
+// BuildApprovalRejectComment — кнопка "без комментария" при вводе причины
+func BuildApprovalRejectComment(approvalID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("Отправить без комментария", fmt.Sprintf("appr_no_skip:%d", approvalID))).
+ Build()
+}
+
+// BuildApprovalStagesButton — кнопка стадий
+func BuildApprovalStagesButton(approvalID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))).
+ Build()
+}
+
+// BuildFileInputKeyboard — управление файлами в процессе флоу
+func BuildFileInputKeyboard(topicCode string, files []state.FileAttachment) interface{} {
+ kb := tgkit.NewInlineKeyboard()
+
+ for i, f := range files {
+ label := []rune(f.FileName)
+ if len(label) > 25 {
+ label = append(label[:22], []rune("...")...)
+ }
+ kb.Row(tgkit.Btn("🗑 "+string(label), fmt.Sprintf("appr_file_detach:%d", i)))
}
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← Назад", fmt.Sprintf("appr_back:%s", topicCode)),
- ))
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
+ submitLabel := "✅ Отправить на согласование (без файлов)"
+ if n := len(files); n > 0 {
+ submitLabel = fmt.Sprintf("✅ Отправить (%s)", utilscore.PluralFiles(n))
+ }
+ kb.Row(tgkit.Btn(submitLabel, "appr_file_submit:"+topicCode))
+
+ if len(files) > 0 {
+ kb.Row(tgkit.Btn("📤 Отправить без файлов", "appr_file_skip:"+topicCode))
+ }
+
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", "appr_back:"+topicCode))
+ return kb.Build()
}
-// BuildApproverDecision строит кнопки Да/Нет для согласующего.
-func BuildApproverDecision(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("✅ Да", fmt.Sprintf("appr_yes:%d", approvalID)),
- tgbotapi.NewInlineKeyboardButtonData("❌ Нет", fmt.Sprintf("appr_no:%d", approvalID)),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID)),
- tgbotapi.NewInlineKeyboardButtonData("📎 Прикрепить файл", fmt.Sprintf("appr_attach:%d", approvalID)),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID)),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("🔄 Вернуть на доработку", fmt.Sprintf("appr_revision:%d", approvalID)),
- ),
- )
-}
-
-// BuildRevokeButton строит кнопку отзыва для инициатора и директора.
-func BuildRevokeButton(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("↩️ Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID)),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID)),
- ),
- )
-}
-
-// BuildApprovalInputPrompt — подсказка ввода с кнопкой назад.
-func BuildApprovalInputPrompt(topicCode string) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← Назад", fmt.Sprintf("appr_back:%s", topicCode)),
- ),
- )
-}
-
-// BuildRejectOptions — варианты при нажатии "Нет".
-func BuildRejectOptions(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "💬 Ввести комментарий",
- fmt.Sprintf("appr_no_comment:%d", approvalID),
- ),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "⏳ Отложить",
- fmt.Sprintf("appr_no_defer:%d", approvalID),
- ),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "✅ Без комментария",
- fmt.Sprintf("appr_no_skip:%d", approvalID),
- ),
- ),
- )
-}
-
-// BuildRevokeOptions — варианты при нажатии "Отозвать".
-func BuildRevokeOptions(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "💬 Ввести комментарий",
- fmt.Sprintf("appr_revoke_comment:%d", approvalID),
- ),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "⏳ Отложить",
- fmt.Sprintf("appr_revoke_defer:%d", approvalID),
- ),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "✅ Без комментария",
- fmt.Sprintf("appr_revoke_skip:%d", approvalID),
- ),
- ),
- )
-}
-
-// BuildPendingCommentsList — список отложенных заявок.
-func BuildPendingCommentsList(items []state.PendingCommentItem, topicNames map[uint64]string) tgbotapi.InlineKeyboardMarkup {
- var rows [][]tgbotapi.InlineKeyboardButton
+// BuildPendingCommentsList — список отложенных заявок
+func BuildPendingCommentsList(items []state.PendingCommentItem, topicNames map[uint64]string) interface{} {
+ kb := tgkit.NewInlineKeyboard()
for _, item := range items {
icon := "❌"
if item.Action == "revoke" {
@@ -207,33 +194,74 @@ func BuildPendingCommentsList(items []state.PendingCommentItem, topicNames map[u
if name, ok := topicNames[item.ApprovalID]; ok {
label += " — " + name
}
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- label,
- fmt.Sprintf("pending_item:%d", item.ApprovalID),
- ),
- ))
+ kb.Row(tgkit.Btn(label, fmt.Sprintf("pending_item:%d", item.ApprovalID)))
}
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
+ return kb.Build()
}
-// BuildPendingItemOptions — действия по конкретной отложенной заявке.
-func BuildPendingItemOptions(approvalID uint64, action string) tgbotapi.InlineKeyboardMarkup {
+// BuildPendingItemOptions — действия по отложенной заявке
+func BuildPendingItemOptions(approvalID uint64, action string) interface{} {
commentCB := fmt.Sprintf("appr_no_comment:%d", approvalID)
skipCB := fmt.Sprintf("appr_no_skip:%d", approvalID)
if action == "revoke" {
commentCB = fmt.Sprintf("appr_revoke_comment:%d", approvalID)
skipCB = fmt.Sprintf("appr_revoke_skip:%d", approvalID)
}
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("💬 Ввести комментарий", commentCB),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("✅ Без комментария", skipCB),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← Назад", "pending_back"),
- ),
- )
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("💬 Написать причину", commentCB)).
+ Row(tgkit.Btn("Без комментария", skipCB)).
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", "pending_back")).
+ Build()
+}
+
+// BuildAttachFileCancel — отмена прикрепления файла
+func BuildAttachFileCancel(approvalID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отмена", fmt.Sprintf("appr_attach_cancel:%d", approvalID))).
+ Build()
+}
+
+// BuildMultiSelectStep — мультиселект (например, системы ОКБ/1С/Битрикс)
+func BuildMultiSelectStep(topicCode string, nodes []*approvalflow.FlowNode, selectedValues []string, allowedTopicCodes map[string]bool) tgbotapi.InlineKeyboardMarkup {
+ selectedSet := make(map[string]bool, len(selectedValues))
+ for _, v := range selectedValues {
+ selectedSet[v] = true
+ }
+
+ kb := tgkit.NewInlineKeyboard()
+ for _, n := range nodes {
+ if n == nil {
+ continue
+ }
+ if n.TopicCode != "" && allowedTopicCodes != nil && !allowedTopicCodes[n.TopicCode] {
+ continue
+ }
+ label := n.Label
+ if selectedSet[n.MultiSelectValue] {
+ label = "✅ " + label
+ }
+ kb.Row(tgkit.Btn(label, fmt.Sprintf("appr_ms_toggle:%s:%s:%s", topicCode, n.Key, n.MultiSelectValue)))
+ }
+
+ confirmLabel := "✅ Подтвердить"
+ if len(selectedValues) > 0 {
+ confirmLabel = fmt.Sprintf("✅ Подтвердить (%d)", len(selectedValues))
+ }
+ kb.Row(tgkit.Btn(confirmLabel, fmt.Sprintf("appr_ms_confirm:%s", topicCode)))
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("appr_back:%s", topicCode)))
+ return kb.Build()
+}
+
+// вспомогательная функция пагинации
+func buildPageRow(page, totalPages int, prefix, noop string) []tgbotapi.InlineKeyboardButton {
+ var row []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ row = append(row, tgkit.Btn("←", fmt.Sprintf("%s:%d", prefix, page-1)).Build())
+ }
+ if page < totalPages-1 {
+ row = append(row, tgkit.Btn(fmt.Sprintf("%d/%d →", page+1, totalPages), fmt.Sprintf("%s:%d", prefix, page+1)).Build())
+ } else {
+ row = append(row, tgkit.Btn(fmt.Sprintf("%d/%d", page+1, totalPages), noop).Build())
+ }
+ return row
}
diff --git a/service/telegram_service/keyboard/approval_stage.go b/service/telegram_service/keyboard/approval_stage.go
deleted file mode 100644
index c28a918..0000000
--- a/service/telegram_service/keyboard/approval_stage.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package keyboard
-
-import (
- "fmt"
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
-)
-
-func BuildApprovalStagesButton(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "Стадия согласования",
- fmt.Sprintf("appr_stage:%d", approvalID),
- ),
- ),
- )
-}
diff --git a/service/telegram_service/keyboard/approver_select.go b/service/telegram_service/keyboard/approver_select.go
deleted file mode 100644
index c00b823..0000000
--- a/service/telegram_service/keyboard/approver_select.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package keyboard
-
-import (
- "bitrix_balancer_api/core/typescore"
- "fmt"
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
-)
-
-const approverSelectionPerPage = 8
-
-func BuildApproverSelectionMenu(approvers []*typescore.User, page int) tgbotapi.InlineKeyboardMarkup {
- total := len(approvers)
- totalPages := (total + approverSelectionPerPage - 1) / approverSelectionPerPage
-
- if page < 0 {
- page = 0
- }
- if page >= totalPages && totalPages > 0 {
- page = totalPages - 1
- }
-
- start := page * approverSelectionPerPage
- end := start + approverSelectionPerPage
- if end > total {
- end = total
- }
-
- var rows [][]tgbotapi.InlineKeyboardButton
-
- for _, a := range approvers[start:end] {
- if a.ID == nil || a.FullName == nil {
- continue
- }
- btn := tgbotapi.NewInlineKeyboardButtonData(
- *a.FullName,
- fmt.Sprintf("select_approver:%d", *a.ID),
- )
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
- }
-
- if totalPages > 1 {
- var navRow []tgbotapi.InlineKeyboardButton
- if page > 0 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "← Назад",
- fmt.Sprintf("select_approver_page:%d", page-1),
- ))
- }
- if page < totalPages-1 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d →", page+1, totalPages),
- fmt.Sprintf("select_approver_page:%d", page+1),
- ))
- } else {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d", page+1, totalPages),
- "select_approver_noop",
- ))
- }
- rows = append(rows, navRow)
- }
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
-}
diff --git a/service/telegram_service/keyboard/attach_file.go b/service/telegram_service/keyboard/attach_file.go
deleted file mode 100644
index 3aedc69..0000000
--- a/service/telegram_service/keyboard/attach_file.go
+++ /dev/null
@@ -1,14 +0,0 @@
-package keyboard
-
-import (
- "fmt"
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
-)
-
-func BuildAttachFileCancel(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("❌ Отмена", fmt.Sprintf("appr_attach_cancel:%d", approvalID)),
- ),
- )
-}
diff --git a/service/telegram_service/keyboard/build_multiselect.go b/service/telegram_service/keyboard/build_multiselect.go
deleted file mode 100644
index d67eb61..0000000
--- a/service/telegram_service/keyboard/build_multiselect.go
+++ /dev/null
@@ -1,95 +0,0 @@
-package keyboard
-
-import (
- "bitrix_balancer_api/telegram_service/approvalflow"
- "fmt"
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
-)
-
-// BuildApprovalStep строит обычные кнопки выбора (без мультиселекта).
-// allowedTopicCodes — список кодов тем, на которые у пользователя есть права.
-// Если nil — фильтрация не применяется.
-//func BuildApprovalStep(
-// topicCode string,
-// nodes []*approvalflow.FlowNode,
-// allowedTopicCodes map[string]bool, // nil = без фильтрации
-//) tgbotapi.InlineKeyboardMarkup {
-// var rows [][]tgbotapi.InlineKeyboardButton
-//
-// for _, n := range nodes {
-// if n == nil {
-// continue
-// }
-// // Проверяем право доступа если задан TopicCode узла
-// if n.TopicCode != "" && allowedTopicCodes != nil {
-// if !allowedTopicCodes[n.TopicCode] {
-// continue
-// }
-// }
-//
-// rows = append(rows, tgbotapi.NewInlineKeyboardRow(
-// tgbotapi.NewInlineKeyboardButtonData(
-// n.Label,
-// fmt.Sprintf("appr:%s:%s", topicCode, n.Key),
-// ),
-// ))
-// }
-//
-// rows = append(rows, tgbotapi.NewInlineKeyboardRow(
-// tgbotapi.NewInlineKeyboardButtonData("← Назад", fmt.Sprintf("appr_back:%s", topicCode)),
-// ))
-//
-// return tgbotapi.NewInlineKeyboardMarkup(rows...)
-//}
-
-// BuildMultiSelectStep строит кнопки мультиселекта с чекбоксами.
-func BuildMultiSelectStep(
- topicCode string,
- nodes []*approvalflow.FlowNode,
- selectedValues []string,
- allowedTopicCodes map[string]bool,
-) tgbotapi.InlineKeyboardMarkup {
- selectedSet := make(map[string]bool, len(selectedValues))
- for _, v := range selectedValues {
- selectedSet[v] = true
- }
-
- var rows [][]tgbotapi.InlineKeyboardButton
-
- for _, n := range nodes {
- if n == nil {
- continue
- }
- if n.TopicCode != "" && allowedTopicCodes != nil {
- if !allowedTopicCodes[n.TopicCode] {
- continue
- }
- }
-
- label := n.Label
- if selectedSet[n.MultiSelectValue] {
- label = "✅ " + label
- }
-
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- label,
- fmt.Sprintf("appr_ms_toggle:%s:%s:%s", topicCode, n.Key, n.MultiSelectValue),
- ),
- ))
- }
-
- // Кнопка подтверждения
- confirmLabel := "✅ Подтвердить"
- if len(selectedValues) > 0 {
- confirmLabel = fmt.Sprintf("✅ Подтвердить (%d)", len(selectedValues))
- }
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(confirmLabel, fmt.Sprintf("appr_ms_confirm:%s", topicCode)),
- ))
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← Назад", fmt.Sprintf("appr_back:%s", topicCode)),
- ))
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
-}
diff --git a/service/telegram_service/keyboard/builder.go b/service/telegram_service/keyboard/builder.go
index 19c748a..36a4737 100644
--- a/service/telegram_service/keyboard/builder.go
+++ b/service/telegram_service/keyboard/builder.go
@@ -2,110 +2,6 @@ package keyboard
import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
-// MainMenuKeyboard - главное меню (без изменений в структуре)
-func MainMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
- return tgbotapi.NewReplyKeyboard(
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Согласование"),
- tgbotapi.NewKeyboardButton("Мои заявки"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Отложенные"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Предложения и пожелания"),
- ),
- )
-}
-
-func ExecutorMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
- return tgbotapi.NewReplyKeyboard(
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Согласование"),
- tgbotapi.NewKeyboardButton("Мои заявки"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Мои задачи"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Предложения и пожелания"),
- ),
- )
-}
-
-func ApproverExecutorMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
- return tgbotapi.NewReplyKeyboard(
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Согласование"),
- tgbotapi.NewKeyboardButton("Мои заявки"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Согласовать"),
- tgbotapi.NewKeyboardButton("Мои задачи"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Отложенные"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Предложения и пожелания"),
- ),
- )
-}
-
-func ObserverExecutorMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
- return tgbotapi.NewReplyKeyboard(
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Согласование"),
- tgbotapi.NewKeyboardButton("Мои заявки"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Наблюдаемые"),
- tgbotapi.NewKeyboardButton("Мои задачи"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Отложенные"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Предложения и пожелания"),
- ),
- )
-}
-
-func ApproverObserverExecutorMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
- return tgbotapi.NewReplyKeyboard(
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Согласование"),
- tgbotapi.NewKeyboardButton("Мои заявки"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Согласовать"),
- tgbotapi.NewKeyboardButton("Мои задачи"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Отложенные"),
- tgbotapi.NewKeyboardButton("Наблюдаемые"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Предложения и пожелания"),
- ),
- )
-}
-
// ApprovalsSubmenuKeyboard - подменю "Согласования"
func ApprovalsSubmenuKeyboard(isObserver, isApprover bool) tgbotapi.ReplyKeyboardMarkup {
rows := [][]tgbotapi.KeyboardButton{
@@ -147,66 +43,3 @@ func ApprovalsListSubmenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
),
)
}
-
-// ObserverMenuKeyboard - меню для наблюдателя
-func ObserverMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
- return tgbotapi.NewReplyKeyboard(
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Согласование"),
- tgbotapi.NewKeyboardButton("Мои заявки"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Отложенные"),
- tgbotapi.NewKeyboardButton("Наблюдаемые"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Предложения и пожелания"),
- ),
- )
-}
-
-// ApproverMenuKeyboard - меню для согласующего
-func ApproverMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
- return tgbotapi.NewReplyKeyboard(
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Согласование"),
- tgbotapi.NewKeyboardButton("Мои заявки"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Согласовать"),
- tgbotapi.NewKeyboardButton("Отложенные"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Предложения и пожелания"),
- ),
- )
-}
-
-// ApproverObserverMenuKeyboard - меню для согласующего + наблюдателя
-func ApproverObserverMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
- return tgbotapi.NewReplyKeyboard(
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Согласование"),
- tgbotapi.NewKeyboardButton("Мои заявки"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Согласовать"),
- tgbotapi.NewKeyboardButton("Отложенные"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Наблюдаемые"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
- ),
- tgbotapi.NewKeyboardButtonRow(
- tgbotapi.NewKeyboardButton("Предложения и пожелания"),
- ),
- )
-}
diff --git a/service/telegram_service/keyboard/delegation.go b/service/telegram_service/keyboard/delegation.go
index 62478b0..75e6cd4 100644
--- a/service/telegram_service/keyboard/delegation.go
+++ b/service/telegram_service/keyboard/delegation.go
@@ -1,8 +1,9 @@
-// telegram_service/keyboard/handler_delegation.go - полностью переписать
+// telegram_service/keyboard/delegation.go - ПОЛНОСТЬЮ ЗАМЕНИТЬ
package keyboard
import (
+ "bitrix_balancer_api/core/lib/external/tgkit"
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/telegram_service/types"
"context"
@@ -10,206 +11,154 @@ import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
-const delegationCategoriesPerPage = 6
-const delegationTopicsPerPage = 6
-const delegationUsersPerPage = 8
-const delegationListPerPage = 6
+const delegationPerPage = 6
-func BuildDelegationMainMenu() tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("➕ Делегировать", "deleg_create"),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("Делегированные права", "deleg_list"),
- ),
- )
+func BuildDelegationMainMenu() interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Делегировать права", "deleg_create")).
+ Row(tgkit.Btn("📋 Делегированные права", "deleg_list")).
+ Build()
}
-func BuildDelegationCategoryMenu(categories []*typescore.ApprovalTopicCategory, page int) tgbotapi.InlineKeyboardMarkup {
+func BuildDelegationCategoryMenu(categories []*typescore.ApprovalTopicCategory, page int) interface{} {
total := len(categories)
- totalPages := (total + delegationCategoriesPerPage - 1) / delegationCategoriesPerPage
-
+ totalPages := (total + delegationPerPage - 1) / delegationPerPage
if page < 0 {
page = 0
}
if page >= totalPages && totalPages > 0 {
page = totalPages - 1
}
-
- start := page * delegationCategoriesPerPage
- end := start + delegationCategoriesPerPage
+ start, end := page*delegationPerPage, page*delegationPerPage+delegationPerPage
if end > total {
end = total
}
- var rows [][]tgbotapi.InlineKeyboardButton
-
+ kb := tgkit.NewInlineKeyboard()
for _, c := range categories[start:end] {
if c.ID == nil || c.Name == nil {
continue
}
- btn := tgbotapi.NewInlineKeyboardButtonData(
- *c.Name,
- fmt.Sprintf("deleg_category:%d", *c.ID),
- )
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ kb.Row(tgkit.Btn(*c.Name, fmt.Sprintf("deleg_category:%d", *c.ID)))
}
-
if totalPages > 1 {
- var navRow []tgbotapi.InlineKeyboardButton
- if page > 0 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "← Назад",
- fmt.Sprintf("deleg_category_page:%d", page-1),
- ))
- }
- if page < totalPages-1 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d →", page+1, totalPages),
- fmt.Sprintf("deleg_category_page:%d", page+1),
- ))
- } else {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d", page+1, totalPages),
- "deleg_page_noop",
- ))
- }
- rows = append(rows, navRow)
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "deleg_category_page", "deleg_page_noop"))
}
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
+ return kb.Build()
}
-func BuildDelegationTopicMenu(topics []*typescore.ApprovalTopic, categoryID uint64, page int) tgbotapi.InlineKeyboardMarkup {
+func BuildDelegationTopicMenu(topics []*typescore.ApprovalTopic, categoryID uint64, page int) interface{} {
+ const perPage = 6
total := len(topics)
- totalPages := (total + delegationTopicsPerPage - 1) / delegationTopicsPerPage
-
+ totalPages := (total + perPage - 1) / perPage
if page < 0 {
page = 0
}
if page >= totalPages && totalPages > 0 {
page = totalPages - 1
}
-
- start := page * delegationTopicsPerPage
- end := start + delegationTopicsPerPage
+ start, end := page*perPage, page*perPage+perPage
if end > total {
end = total
}
- var rows [][]tgbotapi.InlineKeyboardButton
-
- // Кнопка "Все"
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "✅ Вся категория",
- fmt.Sprintf("deleg_all_category:%d", categoryID),
- ),
- ))
+ kb := tgkit.NewInlineKeyboard()
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Вся категория", fmt.Sprintf("deleg_all_category:%d", categoryID)))
for _, t := range topics[start:end] {
if t.ID == nil || t.Name == nil {
continue
}
- btn := tgbotapi.NewInlineKeyboardButtonData(
- *t.Name,
- fmt.Sprintf("deleg_topic:%d", *t.ID),
- )
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ kb.Row(tgkit.Btn(*t.Name, fmt.Sprintf("deleg_topic:%d", *t.ID)))
}
-
if totalPages > 1 {
- var navRow []tgbotapi.InlineKeyboardButton
- if page > 0 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "← Назад",
- fmt.Sprintf("deleg_topic_page:%d:%d", categoryID, page-1),
- ))
- }
- if page < totalPages-1 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d →", page+1, totalPages),
- fmt.Sprintf("deleg_topic_page:%d:%d", categoryID, page+1),
- ))
- } else {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d", page+1, totalPages),
- "deleg_page_noop",
- ))
- }
- rows = append(rows, navRow)
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages,
+ fmt.Sprintf("deleg_topic_page:%d", categoryID), "deleg_page_noop"))
}
-
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← К категориям", "deleg_back_categories"),
- ))
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К категориям", "deleg_back_categories"))
+ return kb.Build()
}
-func BuildDelegationUserMenu(users []*typescore.User, categoryID, topicID uint64, page int) tgbotapi.InlineKeyboardMarkup {
+func BuildDelegationUserMenu(users []*typescore.User, categoryID, topicID uint64, page int) interface{} {
+ const perPage = 8
total := len(users)
- totalPages := (total + delegationUsersPerPage - 1) / delegationUsersPerPage
-
+ totalPages := (total + perPage - 1) / perPage
if page < 0 {
page = 0
}
if page >= totalPages && totalPages > 0 {
page = totalPages - 1
}
-
- start := page * delegationUsersPerPage
- end := start + delegationUsersPerPage
+ start, end := page*perPage, page*perPage+perPage
if end > total {
end = total
}
- var rows [][]tgbotapi.InlineKeyboardButton
-
+ kb := tgkit.NewInlineKeyboard()
for _, u := range users[start:end] {
if u.ID == nil || u.FullName == nil {
continue
}
- btn := tgbotapi.NewInlineKeyboardButtonData(
- *u.FullName,
- fmt.Sprintf("deleg_user:%d", *u.ID),
- )
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
+ kb.Row(tgkit.Btn(*u.FullName, fmt.Sprintf("deleg_user:%d", *u.ID)))
}
-
if totalPages > 1 {
- var navRow []tgbotapi.InlineKeyboardButton
- if page > 0 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "← Назад",
- fmt.Sprintf("deleg_user_page:%d:%d:%d", categoryID, topicID, page-1),
- ))
- }
- if page < totalPages-1 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d →", page+1, totalPages),
- fmt.Sprintf("deleg_user_page:%d:%d:%d", categoryID, topicID, page+1),
- ))
- } else {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d", page+1, totalPages),
- "deleg_page_noop",
- ))
- }
- rows = append(rows, navRow)
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages,
+ fmt.Sprintf("deleg_user_page:%d:%d", categoryID, topicID), "deleg_page_noop"))
+ }
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", fmt.Sprintf("deleg_category:%d", categoryID)))
+ return kb.Build()
+}
+
+func BuildDelegatedRightsList(delegations []*typescore.ApprovalDelegation, page int, ctx context.Context, ipc *types.InternalProviderControl) interface{} {
+ const perPage = 6
+ total := len(delegations)
+ totalPages := (total + perPage - 1) / perPage
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+ start, end := page*perPage, page*perPage+perPage
+ if end > total {
+ end = total
}
- backCallback := fmt.Sprintf("deleg_category:%d", categoryID)
- if topicID > 0 {
- backCallback = fmt.Sprintf("deleg_category:%d", categoryID)
+ kb := tgkit.NewInlineKeyboard()
+ for _, d := range delegations[start:end] {
+ if d.ID == nil {
+ continue
+ }
+ scopeName := "—"
+ if d.TopicID != nil {
+ if t, _ := ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *d.TopicID); t != nil && t.Name != nil {
+ scopeName = *t.Name
+ }
+ } else if d.CategoryID != nil {
+ if c, _ := ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *d.CategoryID); c != nil && c.Name != nil {
+ scopeName = *c.Name
+ }
+ }
+ kb.Row(tgkit.Btn(scopeName, fmt.Sprintf("deleg_detail:%d", *d.ID)))
}
+ if totalPages > 1 {
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "deleg_list_page", "deleg_page_noop"))
+ }
+ return kb.Build()
+}
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← Назад", backCallback),
- ))
+func BuildDelegationActions(delegationID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("📅 Изменить срок", fmt.Sprintf("deleg_extend:%d", delegationID))).
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отозвать делегирование", fmt.Sprintf("deleg_revoke:%d", delegationID))).
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", "deleg_list")).
+ Build()
+}
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
+func BuildDelegationExtendCancel(delegationID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Отмена", fmt.Sprintf("deleg_detail:%d", delegationID))).
+ Build()
}
func BuildDelegationBackToUsers(categoryID, topicID uint64) tgbotapi.InlineKeyboardMarkup {
@@ -217,100 +166,7 @@ func BuildDelegationBackToUsers(categoryID, topicID uint64) tgbotapi.InlineKeybo
if topicID > 0 {
callback = fmt.Sprintf("deleg_topic:%d", topicID)
}
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← Назад", callback),
- ),
- )
-}
-
-func BuildDelegatedRightsList(delegations []*typescore.ApprovalDelegation, page int, ctx context.Context, ipc *types.InternalProviderControl) tgbotapi.InlineKeyboardMarkup {
- total := len(delegations)
- totalPages := (total + delegationListPerPage - 1) / delegationListPerPage
-
- if page < 0 {
- page = 0
- }
- if page >= totalPages && totalPages > 0 {
- page = totalPages - 1
- }
-
- start := page * delegationListPerPage
- end := start + delegationListPerPage
- if end > total {
- end = total
- }
-
- var rows [][]tgbotapi.InlineKeyboardButton
-
- for _, d := range delegations[start:end] {
- if d.ID == nil {
- continue
- }
-
- scopeName := "—"
- if d.TopicID != nil {
- topic, _ := ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *d.TopicID)
- if topic != nil && topic.Name != nil {
- scopeName = *topic.Name
- }
- } else if d.CategoryID != nil {
- category, _ := ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *d.CategoryID)
- if category != nil && category.Name != nil {
- scopeName = *category.Name
- }
- }
-
- btn := tgbotapi.NewInlineKeyboardButtonData(
- scopeName,
- fmt.Sprintf("deleg_detail:%d", *d.ID),
- )
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
- }
-
- if totalPages > 1 {
- var navRow []tgbotapi.InlineKeyboardButton
- if page > 0 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "← Назад",
- fmt.Sprintf("deleg_list_page:%d", page-1),
- ))
- }
- if page < totalPages-1 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d →", page+1, totalPages),
- fmt.Sprintf("deleg_list_page:%d", page+1),
- ))
- } else {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d", page+1, totalPages),
- "deleg_page_noop",
- ))
- }
- rows = append(rows, navRow)
- }
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
-}
-
-func BuildDelegationActions(delegationID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("Изменить срок", fmt.Sprintf("deleg_extend:%d", delegationID)),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("❌ Отозвать", fmt.Sprintf("deleg_revoke:%d", delegationID)),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← К списку", "deleg_list"),
- ),
- )
-}
-
-func BuildDelegationExtendCancel(delegationID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← Отмена", fmt.Sprintf("deleg_detail:%d", delegationID)),
- ),
- )
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "Назад", callback)).
+ Build()
}
diff --git a/service/telegram_service/keyboard/executor.go b/service/telegram_service/keyboard/executor.go
deleted file mode 100644
index 1906ed3..0000000
--- a/service/telegram_service/keyboard/executor.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package keyboard
-
-import (
- "fmt"
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
-)
-
-func BuildExecutorTaskActions(taskID, approvalID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("✅ Выполнено", fmt.Sprintf("task_complete:%d", taskID)),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID)),
- ),
- )
-}
diff --git a/service/telegram_service/keyboard/file_input.go b/service/telegram_service/keyboard/file_input.go
deleted file mode 100644
index e2fc01f..0000000
--- a/service/telegram_service/keyboard/file_input.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package keyboard
-
-import (
- "bitrix_balancer_api/core/utilscore"
- "bitrix_balancer_api/telegram_service/state"
- "fmt"
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
-)
-
-// BuildFileInputKeyboard строит клавиатуру с кнопками открепления каждого файла,
-// кнопкой отправки (с количеством) и кнопкой отправки без файлов.
-// keyboard/file_input.go
-func BuildFileInputKeyboard(topicCode string, files []state.FileAttachment) tgbotapi.InlineKeyboardMarkup {
- var rows [][]tgbotapi.InlineKeyboardButton
-
- // Кнопка «Открепить» для каждого файла
- for i, f := range files {
- label := []rune(f.FileName)
- if len(label) > 25 {
- label = append(label[:22], []rune("...")...)
- }
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "🗑 "+string(label),
- fmt.Sprintf("appr_file_detach:%d", i),
- ),
- ))
- }
-
- // Кнопка отправки — показывает количество файлов
- submitLabel := "✅ Отправить на согласование"
- if n := len(files); n > 0 {
- submitLabel = fmt.Sprintf("✅ Отправить (%s)", utilscore.PluralFiles(n))
- }
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(submitLabel, "appr_file_submit:"+topicCode),
- ))
-
- // Кнопка «без файлов» появляется только если уже что-то прикреплено
- if len(files) > 0 {
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("📤 Отправить без файлов", "appr_file_skip:"+topicCode),
- ))
- }
-
- // Кнопка «Назад» — всегда внизу
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("← Назад", "appr_back:"+topicCode),
- ))
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
-}
diff --git a/service/telegram_service/keyboard/first_approver_select.go b/service/telegram_service/keyboard/first_approver_select.go
deleted file mode 100644
index 7f00817..0000000
--- a/service/telegram_service/keyboard/first_approver_select.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package keyboard
-
-import (
- "bitrix_balancer_api/core/typescore"
- "fmt"
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
-)
-
-const firstApproverPerPage = 8
-
-func BuildFirstApproverSelectionMenu(
- users []*typescore.User,
- roleLabel string,
- page int,
-) tgbotapi.InlineKeyboardMarkup {
- total := len(users)
- totalPages := (total + firstApproverPerPage - 1) / firstApproverPerPage
- if page < 0 {
- page = 0
- }
- if page >= totalPages && totalPages > 0 {
- page = totalPages - 1
- }
-
- start := page * firstApproverPerPage
- end := min(start+firstApproverPerPage, total)
-
- var rows [][]tgbotapi.InlineKeyboardButton
-
- for _, u := range users[start:end] {
- if u.ID == nil || u.FullName == nil {
- continue
- }
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- *u.FullName,
- fmt.Sprintf("first_approver_select:%d", *u.ID),
- ),
- ))
- }
-
- if totalPages > 1 {
- var navRow []tgbotapi.InlineKeyboardButton
- if page > 0 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "← Назад", fmt.Sprintf("first_approver_page:%d", page-1),
- ))
- }
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d", page+1, totalPages), "first_approver_noop",
- ))
- if page < totalPages-1 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "→ Вперёд", fmt.Sprintf("first_approver_page:%d", page+1),
- ))
- }
- rows = append(rows, navRow)
- }
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
-}
diff --git a/service/telegram_service/keyboard/menu.go b/service/telegram_service/keyboard/menu.go
new file mode 100644
index 0000000..8d9afb0
--- /dev/null
+++ b/service/telegram_service/keyboard/menu.go
@@ -0,0 +1,88 @@
+package keyboard
+
+import (
+ "bitrix_balancer_api/core/lib/external/tgkit"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+// UserRole — набор ролей пользователя для построения меню
+type UserRole struct {
+ IsApprover bool
+ IsObserver bool
+ IsExecutor bool
+ IsDirector bool
+}
+
+// BuildMainMenu — главное меню с разделами по ролям
+func BuildMainMenu(roles UserRole) tgbotapi.ReplyKeyboardMarkup {
+ kb := tgkit.NewReplyKeyboard()
+
+ // Раздел: Инициатор (всегда видим)
+ kb.Row("👤 Инициатор")
+
+ // Раздел: Согласующий
+ if roles.IsApprover || roles.IsDirector {
+ kb.Row("✅ Согласующий")
+ }
+
+ // Раздел: Наблюдатель
+ if roles.IsObserver {
+ kb.Row("👁 Наблюдатель")
+ }
+
+ // Раздел: Исполнитель
+ if roles.IsExecutor {
+ kb.Row("Задачи к исполнению")
+ }
+
+ // Общие кнопки — всегда внизу
+ kb.Row("❓ Как создать согласование?")
+ kb.Row("💬 Предложения и пожелания")
+
+ return kb.Build()
+}
+
+// BuildInitiatorSubmenu — подменю для инициатора
+func BuildInitiatorSubmenu() tgbotapi.ReplyKeyboardMarkup {
+ return tgkit.NewReplyKeyboard().
+ Row("➕ Создать согласование").
+ Row("Ранее созданные согласования").
+ Row("← Назад").
+ Build()
+}
+
+// BuildApproverSubmenu — подменю для согласующего
+func BuildApproverSubmenu() tgbotapi.ReplyKeyboardMarkup {
+ return tgkit.NewReplyKeyboard().
+ Row("Принять согласование в работу").
+ Row("Список согласований", "Отложенные согласования").
+ Row("📊 Сформировать отчёт", "Делегировать права").
+ Row("← Назад").
+ Build()
+}
+
+// BuildObserverSubmenu — подменю для наблюдателя
+func BuildObserverSubmenu() tgbotapi.ReplyKeyboardMarkup {
+ return tgkit.NewReplyKeyboard().
+ Row("Наблюдать за согласованием").
+ Row("📊 Сформировать отчёт").
+ Row("← Назад").
+ Build()
+}
+
+func BuildFilterSubmenu(withAddApprover bool) tgbotapi.ReplyKeyboardMarkup {
+ kb := tgkit.NewReplyKeyboard()
+
+ if withAddApprover {
+ kb.Row("Все")
+ kb.Row("Согласованные")
+ kb.Row("Не согласованные")
+ kb.Row("Ожидают согласования")
+ } else {
+ kb.Row("Все", "Согласованные")
+ kb.Row("Не согласованные", "Ожидают согласования")
+ }
+
+ kb.Row("← Назад")
+ return kb.Build()
+}
diff --git a/service/telegram_service/keyboard/misc.go b/service/telegram_service/keyboard/misc.go
new file mode 100644
index 0000000..35e330c
--- /dev/null
+++ b/service/telegram_service/keyboard/misc.go
@@ -0,0 +1,198 @@
+package keyboard
+
+import (
+ "bitrix_balancer_api/core/lib/external/tgkit"
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/telegram_service/approvalflow"
+ "fmt"
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+// ── Выбор согласующего ──────────────────────────────────────────
+
+func BuildApproverSelectionMenu(approvers []*typescore.User, page int) interface{} {
+ const perPage = 8
+ total := len(approvers)
+ totalPages := (total + perPage - 1) / perPage
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages && totalPages > 0 {
+ page = totalPages - 1
+ }
+ start, end := page*perPage, page*perPage+perPage
+ if end > total {
+ end = total
+ }
+
+ kb := tgkit.NewInlineKeyboard()
+ for _, a := range approvers[start:end] {
+ if a.ID == nil || a.FullName == nil {
+ continue
+ }
+ kb.Row(tgkit.Btn(*a.FullName, fmt.Sprintf("select_approver:%d", *a.ID)))
+ }
+ if totalPages > 1 {
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "select_approver_page", "select_approver_noop"))
+ }
+ return kb.Build()
+}
+
+func BuildFirstApproverSelectionMenu(users []*typescore.User, page int) tgbotapi.InlineKeyboardMarkup {
+ const perPage = 8
+ total := len(users)
+ 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 _, u := range users[start:end] {
+ if u.ID == nil || u.FullName == nil {
+ continue
+ }
+ kb.Row(tgkit.Btn(*u.FullName, fmt.Sprintf("first_approver_select:%d", *u.ID)))
+ }
+ if totalPages > 1 {
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "first_approver_page", "first_approver_noop"))
+ }
+ return kb.Build()
+}
+
+// ── Выбор наблюдателей ──────────────────────────────────────────
+
+func BuildObserverSelectionMenu(observers []*typescore.User, selectedIDs []uint64, page int) tgbotapi.InlineKeyboardMarkup {
+ const perPage = 8
+ if len(observers) == 0 {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("✅ Подтвердить без наблюдателей", "obs_select_confirm")).
+ Build()
+ }
+
+ total := len(observers)
+ totalPages := (total + perPage - 1) / perPage
+ if page < 0 {
+ page = 0
+ }
+ if page >= totalPages {
+ page = totalPages - 1
+ }
+ start := page * perPage
+ end := start + perPage
+ if end > total {
+ end = total
+ }
+
+ selected := make(map[uint64]bool, len(selectedIDs))
+ for _, id := range selectedIDs {
+ selected[id] = true
+ }
+
+ kb := tgkit.NewInlineKeyboard()
+ for _, u := range observers[start:end] {
+ if u.ID == nil || u.FullName == nil {
+ continue
+ }
+ label := *u.FullName
+ if selected[*u.ID] {
+ label = "✅ " + label
+ }
+ kb.Row(tgkit.Btn(label, fmt.Sprintf("obs_select_toggle:%d", *u.ID)))
+ }
+ if totalPages > 1 {
+ kb.Rows = append(kb.Rows, buildPageRow(page, totalPages, "obs_select_page", "obs_select_noop"))
+ }
+ confirmLabel := "✅ Подтвердить"
+ if len(selectedIDs) > 0 {
+ confirmLabel = fmt.Sprintf("✅ Подтвердить (%d выбрано)", len(selectedIDs))
+ }
+ kb.Row(tgkit.Btn(confirmLabel, "obs_select_confirm"))
+ return kb.Build()
+}
+
+// ── Наблюдатель ─────────────────────────────────────────────────
+
+func BuildObserverTopicMenu(topics []approvalflow.Topic) interface{} {
+ kb := tgkit.NewInlineKeyboard()
+ for _, t := range topics {
+ kb.Row(tgkit.Btn(t.Name(), fmt.Sprintf("obs_topic:%s", t.Code())))
+ }
+ return kb.Build()
+}
+
+func BuildObserverApprovalList(approvals []*typescore.Approval, initiators map[uint64]*typescore.User, departments map[uint64]*typescore.Department) interface{} {
+ kb := tgkit.NewInlineKeyboard()
+ for _, a := range approvals {
+ if a.ID == nil {
+ continue
+ }
+ label := fmt.Sprintf("#%d", *a.ID)
+ if a.InitiatorID != nil {
+ if u, ok := initiators[*a.InitiatorID]; ok && u.FullName != nil {
+ label += " " + *u.FullName
+ }
+ }
+ if a.DepartmentID != nil {
+ if d, ok := departments[*a.DepartmentID]; ok && d.Name != nil {
+ label += " — " + *d.Name
+ }
+ }
+ kb.Row(tgkit.Btn(label, fmt.Sprintf("obs_approval:%d", *a.ID)))
+ }
+ kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К темам", "obs_back_topics"))
+ return kb.Build()
+}
+
+// ── Отчёты ──────────────────────────────────────────────────────
+
+func BuildReportTypeMenu() interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("📊 Согласования", "report_type_approvals")).
+ Row(tgkit.Btn("📋 Задачи", "report_type_tasks")).
+ Build()
+}
+
+func BuildReportFilterMenu() interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("📅 Указать период", "report_set_dates")).
+ Row(tgkit.Btn("📤 Выгрузить за всё время", "report_all_time")).
+ Build()
+}
+
+func BuildReportDateToMenu() interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("📤 Выгрузить (по сегодня)", "report_generate")).
+ Build()
+}
+
+// ── Доработка ───────────────────────────────────────────────────
+
+func BuildRevisionOptions(approvalID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("✏️ Изменить текст", fmt.Sprintf("revision_edit_text:%d", approvalID))).
+ Row(tgkit.Btn("📎 Добавить файлы", fmt.Sprintf("revision_add_files:%d", approvalID))).
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Отправить на повторное согласование", fmt.Sprintf("revision_resubmit:%d", approvalID))).
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отозвать заявку", fmt.Sprintf("appr_revoke:%d", approvalID))).
+ Build()
+}
+
+func BuildRevisionRejectOptions(approvalID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.Btn("💬 Указать причину", fmt.Sprintf("appr_revision_comment:%d", approvalID))).
+ Row(tgkit.Btn("↩️ Вернуть без комментария", fmt.Sprintf("appr_revision_skip:%d", approvalID))).
+ Build()
+}
+
+func BuildRevisionAttachCancel(approvalID uint64) interface{} {
+ return tgkit.NewInlineKeyboard().
+ Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отмена", fmt.Sprintf("revision_attach_cancel:%d", approvalID))).
+ Build()
+}
diff --git a/service/telegram_service/keyboard/observer.go b/service/telegram_service/keyboard/observer.go
index 505d3d8..7bb207b 100644
--- a/service/telegram_service/keyboard/observer.go
+++ b/service/telegram_service/keyboard/observer.go
@@ -1,58 +1,10 @@
package keyboard
import (
- "bitrix_balancer_api/core/typescore"
- "bitrix_balancer_api/telegram_service/approvalflow"
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
-// BuildObserverTopicMenu — список тем для наблюдателя.
-func BuildObserverTopicMenu(topics []approvalflow.Topic) tgbotapi.InlineKeyboardMarkup {
- var rows [][]tgbotapi.InlineKeyboardButton
- for _, t := range topics {
- btn := tgbotapi.NewInlineKeyboardButtonData(
- t.Name(),
- fmt.Sprintf("obs_topic:%s", t.Code()),
- )
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(btn))
- }
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
-}
-
-// BuildObserverApprovalList — список заявок в теме (ФИО — Отдел).
-func BuildObserverApprovalList(
- approvals []*typescore.Approval,
- initiators map[uint64]*typescore.User,
- departments map[uint64]*typescore.Department,
- topicCode string,
-) tgbotapi.InlineKeyboardMarkup {
- var rows [][]tgbotapi.InlineKeyboardButton
- for _, a := range approvals {
- if a.ID == nil {
- continue
- }
- label := fmt.Sprintf("#%d", *a.ID)
- if a.InitiatorID != nil {
- if u, ok := initiators[*a.InitiatorID]; ok && u.FullName != nil {
- label += " " + *u.FullName
- }
- }
- if a.DepartmentID != nil {
- if d, ok := departments[*a.DepartmentID]; ok && d.Name != nil {
- label += " — " + *d.Name
- }
- }
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(label, fmt.Sprintf("obs_approval:%d", *a.ID)),
- ))
- }
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("🔙 К темам", "obs_back_topics"),
- ))
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
-}
-
// BuildObserverApprovalDetail — карточка заявки с кнопками наблюдателя.
func BuildObserverApprovalDetail(approvalID uint64, topicCode string) tgbotapi.InlineKeyboardMarkup {
return tgbotapi.NewInlineKeyboardMarkup(
diff --git a/service/telegram_service/keyboard/observer_select.go b/service/telegram_service/keyboard/observer_select.go
deleted file mode 100644
index 193e511..0000000
--- a/service/telegram_service/keyboard/observer_select.go
+++ /dev/null
@@ -1,96 +0,0 @@
-package keyboard
-
-import (
- "bitrix_balancer_api/core/typescore"
- "fmt"
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
-)
-
-const observerSelectionPerPage = 8
-
-func BuildObserverSelectionMenu(
- observers []*typescore.User,
- selectedIDs []uint64,
- page int,
-) tgbotapi.InlineKeyboardMarkup {
- total := len(observers)
- if total == 0 {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("✅ Подтвердить без наблюдателей", "obs_select_confirm"),
- ),
- )
- }
-
- totalPages := (total + observerSelectionPerPage - 1) / observerSelectionPerPage
- if page < 0 {
- page = 0
- }
- if page >= totalPages {
- page = totalPages - 1
- }
-
- start := page * observerSelectionPerPage
- end := min(start+observerSelectionPerPage, total)
-
- // Множество выбранных для быстрой проверки
- selectedSet := make(map[uint64]bool, len(selectedIDs))
- for _, id := range selectedIDs {
- selectedSet[id] = true
- }
-
- var rows [][]tgbotapi.InlineKeyboardButton
-
- for _, u := range observers[start:end] {
- if u.ID == nil || u.FullName == nil {
- continue
- }
-
- label := *u.FullName
- if selectedSet[*u.ID] {
- label = "✅ " + label
- }
-
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(label, fmt.Sprintf("obs_select_toggle:%d", *u.ID)),
- ))
- }
-
- // Навигация
- if totalPages > 1 {
- var navRow []tgbotapi.InlineKeyboardButton
- if page > 0 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "← Назад", fmt.Sprintf("obs_select_page:%d", page-1),
- ))
- }
- pageBtn := tgbotapi.NewInlineKeyboardButtonData(
- fmt.Sprintf("%d / %d", page+1, totalPages), "obs_select_noop",
- )
- navRow = append(navRow, pageBtn)
- if page < totalPages-1 {
- navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData(
- "→ Вперёд", fmt.Sprintf("obs_select_page:%d", page+1),
- ))
- }
- rows = append(rows, navRow)
- }
-
- // Кнопка подтверждения
- confirmLabel := "✅ Подтвердить"
- if len(selectedIDs) > 0 {
- confirmLabel = fmt.Sprintf("✅ Подтвердить (%d выбрано)", len(selectedIDs))
- }
- rows = append(rows, tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(confirmLabel, "obs_select_confirm"),
- ))
-
- return tgbotapi.NewInlineKeyboardMarkup(rows...)
-}
-
-func min(a, b int) int {
- if a < b {
- return a
- }
- return b
-}
diff --git a/service/telegram_service/keyboard/report.go b/service/telegram_service/keyboard/report.go
deleted file mode 100644
index c9f3428..0000000
--- a/service/telegram_service/keyboard/report.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package keyboard
-
-import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
-
-// BuildReportTypeMenu — выбор типа отчёта (согласования или задачи)
-func BuildReportTypeMenu() tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("📊 Согласования", "report_type_approvals"),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("📋 Задачи", "report_type_tasks"),
- ),
- )
-}
-
-// BuildReportFilterMenu — выбор периода для отчёта
-func BuildReportFilterMenu() tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("📅 Указать период", "report_set_dates"),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("📤 Выгрузить за всё время", "report_all_time"),
- ),
- )
-}
-
-// BuildReportDateToMenu — кнопка для выгрузки по сегодня
-func BuildReportDateToMenu() tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData("📤 Выгрузить (по сегодня)", "report_generate"),
- ),
- )
-}
diff --git a/service/telegram_service/keyboard/revision.go b/service/telegram_service/keyboard/revision.go
deleted file mode 100644
index d2812b6..0000000
--- a/service/telegram_service/keyboard/revision.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package keyboard
-
-import (
- "fmt"
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
-)
-
-func BuildRevisionOptions(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "✏️ Изменить текст",
- fmt.Sprintf("revision_edit_text:%d", approvalID),
- ),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "📎 Добавить файлы",
- fmt.Sprintf("revision_add_files:%d", approvalID),
- ),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "✅ Отправить на повторное согласование",
- fmt.Sprintf("revision_resubmit:%d", approvalID),
- ),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "🗑 Отозвать заявку",
- fmt.Sprintf("appr_revoke:%d", approvalID),
- ),
- ),
- )
-}
-
-// BuildRevisionRejectOptions — варианты при нажатии "Вернуть на доработку"
-func BuildRevisionRejectOptions(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "💬 Указать причину",
- fmt.Sprintf("appr_revision_comment:%d", approvalID),
- ),
- ),
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "↩️ Вернуть без комментария",
- fmt.Sprintf("appr_revision_skip:%d", approvalID),
- ),
- ),
- )
-}
-
-func BuildRevisionAttachCancel(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
- return tgbotapi.NewInlineKeyboardMarkup(
- tgbotapi.NewInlineKeyboardRow(
- tgbotapi.NewInlineKeyboardButtonData(
- "❌ Отмена",
- fmt.Sprintf("revision_attach_cancel:%d", approvalID),
- ),
- ),
- )
-}