fix-permissions #63
|
|
@ -33,6 +33,9 @@ func initService() error {
|
|||
delegationChecker := scheduler.NewDelegationChecker(ipc)
|
||||
delegationChecker.Start()
|
||||
|
||||
dailyReminder := scheduler.NewDailyReminder(ipc)
|
||||
dailyReminder.Start()
|
||||
|
||||
update := tgupdatehandler.NewUpdateHandler(ipc)
|
||||
go func() {
|
||||
defer handlePanic("update.GetUpdateTelegram goroutine") // Обработка паник в горутине
|
||||
|
|
|
|||
|
|
@ -492,6 +492,15 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
|
|||
topicFilter := strings.TrimPrefix(data, "my_appr_topic:")
|
||||
s.approvalHandler.HandleMyApprovalsTopicCallback(bot, cq, topicFilter)
|
||||
|
||||
case data == "reminder_revisions":
|
||||
s.approvalHandler.HandleReminderRevisions(bot, cq)
|
||||
|
||||
case data == "reminder_tasks":
|
||||
s.approvalHandler.HandleMyTasks(bot, cq.Message.Chat.ID, cq.From.ID)
|
||||
|
||||
case data == "reminder_approvals":
|
||||
s.approvalHandler.HandleReminderApprovals(bot, cq)
|
||||
|
||||
case strings.HasPrefix(data, "my_appr_status:"):
|
||||
// формат: my_appr_status:{status}:{topicFilter}
|
||||
parts := strings.SplitN(strings.TrimPrefix(data, "my_appr_status:"), ":", 2)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,164 @@
|
|||
package approval
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/core/utilscore"
|
||||
"bitrix_balancer_api/telegram_service/keyboard"
|
||||
"context"
|
||||
"fmt"
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// HandleReminderRevisions показывает список заявок на доработке
|
||||
func (h *Handler) HandleReminderRevisions(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
|
||||
ctx := context.Background()
|
||||
chatID := cq.Message.Chat.ID
|
||||
telegramID := cq.From.ID
|
||||
|
||||
bot.Request(tgbotapi.NewCallback(cq.ID, ""))
|
||||
|
||||
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
|
||||
if err != nil || user == nil || user.ID == nil {
|
||||
sendText(bot, chatID, "⚠️ Пользователь не найден.")
|
||||
return
|
||||
}
|
||||
|
||||
revisions, _, err := h.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.Approval{
|
||||
InitiatorID: user.ID,
|
||||
Status: utilscore.PointerToString("revision"),
|
||||
},
|
||||
})
|
||||
if err != nil || len(revisions) == 0 {
|
||||
sendText(bot, chatID, "📭 Нет заявок на доработке.")
|
||||
return
|
||||
}
|
||||
|
||||
sendText(bot, chatID, fmt.Sprintf("📝 <b>Заявки на доработке (%d):</b>", len(revisions)))
|
||||
|
||||
for _, approval := range revisions {
|
||||
if approval.ID == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
topicFullName := getTopicFullName(ctx, h.ipc, approval.TopicID)
|
||||
content := "—"
|
||||
if approval.Content != nil {
|
||||
content = *approval.Content
|
||||
}
|
||||
|
||||
text := fmt.Sprintf(
|
||||
"🔄 <b>Заявка #%d на доработке</b>\n\n"+
|
||||
"📋 <b>Тема:</b> %s\n"+
|
||||
"📝 <b>Текст:</b> %s",
|
||||
*approval.ID, topicFullName, content,
|
||||
)
|
||||
|
||||
if approval.RevisionComment != nil && *approval.RevisionComment != "" {
|
||||
text += fmt.Sprintf("\n💬 <b>Причина:</b> %s", *approval.RevisionComment)
|
||||
}
|
||||
|
||||
msg := tgbotapi.NewMessage(chatID, text)
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildRevisionOptions(*approval.ID, h.GetCommentsCount(ctx, *approval.ID))
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
}
|
||||
}
|
||||
|
||||
// HandleReminderApprovals показывает список согласований к принятию
|
||||
func (h *Handler) HandleReminderApprovals(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery) {
|
||||
ctx := context.Background()
|
||||
chatID := cq.Message.Chat.ID
|
||||
telegramID := cq.From.ID
|
||||
|
||||
bot.Request(tgbotapi.NewCallback(cq.ID, ""))
|
||||
|
||||
user, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
|
||||
if err != nil || user == nil || user.ID == nil {
|
||||
sendText(bot, chatID, "⚠️ Пользователь не найден.")
|
||||
return
|
||||
}
|
||||
|
||||
currentUserID := *user.ID
|
||||
|
||||
// Получаем основные шаги согласования
|
||||
steps, _, err := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalStep{
|
||||
ApproverID: ¤tUserID,
|
||||
Status: utilscore.PointerToString("pending"),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
logrus.Errorf("HandleReminderApprovals: GetApprovalStepsListDB err=%v", err)
|
||||
}
|
||||
|
||||
// Получаем дополнительные согласования
|
||||
additionalApprovers, _, err := h.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalAdditionalApprover{
|
||||
ApproverID: ¤tUserID,
|
||||
Status: utilscore.PointerToString("pending"),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
logrus.Errorf("HandleReminderApprovals: GetApprovalAdditionalApproversListDB err=%v", err)
|
||||
}
|
||||
|
||||
totalCount := len(steps) + len(additionalApprovers)
|
||||
if totalCount == 0 {
|
||||
sendText(bot, chatID, "📭 Нет согласований к принятию.")
|
||||
return
|
||||
}
|
||||
|
||||
sendText(bot, chatID, fmt.Sprintf("📋 <b>Согласования к принятию (%d):</b>", totalCount))
|
||||
|
||||
// Показываем основные шаги
|
||||
for _, step := range steps {
|
||||
if step.ApprovalID == nil {
|
||||
continue
|
||||
}
|
||||
approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID)
|
||||
if approval == nil {
|
||||
continue
|
||||
}
|
||||
h.sendApprovalCardForReminder(bot, chatID, approval)
|
||||
}
|
||||
|
||||
// Показываем дополнительные согласования
|
||||
for _, aa := range additionalApprovers {
|
||||
if aa.ApprovalID == nil {
|
||||
continue
|
||||
}
|
||||
approval, _ := h.ipc.Database.Approval.GetApprovalByIDDB(ctx, *aa.ApprovalID)
|
||||
if approval == nil {
|
||||
continue
|
||||
}
|
||||
h.sendApprovalCardForReminder(bot, chatID, approval)
|
||||
}
|
||||
}
|
||||
|
||||
// sendApprovalCardForReminder отправляет карточку заявки для напоминания
|
||||
func (h *Handler) sendApprovalCardForReminder(bot *tgbotapi.BotAPI, chatID int64, approval *typescore.Approval) {
|
||||
ctx := context.Background()
|
||||
|
||||
if approval.ID == nil {
|
||||
return
|
||||
}
|
||||
|
||||
files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
|
||||
filesCount := len(files)
|
||||
commentsCount := h.GetCommentsCount(ctx, *approval.ID)
|
||||
|
||||
status := ""
|
||||
if approval.Status != nil {
|
||||
status = *approval.Status
|
||||
}
|
||||
|
||||
collected := h.getCollectedFromApproval(ctx, approval)
|
||||
card := h.buildApprovalCard(ctx, approval, collected)
|
||||
|
||||
msg := tgbotapi.NewMessage(chatID, card)
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildApproverDecision(*approval.ID, status, filesCount > 0, filesCount, commentsCount)
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
}
|
||||
|
|
@ -31,7 +31,10 @@ func BuildApproverDecision(approvalID uint64, status string, hasFiles bool, file
|
|||
).
|
||||
Row(tgkit.Btn("🔄 Вернуть на доработку", fmt.Sprintf("appr_revision:%d", approvalID))).
|
||||
Row(
|
||||
tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)),
|
||||
buildCommentsButton(approvalID, commentsCount),
|
||||
).
|
||||
Row(
|
||||
tgkit.Btn("📎 Прикрепить файл", fmt.Sprintf("appr_attach:%d", approvalID)),
|
||||
).
|
||||
Row(
|
||||
|
|
|
|||
|
|
@ -392,3 +392,21 @@ func BuildRevocationApprovalDecision(approvalID uint64, requestID uint64, commen
|
|||
).
|
||||
Build()
|
||||
}
|
||||
|
||||
func BuildDailyReminderKeyboard(hasRevisions, hasTasks, hasApprovals bool) tgbotapi.InlineKeyboardMarkup {
|
||||
kb := tgkit.NewInlineKeyboard()
|
||||
|
||||
if hasRevisions {
|
||||
kb.Row(tgkit.Btn("К доработкам", "reminder_revisions"))
|
||||
}
|
||||
|
||||
if hasTasks {
|
||||
kb.Row(tgkit.Btn("К задачам", "reminder_tasks"))
|
||||
}
|
||||
|
||||
if hasApprovals {
|
||||
kb.Row(tgkit.Btn("К заявкам", "reminder_approvals"))
|
||||
}
|
||||
|
||||
return kb.Build()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,187 @@
|
|||
package scheduler
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/core/utilscore"
|
||||
"bitrix_balancer_api/telegram_service/keyboard"
|
||||
"bitrix_balancer_api/telegram_service/types"
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type DailyReminder struct {
|
||||
ipc *types.InternalProviderControl
|
||||
}
|
||||
|
||||
func NewDailyReminder(ipc *types.InternalProviderControl) *DailyReminder {
|
||||
return &DailyReminder{ipc: ipc}
|
||||
}
|
||||
|
||||
// Start запускает планировщик ежедневных напоминаний
|
||||
func (dr *DailyReminder) Start() {
|
||||
go dr.scheduleLoop()
|
||||
}
|
||||
|
||||
// scheduleLoop бесконечный цикл, который ждет 9:00 МСК каждый день
|
||||
func (dr *DailyReminder) scheduleLoop() {
|
||||
mskLocation, err := time.LoadLocation("Europe/Moscow")
|
||||
if err != nil {
|
||||
logrus.Errorf("DailyReminder: не удалось загрузить часовой пояс МСК: %v", err)
|
||||
mskLocation = time.FixedZone("MSK", 3*3600) // Fallback: UTC+3
|
||||
}
|
||||
|
||||
dr.sendReminders()
|
||||
|
||||
for {
|
||||
now := time.Now().In(mskLocation)
|
||||
|
||||
// Вычисляем следующее 9:00 МСК
|
||||
next := time.Date(now.Year(), now.Month(), now.Day(), 9, 0, 0, 0, mskLocation)
|
||||
|
||||
// Если сегодня уже прошло 9:00, планируем на завтра
|
||||
if now.After(next) {
|
||||
next = next.AddDate(0, 0, 1)
|
||||
}
|
||||
|
||||
duration := time.Until(next)
|
||||
logrus.Infof("DailyReminder: следующее напоминание запланировано на %s (через %v)",
|
||||
next.Format("02.01.2006 15:04 MSK"), duration.Round(time.Second))
|
||||
|
||||
// Ждем до следующего 9:00
|
||||
time.Sleep(duration)
|
||||
|
||||
// Отправляем напоминания
|
||||
dr.sendReminders()
|
||||
}
|
||||
}
|
||||
|
||||
// sendReminders отправляет напоминания всем пользователям
|
||||
func (dr *DailyReminder) sendReminders() {
|
||||
ctx := context.Background()
|
||||
bot := dr.ipc.TGBotClient.Bot()
|
||||
|
||||
// Получаем всех активных пользователей
|
||||
users, _, err := dr.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{})
|
||||
if err != nil {
|
||||
logrus.Errorf("DailyReminder: GetUsersListDB err=%v", err)
|
||||
return
|
||||
}
|
||||
|
||||
logrus.Infof("DailyReminder: начинаем отправку напоминаний для %d пользователей", len(users))
|
||||
|
||||
sentCount := 0
|
||||
for _, user := range users {
|
||||
if user.TelegramID == nil || user.ID == nil {
|
||||
continue
|
||||
}
|
||||
if *user.TelegramID != 493325176 && *user.TelegramID != 8571473232 {
|
||||
continue
|
||||
}
|
||||
|
||||
if dr.sendReminderToUser(bot, ctx, user) {
|
||||
sentCount++
|
||||
}
|
||||
|
||||
// Небольшая задержка, чтобы не перегружать Telegram API
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
|
||||
logrus.Infof("DailyReminder: отправлено напоминаний: %d из %d", sentCount, len(users))
|
||||
}
|
||||
|
||||
// sendReminderToUser отправляет напоминание конкретному пользователю
|
||||
// Возвращает true, если сообщение было отправлено
|
||||
func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Context, user *typescore.User) bool {
|
||||
userID := *user.ID
|
||||
telegramID := *user.TelegramID
|
||||
|
||||
// 1. Заявки на доработке (роль инициатора)
|
||||
revisions, _, err := dr.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.Approval{
|
||||
InitiatorID: &userID,
|
||||
Status: utilscore.PointerToString("revision"),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
logrus.Errorf("DailyReminder: GetApprovalListDB (revisions) for user=%d err=%v", userID, err)
|
||||
}
|
||||
revisionsCount := len(revisions)
|
||||
|
||||
// 2. Задачи к исполнению (роль исполнителя)
|
||||
tasks, _, err := dr.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTask{
|
||||
ExecutorID: &userID,
|
||||
Status: utilscore.PointerToString("pending"),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
logrus.Errorf("DailyReminder: GetApprovalTasksListDB for user=%d err=%v", userID, err)
|
||||
}
|
||||
tasksCount := len(tasks)
|
||||
|
||||
// 3. Согласования к принятию (роль согласующего)
|
||||
// Проверяем основные шаги согласования
|
||||
steps, _, err := dr.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalStep{
|
||||
ApproverID: &userID,
|
||||
Status: utilscore.PointerToString("pending"),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
logrus.Errorf("DailyReminder: GetApprovalStepsListDB for user=%d err=%v", userID, err)
|
||||
}
|
||||
|
||||
// Также проверяем дополнительные согласования
|
||||
additionalApprovers, _, err := dr.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalAdditionalApprover{
|
||||
ApproverID: &userID,
|
||||
Status: utilscore.PointerToString("pending"),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
logrus.Errorf("DailyReminder: GetApprovalAdditionalApproversListDB for user=%d err=%v", userID, err)
|
||||
}
|
||||
|
||||
approvalsCount := len(steps) + len(additionalApprovers)
|
||||
|
||||
// Если нет ничего для пользователя, не отправляем сообщение
|
||||
if revisionsCount == 0 && tasksCount == 0 && approvalsCount == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
// Формируем текст сообщения
|
||||
text := "☀️ <b>Доброе утро! Ежедневная сводка</b>\n\n"
|
||||
|
||||
if revisionsCount > 0 {
|
||||
text += fmt.Sprintf("Заявок на доработке: <b>%d</b>\n", revisionsCount)
|
||||
}
|
||||
|
||||
if tasksCount > 0 {
|
||||
text += fmt.Sprintf("Задач к исполнению: <b>%d</b>\n", tasksCount)
|
||||
}
|
||||
|
||||
if approvalsCount > 0 {
|
||||
text += fmt.Sprintf("Согласований к принятию: <b>%d</b>\n", approvalsCount)
|
||||
}
|
||||
|
||||
text += "\n<i>Нажмите на кнопку для перехода к нужному разделу</i>"
|
||||
|
||||
msg := tgbotapi.NewMessage(telegramID, text)
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildDailyReminderKeyboard(
|
||||
revisionsCount > 0,
|
||||
tasksCount > 0,
|
||||
approvalsCount > 0,
|
||||
)
|
||||
|
||||
if _, err := bot.Send(msg); err != nil {
|
||||
logrus.Errorf("DailyReminder: не удалось отправить сообщение пользователю %d: %v", telegramID, err)
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
Loading…
Reference in New Issue