From 71a6b0959c5f224c420fa815fa7d82a7c6491b18 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Tue, 7 Jul 2026 13:11:20 +0300 Subject: [PATCH] Update comment block. Added additional filters for approver && initiator --- core/db/methods/user.go | 85 +++++- core/typescore/role.go | 23 +- .../common/update/callback.go | 8 +- .../handlers/approval/handler_add_approver.go | 8 +- .../handlers/approval/handler_comment.go | 259 ++++++++++++------ .../handlers/approval/handler_decision.go | 45 ++- .../handlers/approval/handler_executor.go | 39 ++- .../handlers/approval/handler_observer.go | 4 +- .../handlers/approval/helper.go | 11 +- .../handlers/approval/list.go | 13 +- .../handlers/approval/notify.go | 103 ++++--- .../handlers/approval/revision.go | 12 +- .../telegram_service/keyboard/add_approver.go | 2 - service/telegram_service/keyboard/approval.go | 28 +- service/telegram_service/keyboard/builder.go | 17 +- service/telegram_service/keyboard/misc.go | 18 +- service/telegram_service/keyboard/observer.go | 13 +- 17 files changed, 512 insertions(+), 176 deletions(-) diff --git a/core/db/methods/user.go b/core/db/methods/user.go index 29e159b..41dcc5a 100644 --- a/core/db/methods/user.go +++ b/core/db/methods/user.go @@ -6,10 +6,10 @@ import ( dbutils "bitrix_balancer_api/core/utilscore/db" "context" "errors" + "github.com/jackc/pgx/v5" "github.com/sirupsen/logrus" "github.com/Masterminds/squirrel" - "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) @@ -40,6 +40,9 @@ type UserDBI interface { GetObserversForApprovalDB(ctx context.Context, categoryCode string, topicID *uint64) ([]*typescore.User, error) GetUsersListByRoleIDsDB(ctx context.Context, opts typescore.ListDbOptions, roleIDs []uint64) ([]*typescore.User, uint64, error) GetUsersByIDsDB(ctx context.Context, ids []uint64) ([]*typescore.User, error) + + IsControllerDB(ctx context.Context, userID uint64) (bool, error) + GetControllerObserversForApprovalDB(ctx context.Context, categoryCode string, topicID *uint64) ([]*typescore.User, error) } func (u *UserDB) GetUsersListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.User, uint64, error) { @@ -609,3 +612,83 @@ func (u *UserDB) GetUsersByIDsDB(ctx context.Context, ids []uint64) ([]*typescor return users, nil } + +// IsControllerDB проверяет, есть ли у пользователя роль наблюдателя с флагом is_controller = true. +func (u *UserDB) IsControllerDB(ctx context.Context, userID uint64) (bool, error) { + sql, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("COUNT(*)"). + From(dbcoretablenames.TableNameUserRoles.ToString() + " ur"). + Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id"). + Where(squirrel.Eq{"ur.user_id": userID}). + Where(squirrel.Eq{"r.is_observer": true}). + Where(squirrel.Eq{"r.is_controller": true}). + ToSql() + if err != nil { + return false, err + } + + var count int + if err := u.pool.QueryRow(ctx, sql, args...).Scan(&count); err != nil { + return false, err + } + return count > 0, nil +} + +// GetControllerObserversForApprovalDB — то же самое, что GetObserversForApprovalDB, +// но только пользователи, у которых роль имеет флаг is_controller = true. +func (u *UserDB) GetControllerObserversForApprovalDB( + ctx context.Context, + categoryCode string, + topicID *uint64, +) ([]*typescore.User, error) { + q := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar). + Select("DISTINCT u.*"). + From(dbcoretablenames.TableNameUsers.ToString() + " u"). + Join(dbcoretablenames.TableNameUserRoles.ToString() + " ur ON ur.user_id = u.id"). + Join(dbcoretablenames.TableNameRoles.ToString() + " r ON r.id = ur.role_id"). + Join(dbcoretablenames.TableNamePermissions.ToString() + " p ON p.role_id = r.id"). + Where(squirrel.Eq{"r.is_observer": true}). + Where(squirrel.Eq{"r.is_controller": true}). + Where(squirrel.Eq{"p.action": "observe"}). + Where(squirrel.Eq{"u.is_blocked": false}) + + if topicID != nil { + q = q.Where(squirrel.Or{ + squirrel.And{ + squirrel.Expr("p.topic_id IS NULL"), + squirrel.Expr( + "p.topic_category_id IN (SELECT id FROM approval_topic_categories WHERE code = ?)", + categoryCode, + ), + }, + squirrel.Eq{"p.topic_id": *topicID}, + }) + } else { + q = q.Join( + dbcoretablenames.TableNameApprovalTopicCategories.ToString() + + " c ON c.id = p.topic_category_id", + ).Where(squirrel.Eq{"c.code": categoryCode}) + } + + sql, args, err := q.ToSql() + if err != nil { + return nil, err + } + + rows, err := u.pool.Query(ctx, sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + var result []*typescore.User + for rows.Next() { + usr := &typescore.User{} + if err := dbutils.ScanRowsToStructRows(rows, usr, nil); err != nil { + logrus.Warn("GetControllerObserversForApprovalDB:ScanRowsToStruct", err) + continue + } + result = append(result, usr) + } + return result, nil +} diff --git a/core/typescore/role.go b/core/typescore/role.go index a9445d6..5a79688 100644 --- a/core/typescore/role.go +++ b/core/typescore/role.go @@ -3,17 +3,18 @@ package typescore import "time" type Role struct { - ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` - Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"` - Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"` - IsDefault *bool `gorm:"type:boolean;not null;default:false;column:is_default" json:"is_default" db:"is_default" mapstructure:"is_default"` - IsDirector *bool `gorm:"type:boolean;not null;default:false;column:is_director" json:"is_director" db:"is_director" mapstructure:"is_director"` - IsApprover *bool `gorm:"type:boolean;not null;default:false;column:is_approver" json:"is_approver" db:"is_approver" mapstructure:"is_approver"` - IsObserver *bool `gorm:"type:boolean;not null;default:false;column:is_observer" json:"is_observer" db:"is_observer" mapstructure:"is_observer"` - IsExecutor *bool `gorm:"type:boolean;not null;default:false;column:is_executor" json:"is_executor" db:"is_executor" mapstructure:"is_executor"` - Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"` - CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` - UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` + ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` + Name *string `gorm:"type:text;not null;column:name" json:"name" db:"name" mapstructure:"name"` + Code *string `gorm:"type:text;not null;unique;column:code" json:"code" db:"code" mapstructure:"code"` + IsDefault *bool `gorm:"type:boolean;not null;default:false;column:is_default" json:"is_default" db:"is_default" mapstructure:"is_default"` + IsDirector *bool `gorm:"type:boolean;not null;default:false;column:is_director" json:"is_director" db:"is_director" mapstructure:"is_director"` + IsApprover *bool `gorm:"type:boolean;not null;default:false;column:is_approver" json:"is_approver" db:"is_approver" mapstructure:"is_approver"` + IsObserver *bool `gorm:"type:boolean;not null;default:false;column:is_observer" json:"is_observer" db:"is_observer" mapstructure:"is_observer"` + IsExecutor *bool `gorm:"type:boolean;not null;default:false;column:is_executor" json:"is_executor" db:"is_executor" mapstructure:"is_executor"` + IsController *bool `gorm:"type:boolean;not null;default:false;column:is_controller" json:"is_controller" db:"is_controller" mapstructure:"is_controller"` + Description *string `gorm:"type:text;column:description" json:"description,omitempty" db:"description" mapstructure:"description"` + CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` + UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"` Permissions []*Permission `gorm:"-" json:"permissions,omitempty"` } diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go index d637a2c..862c4eb 100644 --- a/service/telegram_service/common/update/callback.go +++ b/service/telegram_service/common/update/callback.go @@ -58,10 +58,12 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba s.ipc.RedisClient.Del(ctx, key) //nolint:errcheck bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck bot.Request(tgbotapi.NewDeleteMessage(cq.Message.Chat.ID, cq.Message.MessageID)) //nolint:errcheck + commentsCount := s.approvalHandler.GetCommentsCount(ctx, approvalID) + // Возвращаем меню доработки optMsg := tgbotapi.NewMessage(cq.Message.Chat.ID, fmt.Sprintf("📋 Заявка #%d на доработке:", approvalID)) optMsg.ParseMode = "HTML" - optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(approvalID) + optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(approvalID, commentsCount) bot.Send(optMsg) //nolint:errcheck case strings.HasPrefix(data, "appr_revision:"): @@ -399,6 +401,10 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba approvalID := parseID(data, "comment_reply:") s.approvalHandler.HandleCommentReplyCallback(bot, cq, approvalID) + case strings.HasPrefix(data, "appr_view_comments:"): + approvalID := parseID(data, "appr_view_comments:") + s.approvalHandler.HandleViewCommentsCallback(bot, cq, approvalID) + // ВЫБОР СОГЛАСУЮЩЕГО case strings.HasPrefix(data, "select_approver:"): approverID := parseID(data, "select_approver:") diff --git a/service/telegram_service/handlers/approval/handler_add_approver.go b/service/telegram_service/handlers/approval/handler_add_approver.go index 4800c9b..ceb68cb 100644 --- a/service/telegram_service/handlers/approval/handler_add_approver.go +++ b/service/telegram_service/handlers/approval/handler_add_approver.go @@ -347,15 +347,17 @@ func (h *Handler) HandleAddApproverUserCallback(bot *tgbotapi.BotAPI, cq *tgbota } files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) + commentsSection := h.formatCommentsSection(ctx, addApproverState.ApprovalID, 4) + notifyMsg := tgbotapi.NewMessage(*addedApprover.TelegramID, fmt.Sprintf( "➕ Вас добавили к согласованию заявки #%d\n\n"+ "👤 Инициатор: %s\n"+ "📋 Тема: %s\n"+ - "📝 Текст: %s", - addApproverState.ApprovalID, initiatorName, topicFullName, content, + "📝 Текст: %s%s", + addApproverState.ApprovalID, initiatorName, topicFullName, content, commentsSection, )) notifyMsg.ParseMode = "HTML" - notifyMsg.ReplyMarkup = keyboard.BuildApproverDecision(addApproverState.ApprovalID, status, len(files) > 0, len(files)) + notifyMsg.ReplyMarkup = keyboard.BuildApproverDecision(addApproverState.ApprovalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) bot.Send(notifyMsg) //nolint:errcheck } } diff --git a/service/telegram_service/handlers/approval/handler_comment.go b/service/telegram_service/handlers/approval/handler_comment.go index b1928e4..d108f74 100644 --- a/service/telegram_service/handlers/approval/handler_comment.go +++ b/service/telegram_service/handlers/approval/handler_comment.go @@ -8,6 +8,7 @@ import ( "fmt" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" "github.com/sirupsen/logrus" + "strings" ) func (h *Handler) HandleAddCommentCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { @@ -108,13 +109,21 @@ func (h *Handler) canUserCommentApproval(ctx context.Context, userID uint64, app if err == nil && topic != nil && topic.Code != nil { isObserver, _ := h.ipc.Database.User.IsObserverDB(ctx, userID) if isObserver { - // Проверяем права наблюдателя на эту категорию - observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, *topic.Code, topic.ID) - if observers != nil { - for _, obs := range observers { - if obs.ID != nil && *obs.ID == userID { - return true, nil - } + isFinal := approval.Status != nil && + (*approval.Status == "approved" || *approval.Status == "rejected" || *approval.Status == "revoked") + + var relevant []*typescore.User + if isFinal { + // после завершения — комментировать может любой наблюдатель темы + relevant, _ = h.ipc.Database.User.GetObserversForApprovalDB(ctx, *topic.Code, topic.ID) + } else { + // в процессе — только контролёр + relevant, _ = h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, *topic.Code, topic.ID) + } + + for _, obs := range relevant { + if obs.ID != nil && *obs.ID == userID { + return true, nil } } } @@ -133,7 +142,8 @@ func (h *Handler) canUserCommentApproval(ctx context.Context, userID uint64, app return isDirector, nil } -func (h *Handler) formatCommentsSection(ctx context.Context, approvalID uint64) string { +// formatCommentsSection возвращает секцию с последними limit комментариями. +func (h *Handler) formatCommentsSection(ctx context.Context, approvalID uint64, limit int) string { comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID) if err != nil { logrus.Errorf("formatCommentsSection: GetCommentsByApprovalIDDB err=%v", err) @@ -144,26 +154,25 @@ func (h *Handler) formatCommentsSection(ctx context.Context, approvalID uint64) return "" } - result := "\n\n💬 Комментарии:" + total := len(comments) + if limit > 0 && total > limit { + comments = comments[total-limit:] + } + + header := "\n\n💬 Комментарии:" + if limit > 0 && total > limit { + header = fmt.Sprintf("\n\n💬 Последние %d комментариев (из %d):", limit, total) + } + + result := header for _, comment := range comments { - if comment == nil { - continue - } - - if comment.UserID == nil || comment.Comment == nil { - logrus.Warnf("formatCommentsSection: comment UserID or Comment is nil, commentID=%v", comment.ID) + if comment == nil || comment.UserID == nil || comment.Comment == nil { continue } user, err := h.ipc.Database.User.GetUserByIDDB(ctx, *comment.UserID) - if err != nil { - logrus.Errorf("formatCommentsSection: GetUserByIDDB err=%v", err) - continue - } - - if user == nil { - logrus.Warnf("formatCommentsSection: user is nil for userID=%d", *comment.UserID) + if err != nil || user == nil { continue } @@ -287,71 +296,18 @@ func (h *Handler) notifyAllParticipantsAboutComment( *approval.ID, topicName, content, commenterName, *comment.Comment, ) - // 🚀 Определяем, является ли статус финальным - isFinalStatus := approval.Status != nil && - (*approval.Status == "approved" || *approval.Status == "rejected" || *approval.Status == "revoked") + commentsCount := h.GetCommentsCount(ctx, *approval.ID) - recipients := make(map[int64]bool) - - // Инициатор — всегда получает уведомления о комментариях - if approval.InitiatorID != nil { - initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) - if initiator != nil && initiator.TelegramID != nil && *initiator.TelegramID != skipTelegramID { - recipients[*initiator.TelegramID] = true + participants := h.getChatParticipants(ctx, approval) + for _, u := range participants { + if u.TelegramID == nil || *u.TelegramID == skipTelegramID { + continue } - } - - // Текущий согласующий — всегда получает - activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, *approval.ID) - if activeStep != nil && activeStep.ApproverID != nil { - approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) - if approver != nil && approver.TelegramID != nil && *approver.TelegramID != skipTelegramID { - recipients[*approver.TelegramID] = true - } - } - - // Дополнительные согласующие — всегда получают - additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ - Filtering: &typescore.ApprovalAdditionalApprover{ - ApprovalID: approval.ID, - }, - }) - for _, aa := range additionalApprovers { - if aa.ApproverID != nil { - addApprover, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) - if addApprover != nil && addApprover.TelegramID != nil && *addApprover.TelegramID != skipTelegramID { - recipients[*addApprover.TelegramID] = true - } - } - } - - if isFinalStatus && approval.TopicID != nil { - categoryCode := h.getTopicCodeByApproval(ctx, approval) - if categoryCode != "" { - observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID) - for _, obs := range observers { - if obs.TelegramID != nil && *obs.TelegramID != skipTelegramID { - recipients[*obs.TelegramID] = true - } - } - } - } - - if isFinalStatus { - directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx) - for _, dir := range directors { - if dir.TelegramID != nil && *dir.TelegramID != skipTelegramID { - recipients[*dir.TelegramID] = true - } - } - } - - for telegramID := range recipients { - msg := tgbotapi.NewMessage(telegramID, text) + msg := tgbotapi.NewMessage(*u.TelegramID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildCommentReplyKeyboard(*approval.ID) + msg.ReplyMarkup = keyboard.BuildCommentReplyKeyboard(*approval.ID, commentsCount) if _, err := bot.Send(msg); err != nil { - logrus.Errorf("notifyAllParticipantsAboutComment: Send to %d err=%v", telegramID, err) + logrus.Errorf("notifyAllParticipantsAboutComment: Send to %d err=%v", *u.TelegramID, err) } } } @@ -395,3 +351,140 @@ func (h *Handler) HandleCommentReplyInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Me return true } + +func (h *Handler) HandleViewCommentsCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) { + ctx := context.Background() + chatID := cq.Message.Chat.ID + + bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck + + comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID) + if err != nil { + logrus.Errorf("HandleViewCommentsCallback: GetCommentsByApprovalIDDB err=%v", err) + sendText(bot, chatID, "⚠️ Ошибка при получении комментариев.") + return + } + + if len(comments) == 0 { + sendText(bot, chatID, fmt.Sprintf("📭 По заявке #%d пока нет комментариев.", approvalID)) + return + } + + var sb strings.Builder + sb.WriteString(fmt.Sprintf("💬 Комментарии по заявке #%d (%d):\n", approvalID, len(comments))) + + for _, c := range comments { + if c.UserID == nil || c.Comment == nil { + continue + } + user, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *c.UserID) + name := "—" + if user != nil && user.FullName != nil { + name = *user.FullName + } + timestamp := "—" + if c.CreatedAt != nil { + timestamp = c.CreatedAt.Format("02.01.2006 15:04") + } + sb.WriteString(fmt.Sprintf("\n👤 %s (%s):\n%s\n", name, timestamp, *c.Comment)) + } + + msg := tgbotapi.NewMessage(chatID, sb.String()) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildCommentNotificationKeyboard(approvalID, h.GetCommentsCount(ctx, approvalID)) + bot.Send(msg) //nolint:errcheck +} + +// getChatParticipants собирает всех участников "виртуального чата" заявки: +// инициатор, активный согласующий, доп. согласующие, исполнители, +// наблюдатели категории/темы, доп. наблюдатели. +func (h *Handler) getChatParticipants(ctx context.Context, approval *typescore.Approval) []*typescore.User { + if approval == nil || approval.ID == nil { + return nil + } + + seen := make(map[uint64]bool) + var result []*typescore.User + + add := func(u *typescore.User) { + if u == nil || u.ID == nil || u.TelegramID == nil { + return + } + if seen[*u.ID] { + return + } + seen[*u.ID] = true + result = append(result, u) + } + + if approval.InitiatorID != nil { + initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID) + add(initiator) + } + + if activeStep, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, *approval.ID); activeStep != nil && activeStep.ApproverID != nil { + approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID) + add(approver) + } + + additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: approval.ID}, + }) + for _, aa := range additionalApprovers { + if aa.ApproverID == nil { + continue + } + u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID) + add(u) + } + + tasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalTask{ApprovalID: approval.ID}, + }) + for _, t := range tasks { + if t.ExecutorID == nil { + continue + } + u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *t.ExecutorID) + add(u) + } + + categoryCode := h.getTopicCodeByApproval(ctx, approval) + isFinal := approval.Status != nil && + (*approval.Status == "approved" || *approval.Status == "rejected" || *approval.Status == "revoked") + + if isFinal { + observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID) + for _, obs := range observers { + add(obs) + } + } else { + controllers, _ := h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, categoryCode, approval.TopicID) + for _, c := range controllers { + add(c) + } + } + + additionalObservers, _, _ := h.ipc.Database.ApprovalAdditionalObserver.GetApprovalAdditionalObserversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalObserver{ + ApprovalID: approval.ID, + }, + }) + for _, ao := range additionalObservers { + if ao.UserID == nil { + continue + } + u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *ao.UserID) + add(u) + } + + return result +} + +func (h *Handler) GetCommentsCount(ctx context.Context, approvalID uint64) int { + comments, err := h.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID) + if err != nil { + return 0 + } + return len(comments) +} diff --git a/service/telegram_service/handlers/approval/handler_decision.go b/service/telegram_service/handlers/approval/handler_decision.go index f36635d..a126014 100644 --- a/service/telegram_service/handlers/approval/handler_decision.go +++ b/service/telegram_service/handlers/approval/handler_decision.go @@ -85,18 +85,18 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co } } + currentApproverName := "—" + if currentStep.ApproverNameSnapshot != nil { + currentApproverName = *currentStep.ApproverNameSnapshot + } + + nextApproverName := "—" + if actualApprover != nil && actualApprover.FullName != nil { + nextApproverName = *actualApprover.FullName + } + // Уведомляем инициатора о прогрессе if initiator.TelegramID != nil { - currentApproverName := "—" - if currentStep.ApproverNameSnapshot != nil { - currentApproverName = *currentStep.ApproverNameSnapshot - } - - nextApproverName := "—" - if actualApprover != nil && actualApprover.FullName != nil { - nextApproverName = *actualApprover.FullName - } - topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) content := "—" @@ -159,6 +159,31 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co notifier.NotifyApprover(bot, actualApprover, initiator, approval, collected) } + // Уведомляем наблюдателей-контролёров о прогрессе согласования + if controllers, cErr := h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, categoryCode, approval.TopicID); cErr != nil { + logrus.Warnf("processNextStepOrComplete: GetControllerObserversForApprovalDB err=%v", cErr) + } else if len(controllers) > 0 { + commentsCount := h.GetCommentsCount(ctx, approvalID) + commentsSection := h.formatCommentsSection(ctx, approvalID, 4) + + controllerText := fmt.Sprintf( + "👁 Заявка #%d передана следующему согласующему\n\n"+ + "✅ Согласовал: %s\n"+ + "⏳ Передано: %s\n\n%s%s", + approvalID, currentApproverName, nextApproverName, approvalCard, commentsSection, + ) + + for _, controller := range controllers { + if controller.TelegramID == nil { + continue + } + controllerMsg := tgbotapi.NewMessage(*controller.TelegramID, controllerText) + controllerMsg.ParseMode = "HTML" + controllerMsg.ReplyMarkup = keyboard.BuildObserverActions(approvalID, "", "pending", len(approval.Files), commentsCount) + bot.Send(controllerMsg) //nolint:errcheck + } + } + if actualApprover != nextApprover && nextApprover != nil && nextApprover.TelegramID != nil { delegateName := "—" if actualApprover != nil && actualApprover.FullName != nil { diff --git a/service/telegram_service/handlers/approval/handler_executor.go b/service/telegram_service/handlers/approval/handler_executor.go index ee130d9..75bb92d 100644 --- a/service/telegram_service/handlers/approval/handler_executor.go +++ b/service/telegram_service/handlers/approval/handler_executor.go @@ -115,12 +115,12 @@ func (h *Handler) sendTaskCard(bot *tgbotapi.BotAPI, chatID int64, approval *typ } } - commentsSection := h.formatCommentsSection(ctx, *approval.ID) + commentsSection := h.formatCommentsSection(ctx, *approval.ID, 4) text += commentsSection msg := tgbotapi.NewMessage(chatID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, len(allFiles)) + msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, len(allFiles), h.GetCommentsCount(ctx, *approval.ID)) bot.Send(msg) //nolint:errcheck } @@ -180,7 +180,7 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback "⚠️ Для завершения необходимо прикрепить файл.\n\n"+ "Нажмите «📎 Прикрепить файл», прикрепите документ, затем нажмите «Выполнено».") msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, len(files)) + msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, len(files), h.GetCommentsCount(ctx, *approval.ID)) bot.Send(msg) //nolint:errcheck return } @@ -300,6 +300,37 @@ func (h *Handler) handleRevokeCancellationTask(bot *tgbotapi.BotAPI, ctx context return } + allSteps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID}, + }) + if err != nil { + logrus.Errorf("handleRevokeCancellationTask: GetApprovalStepsListDB err=%v", err) + } + + cancelledStepStatus := "cancelled" + for _, s := range allSteps { + if s.Status == nil { + continue + } + if *s.Status == "pending" || *s.Status == "waiting" { + s.Status = &cancelledStepStatus + if _, _, err := h.ipc.Database.ApprovalStep.UpdateApprovalStepDB(ctx, nil, s); err != nil { + logrus.Errorf("handleRevokeCancellationTask: UpdateApprovalStepDB stepID=%v err=%v", s.ID, err) + } + } + } + + additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ + Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: approval.ID}, + }) + cancelledAAStatus := "cancelled" + for _, aa := range additionalApprovers { + if aa.Status != nil && *aa.Status == "pending" { + aa.Status = &cancelledAAStatus + h.ipc.Database.ApprovalAdditionalApprover.UpdateApprovalAdditionalApproverDB(ctx, nil, aa) //nolint:errcheck + } + } + tasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{ Filtering: &typescore.ApprovalTask{ApprovalID: approval.ID}, }) @@ -398,7 +429,7 @@ func (h *Handler) createReversalTask( *approval.ID, topicFullName, content, reversalText, )) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*created.ID, *approval.ID, len(files)) + msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*created.ID, *approval.ID, len(files), h.GetCommentsCount(ctx, *approval.ID)) bot.Send(msg) //nolint:errcheck } diff --git a/service/telegram_service/handlers/approval/handler_observer.go b/service/telegram_service/handlers/approval/handler_observer.go index 8849a63..9341f2a 100644 --- a/service/telegram_service/handlers/approval/handler_observer.go +++ b/service/telegram_service/handlers/approval/handler_observer.go @@ -192,7 +192,7 @@ func (h *Handler) HandleObserverApprovalCallback(bot *tgbotapi.BotAPI, cq *tgbot msg := tgbotapi.NewMessage(chatID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverApprovalDetail(approvalID, categoryCode) + msg.ReplyMarkup = keyboard.BuildObserverApprovalDetail(approvalID, categoryCode, h.GetCommentsCount(ctx, *approval.ID)) bot.Send(msg) //nolint:errcheck } @@ -255,7 +255,7 @@ func (h *Handler) HandleObserverReminderCallback(bot *tgbotapi.BotAPI, cq *tgbot reminderMsg := tgbotapi.NewMessage(*approver.TelegramID, reminder) reminderMsg.ParseMode = "HTML" - reminderMsg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files)) + reminderMsg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) bot.Send(reminderMsg) //nolint:errcheck approverName := "согласующему" diff --git a/service/telegram_service/handlers/approval/helper.go b/service/telegram_service/handlers/approval/helper.go index e7ae3c5..0c00c92 100644 --- a/service/telegram_service/handlers/approval/helper.go +++ b/service/telegram_service/handlers/approval/helper.go @@ -237,6 +237,15 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele h.saveSelectedObservers(ctx, *created.ID, *initiator.ID, flowState.SelectedObserverIDs) } + // Уведомляем наблюдателей-контролёров о создании заявки + controllers, cErr := h.ipc.Database.User.GetControllerObserversForApprovalDB(ctx, topic.Code(), approvalTopic.ID) + if cErr != nil { + logrus.Warnf("submitApproval: GetControllerObserversForApprovalDB err=%v", cErr) + } + for _, controller := range controllers { + h.notifyControllerAboutCreation(bot, ctx, controller, initiator, created, flowState.Collected) + } + // === НОВЫЙ БЛОК: УВЕДОМЛЕНИЕ ВСЕХ ИЗ ПЕРВОЙ ГРУППЫ === firstGroup := priorityGroups[0] notifier := NewNotifier(h.ipc, topic) @@ -666,7 +675,7 @@ func (h *Handler) buildApprovalCard(ctx context.Context, approval *typescore.App } // Добавляем комментарии - commentsSection := h.formatCommentsSection(ctx, approvalID) + commentsSection := h.formatCommentsSection(ctx, approvalID, 4) card += commentsSection return card diff --git a/service/telegram_service/handlers/approval/list.go b/service/telegram_service/handlers/approval/list.go index 7d7a65c..aeb8822 100644 --- a/service/telegram_service/handlers/approval/list.go +++ b/service/telegram_service/handlers/approval/list.go @@ -156,7 +156,7 @@ func (h *Handler) HandleMyApprovalsStatusCallback(bot *tgbotapi.BotAPI, cq *tgbo files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) msg := tgbotapi.NewMessage(chatID, card) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildInitiatorCard(*approval.ID, approvalStatus, len(files) > 0, len(files)) + msg.ReplyMarkup = keyboard.BuildInitiatorCard(*approval.ID, approvalStatus, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) bot.Send(msg) //nolint:errcheck } } @@ -234,8 +234,10 @@ func (h *Handler) HandleIncomingApprovals(bot *tgbotapi.BotAPI, chatID int64, te if approval == nil { continue } + if approval.Status == nil || (*approval.Status != "pending" && *approval.Status != "revision") { + continue + } - // Проверяем добавленных согласующих addedApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{ Filtering: &typescore.ApprovalAdditionalApprover{ ApprovalID: step.ApprovalID, @@ -250,6 +252,9 @@ func (h *Handler) HandleIncomingApprovals(bot *tgbotapi.BotAPI, chatID int64, te if aa.ApprovalID == nil { continue } + if aa.Status == nil || (*aa.Status != "pending" && *aa.Status != "revision") { + continue + } approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *aa.ApprovalID) if approval == nil { continue @@ -329,7 +334,7 @@ func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval if withButtons && approval.Status != nil && *approval.Status == "pending" { files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID) - markup := keyboard.BuildApproverDecision(*approval.ID, *approval.Status, len(files) > 0, len(files)) + markup := keyboard.BuildApproverDecision(*approval.ID, *approval.Status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) //if showAddApprover { // addBtn := tgbotapi.NewInlineKeyboardButtonData( @@ -346,7 +351,7 @@ func (h *Handler) sendApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval if err != nil { logrus.Errorf("failed to load files for approval, %v", err) } - markup := keyboard.BuildInitiatorCard(*approval.ID, *approval.Status, len(files) > 0, len(files)) + markup := keyboard.BuildInitiatorCard(*approval.ID, *approval.Status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) msg.ReplyMarkup = markup } diff --git a/service/telegram_service/handlers/approval/notify.go b/service/telegram_service/handlers/approval/notify.go index 1fa8635..6f66634 100644 --- a/service/telegram_service/handlers/approval/notify.go +++ b/service/telegram_service/handlers/approval/notify.go @@ -54,7 +54,7 @@ func (h *Handler) notifyExecutor(bot *tgbotapi.BotAPI, ctx context.Context, exec ) // Добавляем комментарии - commentsSection := h.formatCommentsSection(ctx, *approval.ID) + commentsSection := h.formatCommentsSection(ctx, *approval.ID, 4) text += commentsSection // 🆕 Получаем все файлы заявки @@ -81,7 +81,7 @@ func (h *Handler) notifyExecutor(bot *tgbotapi.BotAPI, ctx context.Context, exec // 🆕 Передаём filesCount в клавиатуру msg := tgbotapi.NewMessage(*executor.TelegramID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, filesCount) + msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, filesCount, h.GetCommentsCount(ctx, *approval.ID)) bot.Send(msg) //nolint:errcheck } @@ -126,27 +126,7 @@ func (n *Notifier) NotifyApprover( n.topic.FormatApproverMessage(initiator, collected) // Добавляем комментарии если есть - comments, _ := n.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, *approval.ID) - if len(comments) > 0 { - msgText += "\n\n💬 Комментарии:" - for _, comment := range comments { - if comment.UserID == nil || comment.Comment == nil { - continue - } - - user, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *comment.UserID) - if user == nil || user.FullName == nil { - continue - } - - timestamp := "" - if comment.CreatedAt != nil { - timestamp = comment.CreatedAt.Format("02.01.2006 15:04") - } - - msgText += fmt.Sprintf("\n\n%s (%s):\n%s", *user.FullName, timestamp, *comment.Comment) - } - } + msgText += n.formatCommentsSection(ctx, *approval.ID, 4) // Отправляем с файлами или без if len(approval.Files) == 0 { @@ -166,7 +146,7 @@ func (n *Notifier) NotifyApprover( *approver.TelegramID, approval, msgText, - keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files)), + keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files), n.GetCommentsCount(ctx, *approval.ID)), ) } @@ -180,7 +160,7 @@ func (n *Notifier) sendTextToApprover(bot *tgbotapi.BotAPI, approver *typescore. msg := tgbotapi.NewMessage(*approver.TelegramID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files)) + msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files), n.GetCommentsCount(ctx, *approval.ID)) bot.Send(msg) //nolint:errcheck } @@ -232,7 +212,7 @@ func (n *Notifier) NotifyInitiatorApproved( msg := tgbotapi.NewMessage(*initiator.TelegramID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount) + msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount, n.GetCommentsCount(ctx, *approval.ID)) if _, err := bot.Send(msg); err != nil { logrus.Errorf("NotifyInitiatorApproved: Send err=%v", err) } @@ -286,7 +266,6 @@ func (n *Notifier) NotifyDirector(bot *tgbotapi.BotAPI, director *typescore.User } ctx := context.Background() - // 🚀 Передаем initiator и collected для построения ПОЛНОЙ карточки card := n.buildApprovalCard(ctx, approval, initiator, collected) text := "📌 Финально согласовано\n\n" + card @@ -306,7 +285,7 @@ func (n *Notifier) NotifyDirector(bot *tgbotapi.BotAPI, director *typescore.User msg := tgbotapi.NewMessage(*director.TelegramID, text) msg.ParseMode = "HTML" // 🚀 Передаем filesCount в клавиатуру - msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount) + msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount, n.GetCommentsCount(ctx, *approval.ID)) bot.Send(msg) //nolint:errcheck } @@ -375,7 +354,7 @@ func (n *Notifier) NotifyObserversDecision( msg := tgbotapi.NewMessage(*obs.TelegramID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildObserverActions(*approval.ID, "", status, filesCount) + msg.ReplyMarkup = keyboard.BuildObserverActions(*approval.ID, "", status, filesCount, n.GetCommentsCount(ctx, *approval.ID)) if _, err := bot.Send(msg); err != nil { logrus.Errorf("❌ NotifyObserversDecision: Send to %d err=%v", *obs.TelegramID, err) @@ -560,7 +539,7 @@ func (h *Handler) sendAdditionalApprovalCard(bot *tgbotapi.BotAPI, chatID int64, if len(files) == 0 { msg := tgbotapi.NewMessage(chatID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files)) + msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) bot.Send(msg) //nolint:errcheck return } @@ -569,7 +548,7 @@ func (h *Handler) sendAdditionalApprovalCard(bot *tgbotapi.BotAPI, chatID int64, topic, _ := h.Registry.Get(categoryCode) if topic != nil { notifier := NewNotifier(h.ipc, topic) - notifier.sendFilesToRecipient(bot, chatID, approval, text, keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files))) + notifier.sendFilesToRecipient(bot, chatID, approval, text, keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID))) } } @@ -814,13 +793,13 @@ func (n *Notifier) buildApprovalCard(ctx context.Context, approval *typescore.Ap } // Добавляем комментарии - commentsSection := n.formatCommentsSection(ctx, approvalID) + commentsSection := n.formatCommentsSection(ctx, approvalID, 4) card += commentsSection return card } -func (n *Notifier) formatCommentsSection(ctx context.Context, approvalID uint64) string { +func (n *Notifier) formatCommentsSection(ctx context.Context, approvalID uint64, limit int) string { comments, _, _ := n.ipc.Database.ApprovalComment.GetApprovalCommentsListDB(ctx, typescore.ListDbOptions{ Filtering: &typescore.ApprovalComment{ApprovalID: &approvalID}, }) @@ -828,7 +807,16 @@ func (n *Notifier) formatCommentsSection(ctx context.Context, approvalID uint64) return "" } + total := len(comments) + if limit > 0 && total > limit { + comments = comments[total-limit:] + } + section := "\n\n💬 Комментарии:" + if limit > 0 && total > limit { + section = fmt.Sprintf("\n\n💬 Последние %d комментариев (из %d):", limit, total) + } + for _, c := range comments { authorName := "—" if c.UserID != nil { @@ -849,3 +837,52 @@ func (n *Notifier) formatCommentsSection(ctx context.Context, approvalID uint64) } return section } + +func (n *Notifier) GetCommentsCount(ctx context.Context, approvalID uint64) int { + comments, err := n.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, approvalID) + if err != nil { + return 0 + } + return len(comments) +} + +func (h *Handler) notifyControllerAboutCreation( + bot *tgbotapi.BotAPI, + ctx context.Context, + controller *typescore.User, + initiator *typescore.User, + approval *typescore.Approval, + collected map[string]string, +) { + if controller.TelegramID == nil || approval.ID == nil { + return + } + + initiatorName := "—" + if initiator.FullName != nil { + initiatorName = *initiator.FullName + } + topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID) + content := collected["content"] + if content == "" { + content = "—" + } + + text := fmt.Sprintf( + "👁 Создана заявка на согласование #%d\n\n"+ + "👤 Инициатор: %s\n"+ + "📋 Тема: %s\n"+ + "📝 Текст: %s", + *approval.ID, initiatorName, topicFullName, content, + ) + + status := "" + if approval.Status != nil { + status = *approval.Status + } + + msg := tgbotapi.NewMessage(*controller.TelegramID, text) + msg.ParseMode = "HTML" + msg.ReplyMarkup = keyboard.BuildObserverActions(*approval.ID, "", status, len(approval.Files), h.GetCommentsCount(ctx, *approval.ID)) + bot.Send(msg) //nolint:errcheck +} diff --git a/service/telegram_service/handlers/approval/revision.go b/service/telegram_service/handlers/approval/revision.go index ddd1848..38d93fa 100644 --- a/service/telegram_service/handlers/approval/revision.go +++ b/service/telegram_service/handlers/approval/revision.go @@ -163,7 +163,7 @@ func (h *Handler) notifyInitiatorRevision( msg := tgbotapi.NewMessage(*initiator.TelegramID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildRevisionOptions(*approval.ID) + msg.ReplyMarkup = keyboard.BuildRevisionOptions(*approval.ID, h.GetCommentsCount(context.Background(), *approval.ID)) bot.Send(msg) //nolint:errcheck } @@ -256,7 +256,7 @@ func (h *Handler) HandleRevisionTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Me // Показываем опции снова optMsg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Заявка #%d на доработке:", revisionState.ApprovalID)) optMsg.ParseMode = "HTML" - optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(revisionState.ApprovalID) + optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(revisionState.ApprovalID, h.GetCommentsCount(ctx, *approval.ID)) bot.Send(optMsg) //nolint:errcheck return true @@ -364,15 +364,15 @@ func (h *Handler) HandleRevisionResubmit(bot *tgbotapi.BotAPI, cq *tgbotapi.Call if len(files) == 0 { msg := tgbotapi.NewMessage(*approver.TelegramID, fullText) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files)) + msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) bot.Send(msg) //nolint:errcheck } else { - notifier.sendFilesToRecipient(bot, *approver.TelegramID, approval, fullText, keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files))) + notifier.sendFilesToRecipient(bot, *approver.TelegramID, approval, fullText, keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID))) } } else { msg := tgbotapi.NewMessage(*approver.TelegramID, text) msg.ParseMode = "HTML" - msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files)) + msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, len(files) > 0, len(files), h.GetCommentsCount(ctx, *approval.ID)) bot.Send(msg) //nolint:errcheck } } @@ -488,7 +488,7 @@ func (h *Handler) HandleRevisionFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Me // Показываем опции снова optMsg := tgbotapi.NewMessage(chatID, fmt.Sprintf("📋 Заявка #%d на доработке:", approvalID)) optMsg.ParseMode = "HTML" - optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(approvalID) + optMsg.ReplyMarkup = keyboard.BuildRevisionOptions(approvalID, h.GetCommentsCount(ctx, approvalID)) bot.Send(optMsg) //nolint:errcheck return true diff --git a/service/telegram_service/keyboard/add_approver.go b/service/telegram_service/keyboard/add_approver.go index 2ae5a3e..6cac8ae 100644 --- a/service/telegram_service/keyboard/add_approver.go +++ b/service/telegram_service/keyboard/add_approver.go @@ -1,5 +1,3 @@ -// telegram_service/keyboard/add_approver.go - ПОЛНОСТЬЮ ЗАМЕНИТЬ - package keyboard import ( diff --git a/service/telegram_service/keyboard/approval.go b/service/telegram_service/keyboard/approval.go index e5b1a96..88ec23b 100644 --- a/service/telegram_service/keyboard/approval.go +++ b/service/telegram_service/keyboard/approval.go @@ -10,12 +10,13 @@ import ( ) // BuildApproverDecision — кнопки для согласующего -func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, filesCount int) tgbotapi.InlineKeyboardMarkup { +func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, filesCount int, commentsCount int) tgbotapi.InlineKeyboardMarkup { kb := tgkit.NewInlineKeyboard() if status == "approved" { kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID))) kb.Row(tgkit.Btn("📊 Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID))) + kb.Row(buildCommentsButton(approvalID, commentsCount)) return kb.Build() } @@ -24,14 +25,13 @@ func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, file kb.Row(tgkit.Btn(buttonTitle, fmt.Sprintf("appr_view_files:%d", approvalID))) } - // Для всех остальных статусов — полный набор кнопок kb.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)), + buildCommentsButton(approvalID, commentsCount), tgkit.Btn("📎 Прикрепить файл", fmt.Sprintf("appr_attach:%d", approvalID)), ). Row( @@ -43,7 +43,7 @@ func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, file } // BuildInitiatorCard — кнопки инициатора на карточке заявки -func BuildInitiatorCard(approvalID uint64, status string, hasFiles bool, filesCount int) interface{} { +func BuildInitiatorCard(approvalID uint64, status string, hasFiles bool, filesCount int, commentsCount int) interface{} { kb := tgkit.NewInlineKeyboard() if hasFiles { @@ -54,6 +54,9 @@ func BuildInitiatorCard(approvalID uint64, status string, hasFiles bool, filesCo if status != "approved" { kb.Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))) } + if commentsCount > 0 { + buildCommentsButton(approvalID, commentsCount) + } if status == "pending" || status == "revision" || status == "approved" { kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать", fmt.Sprintf("appr_revoke:%d", approvalID))) @@ -64,13 +67,18 @@ func BuildInitiatorCard(approvalID uint64, status string, hasFiles bool, filesCo } // BuildRevokeButton — кнопка отзыва (для директора и инициатора) -func BuildRevokeButton(approvalID uint64, status string, filesCount int) interface{} { +func BuildRevokeButton(approvalID uint64, status string, filesCount int, commentsCount int) interface{} { kb := tgkit.NewInlineKeyboard() if filesCount > 0 { kb.Row(tgkit.Btn(fmt.Sprintf("📎 Просмотреть файлы (%d)", filesCount), fmt.Sprintf("appr_view_files:%d", approvalID))) } + kb.Row( + tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)), + buildCommentsButton(approvalID, commentsCount), + ) + if status == "pending" || status == "revision" || status == "approved" { kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleRevision, "Отозвать заявку", fmt.Sprintf("appr_revoke:%d", approvalID))) } @@ -80,7 +88,7 @@ func BuildRevokeButton(approvalID uint64, status string, filesCount int) interfa } // BuildObserverActions — кнопки наблюдателя -func BuildObserverActions(approvalID uint64, topicCode string, status string, filesCount int) tgbotapi.InlineKeyboardMarkup { +func BuildObserverActions(approvalID uint64, topicCode string, status string, filesCount, commentsCount int) tgbotapi.InlineKeyboardMarkup { kb := tgkit.NewInlineKeyboard() if filesCount > 0 { @@ -91,6 +99,7 @@ func BuildObserverActions(approvalID uint64, topicCode string, status string, fi } kb.Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))) + buildCommentsButton(approvalID, commentsCount) return kb.Build() } @@ -328,7 +337,7 @@ func BuildAttachSessionKeyboard(approvalID uint64, fileCount int) tgbotapi.Inlin } // BuildExecutorTaskActions — кнопки исполнителя -func BuildExecutorTaskActions(taskID, approvalID uint64, filesCount int) interface{} { +func BuildExecutorTaskActions(taskID, approvalID uint64, filesCount int, commentsCount int) interface{} { kb := tgkit.NewInlineKeyboard() if filesCount > 0 { @@ -340,7 +349,10 @@ func BuildExecutorTaskActions(taskID, approvalID uint64, filesCount int) interfa kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Выполнено", fmt.Sprintf("task_complete:%d", taskID))). Row(tgkit.Btn("📎 Прикрепить файл к задаче", fmt.Sprintf("executor_attach:%d:%d", taskID, approvalID))). - Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))) + Row( + tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)), + buildCommentsButton(approvalID, commentsCount), + ) return kb.Build() } diff --git a/service/telegram_service/keyboard/builder.go b/service/telegram_service/keyboard/builder.go index 419a008..5d68d06 100644 --- a/service/telegram_service/keyboard/builder.go +++ b/service/telegram_service/keyboard/builder.go @@ -49,16 +49,29 @@ func ApprovalsListSubmenuKeyboard() tgbotapi.ReplyKeyboardMarkup { } // BuildCommentNotificationKeyboard — для уведомления инициатора о комментарии -func BuildCommentNotificationKeyboard(approvalID uint64) interface{} { +func BuildCommentNotificationKeyboard(approvalID uint64, commentsCount int) interface{} { + viewLabel := "💬 Посмотреть все комментарии" + if commentsCount > 0 { + viewLabel = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount) + } + return tgkit.NewInlineKeyboard(). Row(tgkit.Btn("↩️ Ответить на комментарий", fmt.Sprintf("comment_reply:%d", approvalID))). + Row(tgkit.Btn("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID))). + Row(tgkit.Btn(viewLabel, fmt.Sprintf("appr_view_comments:%d", approvalID))). Build() } // BuildCommentReplyKeyboard — для согласующего/наблюдателя при получении ответа -func BuildCommentReplyKeyboard(approvalID uint64) interface{} { +func BuildCommentReplyKeyboard(approvalID uint64, commentsCount int) interface{} { + viewLabel := "💬 Посмотреть все комментарии" + if commentsCount > 0 { + viewLabel = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount) + } + return tgkit.NewInlineKeyboard(). Row(tgkit.Btn("↩️ Ответить на комментарий", fmt.Sprintf("comment_reply:%d", approvalID))). Row(tgkit.Btn("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID))). + Row(tgkit.Btn(viewLabel, fmt.Sprintf("appr_view_comments:%d", approvalID))). Build() } diff --git a/service/telegram_service/keyboard/misc.go b/service/telegram_service/keyboard/misc.go index 0f32e55..8896419 100644 --- a/service/telegram_service/keyboard/misc.go +++ b/service/telegram_service/keyboard/misc.go @@ -8,8 +8,6 @@ import ( 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) @@ -240,12 +238,16 @@ func BuildReportDateToMenu() interface{} { Build() } -// ── Доработка ─────────────────────────────────────────────────── +func BuildRevisionOptions(approvalID uint64, commentsCount int) interface{} { + viewLabel := "💬 Посмотреть все комментарии" + if commentsCount > 0 { + viewLabel = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount) + } -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.Btn(viewLabel, fmt.Sprintf("appr_view_comments:%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() @@ -280,3 +282,11 @@ func BuildRevokeTaskConfirmation(taskID uint64, approvalID uint64) tgbotapi.Inli ), ) } + +func buildCommentsButton(approvalID uint64, commentsCount int) tgkit.InlineButton { + label := "💬 Посмотреть все комментарии" + if commentsCount > 0 { + label = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount) + } + return tgkit.Btn(label, fmt.Sprintf("appr_view_comments:%d", approvalID)) +} diff --git a/service/telegram_service/keyboard/observer.go b/service/telegram_service/keyboard/observer.go index 7bb207b..70c7b51 100644 --- a/service/telegram_service/keyboard/observer.go +++ b/service/telegram_service/keyboard/observer.go @@ -6,12 +6,15 @@ import ( ) // BuildObserverApprovalDetail — карточка заявки с кнопками наблюдателя. -func BuildObserverApprovalDetail(approvalID uint64, topicCode string) tgbotapi.InlineKeyboardMarkup { +func BuildObserverApprovalDetail(approvalID uint64, topicCode string, commentsCount int) tgbotapi.InlineKeyboardMarkup { return tgbotapi.NewInlineKeyboardMarkup( tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonData("🔔 Напомнить согласующему", fmt.Sprintf("obs_remind:%d", approvalID)), tgbotapi.NewInlineKeyboardButtonData("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID)), ), + tgbotapi.NewInlineKeyboardRow( + buildCommentsButtonData(approvalID, commentsCount), + ), tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonData( "🔙 Назад к списку", @@ -20,3 +23,11 @@ func BuildObserverApprovalDetail(approvalID uint64, topicCode string) tgbotapi.I ), ) } + +func buildCommentsButtonData(approvalID uint64, commentsCount int) tgbotapi.InlineKeyboardButton { + label := "💬 Посмотреть все комментарии" + if commentsCount > 0 { + label = fmt.Sprintf("💬 Посмотреть все комментарии (%d)", commentsCount) + } + return tgbotapi.NewInlineKeyboardButtonData(label, fmt.Sprintf("appr_view_comments:%d", approvalID)) +} -- 2.43.0