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

848 lines
29 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 approval
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/variables"
"bitrix_balancer_api/telegram_service/approvalflow"
"bitrix_balancer_api/telegram_service/keyboard"
"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"
"time"
)
type Handler struct {
ipc *types.InternalProviderControl
Registry *Registry
States *state.StateManager
}
func NewHandler(ipc *types.InternalProviderControl) *Handler {
h := &Handler{
ipc: ipc,
Registry: NewRegistry(ipc),
States: state.NewStateManager(ipc.RedisClient),
}
// Загружаем темы из БД при старте
ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutLong)
if err := h.Registry.LoadFromDB(ctx); err != nil {
logrus.Errorf("Failed to load topics from DB: %v", err)
}
cancel()
// Фоновая проверка изменений дерева тем/категорий из конструктора —
// см. reload_watcher.go (новый файл, package approval).
go h.watchRegistryReload()
return h
}
// HandleMenu — первая страница меню.
func (h *Handler) HandleMenu(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
h.HandleMenuPage(bot, chatID, telegramID, 0, 0)
}
func (h *Handler) HandleInitiatorSubmenu(bot *tgbotapi.BotAPI, chatID int64) {
msg := tgbotapi.NewMessage(chatID, "👤 <b>Инициатор</b>\n\nВыберите действие:")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildInitiatorSubmenu()
bot.Send(msg) //nolint:errcheck
}
// HandleApproverSubmenu — подменю для согласующего
func (h *Handler) HandleApproverSubmenu(bot *tgbotapi.BotAPI, chatID int64) {
msg := tgbotapi.NewMessage(chatID, "✅ <b>Согласующий</b>\n\nВыберите действие:")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildApproverSubmenu()
bot.Send(msg) //nolint:errcheck
}
// HandleObserverSubmenu — подменю для наблюдателя
func (h *Handler) HandleObserverSubmenu(bot *tgbotapi.BotAPI, chatID int64) {
msg := tgbotapi.NewMessage(chatID, "✅ <b>Наблюдатель</b>\n\nВыберите действие:")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildObserverSubmenu()
bot.Send(msg) //nolint:errcheck
}
// HandleMenuPage — показывает меню на нужной странице.
// prevMessageID != 0 — удаляем старое сообщение с пагинацией.
func (h *Handler) HandleMenuPage(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, page int, prevMessageID int) {
ctx := context.Background()
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
if err != nil || user == nil {
return
}
allowed, err := h.getAllowedTopicCodes(ctx, user)
if err != nil {
logrus.Error("HandleMenuPage: getAllowedTopicCodes: ", err)
return
}
var visibleTopics []approvalflow.Topic
for _, t := range h.Registry.All() {
if allowed[t.Code()] {
visibleTopics = append(visibleTopics, t)
}
}
if len(visibleTopics) == 0 {
msg := tgbotapi.NewMessage(chatID, "У вас нет доступных тем для согласования")
msg.ParseMode = "HTML"
bot.Send(msg) //nolint:errcheck
return
}
if prevMessageID != 0 {
bot.Request(tgbotapi.NewDeleteMessage(chatID, prevMessageID)) //nolint:errcheck
}
msg := tgbotapi.NewMessage(chatID, "Выберите тип согласования:")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildApprovalMenu(visibleTopics, page)
bot.Send(msg) //nolint:errcheck
}
// HandleCallback обрабатывает нажатие inline-кнопки внутри флоу согласования.
// callbackData формат: appr:{topic_code}:{node_key}
// HandleCallback обрабатывает нажатие inline-кнопки внутри флоу согласования.
func (h *Handler) HandleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode, nodeKey string) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
telegramID := cq.From.ID
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
topic, err := h.Registry.Get(topicCode)
if err != nil {
logrus.Warnf("HandleCallback: unknown topic %s", topicCode)
return
}
flowState, err := h.States.Get(ctx, telegramID)
if err != nil {
logrus.Error("HandleCallback: get state error", err)
return
}
isNew := flowState == nil
if isNew {
flowState = &state.ApprovalFlowState{
TopicCode: topicCode,
NodeKey: nodeKey,
Collected: make(map[string]string),
}
}
tree := topic.BuildTree()
node := approvalflow.FindNode(tree, nodeKey)
if node == nil {
logrus.Warnf("HandleCallback: node not found: %s", nodeKey)
return
}
if !isNew {
flowState.History = append(flowState.History, flowState.NodeKey)
}
if node.DataKey != "" {
flowState.Collected[node.DataKey] = node.DataValue
}
if len(node.Children) == 0 && !node.IsInput {
logrus.Warnf("HandleCallback: leaf node without IsInput: %s", nodeKey)
return
}
// Единственный ребёнок — input
if len(node.Children) == 1 && node.Children[0].IsInput {
inputNode := node.Children[0]
if inputNode.DataKey != "" {
flowState.Collected[inputNode.DataKey] = inputNode.DataValue
}
flowState.AwaitInput = true
flowState.InputKey = inputNode.InputKey
flowState.NodeKey = nodeKey
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
hint := fmt.Sprintf("Введите данные по шаблону:\n<code>%s</code>", inputNode.InputHint)
msg := tgbotapi.NewMessage(chatID, hint)
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildApprovalInputPrompt(topicCode)
bot.Send(msg) //nolint:errcheck
return
}
flowState.NodeKey = nodeKey
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children)
if len(visibleChildren) == 0 {
sendText(bot, chatID, "⚠️ У вас нет доступа к подкатегориям этого раздела.")
h.States.Clear(ctx, telegramID)
return
}
// Детектируем мультиселект
isMultiSelect := len(visibleChildren) > 0 && visibleChildren[0].IsMultiSelect
if isMultiSelect {
if flowState.MultiSelected == nil {
flowState.MultiSelected = make(map[string][]string)
}
flowState.AwaitMultiSelectConfirm = true
flowState.MultiSelectNodeKey = nodeKey
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
msg := tgbotapi.NewMessage(chatID, "Выберите системы (можно несколько):")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildMultiSelectStep(topicCode, visibleChildren, nil, nil)
bot.Send(msg) //nolint:errcheck
return
}
msg := tgbotapi.NewMessage(chatID, "Выберите:")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildApprovalStep(topicCode, visibleChildren)
bot.Send(msg) //nolint:errcheck
}
func (h *Handler) HandleTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
ctx := context.Background()
telegramID := msg.From.ID
chatID := msg.Chat.ID
commentKey := fmt.Sprintf("appr_approve_comment_pending:%d", telegramID)
commentApprovalIDStr, err := h.ipc.RedisClient.Get(ctx, commentKey)
if err == nil && commentApprovalIDStr != "" {
var approvalID uint64
if _, scanErr := fmt.Sscanf(commentApprovalIDStr, "%d", &approvalID); scanErr == nil {
h.ipc.RedisClient.Del(ctx, commentKey) //nolint:errcheck
h.HandleDecisionWithChat(bot, chatID, telegramID, approvalID, true, msg.Text)
return true
}
}
commentState, _ := h.States.GetCommentFlow(ctx, telegramID)
if commentState != nil && commentState.Stage == "await_text" {
// Делегируем в HandleCommentTextInput
return h.HandleCommentTextInput(bot, msg)
}
replyState, _ := h.States.GetCommentReply(ctx, telegramID)
if replyState != nil && replyState.Stage == "await_text" {
return h.HandleCommentReplyInput(bot, msg)
}
flowState, err := h.States.Get(ctx, telegramID)
if err != nil || flowState == nil || !flowState.AwaitInput {
return false
}
flowState.Collected[flowState.InputKey] = msg.Text
flowState.AwaitInput = false
topic, _ := h.Registry.Get(flowState.TopicCode)
if topic != nil {
tree := topic.BuildTree()
parentNode := approvalflow.FindNode(tree, flowState.NodeKey)
if parentNode != nil && len(parentNode.Children) == 1 && parentNode.Children[0].IsInput {
inputNode := parentNode.Children[0]
if len(inputNode.Children) > 0 {
visibleChildren := h.filterNodesByAccess(ctx, telegramID, inputNode.Children)
if len(visibleChildren) == 0 {
sendText(bot, chatID, "⚠️ У вас нет доступа к подкатегориям этого раздела.")
h.States.Clear(ctx, telegramID) //nolint:errcheck
return true
}
flowState.NodeKey = inputNode.Key
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
msg := tgbotapi.NewMessage(chatID, "Выберите:")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildApprovalStep(flowState.TopicCode, visibleChildren)
bot.Send(msg) //nolint:errcheck
return true
}
}
}
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
return true
}
func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, approvalID uint64, comment string) {
ctx := context.Background()
revoker, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, int64(telegramID))
if err != nil || revoker == nil || revoker.ID == nil {
sendText(bot, chatID, "⚠️ Пользователь не найден.")
return
}
approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
if err != nil || approval == nil {
sendText(bot, chatID, "⚠️ Заявка не найдена.")
return
}
if approval.Status == nil {
sendText(bot, chatID, "⚠️ Статус заявки не определён.")
return
}
isInitiator := approval.InitiatorID != nil && *approval.InitiatorID == *revoker.ID
isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, *revoker.ID)
isApprover := false
steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalStep{ApprovalID: &approvalID},
})
for _, step := range steps {
if step.ApproverID != nil && *step.ApproverID == *revoker.ID {
isApprover = true
break
}
}
switch *approval.Status {
case "revoked":
sendText(bot, chatID, "Заявка уже отозвана.")
return
case "rejected":
sendText(bot, chatID, "Нельзя отозвать отклонённую заявку.")
return
case "pending", "revision":
if !isInitiator && !isDirector {
sendText(bot, chatID, "⚠️ В процессе согласования заявку может отозвать только инициатор или директор.")
return
}
case "approved":
if !isInitiator && !isDirector && !isApprover {
sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.")
return
}
// Инициатор (не директор) отзывает уже согласованную заявку —
// требуется согласие всех, кто участвовал в согласовании
if isInitiator && !isDirector {
h.startApprovalRevocationRequest(bot, chatID, approval, revoker, comment)
return
}
default:
if !isInitiator && !isDirector {
sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.")
return
}
}
revokerRole := ""
switch {
case isInitiator:
revokerRole = "инициатором"
case isDirector:
revokerRole = "директором"
case isApprover:
revokerRole = "согласующим"
}
h.performActualRevoke(bot, ctx, approval, revoker, revokerRole, comment, steps, isInitiator, isDirector)
// Обратная связь тому, кто выполнил отзыв
topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
content := "—"
if approval.Content != nil {
content = *approval.Content
}
approvalCard := fmt.Sprintf(
"📋 <b>Тема:</b> %s\n📝 <b>Текст:</b> %s\n💬 <b>Причина отзыва:</b> %s",
topicFullName, content, comment,
)
feedbackMsg := tgbotapi.NewMessage(chatID, fmt.Sprintf(
"↩️ <b>Заявка #%d отозвана</b>\n\n%s",
approvalID, approvalCard,
))
feedbackMsg.ParseMode = "HTML"
feedbackMsg.ReplyMarkup = keyboard.BuildCommentNotificationKeyboard(approvalID, h.GetCommentsCount(ctx, approvalID))
bot.Send(feedbackMsg) //nolint:errcheck
}
// performActualRevoke выполняет отзыв заявки в БД и уведомляет всех участников
// с возможностью комментирования. Вызывается либо напрямую (директор/согласующий/
// инициатор для pending), либо после того как все согласующие подтвердили согласие
// на отзыв уже одобренной заявки.
func (h *Handler) performActualRevoke(
bot *tgbotapi.BotAPI,
ctx context.Context,
approval *typescore.Approval,
revoker *typescore.User,
revokerRole string,
comment string,
steps []*typescore.ApprovalStep,
isInitiatorRevoking bool,
isDirectorRevoking bool,
) {
if approval.ID == nil {
return
}
approvalID := *approval.ID
now := time.Now().UTC()
revokedStatus := "revoked"
approval.Status = &revokedStatus
approval.RevokedByID = revoker.ID
approval.RevokedAt = &now
if _, _, err := h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval); err != nil {
logrus.Errorf("performActualRevoke: UpdateApprovalDB err=%v", err)
return
}
h.handleRevokeCancellationTask(bot, ctx, approval)
revokerName := "—"
if revoker.FullName != nil {
revokerName = *revoker.FullName
}
topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
content := "—"
if approval.Content != nil {
content = *approval.Content
}
approvalCard := fmt.Sprintf(
"📋 <b>Тема:</b> %s\n"+
"📝 <b>Текст:</b> %s\n"+
"💬 <b>Причина отзыва:</b> %s",
topicFullName, content, comment,
)
commentsCount := h.GetCommentsCount(ctx, approvalID)
commentKeyboard := keyboard.BuildCommentNotificationKeyboard(approvalID, commentsCount)
notify := func(chatID int64, text string) {
msg := tgbotapi.NewMessage(chatID, text)
msg.ParseMode = "HTML"
msg.ReplyMarkup = commentKeyboard
bot.Send(msg) //nolint:errcheck
}
// Инициатор (если не сам отзывал)
if !isInitiatorRevoking && approval.InitiatorID != nil {
initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
if err == nil && initiator != nil && initiator.TelegramID != nil {
notify(*initiator.TelegramID, fmt.Sprintf(
"↩️ <b>Ваша заявка #%d отозвана %s %s</b>\n\n%s",
approvalID, revokerRole, revokerName, approvalCard,
))
}
}
// Директора (если не сам отзывал)
if !isDirectorRevoking {
directors, _ := h.ipc.Database.User.GetDirectorsDB(ctx)
for _, director := range directors {
if director.TelegramID == nil {
continue
}
if revoker.ID != nil && director.ID != nil && *director.ID == *revoker.ID {
continue
}
notify(*director.TelegramID, fmt.Sprintf(
"↩️ <b>Заявка #%d отозвана %s %s</b>\n\n%s",
approvalID, revokerRole, revokerName, approvalCard,
))
}
}
// Согласующие (кроме самого отозвавшего)
notifiedApprovers := make(map[uint64]bool)
for _, step := range steps {
if step.ApproverID == nil {
continue
}
if revoker.ID != nil && *step.ApproverID == *revoker.ID {
continue
}
if notifiedApprovers[*step.ApproverID] {
continue
}
notifiedApprovers[*step.ApproverID] = true
approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
if approver == nil || approver.TelegramID == nil {
continue
}
notify(*approver.TelegramID, fmt.Sprintf(
"↩️ <b>Заявка #%d отозвана %s %s</b>\n\n%s",
approvalID, revokerRole, revokerName, approvalCard,
))
}
// Наблюдатели
categoryCode := h.getTopicCodeByApproval(ctx, approval)
observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID)
for _, obs := range observers {
if obs.TelegramID == nil {
continue
}
if revoker.ID != nil && obs.ID != nil && *obs.ID == *revoker.ID {
continue
}
notify(*obs.TelegramID, fmt.Sprintf(
"↩️ <b>Заявка #%d отозвана %s %s</b>\n\n%s",
approvalID, revokerRole, revokerName, approvalCard,
))
}
}
// HandleBackCallback — обработчик кнопки "← Назад".
// Логика: pop из History → показываем children того узла.
// Если history пуста — возвращаемся в HandleMenu (выбор темы).
// HandleBackCallback возвращает пользователя на предыдущий шаг флоу.
func (h *Handler) HandleBackCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, topicCode string) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
telegramID := cq.From.ID
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
bot.Request(tgbotapi.NewDeleteMessage(chatID, cq.Message.MessageID)) //nolint:errcheck
flowState, err := h.States.Get(ctx, telegramID)
if err != nil || flowState == nil {
logrus.Warnf("HandleBackCallback: no active flow for user=%d", telegramID)
return
}
// Если в режиме файлового ввода — очищаем файлы и статусное сообщение
if flowState.AwaitFileInput {
flowState.AwaitFileInput = false
flowState.Files = nil
// Удаляем статусное сообщение если есть
if flowState.FileStatusMsgID != 0 {
bot.Request(tgbotapi.NewDeleteMessage(chatID, flowState.FileStatusMsgID)) //nolint:errcheck
flowState.FileStatusMsgID = 0
}
}
// Если в режиме текстового ввода — очищаем
if flowState.AwaitInput {
flowState.AwaitInput = false
flowState.InputKey = ""
}
// Проверяем историю
if len(flowState.History) == 0 {
// Нет истории — возвращаемся в главное меню
h.States.Clear(ctx, telegramID) //nolint:errcheck
h.HandleMenu(bot, chatID, telegramID)
return
}
// Достаём предыдущий узел из стека
prevNodeKey := flowState.History[len(flowState.History)-1]
flowState.History = flowState.History[:len(flowState.History)-1]
flowState.NodeKey = prevNodeKey
topic, err := h.Registry.Get(topicCode)
if err != nil {
logrus.Errorf("HandleBackCallback: unknown topic %s", topicCode)
return
}
tree := topic.BuildTree()
node := approvalflow.FindNode(tree, prevNodeKey)
if node == nil {
logrus.Warnf("HandleBackCallback: node not found: %s", prevNodeKey)
return
}
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
// Фильтруем по правам
visibleChildren := h.filterNodesByAccess(ctx, telegramID, node.Children)
msg := tgbotapi.NewMessage(chatID, "Выберите:")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildApprovalStep(topicCode, visibleChildren)
bot.Send(msg) //nolint:errcheck
}
func (h *Handler) continueFlowAfterInput(
bot *tgbotapi.BotAPI,
ctx context.Context,
chatID int64,
telegramID int64,
flowState *state.ApprovalFlowState,
) {
topic, _ := h.Registry.Get(flowState.TopicCode)
if topic == nil {
h.States.Clear(ctx, telegramID) //nolint:errcheck
return
}
topicCode, err := topic.TopicCodeFromCollected(flowState.Collected)
if err != nil {
logrus.Warnf("continueFlowAfterInput: TopicCodeFromCollected err=%v", err)
h.States.Clear(ctx, telegramID) //nolint:errcheck
return
}
approvalTopic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
if err != nil {
logrus.Errorf("continueFlowAfterInput: GetApprovalTopicByCodeDB topicCode=%s err=%v", topicCode, err)
}
if approvalTopic != nil && !flowState.FilesStepCompleted {
requiresFile := approvalTopic.RequiresFile != nil && *approvalTopic.RequiresFile
allowsFile := approvalTopic.AllowsFile != nil && *approvalTopic.AllowsFile
isOfficial := flowState.Collected["payment_type"] == "official"
needFileStep := requiresFile || allowsFile || isOfficial
if needFileStep && !flowState.AwaitFileInput {
flowState.AwaitFileInput = true
flowState.FilesStepCompleted = false
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
h.showFileStatus(bot, chatID, telegramID, flowState, requiresFile || isOfficial)
return
}
}
if approvalTopic != nil &&
approvalTopic.FirstApproverRoleCode != nil &&
*approvalTopic.FirstApproverRoleCode != "" &&
flowState.SelectedFirstApproverID == 0 &&
!flowState.AwaitFirstApproverSelection {
flowState.AwaitFirstApproverSelection = true
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
roleCode := *approvalTopic.FirstApproverRoleCode
roleLabel := roleCode
role := h.getRoleLabelByCode(ctx, roleCode)
if role != nil && role.Name != nil {
roleLabel = *role.Name
}
h.showFirstApproverSelection(bot, ctx, chatID, telegramID, roleCode, roleLabel)
return
}
if approvalTopic != nil &&
approvalTopic.AllowApproverSelection != nil &&
*approvalTopic.AllowApproverSelection &&
flowState.SelectedApproverID == 0 &&
!flowState.AwaitApproverSelection {
flowState.AwaitApproverSelection = true
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
h.showApproverSelection(bot, ctx, chatID, telegramID, approvalTopic)
return
}
if approvalTopic != nil &&
approvalTopic.AllowObserverSelection != nil &&
*approvalTopic.AllowObserverSelection &&
!flowState.ObserverSelectionDone {
flowState.ObserverSelectionDone = true
flowState.AwaitObserverSelection = true
h.States.Set(ctx, telegramID, flowState)
h.showObserverSelection(bot, ctx, chatID, telegramID, flowState, approvalTopic)
return
}
h.States.Clear(ctx, telegramID) //nolint:errcheck
h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState)
}
func (h *Handler) HandleViewFilesCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID)
if err != nil || len(files) == 0 {
sendText(bot, chatID, "📭 Файлы не найдены.")
return
}
//cardButton := tgkit.NewInlineKeyboard().
// Row(tgkit.Btn("📋 Показать заявку", fmt.Sprintf("appr_show_card:%d", approvalID))).
// Build()
caption := fmt.Sprintf("📎 <b>Файлы к заявке #%d (%d шт.):</b>", approvalID, len(files))
for i, f := range files {
if f.FileBase64 == nil || f.FileName == nil {
continue
}
data, err := base64.StdEncoding.DecodeString(*f.FileBase64)
if err != nil {
logrus.Errorf("HandleViewFilesCallback: decode err=%v", err)
continue
}
doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{
Name: *f.FileName,
Bytes: data,
})
doc.ParseMode = "HTML"
//isLast := i == len(files)-1
// Подпись — на первом файле, чтобы сразу было видно к какой заявке относится
if i == 0 {
doc.Caption = caption
}
//// Кнопка возврата к карточке — на последнем файле
//if isLast {
// doc.ReplyMarkup = cardButton
//}
if _, err := bot.Send(doc); err != nil {
logrus.Errorf("HandleViewFilesCallback: Send err=%v", err)
}
}
}
// HandleShowApprovalCardCallback показывает карточку заявки с кнопками,
// соответствующими роли нажавшего пользователя именно в этой заявке.
// Порядок проверки важен: сначала более специфичные роли (исполнитель активной
// задачи, активный согласующий), затем инициатор, затем директор/наблюдатель.
func (h *Handler) HandleShowApprovalCardCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID 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
}
currentUserID := *user.ID
approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
if err != nil || approval == nil {
sendText(bot, chatID, "⚠️ Заявка не найдена.")
return
}
files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID)
approval.Files = files
filesCount := len(files)
commentsCount := h.GetCommentsCount(ctx, approvalID)
status := ""
if approval.Status != nil {
status = *approval.Status
}
collected := h.getCollectedFromApproval(ctx, approval)
card := h.buildApprovalCard(ctx, approval, collected)
// 1. Исполнитель активной задачи по этой заявке
tasks, _, err := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTask{ApprovalID: &approvalID, ExecutorID: &currentUserID},
})
if err == nil {
for _, task := range tasks {
if task.Status != nil && *task.Status == "pending" {
h.sendTaskCard(bot, chatID, approval, task)
return
}
}
}
// 2. Активный согласующий (включая делегатов) по этой заявке
categoryCode := h.getTopicCodeByApproval(ctx, approval)
approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
isAnyOf := approvalTopic != nil && approvalTopic.ApprovalMode != nil && *approvalTopic.ApprovalMode == "any_of"
if status == "pending" {
if step := h.findStepForCurrentApprover(ctx, approvalID, currentUserID, approval, isAnyOf); step != nil {
msg := tgbotapi.NewMessage(chatID, card)
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, filesCount > 0, filesCount, commentsCount)
bot.Send(msg) //nolint:errcheck
return
}
}
// 3. Дополнительный согласующий (pending) по этой заявке
additionalApprovers, _, _ := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalAdditionalApprover{ApprovalID: &approvalID},
})
for _, aa := range additionalApprovers {
if aa.ApproverID != nil && *aa.ApproverID == currentUserID && aa.Status != nil && *aa.Status == "pending" {
msg := tgbotapi.NewMessage(chatID, card)
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildApproverDecision(approvalID, status, filesCount > 0, filesCount, commentsCount)
bot.Send(msg) //nolint:errcheck
return
}
}
// 4. Инициатор заявки
if approval.InitiatorID != nil && *approval.InitiatorID == currentUserID {
msg := tgbotapi.NewMessage(chatID, card)
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildRevokeButton(approvalID, status, filesCount, commentsCount)
bot.Send(msg) //nolint:errcheck
return
}
// 5. Директор
if isDirector, _ := h.ipc.Database.User.IsDirectorDB(ctx, currentUserID); isDirector {
msg := tgbotapi.NewMessage(chatID, card)
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildRevokeButton(approvalID, status, filesCount, commentsCount)
bot.Send(msg) //nolint:errcheck
return
}
// 6. Наблюдатель категории/темы
if h.canUserAccessObserverView(ctx, currentUserID, categoryCode, approval.TopicID) {
msg := tgbotapi.NewMessage(chatID, card)
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildObserverActions(approvalID, "", status, filesCount, commentsCount)
bot.Send(msg) //nolint:errcheck
return
}
// 7. Ни одна роль не подошла — показываем карточку без действий (просмотр)
msg := tgbotapi.NewMessage(chatID, card)
msg.ParseMode = "HTML"
bot.Send(msg) //nolint:errcheck
}
// canUserAccessObserverView проверяет, входит ли пользователь в список наблюдателей
// для категории/темы этой заявки.
func (h *Handler) canUserAccessObserverView(ctx context.Context, userID uint64, categoryCode string, topicID *uint64) bool {
observers, err := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, topicID)
if err != nil {
return false
}
for _, obs := range observers {
if obs.ID != nil && *obs.ID == userID {
return true
}
}
return false
}