diff --git a/core/typescore/approval_topic.go b/core/typescore/approval_topic.go
index 5294fd1..3e3c3ae 100644
--- a/core/typescore/approval_topic.go
+++ b/core/typescore/approval_topic.go
@@ -29,6 +29,7 @@ type ApprovalTopic struct {
RequireApproverComment *bool `gorm:"type:boolean;default:false;column:require_approver_comment" json:"require_approver_comment" db:"require_approver_comment"`
RequiresFile *bool `gorm:"type:boolean;not null;default:false;column:requires_file" json:"requires_file" db:"requires_file"`
RequireObserverSelection *bool `gorm:"type:boolean;not null;default:false;column:require_observer_selection" json:"require_observer_selection" db:"require_observer_selection"`
+ AllowDelegationSelection *bool `gorm:"type:boolean;not null;default:false;column:allow_delegation_selection" json:"allow_delegation_selection,omitempty" db:"allow_delegation_selection" mapstructure:"allow_delegation_selection"`
IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active" mapstructure:"is_active"`
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
diff --git a/service/telegram_service/common/update/callback.go b/service/telegram_service/common/update/callback.go
index 68719c1..1fc4e6a 100644
--- a/service/telegram_service/common/update/callback.go
+++ b/service/telegram_service/common/update/callback.go
@@ -39,6 +39,22 @@ func (s *UpdateHandler) handleCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.Callba
logrus.Infof("handleCallback: appr_stage approvalID=%d", approvalID)
s.approvalHandler.HandleApprovalStages(bot, cq, approvalID)
+ case data == "appr_deleg_yes":
+ s.approvalHandler.HandleDelegationChoiceCallback(bot, cq, true)
+
+ case data == "appr_deleg_no":
+ s.approvalHandler.HandleDelegationChoiceCallback(bot, cq, false)
+
+ case strings.HasPrefix(data, "appr_deleg_sel:"):
+ idStr := strings.TrimPrefix(data, "appr_deleg_sel:")
+ delegateID, _ := strconv.ParseUint(idStr, 10, 64)
+ s.approvalHandler.HandleDelegateSelectionCallback(bot, cq, delegateID)
+
+ case strings.HasPrefix(data, "appr_deleg_pg:"):
+ pageStr := strings.TrimPrefix(data, "appr_deleg_pg:")
+ page, _ := strconv.Atoi(pageStr)
+ s.approvalHandler.HandleDelegateSelectionPageCallback(bot, cq, page)
+
// Мультиселект кнопок
case strings.HasPrefix(data, "appr_ms_toggle:"):
parts := strings.SplitN(strings.TrimPrefix(data, "appr_ms_toggle:"), ":", 3)
diff --git a/service/telegram_service/handlers/approval/absense_delegation.go b/service/telegram_service/handlers/approval/absense_delegation.go
new file mode 100644
index 0000000..1e9059b
--- /dev/null
+++ b/service/telegram_service/handlers/approval/absense_delegation.go
@@ -0,0 +1,277 @@
+package approval
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "bitrix_balancer_api/core/utilscore"
+ "bitrix_balancer_api/telegram_service/keyboard"
+ "context"
+ "fmt"
+ "regexp"
+ "strconv"
+ "time"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+ "github.com/sirupsen/logrus"
+)
+
+// ============================================================
+// Делегирование обязанностей на время отсутствия (отгул/отпуск/
+// больничный). Включается флагом ApprovalTopic.AllowDelegationSelection
+// (тот же паттерн, что AllowObserverSelection) — см. patch к
+// ApprovalTopic и к continueFlowAfterInput в конце ответа.
+// ============================================================
+
+// showDelegationChoice — экран "делегировать все обязанности?" (Да/Нет).
+func (h *Handler) showDelegationChoice(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
+ text := "🔁 Делегировать все обязанности по согласованию на другого человека на время вашего отсутствия?\n\n" +
+ "Если согласитесь — все заявки, которые сейчас или ещё придут к вам на согласование, " +
+ "будут автоматически передаваться выбранному человеку до конца периода отсутствия."
+
+ msg := tgbotapi.NewMessage(chatID, text)
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDelegationChoiceMenu()
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleDelegationChoiceCallback — пользователь ответил Да/Нет на вопрос о делегировании.
+func (h *Handler) HandleDelegationChoiceCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, wantsDelegate bool) {
+ 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 || !flowState.AwaitDelegationChoice {
+ return
+ }
+
+ if !wantsDelegate {
+ flowState.AwaitDelegationChoice = false
+ flowState.DelegationSelectionDone = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+
+ sendText(bot, chatID, "☑️ Хорошо — обязанности не делегируются, вы решаете вопросы согласования самостоятельно.")
+ h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
+ return
+ }
+
+ candidates, err := h.getAvailableDelegateCandidates(ctx, telegramID)
+ if err != nil {
+ logrus.Errorf("HandleDelegationChoiceCallback: getAvailableDelegateCandidates err=%v", err)
+ }
+ if len(candidates) == 0 {
+ sendText(bot, chatID, "⚠️ Нет доступных сотрудников для делегирования. Обязанности остаются на вас.")
+ flowState.AwaitDelegationChoice = false
+ flowState.DelegationSelectionDone = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
+ return
+ }
+
+ flowState.AwaitDelegationChoice = false
+ flowState.AwaitDelegateSelection = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+
+ msg := tgbotapi.NewMessage(chatID, "👤 Выберите, кому передать обязанности:")
+ msg.ParseMode = "HTML"
+ msg.ReplyMarkup = keyboard.BuildDelegateSelectionMenu(candidates, 0)
+ bot.Send(msg) //nolint:errcheck
+}
+
+// HandleDelegateSelectionPageCallback — пагинация списка кандидатов.
+func (h *Handler) HandleDelegateSelectionPageCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, page int) {
+ ctx := context.Background()
+ chatID := cq.Message.Chat.ID
+ telegramID := cq.From.ID
+
+ bot.Request(tgbotapi.NewCallback(cq.ID, "")) //nolint:errcheck
+
+ flowState, err := h.States.Get(ctx, telegramID)
+ if err != nil || flowState == nil || !flowState.AwaitDelegateSelection {
+ return
+ }
+
+ candidates, err := h.getAvailableDelegateCandidates(ctx, telegramID)
+ if err != nil {
+ return
+ }
+
+ editMsg := tgbotapi.NewEditMessageReplyMarkup(
+ chatID,
+ cq.Message.MessageID,
+ keyboard.BuildDelegateSelectionMenu(candidates, page),
+ )
+ bot.Request(editMsg) //nolint:errcheck
+}
+
+// HandleDelegateSelectionCallback — пользователь выбрал конкретного делегата.
+func (h *Handler) HandleDelegateSelectionCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegateID uint64) {
+ 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 || !flowState.AwaitDelegateSelection {
+ return
+ }
+
+ me, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || me == nil || me.ID == nil {
+ sendText(bot, chatID, "⚠️ Пользователь не найден.")
+ return
+ }
+
+ delegate, err := h.ipc.Database.User.GetUserByIDDB(ctx, delegateID)
+ if err != nil || delegate == nil {
+ sendText(bot, chatID, "⚠️ Сотрудник не найден.")
+ return
+ }
+
+ // ValidUntil обязателен в схеме (not null) — определяем его из дат,
+ // введённых сотрудником на предыдущем шаге. Тот же терпимый к
+ // опечаткам разбор дат, что в scheduler/daily_reminder.go (там —
+ // уже готовая заявка, тут — ещё не отправленный flowState.Collected,
+ // но логика разбора идентична; продублирована намеренно, чтобы не
+ // тянуть в этот пакет зависимость от scheduler).
+ validUntil, datesFound := delegationValidUntil(flowState.Collected)
+ if !datesFound {
+ logrus.Warnf("HandleDelegateSelectionCallback: не удалось определить дату окончания отсутствия для userID=%d delegate=%d — используется запасной срок 30 дней", *me.ID, delegateID)
+ }
+
+ // Поиск делегата в processNextStepOrComplete/handleDecision матчит
+ // строго по конкретному TopicID ЛИБО конкретному CategoryID — запись
+ // с обоими NULL ("на всё сразу") никогда бы не нашлась. Поэтому
+ // создаём отдельную запись на каждую активную категорию согласований.
+ categories, _, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalTopicCategory{IsActive: utilscore.PointerToBool(true)},
+ })
+ if err != nil {
+ logrus.Errorf("HandleDelegateSelectionCallback: GetApprovalTopicCategoriesListDB err=%v", err)
+ sendText(bot, chatID, "⚠️ Ошибка при настройке делегирования.")
+ return
+ }
+
+ isActive := true
+ notifiedFalse := false
+ created := 0
+ for _, cat := range categories {
+ if cat.ID == nil {
+ continue
+ }
+ catID := *cat.ID
+ delegation := &typescore.ApprovalDelegation{
+ DelegatorID: me.ID,
+ DelegateID: delegate.ID,
+ CategoryID: &catID,
+ ValidUntil: &validUntil,
+ IsActive: &isActive,
+ NotifiedDay: ¬ifiedFalse,
+ Notified2h: ¬ifiedFalse,
+ }
+ if _, _, err := h.ipc.Database.ApprovalDelegation.CreateApprovalDelegationDB(ctx, nil, delegation); err != nil {
+ logrus.Errorf("HandleDelegateSelectionCallback: CreateApprovalDelegationDB categoryID=%d err=%v", catID, err)
+ continue
+ }
+ created++
+ }
+
+ delegateName := "—"
+ if delegate.FullName != nil {
+ delegateName = *delegate.FullName
+ }
+
+ flowState.AwaitDelegateSelection = false
+ flowState.DelegationSelectionDone = true
+ flowState.SelectedDelegateID = delegateID
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+
+ if created == 0 {
+ sendText(bot, chatID, "⚠️ Не удалось настроить делегирование. Обязанности остаются на вас.")
+ } else {
+ sendText(bot, chatID, fmt.Sprintf(
+ "🔁 Обязанности по согласованию делегированы\n\n"+
+ "👤 Кому: %s\n"+
+ "📅 До: %s",
+ delegateName, validUntil.Format("02.01.2006"),
+ ))
+ }
+
+ h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
+}
+
+// getAvailableDelegateCandidates — все активные сотрудники, кроме самого пользователя.
+func (h *Handler) getAvailableDelegateCandidates(ctx context.Context, telegramID int64) ([]*typescore.User, error) {
+ me, err := h.ipc.Database.User.GetUserByTelegramIDDB(ctx, telegramID)
+ if err != nil || me == nil || me.ID == nil {
+ return nil, err
+ }
+
+ users, _, err := h.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.User{IsBlocked: utilscore.PointerToBool(false)},
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ var result []*typescore.User
+ for _, u := range users {
+ if u.ID == nil || *u.ID == *me.ID || u.TelegramID == nil {
+ continue
+ }
+ if u.IsFired != nil && *u.IsFired {
+ continue
+ }
+ result = append(result, u)
+ }
+ return result, nil
+}
+
+// ============================================================
+// Разбор дат из flowState.Collected — тот же терпимый к опечаткам
+// подход, что в scheduler/daily_reminder.go (getAbsentEmployeesToday),
+// намеренно продублирован здесь, а не вынесен в общий пакет.
+// ============================================================
+
+var delegationDateRe = regexp.MustCompile(`(\d{1,2})[.,](\d{1,2})\.(\d{4})`)
+
+// delegationValidUntil ищет во ВСЕХ собранных на этом шаге значениях
+// (обычно дата лежит под ключом "content" — стандартный input_key
+// текстового шага, но на случай нестандартной настройки дерева
+// проверяем все значения) самую позднюю дату. Если ничего не нашлось —
+// возвращает запасной срок в 30 дней от текущего момента, чтобы не
+// оставить not-null колонку без значения вовсе.
+func delegationValidUntil(collected map[string]string) (time.Time, bool) {
+ var dates []time.Time
+ for _, v := range collected {
+ matches := delegationDateRe.FindAllStringSubmatch(v, -1)
+ for _, m := range matches {
+ day, errD := strconv.Atoi(m[1])
+ month, errM := strconv.Atoi(m[2])
+ year, errY := strconv.Atoi(m[3])
+ if errD != nil || errM != nil || errY != nil {
+ continue
+ }
+ if month < 1 || month > 12 || day < 1 || day > 31 {
+ continue
+ }
+ dates = append(dates, time.Date(year, time.Month(month), day, 23, 59, 59, 0, time.UTC))
+ }
+ }
+
+ if len(dates) == 0 {
+ return time.Now().AddDate(0, 0, 30), false
+ }
+
+ maxDate := dates[0]
+ for _, d := range dates[1:] {
+ if d.After(maxDate) {
+ maxDate = d
+ }
+ }
+ return maxDate, true
+}
diff --git a/service/telegram_service/handlers/approval/handler.go b/service/telegram_service/handlers/approval/handler.go
index 7e534ef..f8be6ac 100644
--- a/service/telegram_service/handlers/approval/handler.go
+++ b/service/telegram_service/handlers/approval/handler.go
@@ -653,6 +653,17 @@ func (h *Handler) continueFlowAfterInput(
return
}
+ if approvalTopic != nil &&
+ approvalTopic.AllowDelegationSelection != nil &&
+ *approvalTopic.AllowDelegationSelection &&
+ !flowState.DelegationSelectionDone {
+
+ flowState.AwaitDelegationChoice = true
+ h.States.Set(ctx, telegramID, flowState) //nolint:errcheck
+ h.showDelegationChoice(bot, chatID, telegramID)
+ return
+ }
+
if approvalTopic != nil &&
approvalTopic.AllowObserverSelection != nil &&
*approvalTopic.AllowObserverSelection &&
diff --git a/service/telegram_service/handlers/approval/handler_executor.go b/service/telegram_service/handlers/approval/handler_executor.go
index 75bb92d..b82cc2d 100644
--- a/service/telegram_service/handlers/approval/handler_executor.go
+++ b/service/telegram_service/handlers/approval/handler_executor.go
@@ -221,12 +221,21 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback
content = *approval.Content
}
+ // 🆕 Текст самой выполненной задачи (task.TaskText) — раньше в
+ // уведомлении был только текст заявки целиком (approval.Content),
+ // а что конкретно исполнитель делал — нет.
+ completedTaskText := "—"
+ if task.TaskText != nil {
+ completedTaskText = *task.TaskText
+ }
+
notifyMsg := tgbotapi.NewMessage(*initiator.TelegramID, fmt.Sprintf(
"✅ Исполнитель завершил задачу\n\n"+
"📋 Заявка #%d — %s\n"+
"👤 Исполнитель: %s\n"+
- "📝 Текст: %s",
- *task.ApprovalID, topicName, executorName, content,
+ "📝 Текст: %s\n"+
+ "🎯 Задача: %s",
+ *task.ApprovalID, topicName, executorName, content, completedTaskText,
))
notifyMsg.ParseMode = "HTML"
bot.Send(notifyMsg) //nolint:errcheck
diff --git a/service/telegram_service/keyboard/absense_delegation_keyboard.go b/service/telegram_service/keyboard/absense_delegation_keyboard.go
new file mode 100644
index 0000000..d2de5b1
--- /dev/null
+++ b/service/telegram_service/keyboard/absense_delegation_keyboard.go
@@ -0,0 +1,60 @@
+package keyboard
+
+import (
+ "bitrix_balancer_api/core/typescore"
+ "fmt"
+
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
+)
+
+// BuildDelegationChoiceMenu — клавиатура Да/Нет для вопроса о делегировании.
+func BuildDelegationChoiceMenu() tgbotapi.InlineKeyboardMarkup {
+ return tgbotapi.NewInlineKeyboardMarkup(
+ tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData("✅ Да", "appr_deleg_yes"),
+ tgbotapi.NewInlineKeyboardButtonData("❌ Нет", "appr_deleg_no"),
+ ),
+ )
+}
+
+const delegateCandidatesPerPage = 8
+
+// BuildDelegateSelectionMenu — постраничный список кандидатов на
+// делегирование (одиночный выбор, без toggle — в отличие от наблюдателей).
+func BuildDelegateSelectionMenu(candidates []*typescore.User, page int) tgbotapi.InlineKeyboardMarkup {
+ start := page * delegateCandidatesPerPage
+ if start > len(candidates) {
+ start = len(candidates)
+ }
+ end := start + delegateCandidatesPerPage
+ if end > len(candidates) {
+ end = len(candidates)
+ }
+
+ var rows [][]tgbotapi.InlineKeyboardButton
+ for _, u := range candidates[start:end] {
+ if u.ID == nil {
+ continue
+ }
+ name := "Без имени"
+ if u.FullName != nil {
+ name = *u.FullName
+ }
+ rows = append(rows, tgbotapi.NewInlineKeyboardRow(
+ tgbotapi.NewInlineKeyboardButtonData(name, fmt.Sprintf("appr_deleg_sel:%d", *u.ID)),
+ ))
+ }
+
+ var navRow []tgbotapi.InlineKeyboardButton
+ if page > 0 {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData("⬅️ Назад", fmt.Sprintf("appr_deleg_pg:%d", page-1)))
+ }
+ if end < len(candidates) {
+ navRow = append(navRow, tgbotapi.NewInlineKeyboardButtonData("Вперёд ➡️", fmt.Sprintf("appr_deleg_pg:%d", page+1)))
+ }
+ if len(navRow) > 0 {
+ rows = append(rows, navRow)
+ }
+
+ return tgbotapi.NewInlineKeyboardMarkup(rows...)
+}
diff --git a/service/telegram_service/scheduler/daily_reminder.go b/service/telegram_service/scheduler/daily_reminder.go
index a7f0090..1107589 100644
--- a/service/telegram_service/scheduler/daily_reminder.go
+++ b/service/telegram_service/scheduler/daily_reminder.go
@@ -6,7 +6,11 @@ import (
"bitrix_balancer_api/telegram_service/keyboard"
"bitrix_balancer_api/telegram_service/types"
"context"
+ "encoding/json"
"fmt"
+ "regexp"
+ "strconv"
+ "strings"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
@@ -77,6 +81,12 @@ func (dr *DailyReminder) sendReminders() {
ctx := context.Background()
bot := dr.ipc.TGBotClient.Bot()
+ mskLocation, err := time.LoadLocation("Europe/Moscow")
+ if err != nil {
+ logrus.Errorf("DailyReminder: не удалось загрузить часовой пояс МСК: %v", err)
+ mskLocation = time.FixedZone("MSK", 3*3600)
+ }
+
// Получаем всех активных пользователей
users, _, err := dr.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{})
if err != nil {
@@ -84,7 +94,13 @@ func (dr *DailyReminder) sendReminders() {
return
}
- logrus.Infof("DailyReminder: начинаем отправку напоминаний для %d пользователей", len(users))
+ // 🆕 Список отсутствующих сегодня считаем ОДИН раз на всю рассылку —
+ // это общая для всех информация, а не персональная, поэтому нет смысла
+ // пересчитывать её в цикле для каждого сотрудника отдельно.
+ absentToday := dr.getAbsentEmployeesToday(ctx, mskLocation)
+
+ logrus.Infof("DailyReminder: начинаем отправку напоминаний для %d пользователей (отсутствующих сегодня: %d)",
+ len(users), len(absentToday))
sentCount := 0
for _, user := range users {
@@ -92,7 +108,7 @@ func (dr *DailyReminder) sendReminders() {
continue
}
- if dr.sendReminderToUser(bot, ctx, user) {
+ if dr.sendReminderToUser(bot, ctx, user, absentToday) {
sentCount++
}
@@ -105,7 +121,7 @@ func (dr *DailyReminder) sendReminders() {
// sendReminderToUser отправляет напоминание конкретному пользователю
// Возвращает true, если сообщение было отправлено
-func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Context, user *typescore.User) bool {
+func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Context, user *typescore.User, absentToday []AbsentEmployeeInfo) bool {
userID := *user.ID
telegramID := *user.TelegramID
@@ -156,8 +172,13 @@ func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Co
// 🚀 Считаем только те шаги/доп. согласующих, у которых сама заявка в статусе pending
approvalsCount := dr.countPendingApprovals(ctx, steps, additionalApprovers)
- // Если нет ничего для пользователя, не отправляем сообщение
- if revisionsCount == 0 && tasksCount == 0 && approvalsCount == 0 {
+ hasPersonalItems := revisionsCount > 0 || tasksCount > 0 || approvalsCount > 0
+
+ // 🆕 Раньше: если сообщить нечего — не отправляем совсем. Теперь
+ // список отсутствующих сегодня — самостоятельный повод прислать
+ // сводку, даже если лично у сотрудника пусто (по вашему решению —
+ // присылаем всем каждое утро, пока список непустой).
+ if !hasPersonalItems && len(absentToday) == 0 {
return false
}
@@ -176,15 +197,31 @@ func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Co
text += fmt.Sprintf("Согласований к принятию: %d\n", approvalsCount)
}
- text += "\nНажмите на кнопку для перехода к нужному разделу"
+ if hasPersonalItems {
+ text += "\nНажмите на кнопку для перехода к нужному разделу"
+ }
+
+ if len(absentToday) > 0 {
+ if hasPersonalItems {
+ text += "\n\n"
+ }
+ text += "👥 Сотрудники в отгуле/больничном/отпуске:\n"
+ for _, a := range absentToday {
+ text += fmt.Sprintf("%s - %s - по срочным вопросам обращаться: %s\n", a.Name, a.TimeDescription, a.Contact)
+ }
+ }
msg := tgbotapi.NewMessage(telegramID, text)
msg.ParseMode = "HTML"
- msg.ReplyMarkup = keyboard.BuildDailyReminderKeyboard(
- revisionsCount > 0,
- tasksCount > 0,
- approvalsCount > 0,
- )
+ // Кнопки имеют смысл только если есть личные пункты для перехода —
+ // список отсутствующих никуда вести не должен.
+ if hasPersonalItems {
+ msg.ReplyMarkup = keyboard.BuildDailyReminderKeyboard(
+ revisionsCount > 0,
+ tasksCount > 0,
+ approvalsCount > 0,
+ )
+ }
if _, err := bot.Send(msg); err != nil {
logrus.Errorf("DailyReminder: не удалось отправить сообщение пользователю %d: %v", telegramID, err)
@@ -234,3 +271,242 @@ func (dr *DailyReminder) countPendingApprovals(
return count
}
+
+// ============================================================
+// 🆕 "Кто сегодня отсутствует" — отгул/больничный/отпуск
+// ============================================================
+
+// absenceMetadata — то, что реально надёжно есть в metadata.extra у
+// заявок категорий "Отгул"/"Больничный"/"Отпуск". AbsenceType — маркер
+// того, что это вообще заявка на отсутствие (у остальных категорий
+// этого поля просто нет). TimeType говорит "весь день" или "частично",
+// но САМИ ДАТЫ отдельного структурированного поля не имеют — сотрудник
+// вводит их свободным текстом на последнем шаге дерева, попадает это в
+// Approval.Content. Реальные примеры того, что там оказывается:
+//
+// "11.07.2026-24.07.2026" (диапазон дат)
+// "24,07.2026 и 27.07.2026" (список дат, ЕЩЁ и с опечаткой —
+// запятая вместо точки)
+// "21.07.2026 с 9:00 по 11:00" (один день + время)
+// "22.07.2026" (просто один день)
+//
+// Единого формата нет и не будет, поэтому ниже — терпимый к опечаткам
+// разбор через regexp (вытаскиваем все даты/времена, какие найдутся),
+// а не попытка сопоставить точный шаблон под duration_type. Это
+// осознанный компромисс: часть экзотических формулировок сотрудников
+// распознана не будет, и заявка просто тихо не попадёт в сводку —
+// лучше так, чем показать в сводке неверную дату.
+type absenceMetadata struct {
+ Extra struct {
+ TimeType string `json:"time_type"`
+ AbsenceType string `json:"absence_type"`
+ } `json:"extra"`
+}
+
+type AbsentEmployeeInfo struct {
+ Name string
+ TimeDescription string
+ // 🆕 Contact — кому обращаться по срочным вопросам: делегату, если
+ // сотрудник делегировал обязанности при уходе (см.
+ // handlers/approval/delegation.go), иначе — самому сотруднику.
+ Contact string
+}
+
+// Даты: ДД.MM.ГГГГ, но день от месяца иногда отделён запятой вместо
+// точки (реальная опечатка сотрудника) — поэтому [.,], а не просто ".".
+var absenceDateRe = regexp.MustCompile(`(\d{1,2})[.,](\d{1,2})\.(\d{4})`)
+
+// Время: строго через двоеточие (9:00, 11:00) — специально НЕ через
+// точку, чтобы не перепутать с датами (21.07 иначе тоже подошло бы
+// под "число.число").
+var absenceTimeRe = regexp.MustCompile(`(\d{1,2}):(\d{2}).*?(\d{1,2}):(\d{2})`)
+
+// getAbsentEmployeesToday возвращает всех сотрудников, чьи одобренные
+// заявки на отгул/больничный/отпуск покрывают сегодняшний день.
+func (dr *DailyReminder) getAbsentEmployeesToday(ctx context.Context, mskLocation *time.Location) []AbsentEmployeeInfo {
+ today := time.Now().In(mskLocation)
+ todayY, todayM, todayD := today.Date()
+
+ // Без фильтра по InitiatorID — одним запросом получаем все одобренные
+ // заявки компании и дальше фильтруем в памяти. Так один раз на всю
+ // рассылку, а не по запросу на каждого сотрудника.
+ approvals, _, err := dr.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.Approval{
+ Status: utilscore.PointerToString("approved"),
+ },
+ })
+ if err != nil {
+ logrus.Errorf("DailyReminder: getAbsentEmployeesToday: GetApprovalsListDB err=%v", err)
+ return nil
+ }
+
+ seenUsers := make(map[uint64]bool)
+ var result []AbsentEmployeeInfo
+
+ for _, approval := range approvals {
+ if approval.Metadata == nil || *approval.Metadata == "" || approval.Content == nil {
+ continue
+ }
+
+ var meta absenceMetadata
+ if err := json.Unmarshal([]byte(*approval.Metadata), &meta); err != nil {
+ continue
+ }
+ if meta.Extra.AbsenceType == "" {
+ // Не заявка на отсутствие — это поле есть только у
+ // отгула/больничного/отпуска.
+ continue
+ }
+
+ if approval.InitiatorID == nil || seenUsers[*approval.InitiatorID] {
+ continue
+ }
+
+ dates := parseAbsenceDates(*approval.Content)
+ if len(dates) == 0 {
+ logrus.Warnf("DailyReminder: не удалось разобрать даты в content заявки #%d: %q",
+ derefApprovalID(approval), *approval.Content)
+ continue
+ }
+
+ if !absenceCoversDate(dates, *approval.Content, todayY, todayM, todayD) {
+ continue
+ }
+
+ 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
+ }
+ }
+
+ // 🆕 Формулировка зависит от категории отсутствия: у отгула
+ // показываем время (или "весь день"), у отпуска/больничного —
+ // дату, ДО которой человек отсутствует (последняя из найденных
+ // дат — для диапазона это конец диапазона, для списка вроде
+ // "24.07 и 27.07" — последний день из списка).
+ var timeDescription string
+ switch meta.Extra.AbsenceType {
+ case "timeoff":
+ if meta.Extra.TimeType == "partial" {
+ if m := absenceTimeRe.FindStringSubmatch(*approval.Content); m != nil {
+ timeDescription = fmt.Sprintf("отгул с %s:%s до %s:%s", m[1], m[2], m[3], m[4])
+ } else {
+ timeDescription = "отгул весь день"
+ }
+ } else {
+ timeDescription = "отгул весь день"
+ }
+ case "vacation":
+ timeDescription = fmt.Sprintf("отпуск до %s", maxDate(dates).Format("02.01.2006"))
+ case "sickleave":
+ timeDescription = fmt.Sprintf("больничный до %s", maxDate(dates).Format("02.01.2006"))
+ default:
+ timeDescription = "отсутствует"
+ }
+
+ // 🆕 Контакт по срочным вопросам: если у сотрудника есть активное
+ // делегирование (см. handlers/approval/delegation.go), показываем
+ // делегата, иначе — самого сотрудника. ValidUntil проверяем
+ // дополнительно как подстраховку — на случай, если задача,
+ // отвечающая за деактивацию просроченных делегирований (см.
+ // NotifiedDay/Notified2h в ApprovalDelegation), ещё не отработала.
+ contact := name
+ if delegations, _, dErr := dr.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
+ Filtering: &typescore.ApprovalDelegation{
+ DelegatorID: approval.InitiatorID,
+ IsActive: utilscore.PointerToBool(true),
+ },
+ }); dErr == nil {
+ now := time.Now()
+ for _, d := range delegations {
+ if d.DelegateID == nil {
+ continue
+ }
+ if d.ValidUntil != nil && d.ValidUntil.Before(now) {
+ continue
+ }
+ delegate, uErr := dr.ipc.Database.User.GetUserByIDDB(ctx, *d.DelegateID)
+ if uErr == nil && delegate != nil && delegate.FullName != nil {
+ contact = *delegate.FullName
+ }
+ break
+ }
+ }
+
+ seenUsers[*approval.InitiatorID] = true
+ result = append(result, AbsentEmployeeInfo{
+ Name: name,
+ TimeDescription: timeDescription,
+ Contact: contact,
+ })
+ }
+
+ return result
+}
+
+func derefApprovalID(a *typescore.Approval) uint64 {
+ if a == nil || a.ID == nil {
+ return 0
+ }
+ return *a.ID
+}
+
+// parseAbsenceDates вытаскивает все даты вида ДД.MM.ГГГГ из произвольного
+// текста, независимо от того, что вокруг них написано.
+func parseAbsenceDates(content string) []time.Time {
+ matches := absenceDateRe.FindAllStringSubmatch(content, -1)
+ var dates []time.Time
+ for _, m := range matches {
+ day, errD := strconv.Atoi(m[1])
+ month, errM := strconv.Atoi(m[2])
+ year, errY := strconv.Atoi(m[3])
+ if errD != nil || errM != nil || errY != nil {
+ continue
+ }
+ if month < 1 || month > 12 || day < 1 || day > 31 {
+ continue
+ }
+ dates = append(dates, time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC))
+ }
+ return dates
+}
+
+// maxDate возвращает самую позднюю дату из списка — используется как
+// "дата, до которой отсутствует" для отпуска/больничного.
+func maxDate(dates []time.Time) time.Time {
+ max := dates[0]
+ for _, d := range dates[1:] {
+ if d.After(max) {
+ max = d
+ }
+ }
+ return max
+}
+
+// absenceCoversDate решает, покрывает ли разобранный набор дат указанный
+// день. Если дат ровно 2 и в исходном тексте между ними есть дефис —
+// считаем их непрерывным диапазоном "с ... по ..." (как в
+// "11.07.2026-24.07.2026"). Иначе — это список отдельных дней (как в
+// "24,07.2026 и 27.07.2026", или просто один день).
+func absenceCoversDate(dates []time.Time, content string, y int, m time.Month, d int) bool {
+ 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
+ }
+ return !target.Before(start) && !target.After(end)
+ }
+
+ for _, dt := range dates {
+ if dt.Equal(target) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/service/telegram_service/state/state.go b/service/telegram_service/state/state.go
index dc336bd..d7bfc30 100644
--- a/service/telegram_service/state/state.go
+++ b/service/telegram_service/state/state.go
@@ -46,6 +46,14 @@ type ApprovalFlowState struct {
AwaitObserverSelection bool `json:"await_observer_selection"`
ObserverSelectionDone bool `json:"observer_selection_done"`
SelectedObserverIDs []uint64 `json:"selected_observer_ids,omitempty"`
+
+ // 🆕 Делегирование обязанностей на время отсутствия (отгул/отпуск/
+ // больничный) — см. handlers/approval/delegation.go. Тот же паттерн,
+ // что у наблюдателей: Await*/ *Done флаги + выбранное значение.
+ AwaitDelegationChoice bool `json:"await_delegation_choice,omitempty"`
+ AwaitDelegateSelection bool `json:"await_delegate_selection,omitempty"`
+ DelegationSelectionDone bool `json:"delegation_selection_done,omitempty"`
+ SelectedDelegateID uint64 `json:"selected_delegate_id,omitempty"`
}
type StateManager struct {