Update daily bot message #205

Merged
romanskijdev merged 1 commits from fix-permissions into main 2026-10-28 13:04:39 +03:00
2 changed files with 125 additions and 81 deletions

View File

@ -299,7 +299,6 @@ func (t *CustomAPIProxyTransport) switchToFallbackAndExecute(req *http.Request,
return t.executeFallback(req, body, savedTrans, newProxyURL)
}
// findFastestFreeProxy скачивает списки бесплатных прокси, конкурентно пингует их и возвращает первый успешный
// findFastestFreeProxy скачивает списки бесплатных прокси, конкурентно пингует их и возвращает первый успешный
func findFastestFreeProxy() (string, error) {
sources := []string{

View File

@ -8,13 +8,17 @@ import (
"context"
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
"html"
"regexp"
"strconv"
"time"
)
const (
maxDBFetchLimit = uint64(10000)
telegramMaxMessageLen = 4000 // Запас от лимита 4096 символов Telegram
)
type DailyReminder struct {
@ -78,7 +82,22 @@ func (dr *DailyReminder) skipWeekends(t time.Time) time.Time {
return t
}
// sendReminders отправляет напоминания всем пользователям
// isUserActive проверяет, что пользователь не уволен и не заблокирован.
// Учитывает NULL в БД: если поле nil (NULL) или false — пользователь считается активным.
func isUserActive(u *typescore.User) bool {
if u == nil {
return false
}
if u.IsBlocked != nil && *u.IsBlocked {
return false
}
if u.IsFired != nil && *u.IsFired {
return false
}
return true
}
// sendReminders отправляет напоминания всем активным пользователям
func (dr *DailyReminder) sendReminders() {
logrus.Infof("DailyReminder: sendReminders() запущен")
@ -92,19 +111,37 @@ func (dr *DailyReminder) sendReminders() {
}
logrus.Infof("DailyReminder: сегодняшняя дата (МСК) = %s", time.Now().In(mskLocation).Format("02.01.2006"))
// Получаем всех активных пользователей
users, _, err := dr.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(10000),
Filtering: &typescore.User{
IsBlocked: utilscore.PointerToBool(false),
IsFired: utilscore.PointerToBool(false),
},
// Запрашиваем всех пользователей без фильтра IsBlocked/IsFired в SQL,
// чтобы не потерять записи со значением NULL в БД.
allUsers, _, err := dr.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(maxDBFetchLimit),
})
if err != nil {
logrus.Errorf("DailyReminder: GetUsersListDB err=%v", err)
return
}
logrus.Infof("DailyReminder: получено пользователей из БД: %d", len(users))
// Фильтруем уволенных и заблокированных на уровне Go (корректно обрабатывая NULL как false)
var users []*typescore.User
skippedBlockedOrFired := 0
skippedNoTgID := 0
for _, u := range allUsers {
if !isUserActive(u) {
skippedBlockedOrFired++
continue
}
if u.ID == nil || u.TelegramID == nil || *u.TelegramID == 0 {
skippedNoTgID++
logrus.Warnf("DailyReminder: пропуск активного пользователя без TelegramID/ID (ID=%v, FullName=%v)",
u.ID, derefString(u.FullName))
continue
}
users = append(users, u)
}
logrus.Infof("DailyReminder: всего в БД=%d, активных к отправке=%d (пропущено уволенных/заблокированных=%d, без TelegramID=%d)",
len(allUsers), len(users), skippedBlockedOrFired, skippedNoTgID)
absentToday := dr.getAbsentEmployeesToday(ctx, mskLocation)
@ -113,11 +150,6 @@ func (dr *DailyReminder) sendReminders() {
sentCount := 0
for _, user := range users {
if user.TelegramID == nil || user.ID == nil {
logrus.Debugf("DailyReminder: пропуск пользователя без TelegramID/ID (user=%+v)", user)
continue
}
sent := dr.sendReminderToUser(bot, ctx, user, absentToday)
if sent {
sentCount++
@ -136,6 +168,7 @@ func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Co
telegramID := *user.TelegramID
revisions, _, err := dr.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(maxDBFetchLimit),
Filtering: &typescore.Approval{
InitiatorID: &userID,
Status: utilscore.PointerToString("revision"),
@ -147,6 +180,7 @@ func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Co
revisionsCount := len(revisions)
myPendingApprovals, _, err := dr.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(maxDBFetchLimit),
Filtering: &typescore.Approval{
InitiatorID: &userID,
Status: utilscore.PointerToString("pending"),
@ -158,6 +192,7 @@ func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Co
myPendingCount := len(myPendingApprovals)
tasks, _, err := dr.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(maxDBFetchLimit),
Filtering: &typescore.ApprovalTask{
ExecutorID: &userID,
Status: utilscore.PointerToString("pending"),
@ -169,6 +204,7 @@ func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Co
tasksCount := len(tasks)
steps, _, err := dr.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(maxDBFetchLimit),
Filtering: &typescore.ApprovalStep{
ApproverID: &userID,
Status: utilscore.PointerToString("pending"),
@ -180,6 +216,7 @@ func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Co
// Также проверяем дополнительные согласования
additionalApprovers, _, err := dr.ipc.Database.ApprovalAdditionalApprover.GetApprovalAdditionalApproversListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(maxDBFetchLimit),
Filtering: &typescore.ApprovalAdditionalApprover{
ApproverID: &userID,
Status: utilscore.PointerToString("pending"),
@ -193,42 +230,38 @@ func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Co
hasPersonalItems := revisionsCount > 0 || tasksCount > 0 || approvalsCount > 0 || myPendingCount > 0
logrus.Infof("DailyReminder: userID=%d telegramID=%d — revisions=%d tasks=%d approvals=%d hasPersonalItems=%v absentTodayCount=%d",
userID, telegramID, revisionsCount, tasksCount, approvalsCount, hasPersonalItems, len(absentToday))
if !hasPersonalItems && len(absentToday) == 0 {
logrus.Infof("DailyReminder: userID=%d telegramID=%d — нечего сообщить (нет личных пунктов и список отсутствующих пуст), сообщение НЕ отправляется", userID, telegramID)
return false
}
logrus.Infof("DailyReminder: userID=%d telegramID=%d — myPending=%d revisions=%d tasks=%d approvals=%d hasPersonalItems=%v absentTodayCount=%d",
userID, telegramID, myPendingCount, revisionsCount, tasksCount, approvalsCount, hasPersonalItems, len(absentToday))
text := "☀️ <b>Доброе утро! Ежедневная сводка</b>\n\n"
if myPendingCount > 0 {
text += fmt.Sprintf("Ваших заявок на согласовании: <b>%d</b>\n", myPendingCount)
}
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)
}
if hasPersonalItems {
if myPendingCount > 0 {
text += fmt.Sprintf("Ваших заявок на согласовании: <b>%d</b>\n", myPendingCount)
}
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>"
} else {
text += "✅ У вас нет активных заявок или задач, для которых требуются активные действия."
}
if len(absentToday) > 0 {
if hasPersonalItems {
text += "\n\n"
}
text += "👥 <b>Сотрудники в отгуле/больничном/отпуске:</b>\n"
text += "\n\n👥 <b>Сотрудники в отгуле/больничном/отпуске:</b>\n"
for _, a := range absentToday {
text += fmt.Sprintf("%s - %s - по срочным вопросам обращаться: %s\n", a.Name, a.TimeDescription, a.Contact)
line := fmt.Sprintf("• %s — %s, по срочным вопросам обращаться: %s\n",
html.EscapeString(a.Name),
html.EscapeString(a.TimeDescription),
html.EscapeString(a.Contact),
)
text += line
}
}
@ -243,11 +276,11 @@ func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Co
}
if _, err := bot.Send(msg); err != nil {
logrus.Errorf("DailyReminder: не удалось отправить сообщение пользователю %d: %v", telegramID, err)
logrus.Errorf("DailyReminder: не удалось отправить сообщение пользователю userID=%d (telegramID=%d): %v", userID, telegramID, err)
return false
}
logrus.Infof("DailyReminder: сообщение успешно отправлено telegramID=%d (длина текста=%d символов)", telegramID, len(text))
logrus.Infof("DailyReminder: сообщение успешно отправлено userID=%d telegramID=%d (длина=%d байт)", userID, telegramID, len(text))
return true
}
@ -259,7 +292,6 @@ func (dr *DailyReminder) countPendingApprovals(
steps []*typescore.ApprovalStep,
additionalApprovers []*typescore.ApprovalAdditionalApprover,
) int {
// Собираем уникальные approvalID
approvalIDs := make(map[uint64]bool)
for _, step := range steps {
@ -277,7 +309,6 @@ func (dr *DailyReminder) countPendingApprovals(
return 0
}
// Получаем все заявки одним запросом и фильтруем по статусу pending
count := 0
for approvalID := range approvalIDs {
id := approvalID
@ -315,6 +346,7 @@ func (dr *DailyReminder) getAbsentEmployeesToday(ctx context.Context, mskLocatio
todayY, todayM, todayD := today.Date()
activeCategories, _, errCat := dr.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(maxDBFetchLimit),
Filtering: &typescore.ApprovalTopicCategory{IsActive: utilscore.PointerToBool(true)},
})
if errCat != nil {
@ -322,6 +354,7 @@ func (dr *DailyReminder) getAbsentEmployeesToday(ctx context.Context, mskLocatio
}
approvals, _, err := dr.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(maxDBFetchLimit),
Filtering: &typescore.Approval{
Status: utilscore.PointerToString("approved"),
},
@ -340,7 +373,6 @@ func (dr *DailyReminder) getAbsentEmployeesToday(ctx context.Context, mskLocatio
approvalID := derefApprovalID(approval)
if approval.Metadata == nil || *approval.Metadata == "" || approval.Content == nil {
logrus.Infof("DailyReminder: заявка #%d пропущена — нет Metadata или Content", approvalID)
continue
}
@ -351,19 +383,14 @@ func (dr *DailyReminder) getAbsentEmployeesToday(ctx context.Context, mskLocatio
continue
}
if meta.Extra.AbsenceType == "" {
logrus.Infof("DailyReminder: заявка #%d пропущена — metadata.extra.absence_type пустой (не тема отсутствия), metadata=%q",
approvalID, *approval.Metadata)
continue
}
logrus.Infof("DailyReminder: заявка #%d — absence_type=%q time_type=%q content=%q",
approvalID, meta.Extra.AbsenceType, meta.Extra.TimeType, *approval.Content)
if approval.InitiatorID == nil {
logrus.Warnf("DailyReminder: заявка #%d пропущена — InitiatorID nil", approvalID)
continue
}
if seenUsers[*approval.InitiatorID] {
logrus.Infof("DailyReminder: заявка #%d пропущена — по этому инициатору (userID=%d) уже есть запись в сводке", approvalID, *approval.InitiatorID)
continue
}
@ -373,23 +400,23 @@ func (dr *DailyReminder) getAbsentEmployeesToday(ctx context.Context, mskLocatio
approvalID, *approval.Content)
continue
}
logrus.Infof("DailyReminder: заявка #%d — распознанные даты: %v", approvalID, dates)
if !absenceCoversDate(dates, *approval.Content, todayY, todayM, todayD) {
logrus.Infof("DailyReminder: заявка #%d пропущена — распознанные даты не покрывают сегодня (%04d-%02d-%02d)",
approvalID, todayY, todayM, todayD)
if !absenceCoversDate(dates, todayY, todayM, todayD) {
continue
}
// Проверяем, что сам инициатор заявки не уволен и не заблокирован
initiatorUser, uErr := dr.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
if uErr == nil && initiatorUser != nil && !isUserActive(initiatorUser) {
logrus.Infof("DailyReminder: заявка #%d пропущена — инициатор (userID=%d) уволен или заблокирован", approvalID, *approval.InitiatorID)
continue
}
logrus.Infof("DailyReminder: заявка #%d — покрывает сегодня, добавляем в сводку", approvalID)
name := "—"
if approval.Initiator != nil && approval.Initiator.FullName != nil {
name = *approval.Initiator.FullName
} else {
user, uErr := dr.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
if uErr == nil && user != nil && user.FullName != nil {
name = *user.FullName
}
} else if initiatorUser != nil && initiatorUser.FullName != nil {
name = *initiatorUser.FullName
}
var timeDescription string
@ -416,6 +443,7 @@ func (dr *DailyReminder) getAbsentEmployeesToday(ctx context.Context, mskLocatio
if len(activeCategories) > 0 {
if delegations, _, dErr := dr.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(maxDBFetchLimit),
Filtering: &typescore.ApprovalDelegation{
DelegatorID: approval.InitiatorID,
IsActive: utilscore.PointerToBool(true),
@ -459,8 +487,8 @@ func (dr *DailyReminder) getAbsentEmployeesToday(ctx context.Context, mskLocatio
}
if allDelegatedToSamePerson && primaryDelegateID != 0 {
delegateUser, uErr := dr.ipc.Database.User.GetUserByIDDB(ctx, primaryDelegateID)
if uErr == nil && delegateUser != nil && delegateUser.FullName != nil {
delegateUser, dUserErr := dr.ipc.Database.User.GetUserByIDDB(ctx, primaryDelegateID)
if dUserErr == nil && delegateUser != nil && delegateUser.FullName != nil {
contact = *delegateUser.FullName
}
}
@ -487,6 +515,13 @@ func derefApprovalID(a *typescore.Approval) uint64 {
return *a.ID
}
func derefString(s *string) string {
if s == nil {
return "<nil>"
}
return *s
}
func parseAbsenceDates(content string) []time.Time {
matches := absenceDateRe.FindAllStringSubmatch(content, -1)
var dates []time.Time
@ -505,6 +540,16 @@ func parseAbsenceDates(content string) []time.Time {
return dates
}
func minDate(dates []time.Time) time.Time {
min := dates[0]
for _, d := range dates[1:] {
if d.Before(min) {
min = d
}
}
return min
}
func maxDate(dates []time.Time) time.Time {
max := dates[0]
for _, d := range dates[1:] {
@ -515,21 +560,21 @@ func maxDate(dates []time.Time) time.Time {
return max
}
func absenceCoversDate(dates []time.Time, content string, y int, m time.Month, d int) bool {
// absenceCoversDate проверяет, попадает ли сегодняшняя дата в период отсутствия.
// Если в тексте найдено 2 или более дат (начало и конец отпуска/больничного/отгула),
// проверяется вхождение даты в диапазон [minDate, maxDate] вне зависимости от типа тире или предлогов.
func absenceCoversDate(dates []time.Time, y int, m time.Month, d int) bool {
if len(dates) == 0 {
return false
}
target := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
if len(dates) == 2 && strings.Contains(content, "-") {
start, end := dates[0], dates[1]
if end.Before(start) {
start, end = end, start
}
if len(dates) >= 2 {
start := minDate(dates)
end := maxDate(dates)
return !target.Before(start) && !target.After(end)
}
for _, dt := range dates {
if dt.Equal(target) {
return true
}
}
return false
return dates[0].Equal(target)
}