634 lines
21 KiB
Go
634 lines
21 KiB
Go
package approval
|
||
|
||
import (
|
||
"bitrix_balancer_api/core/typescore"
|
||
"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"
|
||
"time"
|
||
|
||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||
"github.com/sirupsen/logrus"
|
||
)
|
||
|
||
type Handler struct {
|
||
ipc *types.InternalProviderControl
|
||
Registry *Registry
|
||
States *state.StateManager
|
||
}
|
||
|
||
func NewHandler(ipc *types.InternalProviderControl) *Handler {
|
||
return &Handler{
|
||
ipc: ipc,
|
||
Registry: NewRegistry(),
|
||
States: state.NewStateManager(ipc.RedisClient),
|
||
}
|
||
}
|
||
|
||
// 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
|
||
}
|
||
default:
|
||
if !isInitiator && !isDirector {
|
||
sendText(bot, chatID, "⚠️ У вас нет прав для отзыва этой заявки.")
|
||
return
|
||
}
|
||
}
|
||
|
||
now := time.Now()
|
||
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("HandleRevokeWithComment: UpdateApprovalDB err=%v", err)
|
||
sendText(bot, chatID, "Ошибка при отзыве заявки.")
|
||
return
|
||
}
|
||
|
||
h.handleRevokeCancellationTask(bot, ctx, approval, revoker, comment)
|
||
|
||
revokerName := "—"
|
||
if revoker.FullName != nil {
|
||
revokerName = *revoker.FullName
|
||
}
|
||
|
||
topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
|
||
|
||
content := "—"
|
||
if approval.Content != nil {
|
||
content = *approval.Content
|
||
}
|
||
|
||
revokerRole := ""
|
||
switch {
|
||
case isInitiator:
|
||
revokerRole = "инициатором"
|
||
case isDirector:
|
||
revokerRole = "директором"
|
||
case isApprover:
|
||
revokerRole = "согласующим"
|
||
}
|
||
|
||
approvalCard := fmt.Sprintf(
|
||
"📋 <b>Тема:</b> %s\n"+
|
||
"📝 <b>Текст:</b> %s\n"+
|
||
"💬 <b>Причина отзыва:</b> %s",
|
||
topicFullName, content, comment,
|
||
)
|
||
|
||
// Уведомление тому, кто отзывает
|
||
sendText(bot, chatID, fmt.Sprintf(
|
||
"↩️ <b>Заявка #%d отозвана</b>\n\n%s",
|
||
approvalID, approvalCard,
|
||
))
|
||
|
||
if !isInitiator && approval.InitiatorID != nil {
|
||
initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
|
||
if err == nil && initiator != nil && initiator.TelegramID != nil {
|
||
sendText(bot, *initiator.TelegramID, fmt.Sprintf(
|
||
"↩️ <b>Ваша заявка #%d отозвана %s %s</b>\n\n%s",
|
||
approvalID, revokerRole, revokerName, approvalCard,
|
||
))
|
||
}
|
||
}
|
||
|
||
if !isDirector {
|
||
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
|
||
}
|
||
sendText(bot, *director.TelegramID, fmt.Sprintf(
|
||
"↩️ <b>Заявка #%d отозвана %s %s</b>\n\n%s",
|
||
approvalID, revokerRole, revokerName, approvalCard,
|
||
))
|
||
}
|
||
}
|
||
|
||
for _, step := range steps {
|
||
if step.ApproverID == nil {
|
||
continue
|
||
}
|
||
if revoker.ID != nil && *step.ApproverID == *revoker.ID {
|
||
continue
|
||
}
|
||
approver, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
|
||
if approver == nil || approver.TelegramID == nil {
|
||
continue
|
||
}
|
||
sendText(bot, *approver.TelegramID, fmt.Sprintf(
|
||
"↩️ <b>Заявка #%d отозвана %s %s</b>\n\n%s",
|
||
approvalID, revokerRole, revokerName, approvalCard,
|
||
))
|
||
}
|
||
|
||
if *approval.Status == "revoked" {
|
||
categoryCode := h.getTopicCodeByApproval(ctx, approval)
|
||
observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode)
|
||
for _, obs := range observers {
|
||
if obs.TelegramID == nil {
|
||
continue
|
||
}
|
||
if revoker.ID != nil && obs.ID != nil && *obs.ID == *revoker.ID {
|
||
continue
|
||
}
|
||
sendText(bot, *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
|
||
}
|
||
|
||
sendText(bot, chatID, fmt.Sprintf("📎 <b>Файлы к заявке #%d (%d шт.):</b>", approvalID, len(files)))
|
||
|
||
for _, 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,
|
||
})
|
||
bot.Send(doc) //nolint:errcheck
|
||
}
|
||
}
|