ruspet_portal_back/service/telegram_service/common/update/update.go

272 lines
8.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package tgupdatehandler
import (
"context"
"fmt"
"strings"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
)
func (s *UpdateHandler) GetUpdateTelegram() {
bot := s.ipc.TGBotClient.Bot()
u := tgbotapi.NewUpdate(0)
u.Timeout = 10
updates := bot.GetUpdatesChan(u)
logrus.Info("🟢 Telegram Bot запущен. Ожидание обновлений...")
for update := range updates {
if update.Message != nil {
go s.handleMessage(bot, update.Message)
continue
}
if update.CallbackQuery != nil {
go s.handleCallback(bot, update.CallbackQuery)
continue
}
}
}
func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) {
ctx := context.Background()
if msg.IsCommand() {
switch msg.Command() {
case "start":
s.startHandler.Handle(bot, msg)
case "approvals":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleMenu(bot, msg.Chat.ID, msg.From.ID)
})
}
return
}
// Постоянные кнопки меню
switch msg.Text {
// ═══════════════════════════════════════════════════════════
// ГЛАВНОЕ МЕНЮ
// ═══════════════════════════════════════════════════════════
case "Согласование":
s.withDepartmentCheck(bot, msg, func() {
// Открываем подменю согласований
s.approvalHandler.HandleApprovalsSubmenu(bot, msg.Chat.ID, msg.From.ID)
})
return
case "Мои заявки":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleMyApprovals(bot, msg.Chat.ID, msg.From.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
}
isApprover, _ := s.ipc.Database.User.IsApproverDB(ctx, *user.ID)
if !isApprover {
return // молчим — кнопки нет в его клавиатуре
}
s.approvalHandler.HandleIncomingApprovals(bot, msg.Chat.ID, msg.From.ID)
})
return
case "Отложенные":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandlePendingCommentsList(bot, msg.Chat.ID, msg.From.ID)
})
return
case "❓ Как создать согласование":
s.withDepartmentCheck(bot, msg, func() {
s.faqHandler.Handle(bot, msg)
})
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 "Сформировать отчёт":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleReportMenu(bot, msg.Chat.ID, msg.From.ID)
})
return
case "Делегирование прав":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleDelegationMainMenu(bot, msg.Chat.ID, msg.From.ID)
})
return
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 "Мои задачи":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleMyTasks(bot, msg.Chat.ID, msg.From.ID)
})
return
// ═══════════════════════════════════════════════════════════
// ПОДМЕНЮ "СПИСОК СОГЛАСОВАНИЙ"
// ═══════════════════════════════════════════════════════════
case "Все":
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleMyApprovalsByStatus(bot, msg.Chat.ID, msg.From.ID, "all")
})
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 "Предложения и пожелания":
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)
})
return
}
revisionKey := fmt.Sprintf("appr_revision_pending:%d", msg.From.ID)
if val, err := s.ipc.RedisClient.Get(ctx, revisionKey); err == nil && val != "" {
var approvalID uint64
fmt.Sscanf(val, "%d", &approvalID)
s.ipc.RedisClient.Del(ctx, revisionKey) //nolint:errcheck
s.approvalHandler.HandleRevisionWithComment(bot, msg.Chat.ID, msg.From.ID, approvalID, strings.TrimSpace(msg.Text))
return
}
// Обработка текста/файлов инициатором при доработке
if s.approvalHandler.HandleRevisionTextInput(bot, msg) {
return
}
if s.approvalHandler.HandleRevisionFileInput(bot, msg) {
return
}
// Обработка pending состояний
if s.approvalHandler.HandlePendingCommentInput(bot, msg) {
return
}
if s.approvalHandler.HandleReportTextInput(bot, msg) {
return
}
if s.startHandler.HandleTextInput(bot, msg) {
return
}
if s.approvalHandler.HandleCommentTextInput(bot, msg) {
return
}
// Проверяем состояние предложения
if s.suggestionHandler.HandleSuggestionTextInput(bot, msg) {
return
}
// Проверка pending состояния для отказа
rejectKey := fmt.Sprintf("appr_reject_pending:%d", msg.From.ID)
if val, err := s.ipc.RedisClient.Get(ctx, rejectKey); err == nil && val != "" {
var approvalID uint64
fmt.Sscanf(val, "%d", &approvalID)
s.ipc.RedisClient.Del(ctx, rejectKey) //nolint:errcheck
s.approvalHandler.HandleDecisionWithChat(bot, msg.Chat.ID, approvalID, false, strings.TrimSpace(msg.Text))
return
}
if s.approvalHandler.HandleRevisionFileInput(bot, msg) {
return
}
if s.approvalHandler.HandleAttachFileInput(bot, msg) {
return
}
if msg.Photo != nil || msg.Document != nil {
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleFileInput(bot, msg)
})
return
}
if s.approvalHandler.HandleDelegationDateInput(bot, msg) {
return
}
if s.approvalHandler.HandleDelegationExtendInput(bot, msg) {
return
}
// Обработка файлов
if msg.Photo != nil || msg.Document != nil {
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleFileInput(bot, msg)
})
return
}
// Обработка текстового ввода
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleTextInput(bot, msg)
})
}
// withDepartmentCheck блокирует действие если отдел не назначен.
func (s *UpdateHandler) withDepartmentCheck(bot *tgbotapi.BotAPI, msg *tgbotapi.Message, action func()) {
ctx := context.Background()
user, err := s.ipc.Database.User.GetUserByTelegramIDDB(ctx, msg.From.ID)
if err != nil || user == nil || user.DepartmentID == nil {
return // молчим — бот пуст
}
action()
}