From dca05525302b26eb9d380c98330b5b834a9d3484 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Wed, 14 Oct 2026 14:26:04 +0300 Subject: [PATCH] Updated comment flow --- .../common/update/callback.go | 14 + .../handlers/approval/handler_comment.go | 286 +++++++++++++++--- .../handlers/approval/helper.go | 6 + service/telegram_service/keyboard/approval.go | 31 ++ service/telegram_service/state/comment.go | 6 +- 5 files changed, 301 insertions(+), 42 deletions(-) diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go index 283b43e..3fe3d51 100644 --- a/service/telegram_service/common/update/callback.go +++ b/service/telegram_service/common/update/callback.go @@ -460,6 +460,20 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba s.suggestionHandler.HandleViewSuggestion(bot, cq, suggestionID) // КОММЕНТАРИИ К СОГЛАСОВАНИЯМ + case strings.HasPrefix(data, "comment_vis:"): + action := strings.TrimPrefix(data, "comment_vis:") + s.approvalHandler.HandleCommentVisibilityCallback(bot, cq, action) + + case strings.HasPrefix(data, "comment_tgt:"): + targetIDStr := strings.TrimPrefix(data, "comment_tgt:") + s.approvalHandler.HandleCommentTargetToggle(bot, cq, targetIDStr) + + case data == "comment_tgt_done": + s.approvalHandler.HandleCommentTargetDone(bot, cq) + + case data == "comment_tgt_back": + s.approvalHandler.HandleCommentTargetBack(bot, cq) + case strings.HasPrefix(data, "appr_comment:"): approvalID := parseID(data, "appr_comment:") s.approvalHandler.HandleAddCommentCallback(bot, cq, approvalID) diff --git a/service/telegram_service/handlers/approval/handler_comment.go b/service/telegram_service/handlers/approval/handler_comment.go index d108f74..f0022b2 100644 --- a/service/telegram_service/handlers/approval/handler_comment.go +++ b/service/telegram_service/handlers/approval/handler_comment.go @@ -218,48 +218,17 @@ func (h *Handler) HandleCommentTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Mes return false } - user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) - if err != nil || user == nil || user.ID == nil { - return false - } + commentState.Stage = "await_visibility" + commentState.Text = msg.Text + commentState.Targets = make(map[uint64]bool) + h.States.SetCommentFlow(ctx, telegramID, commentState) //nolint:errcheck - approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, commentState.ApprovalID) - if err != nil || approval == nil { - sendText(bot, chatID, "⚠️ Заявка не найдена.") - h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck - return true - } + bot.Request(tgbotapi.NewDeleteMessage(chatID, msg.MessageID)) // Удаляем сообщение с текстом для чистоты - comment := &typescore.ApprovalComment{ - ApprovalID: &commentState.ApprovalID, - UserID: user.ID, - Comment: &msg.Text, - } - - _, _, err = h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment) - if err != nil { - logrus.Errorf("HandleCommentTextInput: CreateApprovalCommentDB err=%v", err) - sendText(bot, chatID, "Ошибка при сохранении комментария.") - h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck - return true - } - - h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck - - userName := "—" - if user.FullName != nil { - userName = *user.FullName - } - - sendText(bot, chatID, fmt.Sprintf( - "✅ Комментарий добавлен\n\n"+ - "📋 Заявка: #%d\n"+ - "👤 Автор: %s\n"+ - "💬 Текст: %s", - commentState.ApprovalID, userName, msg.Text, - )) - - h.notifyAllParticipantsAboutComment(bot, ctx, approval, user, comment, telegramID) + replyMsg := tgbotapi.NewMessage(chatID, "💬 Комментарий сохранен.\n\nВыберите, кому отправить уведомление:") + replyMsg.ParseMode = "HTML" + replyMsg.ReplyMarkup = keyboard.BuildCommentVisibilityMenu() + bot.Send(replyMsg) //nolint:errcheck return true } @@ -488,3 +457,240 @@ func (h *Handler) GetCommentsCount(ctx context.Context, approvalID uint64) int { } return len(comments) } +func (h *Handler) HandleCommentVisibilityCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, action string) { + ctx := context.Background() + telegramID := cq.From.ID + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + if action == "cancel" { + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck + sendText(bot, chatID, "❌ Добавление комментария отменено.") + return + } + + state, err := h.States.GetCommentFlow(ctx, telegramID) + if err != nil || state == nil || state.Stage != "await_visibility" { + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + return + } + + user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, state.ApprovalID) + + // Если выбрали "Конкретным" -> показываем меню мультиселекта + if action == "specific" { + state.Stage = "await_targets" + h.States.SetCommentFlow(ctx, telegramID, state) //nolint:errcheck + + participants := h.getFilteredParticipants(ctx, approval, user) + editMsg := tgbotapi.NewEditMessageTextAndMarkup(chatID, cq.Message.MessageID, + "👤 Выберите, кого нужно уведомить:", + keyboard.BuildCommentTargetsMenu(participants, state.Targets), + ) + editMsg.ParseMode = "HTML" + bot.Request(editMsg) //nolint:errcheck + return + } + + // ─── Если "Всем" или "Без пушей" ─── + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + // Создаем коммент в базе + comment := &typescore.ApprovalComment{ + ApprovalID: &state.ApprovalID, + UserID: user.ID, + Comment: &state.Text, + } + h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment) //nolint:errcheck + + userName := "—" + if user.FullName != nil { + userName = *user.FullName + } + + statusText := "оставлен как дополнение" + if action == "all" { + statusText = "отправлен всем участникам" + h.notifyAllParticipantsAboutComment(bot, ctx, approval, user, comment, telegramID) + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Комментарий %s\n\n"+ + "📋 Заявка: #%d\n"+ + "👤 Автор: %s\n"+ + "💬 Текст: %s", + statusText, state.ApprovalID, userName, state.Text, + )) + + h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck +} + +func (h *Handler) HandleCommentTargetToggle(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, targetIDStr string) { + ctx := context.Background() + telegramID := cq.From.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + state, err := h.States.GetCommentFlow(ctx, telegramID) + if err != nil || state == nil || state.Stage != "await_targets" { + return + } + + targetID := parseID("id:"+targetIDStr, "id:") // Используем вашу функцию parseID + if state.Targets == nil { + state.Targets = make(map[uint64]bool) + } + + if state.Targets[targetID] { + delete(state.Targets, targetID) + } else { + state.Targets[targetID] = true + } + + h.States.SetCommentFlow(ctx, telegramID, state) //nolint:errcheck + + user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, state.ApprovalID) + participants := h.getFilteredParticipants(ctx, approval, user) + + edit := tgbotapi.NewEditMessageReplyMarkup(cq.Message.Chat.ID, cq.Message.MessageID, + keyboard.BuildCommentTargetsMenu(participants, state.Targets), + ) + bot.Request(edit) //nolint:errcheck +} + +func (h *Handler) HandleCommentTargetDone(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + ctx := context.Background() + telegramID := cq.From.ID + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + state, err := h.States.GetCommentFlow(ctx, telegramID) + if err != nil || state == nil || state.Stage != "await_targets" { + return + } + + if len(state.Targets) == 0 { + sendText(bot, chatID, "⚠️ Вы не выбрали ни одного участника. Выберите хотя бы одного или нажмите «Назад».") + return + } + + bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck + + user, _ := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID) + approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, state.ApprovalID) + + // Записываем комментарий + comment := &typescore.ApprovalComment{ + ApprovalID: &state.ApprovalID, + UserID: user.ID, + Comment: &state.Text, + } + h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment) //nolint:errcheck + + userName := "—" + if user.FullName != nil { + userName = *user.FullName + } + + sendText(bot, chatID, fmt.Sprintf( + "✅ Комментарий отправлен выбранным участникам\n\n"+ + "📋 Заявка: #%d\n"+ + "👤 Автор: %s\n"+ + "💬 Текст: %s", + state.ApprovalID, userName, state.Text, + )) + + h.notifySpecificParticipantsAboutComment(bot, ctx, approval, user, comment, state.Targets) + + h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck +} + +func (h *Handler) HandleCommentTargetBack(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) { + ctx := context.Background() + telegramID := cq.From.ID + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + state, err := h.States.GetCommentFlow(ctx, telegramID) + if err == nil && state != nil { + state.Stage = "await_visibility" + h.States.SetCommentFlow(ctx, telegramID, state) //nolint:errcheck + + msg := tgbotapi.NewEditMessageTextAndMarkup(cq.Message.Chat.ID, cq.Message.MessageID, + "💬 Комментарий сохранен.\n\nВыберите, кому отправить уведомление:", + keyboard.BuildCommentVisibilityMenu()) + msg.ParseMode = "HTML" + bot.Request(msg) //nolint:errcheck + } +} + +// ── Вспомогательные функции ── + +// getFilteredParticipants возвращает участников чата заявки, исключая самого комментатора +func (h *Handler) getFilteredParticipants(ctx context.Context, approval *typescore.Approval, excludeUser *typescore.User) []*typescore.User { + all := h.getChatParticipants(ctx, approval) + var filtered []*typescore.User + for _, u := range all { + if excludeUser != nil && excludeUser.ID != nil && u.ID != nil && *u.ID == *excludeUser.ID { + continue // Пропускаем автора + } + filtered = append(filtered, u) + } + return filtered +} + +// notifySpecificParticipantsAboutComment рассылает комментарий только тем, чьи ID есть в мапе targets +func (h *Handler) notifySpecificParticipantsAboutComment( + bot *tgbotapi.BotAPI, + ctx context.Context, + approval *typescore.Approval, + commenter *typescore.User, + comment *typescore.ApprovalComment, + targets map[uint64]bool, +) { + if approval == nil || approval.ID == nil { + return + } + + commenterName := "—" + if commenter != nil && commenter.FullName != nil { + commenterName = *commenter.FullName + } + + topicName := h.getTopicNameByApproval(ctx, approval) + content := "—" + if approval.Content != nil { + content = *approval.Content + } + + text := fmt.Sprintf( + "🔔 Вам отправлен персональный комментарий к заявке #%d\n\n"+ + "📋 Тема: %s\n"+ + "📝 Текст заявки: %s\n\n"+ + "👤 Автор комментария: %s\n"+ + "💬 Комментарий:\n%s", + *approval.ID, topicName, content, commenterName, *comment.Comment, + ) + + commentsCount := h.GetCommentsCount(ctx, *approval.ID) + participants := h.getChatParticipants(ctx, approval) + + for _, u := range participants { + if u.ID == nil || u.TelegramID == nil { + continue + } + if !targets[*u.ID] { // Проверяем, отмечен ли участник + continue + } + msg := tgbotapi.NewMessage(*u.TelegramID, text) + msg.ParseMode = "HTML" + + // Используем клавиатуру для возможности быстро ответить, как и в общей рассылке + msg.ReplyMarkup = keyboard.BuildCommentReplyKeyboard(*approval.ID, commentsCount) + bot.Send(msg) //nolint:errcheck + } +} diff --git a/service/telegram_service/handlers/approval/helper.go b/service/telegram_service/handlers/approval/helper.go index ecdfaa6..8c8410f 100644 --- a/service/telegram_service/handlers/approval/helper.go +++ b/service/telegram_service/handlers/approval/helper.go @@ -846,3 +846,9 @@ func (h *Handler) findStepForCurrentApprover(ctx context.Context, approvalID uin return nil } + +func parseID(data, prefix string) uint64 { + var id uint64 + fmt.Sscanf(strings.TrimPrefix(data, prefix), "%d", &id) + return id +} diff --git a/service/telegram_service/keyboard/approval.go b/service/telegram_service/keyboard/approval.go index 0aa25b0..66963de 100644 --- a/service/telegram_service/keyboard/approval.go +++ b/service/telegram_service/keyboard/approval.go @@ -2,6 +2,7 @@ package keyboard import ( "bitrix_balancer_api/core/lib/external/tgkit" + "bitrix_balancer_api/core/typescore" "bitrix_balancer_api/core/utilscore" "bitrix_balancer_api/telegram_service/approvalflow" "bitrix_balancer_api/telegram_service/state" @@ -360,3 +361,33 @@ func BuildExecutorTaskActions(taskID, approvalID uint64, filesCount int, comment return kb.Build() } + +func BuildCommentVisibilityMenu() tgbotapi.InlineKeyboardMarkup { + return tgkit.NewInlineKeyboard(). + Row(tgkit.Btn("📢 Отправить всем участникам", "comment_vis:all")). + Row(tgkit.Btn("👤 Выбрать конкретных", "comment_vis:specific")). + Row(tgkit.Btn("🔇 Просто дополнение (без уведомлений)", "comment_vis:silent")). + Row(tgkit.BtnStyled(tgkit.ButtonStyleDanger, "Отмена", "comment_vis:cancel")). + Build() +} + +func BuildCommentTargetsMenu(participants []*typescore.User, selected map[uint64]bool) tgbotapi.InlineKeyboardMarkup { + kb := tgkit.NewInlineKeyboard() + + for _, p := range participants { + if p.ID == nil || p.FullName == nil { + continue + } + label := *p.FullName + if selected[*p.ID] { + label = "✅ " + label + } else { + label = "⬜ " + label + } + kb.Row(tgkit.Btn(label, fmt.Sprintf("comment_tgt:%d", *p.ID))) + } + + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "✅ Отправить выбранным", "comment_tgt_done")) + kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "← Назад", "comment_tgt_back")) + return kb.Build() +} diff --git a/service/telegram_service/state/comment.go b/service/telegram_service/state/comment.go index 393f06d..c138017 100644 --- a/service/telegram_service/state/comment.go +++ b/service/telegram_service/state/comment.go @@ -11,8 +11,10 @@ import ( ) type CommentFlowState struct { - ApprovalID uint64 `json:"approval_id"` - Stage string `json:"stage"` // "await_text" + ApprovalID uint64 `json:"approval_id"` + Stage string `json:"stage"` // "await_text", "await_visibility", "await_targets" + Text string `json:"text"` + Targets map[uint64]bool `json:"targets"` } type CommentReplyState struct { -- 2.43.0