diff --git a/core/db/db_migration/tables/suggestion_messages.go b/core/db/db_migration/tables/suggestion_messages.go
index ed424bc..f7bac16 100644
--- a/core/db/db_migration/tables/suggestion_messages.go
+++ b/core/db/db_migration/tables/suggestion_messages.go
@@ -6,9 +6,9 @@ import (
)
func SuggestionMessagesTableMigrate(db *gorm.DB) error {
- hasTable := db.Migrator().HasTable(&LocalSuggestionProvider{})
+ hasTable := db.Migrator().HasTable(&LocalSuggestionMessagesProvider{})
- if err := db.AutoMigrate(&LocalSuggestionProvider{}); err != nil {
+ if err := db.AutoMigrate(&LocalSuggestionMessagesProvider{}); err != nil {
return err
}
diff --git a/service/telegram_service/common/update/0_init.go b/service/telegram_service/common/update/0_init.go
index e0f84b4..67caa75 100644
--- a/service/telegram_service/common/update/0_init.go
+++ b/service/telegram_service/common/update/0_init.go
@@ -5,6 +5,7 @@ import (
"bitrix_balancer_api/telegram_service/handlers/approval"
"bitrix_balancer_api/telegram_service/handlers/faq"
"bitrix_balancer_api/telegram_service/handlers/start"
+ "bitrix_balancer_api/telegram_service/handlers/suggestion"
"bitrix_balancer_api/telegram_service/types"
"context"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
@@ -14,10 +15,11 @@ import (
)
type UpdateHandler struct {
- ipc *types.InternalProviderControl
- approvalHandler *approval.Handler
- startHandler *start.Handler
- faqHandler *faq.HandlerFAQ
+ ipc *types.InternalProviderControl
+ approvalHandler *approval.Handler
+ startHandler *start.Handler
+ suggestionHandler *suggestion.Handler
+ faqHandler *faq.HandlerFAQ
}
func NewUpdateHandler(ipc *types.InternalProviderControl) *UpdateHandler {
@@ -29,10 +31,11 @@ func NewUpdateHandler(ipc *types.InternalProviderControl) *UpdateHandler {
approvalHandler := approval.NewHandler(ipc)
handler := &UpdateHandler{
- ipc: ipc,
- approvalHandler: approvalHandler,
- startHandler: start.NewHandler(ipc, approvalHandler),
- faqHandler: faq.NewHandler(ipc),
+ ipc: ipc,
+ approvalHandler: approvalHandler,
+ suggestionHandler: suggestion.NewHandler(ipc),
+ startHandler: start.NewHandler(ipc, approvalHandler),
+ faqHandler: faq.NewHandler(ipc),
}
// TODO: вызывается только после обновлений
diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go
index 153bf8f..3547626 100644
--- a/service/telegram_service/common/update/callback.go
+++ b/service/telegram_service/common/update/callback.go
@@ -317,6 +317,15 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
case data == "report_generate":
s.approvalHandler.HandleReportGenerate(bot, cq)
+ // ПРЕДЛОЖЕНИЯ И ПОЖЕЛАНИЯ
+ case strings.HasPrefix(data, "sugg_reply:"):
+ suggestionID := parseID(data, "sugg_reply:")
+ s.suggestionHandler.HandleReplyToSuggestion(bot, cq, suggestionID)
+
+ case strings.HasPrefix(data, "sugg_view:"):
+ suggestionID := parseID(data, "sugg_view:")
+ s.suggestionHandler.HandleViewSuggestion(bot, cq, suggestionID)
+
// КОММЕНТАРИИ К СОГЛАСОВАНИЯМ
case strings.HasPrefix(data, "appr_comment:"):
approvalID := parseID(data, "appr_comment:")
diff --git a/service/telegram_service/common/update/update.go b/service/telegram_service/common/update/update.go
index cfedd03..c875588 100644
--- a/service/telegram_service/common/update/update.go
+++ b/service/telegram_service/common/update/update.go
@@ -163,6 +163,11 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag
})
return
+ case "Предложения и пожелания":
+ s.withDepartmentCheck(bot, msg, func() {
+ s.suggestionHandler.HandleCreateSuggestion(bot, msg.Chat.ID, msg.From.ID)
+ })
+ return
// ═══════════════════════════════════════════════════════════
// НАВИГАЦИЯ "НАЗАД"
// ═══════════════════════════════════════════════════════════
@@ -186,6 +191,10 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag
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)
diff --git a/service/telegram_service/handlers/suggestion/handler.go b/service/telegram_service/handlers/suggestion/handler.go
new file mode 100644
index 0000000..5e8796a
--- /dev/null
+++ b/service/telegram_service/handlers/suggestion/handler.go
@@ -0,0 +1,345 @@
+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, "💡 Новое предложение/пожелание\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 || suggestionState == nil {
+ return false
+ }
+
+ user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || user == nil || user.ID == nil {
+ 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:
+ 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 || len(directors) == 0 {
+ sendText(bot, chatID, "⚠️ Директор не найден в системе.")
+ h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck
+ return true
+ }
+
+ director := directors[0] // Берем первого директора
+
+ // Создаем предложение
+ 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
+ }
+
+ // Обновляем state
+ suggestionState := &state.SuggestionFlowState{
+ SuggestionID: *created.ID,
+ Stage: "await_message",
+ }
+ h.States.SetSuggestionFlow(ctx, telegramID, suggestionState) //nolint:errcheck
+
+ sendText(bot, chatID, "✅ Тема сохранена.\n\nТеперь введите ваше предложение или прикрепите файл:")
+
+ 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
+ }
+
+ sendText(bot, chatID, "✅ Ваше сообщение отправлено директору.")
+
+ // Уведомляем директора
+ if suggestion.DirectorID != nil {
+ director, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.DirectorID)
+ if director != nil && director.TelegramID != nil {
+ h.notifyAboutMessage(bot, ctx, *director.TelegramID, suggestion, user, messageText, fileData, fileName, true)
+ }
+ }
+
+ 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
+ }
+
+ if *user.ID != *suggestion.InitiatorID && *user.ID != *suggestion.DirectorID {
+ sendText(bot, chatID, "⚠️ Вы не участник этого диалога.")
+ return
+ }
+
+ // Сохраняем состояние ожидания ответа
+ suggestionState := &state.SuggestionFlowState{
+ SuggestionID: suggestionID,
+ Stage: "await_message",
+ }
+ h.States.SetSuggestionFlow(ctx, telegramID, suggestionState) //nolint:errcheck
+
+ sendText(bot, chatID, "💬 Введите ваш ответ или прикрепите файл:")
+}
+
+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(
+ "💡 Предложение #%d\n\n"+
+ "📋 Тема: %s\n"+
+ "👤 Автор: %s\n\n"+
+ "💬 Переписка:",
+ *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%s (%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"+
+ "📋 Тема: %s\n"+
+ "👤 От: %s\n"+
+ "💬 Сообщение:\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
+}
diff --git a/service/telegram_service/keyboard/builder.go b/service/telegram_service/keyboard/builder.go
index 2148f75..19c748a 100644
--- a/service/telegram_service/keyboard/builder.go
+++ b/service/telegram_service/keyboard/builder.go
@@ -15,6 +15,9 @@ func MainMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
tgbotapi.NewKeyboardButtonRow(
tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Предложения и пожелания"),
+ ),
)
}
@@ -30,6 +33,9 @@ func ExecutorMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
tgbotapi.NewKeyboardButtonRow(
tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Предложения и пожелания"),
+ ),
)
}
@@ -49,6 +55,9 @@ func ApproverExecutorMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
tgbotapi.NewKeyboardButtonRow(
tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Предложения и пожелания"),
+ ),
)
}
@@ -68,6 +77,9 @@ func ObserverExecutorMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
tgbotapi.NewKeyboardButtonRow(
tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Предложения и пожелания"),
+ ),
)
}
@@ -88,6 +100,9 @@ func ApproverObserverExecutorMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
tgbotapi.NewKeyboardButtonRow(
tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Предложения и пожелания"),
+ ),
)
}
@@ -147,6 +162,9 @@ func ObserverMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
tgbotapi.NewKeyboardButtonRow(
tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Предложения и пожелания"),
+ ),
)
}
@@ -164,6 +182,9 @@ func ApproverMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
tgbotapi.NewKeyboardButtonRow(
tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Предложения и пожелания"),
+ ),
)
}
@@ -184,5 +205,8 @@ func ApproverObserverMenuKeyboard() tgbotapi.ReplyKeyboardMarkup {
tgbotapi.NewKeyboardButtonRow(
tgbotapi.NewKeyboardButton("❓ Как создать согласование"),
),
+ tgbotapi.NewKeyboardButtonRow(
+ tgbotapi.NewKeyboardButton("Предложения и пожелания"),
+ ),
)
}
diff --git a/service/telegram_service/state/suggesttion.go b/service/telegram_service/state/suggesttion.go
new file mode 100644
index 0000000..0683eb6
--- /dev/null
+++ b/service/telegram_service/state/suggesttion.go
@@ -0,0 +1,47 @@
+package state
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+type SuggestionFlowState struct {
+ SuggestionID uint64 `json:"suggestion_id,omitempty"`
+ Stage string `json:"stage"` // "await_subject", "await_message", "await_file"
+}
+
+func (s *StateManager) SetSuggestionFlow(ctx context.Context, telegramID int64, state *SuggestionFlowState) error {
+ key := fmt.Sprintf("suggestion_flow:%d", telegramID)
+ data, err := json.Marshal(state)
+ if err != nil {
+ return err
+ }
+ return s.redis.Set(ctx, key, data, 30*time.Minute)
+}
+
+func (s *StateManager) GetSuggestionFlow(ctx context.Context, telegramID int64) (*SuggestionFlowState, error) {
+ key := fmt.Sprintf("suggestion_flow:%d", telegramID)
+ data, err := s.redis.Get(ctx, key)
+ if errors.Is(err, redis.Nil) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ var state SuggestionFlowState
+ if err := json.Unmarshal([]byte(data), &state); err != nil {
+ return nil, err
+ }
+ return &state, nil
+}
+
+func (s *StateManager) ClearSuggestionFlow(ctx context.Context, telegramID int64) error {
+ key := fmt.Sprintf("suggestion_flow:%d", telegramID)
+ return s.redis.Del(ctx, key)
+}