ruspet_portal_back/service/telegram_service/handlers/suggestion/handler.go

451 lines
14 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 suggestion
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/telegram_service/state"
"bitrix_balancer_api/telegram_service/types"
"context"
"encoding/base64"
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
)
type Handler struct {
ipc *types.InternalProviderControl
States *state.StateManager
}
func NewHandler(ipc *types.InternalProviderControl) *Handler {
return &Handler{
ipc: ipc,
States: state.NewStateManager(ipc.RedisClient),
}
}
func (h *Handler) HandleCreateSuggestion(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
ctx := context.Background()
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
if err != nil || user == nil || user.ID == nil {
sendText(bot, chatID, "⚠️ Пользователь не найден.")
return
}
// Сохраняем состояние ожидания темы
suggestionState := &state.SuggestionFlowState{
Stage: "await_subject",
}
h.States.SetSuggestionFlow(ctx, telegramID, suggestionState) //nolint:errcheck
sendText(bot, chatID, "💡 <b>Новое предложение/пожелание</b>\n\nВведите тему предложения:")
}
func (h *Handler) HandleSuggestionTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
ctx := context.Background()
telegramID := msg.From.ID
chatID := msg.Chat.ID
suggestionState, err := h.States.GetSuggestionFlow(ctx, telegramID)
if err != nil {
logrus.Errorf("HandleSuggestionTextInput: GetSuggestionFlow err=%v", err)
return false
}
if suggestionState == nil {
return false
}
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
if err != nil {
logrus.Errorf("HandleSuggestionTextInput: GetUserByTelegramIDDB err=%v", err)
return false
}
if user == nil || user.ID == nil {
logrus.Warnf("HandleSuggestionTextInput: user not found telegramID=%d", telegramID)
return false
}
switch suggestionState.Stage {
case "await_subject":
return h.handleSubjectInput(bot, ctx, chatID, telegramID, user, msg.Text)
case "await_message":
return h.handleMessageInput(bot, ctx, chatID, telegramID, user, suggestionState, msg.Text, nil, nil)
default:
logrus.Warnf("HandleSuggestionTextInput: unknown stage=%s", suggestionState.Stage)
return false
}
}
func (h *Handler) handleSubjectInput(bot *tgbotapi.BotAPI, ctx context.Context, chatID, telegramID int64, user *typescore.User, subject string) bool {
directors, err := h.ipc.Database.User.GetDirectorsDB(ctx)
if err != nil {
logrus.Errorf("handleSubjectInput: GetDirectorsDB err=%v", err)
sendText(bot, chatID, "⚠️ Ошибка при получении списка директоров.")
h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck
return true
}
if len(directors) == 0 {
sendText(bot, chatID, "⚠️ Директор не найден в системе. Обратитесь к администратору.")
h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck
return true
}
// Ищем первого директора с заполненным ID
var director *typescore.User
for _, d := range directors {
if d != nil && d.ID != nil {
director = d
break
}
}
if director == nil {
logrus.Errorf("handleSubjectInput: all directors have nil ID, count=%d", len(directors))
sendText(bot, chatID, "⚠️ Директор не найден в системе. Обратитесь к администратору.")
h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck
return true
}
// Создаем предложение
openStatus := "open"
suggestion := &typescore.Suggestion{
InitiatorID: user.ID,
DirectorID: director.ID,
Subject: &subject,
Status: &openStatus,
}
created, _, err := h.ipc.Database.Suggestion.CreateSuggestionDB(ctx, nil, suggestion, true)
if err != nil {
logrus.Errorf("handleSubjectInput: CreateSuggestionDB err=%v", err)
sendText(bot, chatID, "Ошибка при создании предложения. Попробуйте позже.")
h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck
return true
}
if created == nil || created.ID == nil {
logrus.Errorf("handleSubjectInput: created suggestion is nil or has no ID")
sendText(bot, chatID, "Ошибка при создании предложения. Попробуйте позже.")
h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck
return true
}
// Обновляем state — переходим к вводу текста
suggestionState := &state.SuggestionFlowState{
SuggestionID: *created.ID,
Stage: "await_message",
}
if err := h.States.SetSuggestionFlow(ctx, telegramID, suggestionState); err != nil {
logrus.Errorf("handleSubjectInput: SetSuggestionFlow err=%v", err)
sendText(bot, chatID, "Ошибка при сохранении состояния. Попробуйте позже.")
return true
}
directorName := "директору"
if director.FullName != nil {
directorName = *director.FullName
}
sendText(bot, chatID, fmt.Sprintf(
"✅ <b>Тема сохранена</b>\n\n"+
"📋 <b>Тема:</b> %s\n"+
"👤 <b>Получатель:</b> %s\n\n"+
"Теперь введите текст предложения или прикрепите файл:",
subject, directorName,
))
return true
}
func (h *Handler) handleMessageInput(
bot *tgbotapi.BotAPI,
ctx context.Context,
chatID, telegramID int64,
user *typescore.User,
suggestionState *state.SuggestionFlowState,
messageText string,
fileData, fileName *string,
) bool {
message := &typescore.SuggestionMessage{
SuggestionID: &suggestionState.SuggestionID,
UserID: user.ID,
Message: &messageText,
FileData: fileData,
FileName: fileName,
}
_, _, err := h.ipc.Database.SuggestionMessage.CreateSuggestionMessageDB(ctx, nil, message)
if err != nil {
logrus.Errorf("handleMessageInput: CreateSuggestionMessageDB err=%v", err)
sendText(bot, chatID, "Ошибка при отправке сообщения.")
return true
}
suggestion, err := h.ipc.Database.Suggestion.GetSuggestionByIDDB(ctx, suggestionState.SuggestionID)
if err != nil || suggestion == nil {
logrus.Errorf("handleMessageInput: GetSuggestionByIDDB err=%v", err)
return true
}
if suggestion.InitiatorID == nil || suggestion.DirectorID == nil || user.ID == nil {
logrus.Errorf("handleMessageInput: suggestion participants are nil")
return true
}
sendText(bot, chatID, "✅ Ваше сообщение отправлено.")
var recipientID uint64
if *user.ID == *suggestion.InitiatorID {
recipientID = *suggestion.DirectorID
} else {
recipientID = *suggestion.InitiatorID
}
recipient, err := h.ipc.Database.User.GetUserByIDDB(ctx, recipientID)
if err != nil || recipient == nil {
logrus.Errorf("handleMessageInput: GetUserByIDDB recipient err=%v", err)
h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck
return true
}
if recipient.TelegramID != nil {
isNew := suggestionState.Stage == "await_subject" // первое сообщение
h.notifyAboutMessage(bot, ctx, *recipient.TelegramID, suggestion, user, messageText, fileData, fileName, isNew)
}
h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck
return true
}
func (h *Handler) HandleReplyToSuggestion(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, suggestionID uint64) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
telegramID := cq.From.ID
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
if err != nil || user == nil || user.ID == nil {
sendText(bot, chatID, "⚠️ Пользователь не найден.")
return
}
suggestion, err := h.ipc.Database.Suggestion.GetSuggestionByIDDB(ctx, suggestionID)
if err != nil || suggestion == nil {
sendText(bot, chatID, "⚠️ Предложение не найдено.")
return
}
if suggestion.InitiatorID == nil || suggestion.DirectorID == nil {
sendText(bot, chatID, "⚠️ Ошибка данных предложения.")
return
}
// Проверяем что пользователь - участник диалога
isInitiator := *user.ID == *suggestion.InitiatorID
isDirector := *user.ID == *suggestion.DirectorID
if !isInitiator && !isDirector {
sendText(bot, chatID, "⚠️ Вы не участник этого диалога.")
return
}
suggestionState := &state.SuggestionFlowState{
SuggestionID: suggestionID,
Stage: "await_message",
}
h.States.SetSuggestionFlow(ctx, telegramID, suggestionState) //nolint:errcheck
// Показываем кому пойдёт ответ
var recipientName string
if isInitiator {
director, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.DirectorID)
if director != nil && director.FullName != nil {
recipientName = *director.FullName
}
} else {
initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.InitiatorID)
if initiator != nil && initiator.FullName != nil {
recipientName = *initiator.FullName
}
}
subject := "—"
if suggestion.Subject != nil {
subject = *suggestion.Subject
}
sendText(bot, chatID, fmt.Sprintf(
"💬 <b>Ответить на предложение #%d</b>\n"+
"📋 Тема: %s\n"+
"➡️ Получатель: %s\n\n"+
"Введите текст или прикрепите файл:",
suggestionID, subject, recipientName,
))
}
func (h *Handler) HandleViewSuggestion(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, suggestionID uint64) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
telegramID := cq.From.ID
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
if err != nil || user == nil || user.ID == nil {
return
}
suggestion, err := h.ipc.Database.Suggestion.GetSuggestionByIDDB(ctx, suggestionID)
if err != nil || suggestion == nil {
sendText(bot, chatID, "⚠️ Предложение не найдено.")
return
}
h.showSuggestionThread(bot, ctx, chatID, suggestion)
}
func (h *Handler) showSuggestionThread(bot *tgbotapi.BotAPI, ctx context.Context, chatID int64, suggestion *typescore.Suggestion) {
if suggestion.ID == nil {
return
}
messages, _, err := h.ipc.Database.SuggestionMessage.GetSuggestionMessagesListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.SuggestionMessage{
SuggestionID: suggestion.ID,
},
})
if err != nil {
logrus.Errorf("showSuggestionThread: GetMessagesBySuggestionIDDB err=%v", err)
return
}
subject := "—"
if suggestion.Subject != nil {
subject = *suggestion.Subject
}
initiatorName := "—"
if suggestion.InitiatorID != nil {
initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.InitiatorID)
if initiator != nil && initiator.FullName != nil {
initiatorName = *initiator.FullName
}
}
text := fmt.Sprintf(
"💡 <b>Предложение #%d</b>\n\n"+
"📋 <b>Тема:</b> %s\n"+
"👤 <b>Автор:</b> %s\n\n"+
"💬 <b>Переписка:</b>",
*suggestion.ID, subject, initiatorName,
)
for _, msg := range messages {
if msg.UserID == nil || msg.Message == nil {
continue
}
user, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *msg.UserID)
userName := "—"
if user != nil && user.FullName != nil {
userName = *user.FullName
}
timestamp := ""
if msg.CreatedAt != nil {
timestamp = msg.CreatedAt.Format("02.01.2006 15:04")
}
text += fmt.Sprintf("\n\n<b>%s</b> (%s):\n%s", userName, timestamp, *msg.Message)
if msg.FileData != nil && msg.FileName != nil {
text += fmt.Sprintf("\n📎 %s", *msg.FileName)
}
}
message := tgbotapi.NewMessage(chatID, text)
message.ParseMode = "HTML"
message.ReplyMarkup = buildSuggestionActions(*suggestion.ID)
bot.Send(message) //nolint:errcheck
}
func (h *Handler) notifyAboutMessage(
bot *tgbotapi.BotAPI,
ctx context.Context,
recipientChatID int64,
suggestion *typescore.Suggestion,
sender *typescore.User,
messageText string,
fileData, fileName *string,
isNew bool,
) {
subject := "—"
if suggestion.Subject != nil {
subject = *suggestion.Subject
}
senderName := "—"
if sender.FullName != nil {
senderName = *sender.FullName
}
header := "📬 Новое сообщение"
if isNew {
header = "💡 Новое предложение"
}
text := fmt.Sprintf(
"%s\n\n"+
"📋 <b>Тема:</b> %s\n"+
"👤 <b>От:</b> %s\n"+
"💬 <b>Сообщение:</b>\n%s",
header, subject, senderName, messageText,
)
if fileData != nil && fileName != nil {
// Отправляем файл
decoded, err := base64.StdEncoding.DecodeString(*fileData)
if err != nil {
logrus.Errorf("notifyAboutMessage: base64 decode err=%v", err)
} else {
doc := tgbotapi.NewDocument(recipientChatID, tgbotapi.FileBytes{
Name: *fileName,
Bytes: decoded,
})
doc.Caption = text
doc.ParseMode = "HTML"
doc.ReplyMarkup = buildSuggestionActions(*suggestion.ID)
bot.Send(doc) //nolint:errcheck
return
}
}
msg := tgbotapi.NewMessage(recipientChatID, text)
msg.ParseMode = "HTML"
msg.ReplyMarkup = buildSuggestionActions(*suggestion.ID)
bot.Send(msg) //nolint:errcheck
}
func buildSuggestionActions(suggestionID uint64) tgbotapi.InlineKeyboardMarkup {
return tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("↩️ Ответить", fmt.Sprintf("sugg_reply:%d", suggestionID)),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("👁 Посмотреть всю переписку", fmt.Sprintf("sugg_view:%d", suggestionID)),
),
)
}
func sendText(bot *tgbotapi.BotAPI, chatID int64, text string) {
msg := tgbotapi.NewMessage(chatID, text)
msg.ParseMode = "HTML"
bot.Send(msg) //nolint:errcheck
}