826 lines
25 KiB
Go
826 lines
25 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/types"
|
||
"context"
|
||
"encoding/base64"
|
||
"fmt"
|
||
"github.com/sirupsen/logrus"
|
||
|
||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||
)
|
||
|
||
type Notifier struct {
|
||
ipc *types.InternalProviderControl
|
||
topic approvalflow.Topic
|
||
}
|
||
|
||
func NewNotifier(ipc *types.InternalProviderControl, topic approvalflow.Topic) *Notifier {
|
||
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, task *typescore.ApprovalTask) {
|
||
if executor.TelegramID == nil || task.ID == nil || approval.ID == nil {
|
||
return
|
||
}
|
||
|
||
initiatorName := "—"
|
||
if initiator.FullName != nil {
|
||
initiatorName = *initiator.FullName
|
||
}
|
||
|
||
topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
|
||
|
||
content := "—"
|
||
if approval.Content != nil {
|
||
content = *approval.Content
|
||
}
|
||
|
||
taskText := "—"
|
||
if task.TaskText != nil {
|
||
taskText = *task.TaskText
|
||
}
|
||
|
||
text := fmt.Sprintf(
|
||
"📋 <b>Новая задача по заявке #%d</b>\n\n"+
|
||
"👤 <b>Инициатор:</b> %s\n"+
|
||
"📋 <b>Тема:</b> %s\n"+
|
||
"📝 <b>Текст заявки:</b> %s\n\n"+
|
||
"🎯 <b>Задача:</b>\n%s",
|
||
*approval.ID, initiatorName, topicFullName, content, taskText,
|
||
)
|
||
|
||
// Добавляем комментарии
|
||
commentsSection := h.formatCommentsSection(ctx, *approval.ID)
|
||
text += commentsSection
|
||
|
||
// 🆕 Получаем все файлы заявки
|
||
allFiles, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
|
||
filesCount := len(allFiles)
|
||
|
||
// 🆕 Информация о файлах, приложенных к этой задаче
|
||
var taskFiles []string
|
||
for _, f := range allFiles {
|
||
if f.TaskID != nil && *f.TaskID == *task.ID && f.FileName != nil {
|
||
taskFiles = append(taskFiles, *f.FileName)
|
||
}
|
||
}
|
||
if len(taskFiles) > 0 {
|
||
text += "\n\n📎 <b>Файлы к этой задаче:</b>\n"
|
||
for i, name := range taskFiles {
|
||
text += fmt.Sprintf("%d. %s\n", i+1, name)
|
||
}
|
||
} else if filesCount > 0 {
|
||
// 🆕 Если есть файлы заявки, но не к этой задаче — показываем кнопку
|
||
text += fmt.Sprintf("\n\n📂 <b>В заявке есть файлы (%d шт.) — см. кнопку ниже</b>", filesCount)
|
||
}
|
||
|
||
// 🆕 Передаём filesCount в клавиатуру
|
||
msg := tgbotapi.NewMessage(*executor.TelegramID, text)
|
||
msg.ParseMode = "HTML"
|
||
msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, filesCount)
|
||
bot.Send(msg) //nolint:errcheck
|
||
}
|
||
|
||
func (n *Notifier) ensureInstructions(ctx context.Context, approval *typescore.Approval, collected map[string]string) map[string]string {
|
||
if collected == nil {
|
||
collected = make(map[string]string)
|
||
}
|
||
|
||
// Если инструкция уже есть — ничего не делаем
|
||
if _, ok := collected["instructions"]; ok && collected["instructions"] != "" {
|
||
return collected
|
||
}
|
||
|
||
// Подгружаем тему из БД и берём инструкцию
|
||
if approval != nil && approval.TopicID != nil {
|
||
topic, err := n.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
|
||
if err == nil && topic != nil && topic.Instructions != nil && *topic.Instructions != "" {
|
||
collected["instructions"] = *topic.Instructions
|
||
}
|
||
}
|
||
|
||
return collected
|
||
}
|
||
|
||
// NotifyApprover отправляет уведомление согласующему с кнопками Да/Нет.
|
||
func (n *Notifier) NotifyApprover(
|
||
bot *tgbotapi.BotAPI,
|
||
approver *typescore.User,
|
||
initiator *typescore.User,
|
||
approval *typescore.Approval,
|
||
collected map[string]string,
|
||
) {
|
||
if approver.TelegramID == nil || approval.ID == nil {
|
||
return
|
||
}
|
||
|
||
ctx := context.Background()
|
||
|
||
collected = n.ensureInstructions(ctx, approval, collected)
|
||
|
||
msgText := fmt.Sprintf("📬 <b>Новая заявка #%d на согласование</b>\n\n", *approval.ID) +
|
||
n.topic.FormatApproverMessage(initiator, collected)
|
||
|
||
// Добавляем комментарии если есть
|
||
comments, _ := n.ipc.Database.ApprovalComment.GetCommentsByApprovalIDDB(ctx, *approval.ID)
|
||
if len(comments) > 0 {
|
||
msgText += "\n\n💬 <b>Комментарии:</b>"
|
||
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<b>%s</b> (%s):\n%s", *user.FullName, timestamp, *comment.Comment)
|
||
}
|
||
}
|
||
|
||
// Отправляем с файлами или без
|
||
if len(approval.Files) == 0 {
|
||
n.sendTextToApprover(bot, approver, approval, msgText)
|
||
return
|
||
}
|
||
|
||
status := ""
|
||
if approval.Status != nil {
|
||
status = *approval.Status
|
||
}
|
||
|
||
files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
|
||
|
||
n.sendFilesToRecipient(
|
||
bot,
|
||
*approver.TelegramID,
|
||
approval,
|
||
msgText,
|
||
keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files)),
|
||
)
|
||
}
|
||
|
||
func (n *Notifier) sendTextToApprover(bot *tgbotapi.BotAPI, approver *typescore.User, approval *typescore.Approval, text string) {
|
||
status := ""
|
||
if approval.Status != nil {
|
||
status = *approval.Status
|
||
}
|
||
ctx := context.Background()
|
||
files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
|
||
|
||
msg := tgbotapi.NewMessage(*approver.TelegramID, text)
|
||
msg.ParseMode = "HTML"
|
||
msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files))
|
||
bot.Send(msg) //nolint:errcheck
|
||
}
|
||
|
||
// NotifyInitiatorApproved уведомляет инициатора об одобрении.
|
||
func (n *Notifier) NotifyInitiatorApproved(
|
||
bot *tgbotapi.BotAPI,
|
||
initiator *typescore.User,
|
||
approval *typescore.Approval,
|
||
collected map[string]string,
|
||
lastApprover *typescore.User,
|
||
) {
|
||
if initiator.TelegramID == nil {
|
||
logrus.Warnf("NotifyInitiatorApproved: TelegramID is nil")
|
||
return
|
||
}
|
||
logrus.Infof("NotifyInitiatorApproved: sending to telegramID=%d approvalID=%d", *initiator.TelegramID, *approval.ID)
|
||
|
||
approverName := "—"
|
||
if lastApprover != nil && lastApprover.FullName != nil {
|
||
approverName = *lastApprover.FullName
|
||
}
|
||
|
||
content := collected["content"]
|
||
if content == "" {
|
||
content = "—"
|
||
}
|
||
|
||
status := ""
|
||
if approval.Status != nil {
|
||
status = *approval.Status
|
||
}
|
||
|
||
ctx := context.Background()
|
||
|
||
topicFullName := getTopicFullName(ctx, n.ipc, approval.TopicID)
|
||
text := fmt.Sprintf(
|
||
"✅ <b>Заявка #%d согласована</b>\n\n"+
|
||
"👤 <b>Последний согласующий:</b> %s\n"+
|
||
"📋 <b>Тема:</b> %s\n"+
|
||
"📝 <b>Текст:</b> %s",
|
||
*approval.ID, approverName, topicFullName, content,
|
||
)
|
||
|
||
filesCount := len(approval.Files)
|
||
if filesCount == 0 {
|
||
files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
|
||
filesCount = len(files)
|
||
}
|
||
|
||
msg := tgbotapi.NewMessage(*initiator.TelegramID, text)
|
||
msg.ParseMode = "HTML"
|
||
msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount)
|
||
if _, err := bot.Send(msg); err != nil {
|
||
logrus.Errorf("NotifyInitiatorApproved: Send err=%v", err)
|
||
}
|
||
}
|
||
|
||
// NotifyInitiatorRejected уведомляет инициатора об отклонении.
|
||
func (n *Notifier) NotifyInitiatorRejected(
|
||
bot *tgbotapi.BotAPI,
|
||
initiator *typescore.User,
|
||
approver *typescore.User,
|
||
approval *typescore.Approval,
|
||
collected map[string]string,
|
||
comment string,
|
||
) {
|
||
if initiator.TelegramID == nil {
|
||
return
|
||
}
|
||
|
||
approverName := "—"
|
||
if approver != nil && approver.FullName != nil {
|
||
approverName = *approver.FullName
|
||
}
|
||
|
||
content := collected["content"]
|
||
if content == "" {
|
||
content = "—"
|
||
}
|
||
ctx := context.Background()
|
||
topicFullName := getTopicFullName(ctx, n.ipc, approval.TopicID)
|
||
text := fmt.Sprintf(
|
||
"❌ <b>Заявка #%d отклонена</b>\n\n"+
|
||
"👤 <b>Согласующий:</b> %s\n"+
|
||
"📋 <b>Тема:</b> %s\n"+
|
||
"📝 <b>Текст:</b> %s",
|
||
*approval.ID, approverName, topicFullName, content,
|
||
)
|
||
|
||
if comment != "" {
|
||
text += fmt.Sprintf("\n💬 <b>Причина:</b> %s", comment)
|
||
}
|
||
|
||
msg := tgbotapi.NewMessage(*initiator.TelegramID, text)
|
||
msg.ParseMode = "HTML"
|
||
bot.Send(msg) //nolint:errcheck
|
||
}
|
||
|
||
// NotifyDirector уведомляет директора о финально согласованной заявке.
|
||
func (n *Notifier) NotifyDirector(bot *tgbotapi.BotAPI, director *typescore.User, initiator *typescore.User, approval *typescore.Approval, collected map[string]string) {
|
||
if director.TelegramID == nil {
|
||
return
|
||
}
|
||
|
||
ctx := context.Background()
|
||
// 🚀 Передаем initiator и collected для построения ПОЛНОЙ карточки
|
||
card := n.buildApprovalCard(ctx, approval, initiator, collected)
|
||
|
||
text := "📌 <b>Финально согласовано</b>\n\n" + card
|
||
|
||
status := ""
|
||
if approval.Status != nil {
|
||
status = *approval.Status
|
||
}
|
||
|
||
// Считаем файлы для кнопки
|
||
filesCount := len(approval.Files)
|
||
if filesCount == 0 {
|
||
files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
|
||
filesCount = len(files)
|
||
}
|
||
|
||
msg := tgbotapi.NewMessage(*director.TelegramID, text)
|
||
msg.ParseMode = "HTML"
|
||
// 🚀 Передаем filesCount в клавиатуру
|
||
msg.ReplyMarkup = keyboard.BuildRevokeButton(*approval.ID, status, filesCount)
|
||
bot.Send(msg) //nolint:errcheck
|
||
}
|
||
|
||
// NotifyObserversDecision — кто, кому и что согласовал/отклонил.
|
||
func (n *Notifier) NotifyObserversDecision(
|
||
bot *tgbotapi.BotAPI,
|
||
observers []*typescore.User,
|
||
initiator *typescore.User,
|
||
approver *typescore.User,
|
||
approval *typescore.Approval,
|
||
collected map[string]string,
|
||
) {
|
||
if approval.Status == nil || *approval.Status != "approved" {
|
||
return
|
||
}
|
||
|
||
ctx := context.Background()
|
||
// 🚀 Передаем initiator и collected
|
||
card := n.buildApprovalCard(ctx, approval, initiator, collected)
|
||
|
||
approverName := "—"
|
||
if approver != nil && approver.FullName != nil {
|
||
approverName = *approver.FullName
|
||
}
|
||
header := fmt.Sprintf(
|
||
"✅ <b>%s</b> согласовал(а) заявку\n\n",
|
||
approverName,
|
||
)
|
||
|
||
text := header + card
|
||
|
||
// Считаем файлы для кнопки
|
||
filesCount := len(approval.Files)
|
||
if filesCount == 0 {
|
||
files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
|
||
filesCount = len(files)
|
||
}
|
||
|
||
status := ""
|
||
if approval.Status != nil {
|
||
status = *approval.Status
|
||
}
|
||
for _, obs := range observers {
|
||
if obs.TelegramID == nil {
|
||
continue
|
||
}
|
||
msg := tgbotapi.NewMessage(*obs.TelegramID, text)
|
||
msg.ParseMode = "HTML"
|
||
msg.ReplyMarkup = keyboard.BuildObserverActions(*approval.ID, "", status, filesCount)
|
||
bot.Send(msg) //nolint:errcheck
|
||
}
|
||
}
|
||
|
||
// sendFilesToRecipient отправляет файлы из approval получателю.
|
||
// Текст прикрепляется к первому файлу (caption), клавиатура — к последнему.
|
||
// Если файл не декодируется — пропускается с логированием.
|
||
func (n *Notifier) sendFilesToRecipient(
|
||
bot *tgbotapi.BotAPI,
|
||
chatID int64,
|
||
approval *typescore.Approval,
|
||
text string,
|
||
replyMarkup interface{},
|
||
) {
|
||
type decodedFile struct {
|
||
name string
|
||
bytes []byte
|
||
}
|
||
|
||
var validFiles []decodedFile
|
||
for _, f := range approval.Files {
|
||
if f.FileBase64 == nil || f.FileName == nil {
|
||
continue
|
||
}
|
||
data, err := base64.StdEncoding.DecodeString(*f.FileBase64)
|
||
if err != nil {
|
||
logrus.Errorf("sendFilesToRecipient: base64 decode file=%s err=%v", *f.FileName, err)
|
||
continue
|
||
}
|
||
validFiles = append(validFiles, decodedFile{name: *f.FileName, bytes: data})
|
||
}
|
||
|
||
if len(validFiles) == 0 {
|
||
msg := tgbotapi.NewMessage(chatID, text)
|
||
msg.ParseMode = "HTML"
|
||
if replyMarkup != nil {
|
||
msg.ReplyMarkup = replyMarkup
|
||
}
|
||
bot.Send(msg) //nolint:errcheck
|
||
return
|
||
}
|
||
|
||
const batchSize = 10
|
||
batches := splitIntoBatches(validFiles, batchSize)
|
||
|
||
for batchIdx, batch := range batches {
|
||
isLastBatch := batchIdx == len(batches)-1
|
||
|
||
if len(batch) == 1 {
|
||
// Один файл — отправляем как документ с текстом и кнопками
|
||
doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{
|
||
Name: batch[0].name,
|
||
Bytes: batch[0].bytes,
|
||
})
|
||
doc.ParseMode = "HTML"
|
||
if batchIdx == 0 {
|
||
doc.Caption = text
|
||
}
|
||
if isLastBatch && replyMarkup != nil {
|
||
doc.ReplyMarkup = replyMarkup
|
||
}
|
||
if _, err := bot.Send(doc); err != nil {
|
||
logrus.Errorf("sendFilesToRecipient: Send doc err=%v", err)
|
||
}
|
||
continue
|
||
}
|
||
|
||
var mediaGroup []interface{}
|
||
for i, f := range batch {
|
||
photo := tgbotapi.NewInputMediaDocument(tgbotapi.FileBytes{
|
||
Name: f.name,
|
||
Bytes: f.bytes,
|
||
})
|
||
if i == 0 && batchIdx == 0 {
|
||
photo.Caption = text
|
||
photo.ParseMode = "HTML"
|
||
}
|
||
mediaGroup = append(mediaGroup, photo)
|
||
}
|
||
|
||
mg := tgbotapi.NewMediaGroup(chatID, mediaGroup)
|
||
if _, err := bot.Request(mg); err != nil {
|
||
logrus.Errorf("sendFilesToRecipient: SendMediaGroup batch=%d err=%v", batchIdx, err)
|
||
}
|
||
|
||
if isLastBatch && replyMarkup != nil {
|
||
btnMsg := tgbotapi.NewMessage(chatID, "⬆️ Файлы выше")
|
||
btnMsg.ParseMode = "HTML"
|
||
btnMsg.ReplyMarkup = replyMarkup
|
||
bot.Send(btnMsg) //nolint:errcheck
|
||
}
|
||
}
|
||
}
|
||
|
||
// splitIntoBatches делит слайс на батчи размером size
|
||
func splitIntoBatches[T any](items []T, size int) [][]T {
|
||
if len(items) == 0 {
|
||
return nil
|
||
}
|
||
var batches [][]T
|
||
for len(items) > size {
|
||
batches = append(batches, items[:size])
|
||
items = items[size:]
|
||
}
|
||
return append(batches, items)
|
||
}
|
||
|
||
func (h *Handler) sendDelegationAlreadyExists(bot *tgbotapi.BotAPI, chatID int64, existing *typescore.ApprovalDelegation, telegramID int64) {
|
||
ctx := context.Background()
|
||
|
||
scopeName := "—"
|
||
if existing.TopicID != nil {
|
||
topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *existing.TopicID)
|
||
if topic != nil && topic.Name != nil {
|
||
scopeName = *topic.Name
|
||
}
|
||
} else if existing.CategoryID != nil {
|
||
category, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *existing.CategoryID)
|
||
if category != nil && category.Name != nil {
|
||
scopeName = *category.Name + " (все права)"
|
||
}
|
||
}
|
||
|
||
delegateName := "—"
|
||
if existing.DelegateID != nil {
|
||
delegate, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *existing.DelegateID)
|
||
if delegate != nil && delegate.FullName != nil {
|
||
delegateName = *delegate.FullName
|
||
}
|
||
}
|
||
|
||
validUntil := "—"
|
||
if existing.ValidUntil != nil {
|
||
validUntil = existing.ValidUntil.Format("02.01.2006 15:04")
|
||
}
|
||
|
||
msg := tgbotapi.NewMessage(chatID, fmt.Sprintf(
|
||
"⚠️ <b>Делегирование уже существует</b>\n\n"+
|
||
"📋 <b>Тема:</b> %s\n"+
|
||
"👤 <b>Делегат:</b> %s\n"+
|
||
"📅 <b>Действует до:</b> %s",
|
||
scopeName, delegateName, validUntil,
|
||
))
|
||
msg.ParseMode = "HTML"
|
||
bot.Send(msg) //nolint:errcheck
|
||
h.States.ClearDelegation(ctx, telegramID) //nolint:errcheck
|
||
}
|
||
|
||
func (h *Handler) sendAdditionalApprovalCard(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval, additionalApprover *typescore.ApprovalAdditionalApprover) {
|
||
ctx := context.Background()
|
||
if approval.ID == nil {
|
||
return
|
||
}
|
||
|
||
// Подгружаем актуальные файлы
|
||
files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
|
||
approval.Files = files
|
||
|
||
addedByName := "—"
|
||
if additionalApprover.AddedByID != nil {
|
||
if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *additionalApprover.AddedByID); u != nil && u.FullName != nil {
|
||
addedByName = *u.FullName
|
||
}
|
||
}
|
||
|
||
// Используем единую карточку
|
||
card := h.buildApprovalCard(ctx, approval, h.getCollectedFromApproval(ctx, approval))
|
||
|
||
text := fmt.Sprintf("📄 Добавлен пользователем: %s\n\n%s", addedByName, card)
|
||
|
||
status := ""
|
||
if approval.Status != nil {
|
||
status = *approval.Status
|
||
}
|
||
|
||
if len(files) == 0 {
|
||
msg := tgbotapi.NewMessage(chatID, text)
|
||
msg.ParseMode = "HTML"
|
||
msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, len(files) > 0, len(files))
|
||
bot.Send(msg) //nolint:errcheck
|
||
return
|
||
}
|
||
|
||
categoryCode := h.getTopicCodeByApproval(ctx, approval)
|
||
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)))
|
||
}
|
||
}
|
||
|
||
// notifyObserversAboutNewFile уведомляет наблюдателей о прикреплённом файле
|
||
func (h *Handler) notifyObserversAboutNewFile(
|
||
bot *tgbotapi.BotAPI,
|
||
approvalID uint64,
|
||
attachedBy *typescore.User,
|
||
fileName, fileBase64 string,
|
||
) {
|
||
ctx := context.Background()
|
||
|
||
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.GetObserversForApprovalDB(ctx, *topic.Code, topic.ID)
|
||
if err != nil {
|
||
logrus.Warnf("notifyObserversAboutNewFile: GetObserversForCategoryDB err=%v", err)
|
||
return
|
||
}
|
||
|
||
userName := "Пользователь"
|
||
if attachedBy.FullName != nil {
|
||
userName = *attachedBy.FullName
|
||
}
|
||
|
||
fileData, decodeErr := base64.StdEncoding.DecodeString(fileBase64)
|
||
|
||
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,
|
||
)
|
||
|
||
if decodeErr != nil {
|
||
logrus.Errorf("notifyObserversAboutNewFile: base64 decode err=%v", decodeErr)
|
||
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)
|
||
}
|
||
}
|
||
}
|
||
|
||
func (h *Handler) notifyAllParticipantsAboutFile(
|
||
bot *tgbotapi.BotAPI,
|
||
approvalID uint64,
|
||
attachedBy *typescore.User,
|
||
fileDescription string,
|
||
) {
|
||
ctx := context.Background()
|
||
|
||
approval, err := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
|
||
if err != nil || approval == nil {
|
||
logrus.Errorf("notifyAllParticipantsAboutFile: GetApprovalByIDDB err=%v", err)
|
||
return
|
||
}
|
||
|
||
files, err := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID)
|
||
if err != nil {
|
||
logrus.Warnf("notifyAllParticipantsAboutFile: GetFilesByApprovalIDDB err=%v", err)
|
||
}
|
||
approval.Files = files
|
||
|
||
senderID := uint64(0)
|
||
if attachedBy != nil && attachedBy.ID != nil {
|
||
senderID = *attachedBy.ID
|
||
}
|
||
|
||
senderName := "—"
|
||
if attachedBy != nil && attachedBy.FullName != nil {
|
||
senderName = *attachedBy.FullName
|
||
}
|
||
|
||
text := fmt.Sprintf(
|
||
"📎 <b>Файлы прикреплены к заявке #%d</b>\n\n"+
|
||
"👤 <b>Кем:</b> %s\n"+
|
||
"📄 <b>Количество:</b> %s",
|
||
approvalID, senderName, fileDescription,
|
||
)
|
||
|
||
var recipients []*typescore.User
|
||
|
||
if approval.InitiatorID != nil {
|
||
if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID); u != nil {
|
||
recipients = append(recipients, u)
|
||
}
|
||
}
|
||
|
||
if step, _ := h.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID); step != nil && step.ApproverID != nil {
|
||
if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID); u != nil {
|
||
recipients = append(recipients, u)
|
||
}
|
||
}
|
||
|
||
categoryCode := h.getTopicCodeByApproval(ctx, approval)
|
||
observers, _ := h.ipc.Database.User.GetObserversForApprovalDB(ctx, categoryCode, approval.TopicID)
|
||
recipients = append(recipients, observers...)
|
||
|
||
// Получаем нотифайер для sendFilesToRecipient
|
||
topic, err := h.Registry.Get(categoryCode)
|
||
if err != nil {
|
||
logrus.Errorf("notifyAllParticipantsAboutFile: Registry.Get err=%v", err)
|
||
return
|
||
}
|
||
notifier := NewNotifier(h.ipc, topic)
|
||
|
||
seen := make(map[uint64]bool)
|
||
for _, r := range recipients {
|
||
if r == nil || r.ID == nil || r.TelegramID == nil {
|
||
continue
|
||
}
|
||
if *r.ID == senderID || seen[*r.ID] {
|
||
continue
|
||
}
|
||
seen[*r.ID] = true
|
||
|
||
if len(approval.Files) == 0 {
|
||
msg := tgbotapi.NewMessage(*r.TelegramID, text)
|
||
msg.ParseMode = "HTML"
|
||
bot.Send(msg) //nolint:errcheck
|
||
} else {
|
||
notifier.sendFilesToRecipient(bot, *r.TelegramID, approval, text, nil)
|
||
}
|
||
}
|
||
}
|
||
|
||
func (n *Notifier) formatApprovalMessage(initiator *typescore.User, collected map[string]string) string {
|
||
return n.topic.FormatApproverMessage(initiator, collected)
|
||
}
|
||
|
||
func (n *Notifier) buildApprovalCard(ctx context.Context, approval *typescore.Approval, initiator *typescore.User, collected map[string]string) string {
|
||
if approval.ID == nil {
|
||
return ""
|
||
}
|
||
approvalID := *approval.ID
|
||
|
||
topicInfo := n.topic.FormatApproverMessage(initiator, collected)
|
||
|
||
filesCount := len(approval.Files)
|
||
if filesCount == 0 {
|
||
files, _ := n.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID)
|
||
filesCount = len(files)
|
||
}
|
||
|
||
filesLabel := "Без файлов"
|
||
if filesCount > 0 {
|
||
filesLabel = fmt.Sprintf("📎 %d файл(ов)", filesCount)
|
||
}
|
||
|
||
status := "⏳ ожидает"
|
||
if approval.Status != nil {
|
||
switch *approval.Status {
|
||
case "approved":
|
||
status = "✅ согласована"
|
||
case "rejected":
|
||
status = "❌ отклонена"
|
||
case "revoked":
|
||
status = "🔙 отозвана"
|
||
}
|
||
}
|
||
|
||
createdAt := "—"
|
||
if approval.CreatedAt != nil {
|
||
createdAt = approval.CreatedAt.Format("02.01.2006 15:04")
|
||
}
|
||
|
||
card := fmt.Sprintf(
|
||
"📋 <b>Заявка #%d</b>\n\n"+
|
||
"%s\n\n"+ // 🚀 Сюда вставляется полное тело заявки из topicInfo
|
||
"📎 <b>Файлы:</b> %s\n"+
|
||
"📅 <b>Создана:</b> %s\n"+
|
||
"📊 <b>Статус:</b> %s",
|
||
approvalID, topicInfo, filesLabel, createdAt, status,
|
||
)
|
||
|
||
// Добавляем информацию о текущем согласующем если заявка в процессе
|
||
if approval.Status != nil && *approval.Status == "pending" {
|
||
activeStep, _ := n.ipc.Database.ApprovalStep.GetActiveStepDB(ctx, approvalID)
|
||
if activeStep != nil && activeStep.ApproverID != nil {
|
||
approver, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *activeStep.ApproverID)
|
||
if approver != nil && approver.FullName != nil {
|
||
card += fmt.Sprintf("\n🔄 <b>У согласующего:</b> %s", *approver.FullName)
|
||
}
|
||
}
|
||
}
|
||
|
||
// Добавляем информацию о дополнительных согласующих
|
||
additionalApprovers, _, _ := n.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
|
||
Filtering: &typescore.ApprovalAdditionalApprover{
|
||
ApprovalID: &approvalID,
|
||
},
|
||
})
|
||
if len(additionalApprovers) > 0 {
|
||
card += "\n\n👥 <b>Дополнительные согласующие:</b>"
|
||
for _, aa := range additionalApprovers {
|
||
if aa.ApproverID == nil {
|
||
continue
|
||
}
|
||
approver, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *aa.ApproverID)
|
||
if approver == nil || approver.FullName == nil {
|
||
continue
|
||
}
|
||
|
||
statusIcon := "⏳"
|
||
if aa.Status != nil {
|
||
switch *aa.Status {
|
||
case "approved":
|
||
statusIcon = "✅"
|
||
case "rejected":
|
||
statusIcon = "❌"
|
||
}
|
||
}
|
||
card += fmt.Sprintf("\n• %s %s", statusIcon, *approver.FullName)
|
||
}
|
||
}
|
||
|
||
// Добавляем комментарии
|
||
commentsSection := n.formatCommentsSection(ctx, approvalID)
|
||
card += commentsSection
|
||
|
||
return card
|
||
}
|
||
|
||
func (n *Notifier) formatCommentsSection(ctx context.Context, approvalID uint64) string {
|
||
comments, _, _ := n.ipc.Database.ApprovalComment.GetApprovalCommentsListDB(ctx, typescore.ListDbOptions{
|
||
Filtering: &typescore.ApprovalComment{ApprovalID: &approvalID},
|
||
})
|
||
if len(comments) == 0 {
|
||
return ""
|
||
}
|
||
|
||
section := "\n\n💬 <b>Комментарии:</b>"
|
||
for _, c := range comments {
|
||
authorName := "—"
|
||
if c.UserID != nil {
|
||
author, _ := n.ipc.Database.User.GetUserByIDDB(ctx, *c.UserID)
|
||
if author != nil && author.FullName != nil {
|
||
authorName = *author.FullName
|
||
}
|
||
}
|
||
createdAt := ""
|
||
if c.CreatedAt != nil {
|
||
createdAt = c.CreatedAt.Format("02.01 15:04")
|
||
}
|
||
comment := "-"
|
||
if c.Comment != nil {
|
||
comment = *c.Comment
|
||
}
|
||
section += fmt.Sprintf("\n• <b>%s</b> (%s): %s", authorName, createdAt, comment)
|
||
}
|
||
return section
|
||
}
|