Fix suggestion messager && add file attachment to approval for approver

This commit is contained in:
romanskijdev 2026-04-26 11:42:34 +03:00
parent 99c223308a
commit 8928e8494a
12 changed files with 420 additions and 171 deletions

View File

@ -3,9 +3,10 @@ package typescore
import "time"
type ApprovalFile struct {
ID *uint64 `gorm:"column:id;autoIncrement;not null;unique" json:"id" db:"id"`
ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"`
FileBase64 *string `gorm:"type:text;not null;column:file_base64" json:"file_base64" db:"file_base64"`
FileName *string `gorm:"type:text;not null;column:file_name" json:"file_name" db:"file_name"`
CreatedAt *time.Time `gorm:"default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
ID *uint64 `gorm:"column:id;autoIncrement;not null;unique" json:"id" db:"id"`
ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"`
FileBase64 *string `gorm:"type:text;not null;column:file_base64" json:"file_base64" db:"file_base64"`
FileName *string `gorm:"type:text;not null;column:file_name" json:"file_name" db:"file_name"`
AttachedByID *uint64 `gorm:"type:bigint;index;column:attached_by_id" json:"attached_by_id"`
CreatedAt *time.Time `gorm:"default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
}

View File

@ -138,6 +138,18 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
s.approvalHandler.HandleSubmitFiles(bot, cq.Message.Chat.ID, int64(cq.From.ID), false)
case strings.HasPrefix(data, "appr_attach:"):
approvalID := parseID(data, "appr_attach:")
s.approvalHandler.HandleAttachFileStart(bot, cq, approvalID)
case strings.HasPrefix(data, "appr_attach_cancel:"):
ctx := context.Background()
key := fmt.Sprintf("appr_attach_file:%d", cq.From.ID)
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
bot.Send(tgbotapi.NewMessage(cq.Message.Chat.ID, "❌ Отменено")) //nolint:errcheck
// ── НАВИГАЦИЯ ФЛОУ ──────────────────────────────────────────
case strings.HasPrefix(data, "appr_back:"):
topicCode := strings.TrimPrefix(data, "appr_back:")

View File

@ -206,6 +206,17 @@ func (s *UpdateHandler) handleMessage(bot *tgbotapi.BotAPI, msg *tgbotapi.Messag
return
}
if s.approvalHandler.HandleAttachFileInput(bot, msg) {
return
}
if msg.Photo != nil || msg.Document != nil {
s.withDepartmentCheck(bot, msg, func() {
s.approvalHandler.HandleFileInput(bot, msg)
})
return
}
if s.approvalHandler.HandleDelegationDateInput(bot, msg) {
return
}

View File

@ -92,14 +92,14 @@ func (h *Handler) HandleCommentTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Mes
return true
}
// Создаем комментарий
comment := &typescore.ApprovalComment{
ApprovalID: &commentState.ApprovalID,
UserID: user.ID,
Comment: &msg.Text,
}
createdComment, _, err := h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment)
// Вызываем БЕЗ returnObj=true, чтобы не делать повторный SELECT
_, _, err = h.ipc.Database.ApprovalComment.CreateApprovalCommentDB(ctx, nil, comment)
if err != nil {
logrus.Errorf("HandleCommentTextInput: CreateApprovalCommentDB err=%v", err)
sendText(bot, chatID, "Ошибка при сохранении комментария.")
@ -107,14 +107,6 @@ func (h *Handler) HandleCommentTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Mes
return true
}
// Проверяем, что комментарий создан
if createdComment == nil {
logrus.Errorf("HandleCommentTextInput: createdComment is nil")
sendText(bot, chatID, "Ошибка при сохранении комментария.")
h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck
return true
}
h.States.ClearCommentFlow(ctx, telegramID) //nolint:errcheck
userName := "—"
@ -130,13 +122,13 @@ func (h *Handler) HandleCommentTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Mes
commentState.ApprovalID, userName, msg.Text,
))
// Уведомляем инициатора
// Уведомляем инициатора - передаём comment напрямую без повторного запроса
if approval.InitiatorID != nil {
initiator, err := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
if err != nil {
logrus.Errorf("HandleCommentTextInput: GetUserByIDDB initiator err=%v", err)
} else if initiator != nil && initiator.TelegramID != nil {
h.notifyInitiatorAboutComment(bot, ctx, initiator, approval, user, createdComment)
h.notifyInitiatorAboutComment(bot, ctx, initiator, approval, user, comment)
}
}

View File

@ -231,12 +231,12 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co
if err != nil {
logrus.Errorf("processNextStepOrComplete: CreateApprovalTaskDB err=%v", err)
}
h.notifyExecutor(bot, ctx, executor, initiator, approval, collected, createdTask)
h.notifyExecutor(bot, ctx, executor, initiator, approval, createdTask)
if err != nil {
logrus.Errorf("processNextStepOrComplete: CreateApprovalTaskDB err=%v", err)
} else if createdTask != nil && executor.TelegramID != nil {
// Уведомляем исполнителя
h.notifyExecutor(bot, ctx, executor, initiator, approval, collected, createdTask)
h.notifyExecutor(bot, ctx, executor, initiator, approval, createdTask)
}
}
}

View File

@ -0,0 +1,238 @@
package approval
import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/telegram_service/keyboard"
"bitrix_balancer_api/telegram_service/state"
"context"
"encoding/base64"
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
"io"
"net/http"
"time"
)
// HandleAttachFileInput обрабатывает файл, который согласующий/исполнитель прикрепляет к заявке
func (h *Handler) HandleAttachFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
ctx := context.Background()
telegramID := msg.From.ID
chatID := msg.Chat.ID
// Проверяем режим прикрепления
key := fmt.Sprintf("appr_attach_file:%d", telegramID)
val, err := h.ipc.RedisClient.Get(ctx, key)
if err != nil || val == "" {
return false // не в режиме прикрепления
}
var approvalID uint64
fmt.Sscanf(val, "%d", &approvalID)
var fileID, fileName string
switch {
case msg.Photo != nil && len(msg.Photo) > 0:
best := msg.Photo[len(msg.Photo)-1]
fileID = best.FileID
fileName = fmt.Sprintf("photo_%s.jpg", time.Now().Format("20060102_150405"))
case msg.Document != nil:
fileID = msg.Document.FileID
fileName = msg.Document.FileName
default:
bot.Send(tgbotapi.NewMessage(chatID, "⚠️ Пожалуйста, отправьте фото или документ.")) //nolint:errcheck
return true
}
fileURL, err := bot.GetFileDirectURL(fileID)
if err != nil {
logrus.Errorf("HandleAttachFileInput: GetFileDirectURL err=%v", err)
bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при получении файла.")) //nolint:errcheck
return true
}
base64Data, err := fetchFileAsBase64(fileURL)
if err != nil {
logrus.Errorf("HandleAttachFileInput: fetchFileAsBase64 err=%v", err)
bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при обработке файла.")) //nolint:errcheck
return true
}
// Получаем пользователя
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
if err != nil || user == nil || user.ID == nil {
logrus.Errorf("HandleAttachFileInput: GetUserByTelegramIDDB err=%v", err)
return true
}
// Сохраняем файл в БД
file := &typescore.ApprovalFile{
ApprovalID: &approvalID,
FileBase64: &base64Data,
FileName: &fileName,
AttachedByID: user.ID,
}
if _, _, err := h.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, file); err != nil {
logrus.Errorf("HandleAttachFileInput: CreateApprovalFileDB err=%v", err)
bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при сохранении файла.")) //nolint:errcheck
return true
}
// Очищаем режим прикрепления
h.ipc.RedisClient.Del(ctx, key) //nolint:errcheck
bot.Send(tgbotapi.NewMessage(chatID, "✅ Файл прикреплён к заявке")) //nolint:errcheck
// Уведомляем наблюдателей
h.notifyObserversAboutNewFile(bot, approvalID, user, fileName, base64Data)
return true
}
// HandleFileInput обрабатывает прикреплённый файл (фото или документ) во время флоу.
func (h *Handler) HandleFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
ctx := context.Background()
telegramID := msg.From.ID
chatID := msg.Chat.ID
flowState, err := h.States.Get(ctx, telegramID)
if err != nil || flowState == nil || !flowState.AwaitFileInput {
return false
}
var fileID, fileName string
switch {
case msg.Photo != nil && len(msg.Photo) > 0:
best := msg.Photo[len(msg.Photo)-1]
fileID = best.FileID
// Используем timestamp вместо счётчика
fileName = fmt.Sprintf("photo_%s.jpg", time.Now().Format("20060102_150405"))
case msg.Document != nil:
fileID = msg.Document.FileID
fileName = msg.Document.FileName // оригинальное имя
default:
bot.Send(tgbotapi.NewMessage(chatID, "⚠️ Пожалуйста, отправьте фото или PDF-документ.")) //nolint:errcheck
return true
}
fileURL, err := bot.GetFileDirectURL(fileID)
if err != nil {
logrus.Errorf("HandleFileInput: GetFileDirectURL err=%v", err)
bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при получении файла. Попробуйте ещё раз.")) //nolint:errcheck
return true
}
base64Data, err := fetchFileAsBase64(fileURL)
if err != nil {
logrus.Errorf("HandleFileInput: fetchFileAsBase64 err=%v", err)
bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при обработке файла. Попробуйте ещё раз.")) //nolint:errcheck
return true
}
flowState.Files = append(flowState.Files, state.FileAttachment{
Base64: base64Data,
FileName: fileName,
})
h.showFileStatus(bot, chatID, int64(telegramID), flowState)
return true
}
func (h *Handler) HandleAttachFileStart(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, approvalID uint64) {
ctx := context.Background()
bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
// Сохраняем в Redis режим прикрепления
key := fmt.Sprintf("appr_attach_file:%d", cq.From.ID)
if err := h.ipc.RedisClient.Set(ctx, key, fmt.Sprintf("%d", approvalID), 10*time.Minute); err != nil {
logrus.Errorf("HandleAttachFileStart: Redis.Set err=%v", err)
return
}
msg := tgbotapi.NewMessage(cq.Message.Chat.ID,
"📎 <b>Прикрепление файла к заявке</b>\n\n"+
"Отправьте фото или документ, который нужно добавить к согласованию.")
msg.ParseMode = "HTML"
msg.ReplyMarkup = keyboard.BuildAttachFileCancel(approvalID)
bot.Send(msg) //nolint:errcheck
}
// HandleDetachFile удаляет файл из списка по индексу и обновляет статусное сообщение.
func (h *Handler) HandleDetachFile(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, index int) {
ctx := context.Background()
flowState, err := h.States.Get(ctx, telegramID)
if err != nil || flowState == nil {
return
}
if index < 0 || index >= len(flowState.Files) {
logrus.Warnf("HandleDetachFile: invalid index %d (total=%d)", index, len(flowState.Files))
return
}
removed := flowState.Files[index].FileName
flowState.Files = append(flowState.Files[:index], flowState.Files[index+1:]...)
logrus.Infof("HandleDetachFile: removed file %q, remaining=%d", removed, len(flowState.Files))
h.showFileStatus(bot, chatID, telegramID, flowState)
}
// HandleSubmitFiles финализирует заявку. withFiles=false очищает список файлов перед отправкой.
func (h *Handler) HandleSubmitFiles(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, withFiles bool) {
ctx := context.Background()
flowState, err := h.States.Get(ctx, telegramID)
if err != nil || flowState == nil {
return
}
if !withFiles {
flowState.Files = nil
}
if flowState.FileStatusMsgID != 0 {
bot.Request(tgbotapi.NewDeleteMessage(chatID, flowState.FileStatusMsgID)) //nolint:errcheck
flowState.FileStatusMsgID = 0
}
// Проверяем, нужно ли выбирать согласующего
topic, _ := h.registry.Get(flowState.TopicCode)
if topic != nil {
topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected)
approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
if approvalTopic != nil && approvalTopic.AllowApproverSelection != nil && *approvalTopic.AllowApproverSelection {
// Нужно выбрать согласующего
flowState.AwaitApproverSelection = true
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
h.showApproverSelection(bot, ctx, chatID, telegramID, approvalTopic)
return
}
}
// Если выбор согласующего не нужен - отправляем заявку
h.States.Clear(ctx, telegramID) //nolint:errcheck
h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState)
}
// fetchFileAsBase64 скачивает файл по URL и возвращает base64-строку.
func fetchFileAsBase64(url string) (string, error) {
resp, err := http.Get(url) //nolint:gosec
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(data), nil
}

View File

@ -6,10 +6,7 @@ import (
"bitrix_balancer_api/telegram_service/state"
"bitrix_balancer_api/telegram_service/types"
"context"
"encoding/base64"
"fmt"
"io"
"net/http"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
@ -199,129 +196,6 @@ func (h *Handler) HandleTextInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) b
return true
}
// HandleFileInput обрабатывает прикреплённый файл (фото или документ) во время флоу.
func (h *Handler) HandleFileInput(bot *tgbotapi.BotAPI, msg *tgbotapi.Message) bool {
ctx := context.Background()
telegramID := msg.From.ID
chatID := msg.Chat.ID
flowState, err := h.States.Get(ctx, telegramID)
if err != nil || flowState == nil || !flowState.AwaitFileInput {
return false
}
var fileID, fileName string
switch {
case msg.Photo != nil && len(msg.Photo) > 0:
best := msg.Photo[len(msg.Photo)-1]
fileID = best.FileID
fileName = fmt.Sprintf("photo_%d.jpg", len(flowState.Files)+1)
case msg.Document != nil:
fileID = msg.Document.FileID
fileName = msg.Document.FileName
default:
bot.Send(tgbotapi.NewMessage(chatID, "⚠️ Пожалуйста, отправьте фото или PDF-документ.")) //nolint:errcheck
return true
}
fileURL, err := bot.GetFileDirectURL(fileID)
if err != nil {
logrus.Errorf("HandleFileInput: GetFileDirectURL err=%v", err)
bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при получении файла. Попробуйте ещё раз.")) //nolint:errcheck
return true
}
base64Data, err := fetchFileAsBase64(fileURL)
if err != nil {
logrus.Errorf("HandleFileInput: fetchFileAsBase64 err=%v", err)
bot.Send(tgbotapi.NewMessage(chatID, "Ошибка при обработке файла. Попробуйте ещё раз.")) //nolint:errcheck
return true
}
// Добавляем файл в список — НЕ сабмитим, ждём ещё файлы или кнопку
flowState.Files = append(flowState.Files, state.FileAttachment{
Base64: base64Data,
FileName: fileName,
})
// AwaitFileInput остаётся true
h.showFileStatus(bot, chatID, int64(telegramID), flowState)
return true
}
// HandleDetachFile удаляет файл из списка по индексу и обновляет статусное сообщение.
func (h *Handler) HandleDetachFile(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, index int) {
ctx := context.Background()
flowState, err := h.States.Get(ctx, telegramID)
if err != nil || flowState == nil {
return
}
if index < 0 || index >= len(flowState.Files) {
logrus.Warnf("HandleDetachFile: invalid index %d (total=%d)", index, len(flowState.Files))
return
}
removed := flowState.Files[index].FileName
flowState.Files = append(flowState.Files[:index], flowState.Files[index+1:]...)
logrus.Infof("HandleDetachFile: removed file %q, remaining=%d", removed, len(flowState.Files))
h.showFileStatus(bot, chatID, telegramID, flowState)
}
// HandleSubmitFiles финализирует заявку. withFiles=false очищает список файлов перед отправкой.
func (h *Handler) HandleSubmitFiles(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, withFiles bool) {
ctx := context.Background()
flowState, err := h.States.Get(ctx, telegramID)
if err != nil || flowState == nil {
return
}
if !withFiles {
flowState.Files = nil
}
if flowState.FileStatusMsgID != 0 {
bot.Request(tgbotapi.NewDeleteMessage(chatID, flowState.FileStatusMsgID)) //nolint:errcheck
flowState.FileStatusMsgID = 0
}
// Проверяем, нужно ли выбирать согласующего
topic, _ := h.registry.Get(flowState.TopicCode)
if topic != nil {
topicCode, _ := topic.TopicCodeFromCollected(flowState.Collected)
approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByCodeDB(ctx, topicCode)
if approvalTopic != nil && approvalTopic.AllowApproverSelection != nil && *approvalTopic.AllowApproverSelection {
// Нужно выбрать согласующего
flowState.AwaitApproverSelection = true
h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
h.showApproverSelection(bot, ctx, chatID, telegramID, approvalTopic)
return
}
}
// Если выбор согласующего не нужен - отправляем заявку
h.States.Clear(ctx, telegramID) //nolint:errcheck
h.finalizeAndSubmit(bot, ctx, chatID, telegramID, flowState)
}
// fetchFileAsBase64 скачивает файл по URL и возвращает base64-строку.
func fetchFileAsBase64(url string) (string, error) {
resp, err := http.Get(url) //nolint:gosec
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(data), nil
}
func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, telegramID int64, approvalID uint64, comment string) {
ctx := context.Background()

View File

@ -79,9 +79,10 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
base64Copy := f.Base64
nameCopy := f.FileName
file := &typescore.ApprovalFile{
ApprovalID: created.ID,
FileBase64: &base64Copy,
FileName: &nameCopy,
ApprovalID: created.ID,
FileBase64: &base64Copy,
FileName: &nameCopy,
AttachedByID: initiator.ID,
}
if _, _, err := h.ipc.Database.ApprovalFile.CreateApprovalFileDB(ctx, nil, file); err != nil {
logrus.Errorf("submitApproval: CreateApprovalFileDB err=%v", err)

View File

@ -22,15 +22,7 @@ func NewNotifier(ipc *types.InternalProviderControl, topic approvalflow.Topic) *
return &Notifier{ipc: ipc, topic: topic}
}
func (h *Handler) notifyExecutor(
bot *tgbotapi.BotAPI,
ctx context.Context,
executor *typescore.User,
initiator *typescore.User,
approval *typescore.Approval,
collected map[string]string,
task *typescore.ApprovalTask,
) {
func (h *Handler) notifyExecutor(bot *tgbotapi.BotAPI, ctx context.Context, executor *typescore.User, initiator *typescore.User, approval *typescore.Approval, task *typescore.ApprovalTask) {
if executor.TelegramID == nil || task.ID == nil || approval.ID == nil {
return
}
@ -457,3 +449,67 @@ func (h *Handler) sendAdditionalApprovalCard(bot *tgbotapi.BotAPI, chatID int64,
msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID)
bot.Send(msg) //nolint:errcheck
}
// notifyObserversAboutNewFile уведомляет наблюдателей о прикреплённом файле
func (h *Handler) notifyObserversAboutNewFile(bot *tgbotapi.BotAPI, approvalID uint64, attachedBy *typescore.User, fileName, fileBase64 string) {
ctx := context.Background()
// Получаем заявку для topicCode
approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
if err != nil || approval == nil {
logrus.Errorf("notifyObserversAboutNewFile: GetApprovalByIDDB err=%v", err)
return
}
topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
if err != nil || topic == nil || topic.Code == nil {
logrus.Errorf("notifyObserversAboutNewFile: GetApprovalTopicByIDDB err=%v", err)
return
}
observers, err := h.ipc.Database.User.GetObserversForCategoryDB(ctx, *topic.Code)
if err != nil {
logrus.Warnf("notifyObserversAboutNewFile: GetObserversForCategoryDB err=%v", err)
return
}
userName := "Пользователь"
if attachedBy.FullName != nil {
userName = *attachedBy.FullName
}
for _, obs := range observers {
if obs.TelegramID == nil {
continue
}
text := fmt.Sprintf(
"📎 <b>К заявке #%d добавлен файл</b>\n\n"+
"👤 <b>Кем:</b> %s\n"+
"📄 <b>Файл:</b> %s",
approvalID, userName, fileName,
)
// Декодируем и отправляем файл
fileData, err := base64.StdEncoding.DecodeString(fileBase64)
if err != nil {
logrus.Errorf("notifyObserversAboutNewFile: base64 decode err=%v", err)
// Отправляем хотя бы текст
msg := tgbotapi.NewMessage(*obs.TelegramID, text)
msg.ParseMode = "HTML"
bot.Send(msg) //nolint:errcheck
continue
}
doc := tgbotapi.NewDocument(*obs.TelegramID, tgbotapi.FileBytes{
Name: fileName,
Bytes: fileData,
})
doc.Caption = text
doc.ParseMode = "HTML"
if _, err := bot.Send(doc); err != nil {
logrus.Errorf("notifyObserversAboutNewFile: Send document err=%v", err)
}
}
}

View File

@ -106,8 +106,15 @@ func (h *Handler) handleSubjectInput(bot *tgbotapi.BotAPI, ctx context.Context,
return true
}
func (h *Handler) handleMessageInput(bot *tgbotapi.BotAPI, ctx context.Context, chatID, telegramID int64, user *typescore.User, suggestionState *state.SuggestionFlowState, messageText string, fileData, fileName *string) bool {
// Создаем сообщение
func (h *Handler) handleMessageInput(
bot *tgbotapi.BotAPI,
ctx context.Context,
chatID, telegramID int64,
user *typescore.User,
suggestionState *state.SuggestionFlowState,
messageText string,
fileData, fileName *string,
) bool {
message := &typescore.SuggestionMessage{
SuggestionID: &suggestionState.SuggestionID,
UserID: user.ID,
@ -123,21 +130,36 @@ func (h *Handler) handleMessageInput(bot *tgbotapi.BotAPI, ctx context.Context,
return true
}
// Получаем предложение
suggestion, err := h.ipc.Database.Suggestion.GetSuggestionByIDDB(ctx, suggestionState.SuggestionID)
if err != nil || suggestion == nil {
logrus.Errorf("handleMessageInput: GetSuggestionByIDDB err=%v", err)
return true
}
sendText(bot, chatID, "✅ Ваше сообщение отправлено директору.")
if suggestion.InitiatorID == nil || suggestion.DirectorID == nil || user.ID == nil {
logrus.Errorf("handleMessageInput: suggestion participants are nil")
return true
}
// Уведомляем директора
if suggestion.DirectorID != nil {
director, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.DirectorID)
if director != nil && director.TelegramID != nil {
h.notifyAboutMessage(bot, ctx, *director.TelegramID, suggestion, user, messageText, fileData, fileName, true)
}
sendText(bot, chatID, "✅ Ваше сообщение отправлено.")
var recipientID uint64
if *user.ID == *suggestion.InitiatorID {
recipientID = *suggestion.DirectorID
} else {
recipientID = *suggestion.InitiatorID
}
recipient, err := h.ipc.Database.User.GetUserByIDDB(ctx, recipientID)
if err != nil || recipient == nil {
logrus.Errorf("handleMessageInput: GetUserByIDDB recipient err=%v", err)
h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck
return true
}
if recipient.TelegramID != nil {
isNew := suggestionState.Stage == "await_subject" // первое сообщение
h.notifyAboutMessage(bot, ctx, *recipient.TelegramID, suggestion, user, messageText, fileData, fileName, isNew)
}
h.States.ClearSuggestionFlow(ctx, telegramID) //nolint:errcheck
@ -163,25 +185,52 @@ func (h *Handler) HandleReplyToSuggestion(bot *tgbotapi.BotAPI, cq *tgbotapi.Cal
return
}
// Проверяем, что пользователь - участник диалога
if suggestion.InitiatorID == nil || suggestion.DirectorID == nil {
sendText(bot, chatID, "⚠️ Ошибка данных предложения.")
return
}
if *user.ID != *suggestion.InitiatorID && *user.ID != *suggestion.DirectorID {
// Проверяем что пользователь - участник диалога
isInitiator := *user.ID == *suggestion.InitiatorID
isDirector := *user.ID == *suggestion.DirectorID
if !isInitiator && !isDirector {
sendText(bot, chatID, "⚠️ Вы не участник этого диалога.")
return
}
// Сохраняем состояние ожидания ответа
suggestionState := &state.SuggestionFlowState{
SuggestionID: suggestionID,
Stage: "await_message",
}
h.States.SetSuggestionFlow(ctx, telegramID, suggestionState) //nolint:errcheck
sendText(bot, chatID, "💬 Введите ваш ответ или прикрепите файл:")
// Показываем кому пойдёт ответ
var recipientName string
if isInitiator {
director, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.DirectorID)
if director != nil && director.FullName != nil {
recipientName = *director.FullName
}
} else {
initiator, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *suggestion.InitiatorID)
if initiator != nil && initiator.FullName != nil {
recipientName = *initiator.FullName
}
}
subject := "—"
if suggestion.Subject != nil {
subject = *suggestion.Subject
}
sendText(bot, chatID, fmt.Sprintf(
"💬 <b>Ответить на предложение #%d</b>\n"+
"📋 Тема: %s\n"+
"➡️ Получатель: %s\n\n"+
"Введите текст или прикрепите файл:",
suggestionID, subject, recipientName,
))
}
func (h *Handler) HandleViewSuggestion(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, suggestionID uint64) {

View File

@ -106,6 +106,7 @@ func BuildApproverDecision(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("💬 Добавить комментарий", fmt.Sprintf("appr_comment:%d", approvalID)),
tgbotapi.NewInlineKeyboardButtonData("📎 Прикрепить файл", fmt.Sprintf("appr_attach:%d", approvalID)),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("Стадия согласования", fmt.Sprintf("appr_stage:%d", approvalID)),

View File

@ -0,0 +1,14 @@
package keyboard
import (
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
func BuildAttachFileCancel(approvalID uint64) tgbotapi.InlineKeyboardMarkup {
return tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("❌ Отмена", fmt.Sprintf("appr_attach_cancel:%d", approvalID)),
),
)
}