Updated absense delegation #85

Merged
romanskijdev merged 4 commits from fix-permissions into main 2026-07-28 00:35:17 +03:00
7 changed files with 604 additions and 211 deletions

View File

@ -12,6 +12,7 @@ type ApprovalDelegation struct {
IsActive *bool `gorm:"type:boolean;not null;default:true;column:is_active" json:"is_active" db:"is_active"`
NotifiedDay *bool `gorm:"type:boolean;not null;default:false;column:notified_day" json:"notified_day" db:"notified_day"`
Notified2h *bool `gorm:"type:boolean;not null;default:false;column:notified_2h" json:"notified_2h" db:"notified_2h"`
ApprovalID *uint64 `gorm:"type:bigint;index;column:approval_id" json:"approval_id,omitempty" db:"approval_id" mapstructure:"approval_id"`
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
UpdatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:updated_at" json:"updated_at" db:"updated_at"`

View File

@ -4,7 +4,11 @@ import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
"context"
"encoding/json"
"net/http"
"regexp"
"strconv"
"strings"
"time"
)
@ -55,15 +59,22 @@ func (s *DashboardReg) GetDashboardStatsHandler(w http.ResponseWriter, r *http.R
})
}
// === 4. Топ-5 тем по количеству заявок ===
topTopics := s.getTopTopics(ctx, 5)
// === 4. Разбивка по категориям (вместо топ-5 тем) ===
categoryBreakdown := s.getCategoryBreakdown(ctx)
// === 5. Топ-5 согласующих ===
topApprovers := s.getTopApprovers(ctx, 5)
// === 5. Узкие места: согласующие с просроченными заявками (вместо топ-5 по активности) ===
bottleneckApprovers := s.getBottleneckApprovers(ctx, 5, 7)
// === 6. Старые pending заявки (>7 дней) ===
oldPendingCount := s.countOldPendingApprovals(ctx, 7)
// === 7. 🆕 Задачи: распределение по статусам + динамика за 7 дней ===
taskStatusData := s.getTaskStatusData(ctx)
taskDailyData := s.getTaskDailyData(ctx)
// === 8. 🆕 Кто отсутствует сегодня (отгул/отпуск/больничный) ===
absentToday := s.getAbsentToday(ctx)
return map[string]interface{}{
"users": map[string]int{
"total": totalUsers,
@ -80,15 +91,19 @@ func (s *DashboardReg) GetDashboardStatsHandler(w http.ResponseWriter, r *http.R
"total": totalTopics,
"active": activeTopics,
},
"categories": totalCategories,
"departments": totalDepartments,
"roles": totalRoles,
"executors": totalExecutors,
"statusData": statusData,
"dailyData": dailyData,
"topTopics": topTopics,
"topApprovers": topApprovers,
"oldPendingCount": oldPendingCount,
"categories": totalCategories,
"departments": totalDepartments,
"roles": totalRoles,
"executors": totalExecutors,
"statusData": statusData,
"dailyData": dailyData,
"categoryBreakdown": categoryBreakdown,
"bottleneckApprovers": bottleneckApprovers,
"oldPendingCount": oldPendingCount,
"oldPendingDays": 7,
"taskStatusData": taskStatusData,
"taskDailyData": taskDailyData,
"absentToday": absentToday,
}, nil
}
@ -125,7 +140,6 @@ func (s *DashboardReg) countApprovalsByStatus(ctx context.Context, status string
}
func (s *DashboardReg) countApprovalsByStatusAndDate(ctx context.Context, status string, date time.Time) int {
// Получаем все заявки со статусом за сегодня
opts := typescore.ListDbOptions{
Filtering: &typescore.Approval{Status: &status},
Limit: utilscore.PointerToUint64(10000),
@ -166,7 +180,6 @@ func (s *DashboardReg) countApprovalsCreatedOn(ctx context.Context, date time.Ti
}
func (s *DashboardReg) countApprovalsApprovedOn(ctx context.Context, date time.Time) int {
// Получаем все шаги согласования со статусом approved за день
opts := typescore.ListDbOptions{
Filtering: &typescore.ApprovalStep{Status: strPtr("approved")},
Limit: utilscore.PointerToUint64(10000),
@ -176,7 +189,6 @@ func (s *DashboardReg) countApprovalsApprovedOn(ctx context.Context, date time.T
return 0
}
// Считаем уникальные заявки
uniqueApprovals := make(map[uint64]bool)
target := date.Format("2006-01-02")
for _, step := range steps {
@ -268,130 +280,79 @@ func (s *DashboardReg) countOldPendingApprovals(ctx context.Context, days int) i
}
// ============================================================
// Топ-5 тем по количеству заявок
// Разбивка заявок по категориям (заменяет прежний "топ-5 тем").
// ============================================================
func (s *DashboardReg) getTopTopics(ctx context.Context, limit int) []map[string]interface{} {
// Получаем все заявки
opts := typescore.ListDbOptions{
func (s *DashboardReg) getCategoryBreakdown(ctx context.Context) []map[string]interface{} {
topicOpts := typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopic{},
Limit: utilscore.PointerToUint64(10000),
}
topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, topicOpts)
if err != nil {
return []map[string]interface{}{}
}
topicToCategory := make(map[uint64]uint64, len(topics))
for _, t := range topics {
if t.ID != nil && t.CategoryID != nil {
topicToCategory[*t.ID] = *t.CategoryID
}
}
categoryOpts := typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopicCategory{},
Limit: utilscore.PointerToUint64(10000),
}
categories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, categoryOpts)
if err != nil {
return []map[string]interface{}{}
}
categoryNames := make(map[uint64]string, len(categories))
for _, c := range categories {
if c.ID != nil && c.Name != nil {
categoryNames[*c.ID] = *c.Name
}
}
approvalOpts := typescore.ListDbOptions{
Filtering: &typescore.Approval{},
Limit: utilscore.PointerToUint64(10000),
}
approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts)
approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, approvalOpts)
if err != nil {
return []map[string]interface{}{}
}
// Считаем количество заявок по topic_id
topicCounts := make(map[uint64]int)
topicPending := make(map[uint64]int)
type catStat struct {
total int
pending int
}
byCategory := make(map[uint64]*catStat)
for _, a := range approvals {
if a.TopicID == nil {
continue
}
topicCounts[*a.TopicID]++
categoryID, ok := topicToCategory[*a.TopicID]
if !ok {
continue
}
if byCategory[categoryID] == nil {
byCategory[categoryID] = &catStat{}
}
byCategory[categoryID].total++
if a.Status != nil && *a.Status == "pending" {
topicPending[*a.TopicID]++
byCategory[categoryID].pending++
}
}
// Сортируем по количеству (вручную, без import sort)
type topicStat struct {
id uint64
count int
pending int
}
stats := make([]topicStat, 0, len(topicCounts))
for id, count := range topicCounts {
stats = append(stats, topicStat{id: id, count: count, pending: topicPending[id]})
}
// Простая сортировка (bubble sort для небольшого N)
for i := 0; i < len(stats); i++ {
for j := i + 1; j < len(stats); j++ {
if stats[j].count > stats[i].count {
stats[i], stats[j] = stats[j], stats[i]
}
}
}
// Берём топ-N и обогащаем данными
result := make([]map[string]interface{}, 0, limit)
for i := 0; i < len(stats) && i < limit; i++ {
stat := stats[i]
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, stat.id)
if err != nil || topic == nil {
continue
}
categoryName := ""
if topic.CategoryID != nil {
cat, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
if err == nil && cat != nil && cat.Name != nil {
categoryName = *cat.Name
}
}
topicName := ""
if topic.Name != nil {
topicName = *topic.Name
}
result = append(result, map[string]interface{}{
"id": stat.id,
"name": topicName,
"category_name": categoryName,
"total_count": stat.count,
"pending_count": stat.pending,
})
}
return result
}
// ============================================================
// Топ-5 согласующих
// ============================================================
func (s *DashboardReg) getTopApprovers(ctx context.Context, limit int) []map[string]interface{} {
// Получаем все шаги согласования
opts := typescore.ListDbOptions{
Filtering: &typescore.ApprovalStep{},
Limit: utilscore.PointerToUint64(10000),
}
steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, opts)
if err != nil {
return []map[string]interface{}{}
}
// Считаем по approver_id
type approverStat struct {
total int
pending int
}
stats := make(map[uint64]*approverStat)
for _, step := range steps {
if step.ApproverID == nil {
continue
}
id := *step.ApproverID
if stats[id] == nil {
stats[id] = &approverStat{}
}
stats[id].total++
if step.Status != nil && *step.Status == "pending" {
stats[id].pending++
}
}
// Сортируем
type approverEntry struct {
type entry struct {
id uint64
total int
pending int
}
entries := make([]approverEntry, 0, len(stats))
for id, st := range stats {
entries = append(entries, approverEntry{id: id, total: st.total, pending: st.pending})
entries := make([]entry, 0, len(byCategory))
for id, st := range byCategory {
entries = append(entries, entry{id: id, total: st.total, pending: st.pending})
}
for i := 0; i < len(entries); i++ {
for j := i + 1; j < len(entries); j++ {
@ -401,11 +362,88 @@ func (s *DashboardReg) getTopApprovers(ctx context.Context, limit int) []map[str
}
}
// Берём топ-N
result := make([]map[string]interface{}, 0, len(entries))
for _, e := range entries {
name := categoryNames[e.id]
if name == "" {
continue
}
result = append(result, map[string]interface{}{
"id": e.id,
"name": name,
"total_count": e.total,
"pending_count": e.pending,
})
}
return result
}
// ============================================================
// Узкие места: согласующие с просроченными (>days дней с подачи) заявками.
// ============================================================
func (s *DashboardReg) getBottleneckApprovers(ctx context.Context, limit int, days int) []map[string]interface{} {
stepOpts := typescore.ListDbOptions{
Filtering: &typescore.ApprovalStep{Status: strPtr("pending")},
Limit: utilscore.PointerToUint64(10000),
}
steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, stepOpts)
if err != nil {
return []map[string]interface{}{}
}
cutoff := time.Now().AddDate(0, 0, -days)
type approverStat struct {
pendingTotal int
overdue int
}
stats := make(map[uint64]*approverStat)
for _, step := range steps {
if step.ApproverID == nil || step.ApprovalID == nil {
continue
}
approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *step.ApprovalID)
if err != nil || approval == nil || approval.CreatedAt == nil {
continue
}
id := *step.ApproverID
if stats[id] == nil {
stats[id] = &approverStat{}
}
stats[id].pendingTotal++
if approval.CreatedAt.Before(cutoff) {
stats[id].overdue++
}
}
type entry struct {
id uint64
pendingTotal int
overdue int
}
entries := make([]entry, 0, len(stats))
for id, st := range stats {
if st.overdue == 0 {
continue
}
entries = append(entries, entry{id: id, pendingTotal: st.pendingTotal, overdue: st.overdue})
}
for i := 0; i < len(entries); i++ {
for j := i + 1; j < len(entries); j++ {
if entries[j].overdue > entries[i].overdue {
entries[i], entries[j] = entries[j], entries[i]
}
}
}
result := make([]map[string]interface{}, 0, limit)
for i := 0; i < len(entries) && i < limit; i++ {
entry := entries[i]
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, entry.id)
e := entries[i]
user, err := s.ipc.Database.User.GetUserByIDDB(ctx, e.id)
if err != nil || user == nil {
continue
}
@ -424,16 +462,221 @@ func (s *DashboardReg) getTopApprovers(ctx context.Context, limit int) []map[str
}
result = append(result, map[string]interface{}{
"user_id": entry.id,
"user_id": e.id,
"full_name": fullName,
"department_name": deptName,
"total_steps": entry.total,
"pending_steps": entry.pending,
"pending_total": e.pendingTotal,
"overdue_count": e.overdue,
})
}
return result
}
// ============================================================
// 🆕 Задачи: распределение по статусам + динамика за 7 дней.
// Полностью аналогично разделам про заявки — те же графики, другая
// таблица (ApprovalTask вместо Approval).
// ============================================================
func (s *DashboardReg) getTaskStatusData(ctx context.Context) []map[string]interface{} {
statuses := []string{"pending", "waiting", "completed", "cancelled"}
result := make([]map[string]interface{}, 0, len(statuses))
for _, status := range statuses {
st := status
opts := typescore.ListDbOptions{
Filtering: &typescore.ApprovalTask{Status: &st},
Limit: utilscore.PointerToUint64(10000),
}
list, _, err := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, opts)
count := 0
if err == nil {
count = len(list)
}
result = append(result, map[string]interface{}{
"status": status,
"count": count,
})
}
return result
}
func (s *DashboardReg) getTaskDailyData(ctx context.Context) []map[string]interface{} {
opts := typescore.ListDbOptions{
Filtering: &typescore.ApprovalTask{},
Limit: utilscore.PointerToUint64(10000),
}
tasks, _, err := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, opts)
if err != nil {
tasks = nil
}
result := make([]map[string]interface{}, 0, 7)
now := time.Now()
for i := 6; i >= 0; i-- {
date := now.AddDate(0, 0, -i)
target := date.Format("2006-01-02")
created := 0
completed := 0
for _, t := range tasks {
if t.CreatedAt != nil && t.CreatedAt.Format("2006-01-02") == target {
created++
}
if t.CompletedAt != nil && t.CompletedAt.Format("2006-01-02") == target {
completed++
}
}
result = append(result, map[string]interface{}{
"date": target,
"created": created,
"completed": completed,
})
}
return result
}
// ============================================================
// 🆕 Кто отсутствует сегодня (отгул/отпуск/больничный).
//
// 🩹 Логика разбора дат намеренно продублирована из
// scheduler/daily_reminder.go (getAbsentEmployeesToday) — тот же самый
// терпимый к опечаткам подход через regexp, т.к. у заявок на отсутствие
// нет отдельного структурированного поля с датами. rest_admin_service
// использует свой ipc-тип, отличный от telegram_service, поэтому
// переиспользовать функцию напрямую нельзя — общий пакет пока не заводили.
//
// Упрощение по сравнению с ботом: здесь НЕ подмешивается контакт-делегат
// (ApprovalDelegation) — просто список отсутствующих с описанием.
// ============================================================
type dashboardAbsenceMetadata struct {
Extra struct {
TimeType string `json:"time_type"`
AbsenceType string `json:"absence_type"`
} `json:"extra"`
}
var dashboardAbsenceDateRe = regexp.MustCompile(`(\d{1,2})[.,](\d{1,2})\.(\d{4})`)
var dashboardAbsenceTimeRe = regexp.MustCompile(`(\d{1,2}):(\d{2}).*?(\d{1,2}):(\d{2})`)
func (s *DashboardReg) getAbsentToday(ctx context.Context) []map[string]interface{} {
loc, err := time.LoadLocation("Europe/Moscow")
if err != nil {
loc = time.FixedZone("MSK", 3*3600)
}
today := time.Now().In(loc)
todayY, todayM, todayD := today.Date()
approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.Approval{Status: strPtr("approved")},
Limit: utilscore.PointerToUint64(10000),
})
if err != nil {
return []map[string]interface{}{}
}
seenUsers := make(map[uint64]bool)
result := []map[string]interface{}{}
for _, a := range approvals {
if a.Metadata == nil || *a.Metadata == "" || a.Content == nil || a.InitiatorID == nil {
continue
}
if seenUsers[*a.InitiatorID] {
continue
}
var meta dashboardAbsenceMetadata
if err := json.Unmarshal([]byte(*a.Metadata), &meta); err != nil || meta.Extra.AbsenceType == "" {
continue
}
dates := parseDashboardAbsenceDates(*a.Content)
if len(dates) == 0 || !dashboardAbsenceCoversDate(dates, *a.Content, todayY, todayM, todayD) {
continue
}
name := ""
if user, uErr := s.ipc.Database.User.GetUserByIDDB(ctx, *a.InitiatorID); uErr == nil && user != nil && user.FullName != nil {
name = *user.FullName
}
var description string
switch meta.Extra.AbsenceType {
case "timeoff":
if meta.Extra.TimeType == "partial" {
if mm := dashboardAbsenceTimeRe.FindStringSubmatch(*a.Content); mm != nil {
description = "отгул с " + mm[1] + ":" + mm[2] + " до " + mm[3] + ":" + mm[4]
} else {
description = "отгул весь день"
}
} else {
description = "отгул весь день"
}
case "vacation":
description = "отпуск до " + maxDashboardAbsenceDate(dates).Format("02.01.2006")
case "sickleave":
description = "больничный до " + maxDashboardAbsenceDate(dates).Format("02.01.2006")
default:
description = "отсутствует"
}
seenUsers[*a.InitiatorID] = true
result = append(result, map[string]interface{}{
"name": name,
"description": description,
})
}
return result
}
func parseDashboardAbsenceDates(content string) []time.Time {
matches := dashboardAbsenceDateRe.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
}
func dashboardAbsenceCoversDate(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
}
func maxDashboardAbsenceDate(dates []time.Time) time.Time {
max := dates[0]
for _, d := range dates[1:] {
if d.After(max) {
max = d
}
}
return max
}
func boolPtr(b bool) *bool { return &b }
func strPtr(s string) *string { return &s }

View File

@ -4,6 +4,7 @@ import (
"bitrix_balancer_api/core/typescore"
"bitrix_balancer_api/core/utilscore"
"bitrix_balancer_api/telegram_service/keyboard"
"bitrix_balancer_api/telegram_service/state"
"context"
"fmt"
"regexp"
@ -17,15 +18,27 @@ import (
// ============================================================
// Делегирование обязанностей на время отсутствия (отгул/отпуск/
// больничный). Включается флагом ApprovalTopic.AllowDelegationSelection
// (тот же паттерн, что AllowObserverSelection) — см. patch к
// ApprovalTopic и к continueFlowAfterInput в конце ответа.
// (тот же паттерн, что AllowObserverSelection) — см. DELEGATION_PATCHES.txt.
//
// 🩹 Жизненный цикл делегирования (важное отличие от первой версии):
// запись ApprovalDelegation создаётся СРАЗУ при подаче заявки на
// отсутствие, но НЕАКТИВНОЙ (IsActive=false) — см. createPendingDelegation,
// вызывается из submitApproval. Активируется она ТОЛЬКО когда сама заявка
// будет полностью согласована — activatePendingDelegation, вызывается из
// processNextStepOrComplete в момент финального approved. Если заявку
// впоследствии отзовут — deactivatePendingDelegation (вызывается из
// performActualRevoke) выключает делегирование обратно, независимо от
// того, успело оно активироваться или нет.
//
// Здесь, в диалоге с ботом, происходит только ВЫБОР делегата — реальная
// запись в БД появляется позже, вместе с самой заявкой.
// ============================================================
// showDelegationChoice — экран "делегировать все обязанности?" (Да/Нет).
func (h *Handler) showDelegationChoice(bot *tgbotapi.BotAPI, chatID int64, telegramID int64) {
text := "🔁 <b>Делегировать все обязанности по согласованию на другого человека на время вашего отсутствия?</b>\n\n" +
"<i>Если согласитесь — все заявки, которые сейчас или ещё придут к вам на согласование, " +
"будут автоматически передаваться выбранному человеку до конца периода отсутствия.</i>"
"<i>Делегирование начнёт действовать только после того, как эта заявка будет согласована, " +
"и автоматически отменится, если заявку впоследствии отзовут.</i>"
msg := tgbotapi.NewMessage(chatID, text)
msg.ParseMode = "HTML"
@ -107,6 +120,13 @@ func (h *Handler) HandleDelegateSelectionPageCallback(bot *tgbotapi.BotAPI, cq *
}
// HandleDelegateSelectionCallback — пользователь выбрал конкретного делегата.
//
// 🩹 ВАЖНО: здесь запись в ApprovalDelegation больше НЕ создаётся. Мы
// только запоминаем выбор в flowState.SelectedDelegateID — реальная
// (неактивная) запись появится в submitApproval/createPendingDelegation,
// когда заявка будет фактически отправлена (это происходит сразу вслед
// за этим шагом в том же диалоге, так что 30-минутный TTL состояния в
// Redis не успевает истечь).
func (h *Handler) HandleDelegateSelectionCallback(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, delegateID uint64) {
ctx := context.Background()
chatID := cq.Message.Chat.ID
@ -120,87 +140,33 @@ func (h *Handler) HandleDelegateSelectionCallback(bot *tgbotapi.BotAPI, cq *tgbo
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: &notifiedFalse,
Notified2h: &notifiedFalse,
}
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(
"🔁 <b>Обязанности по согласованию делегированы</b>\n\n"+
"👤 <b>Кому:</b> %s\n"+
"📅 <b>До:</b> %s",
delegateName, validUntil.Format("02.01.2006"),
))
delegateName := "—"
if delegate.FullName != nil {
delegateName = *delegate.FullName
}
// Дата — только для информации в этом сообщении, реальное значение
// пересчитывается и сохраняется в createPendingDelegation.
validUntil, _ := delegationValidUntil(flowState.Collected)
sendText(bot, chatID, fmt.Sprintf(
"🔁 <b>Обязанности будут делегированы: %s</b>\n"+
"📅 <b>Ориентировочно до:</b> %s\n\n"+
"<i>Начнёт действовать после согласования этой заявки и отменится, если её впоследствии отзовут.</i>",
delegateName, validUntil.Format("02.01.2006"),
))
h.continueFlowAfterInput(bot, ctx, chatID, telegramID, flowState)
}
@ -231,6 +197,139 @@ func (h *Handler) getAvailableDelegateCandidates(ctx context.Context, telegramID
return result, nil
}
// ============================================================
// Создание / активация / деактивация делегирования, привязанного к
// конкретной заявке (approval_id — см. DELEGATION_PATCHES.txt).
// ============================================================
// createPendingDelegation вызывается из submitApproval сразу после
// создания заявки. Создаёт по одной НЕАКТИВНОЙ записи ApprovalDelegation
// на каждую активную категорию согласований (поиск делегата в
// processNextStepOrComplete/handleDecision матчит строго по конкретному
// TopicID либо конкретному CategoryID — запись "на всё сразу" с обоими
// NULL никогда бы не нашлась).
func (h *Handler) createPendingDelegation(ctx context.Context, initiator *typescore.User, flowState *state.ApprovalFlowState, approval *typescore.Approval) {
if flowState.SelectedDelegateID == 0 {
return
}
if initiator == nil || initiator.ID == nil || approval == nil || approval.ID == nil {
return
}
delegate, err := h.ipc.Database.User.GetUserByIDDB(ctx, flowState.SelectedDelegateID)
if err != nil || delegate == nil || delegate.ID == nil {
logrus.Errorf("createPendingDelegation: delegate not found id=%d err=%v", flowState.SelectedDelegateID, err)
return
}
validUntil, datesFound := delegationValidUntil(flowState.Collected)
if !datesFound {
logrus.Warnf("createPendingDelegation: не удалось определить дату окончания отсутствия approvalID=%d — используется запасной срок 30 дней", *approval.ID)
}
categories, _, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopicCategory{IsActive: utilscore.PointerToBool(true)},
})
if err != nil {
logrus.Errorf("createPendingDelegation: GetApprovalTopicCategoriesListDB err=%v", err)
return
}
inactive := false
notifiedFalse := false
created := 0
for _, cat := range categories {
if cat.ID == nil {
continue
}
catID := *cat.ID
delegation := &typescore.ApprovalDelegation{
DelegatorID: initiator.ID,
DelegateID: delegate.ID,
CategoryID: &catID,
ApprovalID: approval.ID,
ValidUntil: &validUntil,
IsActive: &inactive, // включится только после одобрения заявки
NotifiedDay: &notifiedFalse,
Notified2h: &notifiedFalse,
}
if _, _, err := h.ipc.Database.ApprovalDelegation.CreateApprovalDelegationDB(ctx, nil, delegation); err != nil {
logrus.Errorf("createPendingDelegation: CreateApprovalDelegationDB categoryID=%d approvalID=%d err=%v", catID, *approval.ID, err)
continue
}
created++
}
logrus.Infof("createPendingDelegation: создано неактивных делегирований=%d approvalID=%d delegatorID=%d delegateID=%d",
created, *approval.ID, *initiator.ID, *delegate.ID)
}
// activatePendingDelegation включает делегирование, привязанное к этой
// заявке (см. createPendingDelegation), в момент её полного одобрения.
// Вызывается из processNextStepOrComplete строго в ветке финального
// approved (не при передаче на следующий шаг).
func (h *Handler) activatePendingDelegation(ctx context.Context, approval *typescore.Approval) {
if approval == nil || approval.ID == nil {
return
}
delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalDelegation{ApprovalID: approval.ID},
})
if err != nil {
logrus.Errorf("activatePendingDelegation: GetApprovalDelegationsListDB approvalID=%d err=%v", *approval.ID, err)
return
}
if len(delegations) == 0 {
return // делегирование при подаче этой заявки не настраивалось
}
active := true
for _, d := range delegations {
d.IsActive = &active
if _, _, err := h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, d); err != nil {
logrus.Errorf("activatePendingDelegation: UpdateApprovalDelegationDB id=%v err=%v", d.ID, err)
}
}
logrus.Infof("activatePendingDelegation: активировано делегирований=%d approvalID=%d", len(delegations), *approval.ID)
}
// deactivatePendingDelegation отменяет делегирование, привязанное к этой
// заявке, при её отзыве — независимо от того, успело оно активироваться
// (заявка уже была одобрена) или ещё оставалось неактивным (заявку
// отозвали прямо во время согласования). Вызывается из performActualRevoke.
func (h *Handler) deactivatePendingDelegation(ctx context.Context, approval *typescore.Approval) {
if approval == nil || approval.ID == nil {
return
}
delegations, _, err := h.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalDelegation{ApprovalID: approval.ID},
})
if err != nil {
logrus.Errorf("deactivatePendingDelegation: GetApprovalDelegationsListDB approvalID=%d err=%v", *approval.ID, err)
return
}
if len(delegations) == 0 {
return
}
inactive := false
changed := 0
for _, d := range delegations {
if d.IsActive != nil && !*d.IsActive {
continue // уже неактивно
}
d.IsActive = &inactive
if _, _, err := h.ipc.Database.ApprovalDelegation.UpdateApprovalDelegationDB(ctx, nil, d); err != nil {
logrus.Errorf("deactivatePendingDelegation: UpdateApprovalDelegationDB id=%v err=%v", d.ID, err)
continue
}
changed++
}
logrus.Infof("deactivatePendingDelegation: отменено делегирований=%d approvalID=%d", changed, *approval.ID)
}
// ============================================================
// Разбор дат из flowState.Collected — тот же терпимый к опечаткам
// подход, что в scheduler/daily_reminder.go (getAbsentEmployeesToday),

View File

@ -409,6 +409,8 @@ func (h *Handler) performActualRevoke(
return
}
h.deactivatePendingDelegation(ctx, approval)
h.handleRevokeCancellationTask(bot, ctx, approval)
revokerName := "—"

View File

@ -205,6 +205,8 @@ func (h *Handler) processNextStepOrComplete(bot *tgbotapi.BotAPI, ctx context.Co
approval.Status = &approvedStatus
h.ipc.Database.Approval.UpdateApprovalDB(ctx, nil, approval) //nolint:errcheck
h.activatePendingDelegation(ctx, approval)
lastStepIsDelegate := currentStep.ApproverID != nil && *currentStep.ApproverID != actualExecutorID
if currentStep.ApproverID != nil {

View File

@ -129,6 +129,8 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
}
created.Files = files
h.createPendingDelegation(ctx, initiator, flowState, created)
var approvers []*typescore.User
// Если выбран первый согласующий по роли — он будет шагом 0
@ -173,7 +175,6 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
return nil, fmt.Errorf("⚠️ Для вас в данной теме не настроены согласующие. Пожалуйста, обратитесь к руководителю с просьбой о настройке прав в системе согласований")
}
// === НОВЫЙ БЛОК: ГРУППИРОВКА ПО ПРИОРИТЕТУ ===
priorityGroups := make(map[int][]*typescore.User)
if approvalTopic.ApprovalMode != nil {

View File

@ -25,10 +25,14 @@ func NewDailyReminder(ipc *types.InternalProviderControl) *DailyReminder {
return &DailyReminder{ipc: ipc}
}
// Start запускает планировщик ежедневных напоминаний
func (dr *DailyReminder) Start() {
logrus.Infof("DailyReminder: Start() вызван — планировщик запускается")
go dr.scheduleLoop()
}
// scheduleLoop бесконечный цикл, который ждет 9:00 МСК каждый день
func (dr *DailyReminder) scheduleLoop() {
mskLocation, err := time.LoadLocation("Europe/Moscow")
if err != nil {
@ -39,8 +43,10 @@ func (dr *DailyReminder) scheduleLoop() {
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)
}
@ -51,23 +57,31 @@ func (dr *DailyReminder) scheduleLoop() {
logrus.Infof("DailyReminder: следующее напоминание запланировано на %s (через %v)",
next.Format("02.01.2006 15:04 MSK"), duration.Round(time.Second))
// Ждем до следующего 9:00
time.Sleep(duration)
// Отправляем напоминания
dr.sendReminders()
}
}
// skipWeekends переносит дату на ближайший будний день,
// если она выпадает на субботу или воскресенье
func (dr *DailyReminder) skipWeekends(t time.Time) time.Time {
switch t.Weekday() {
case time.Saturday:
return t.AddDate(0, 0, 2)
case time.Sunday:
// Воскресенье → понедельник (+1 день)
return t.AddDate(0, 0, 1)
}
return t
}
// sendReminders отправляет напоминания всем пользователям
func (dr *DailyReminder) sendReminders() {
logrus.Infof("DailyReminder: sendReminders() запущен")
ctx := context.Background()
bot := dr.ipc.TGBotClient.Bot()
@ -76,33 +90,30 @@ func (dr *DailyReminder) sendReminders() {
logrus.Errorf("DailyReminder: не удалось загрузить часовой пояс МСК: %v", err)
mskLocation = time.FixedZone("MSK", 3*3600)
}
logrus.Infof("DailyReminder: сегодняшняя дата (МСК) = %s", time.Now().In(mskLocation).Format("02.01.2006"))
// Получаем всех активных пользователей
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))
absentToday := dr.getAbsentEmployeesToday(ctx, mskLocation)
logrus.Infof("DailyReminder: начинаем отправку напоминаний для %d пользователей (отсутствующих сегодня: %d)",
len(users), len(absentToday))
// TODO: удалить после тестов
const testOnlyTelegramID int64 = 493325176
sentCount := 0
for _, user := range users {
if user.TelegramID == nil || user.ID == nil {
logrus.Debugf("DailyReminder: пропуск пользователя без TelegramID/ID (user=%+v)", user)
continue
}
// 🧪 ВРЕМЕННО ДЛЯ ТЕСТА
if *user.TelegramID != testOnlyTelegramID {
continue
}
if dr.sendReminderToUser(bot, ctx, user, absentToday) {
sent := dr.sendReminderToUser(bot, ctx, user, absentToday)
if sent {
sentCount++
}
@ -112,6 +123,8 @@ func (dr *DailyReminder) sendReminders() {
logrus.Infof("DailyReminder: отправлено напоминаний: %d из %d", sentCount, len(users))
}
// sendReminderToUser отправляет напоминание конкретному пользователю
// Возвращает true, если сообщение было отправлено
func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Context, user *typescore.User, absentToday []AbsentEmployeeInfo) bool {
userID := *user.ID
telegramID := *user.TelegramID
@ -148,6 +161,7 @@ func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Co
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,
@ -162,11 +176,14 @@ func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Co
hasPersonalItems := revisionsCount > 0 || tasksCount > 0 || approvalsCount > 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
}
// Формируем текст сообщения
text := "☀️ <b>Доброе утро! Ежедневная сводка</b>\n\n"
if revisionsCount > 0 {
@ -210,9 +227,13 @@ func (dr *DailyReminder) sendReminderToUser(bot *tgbotapi.BotAPI, ctx context.Co
return false
}
logrus.Infof("DailyReminder: сообщение успешно отправлено telegramID=%d (длина текста=%d символов)", telegramID, len(text))
return true
}
// countPendingApprovals считает количество заявок со статусом "pending"
// из списка шагов и дополнительных согласующих
func (dr *DailyReminder) countPendingApprovals(
ctx context.Context,
steps []*typescore.ApprovalStep,
@ -236,6 +257,7 @@ func (dr *DailyReminder) countPendingApprovals(
return 0
}
// Получаем все заявки одним запросом и фильтруем по статусу pending
count := 0
for approvalID := range approvalIDs {
id := approvalID
@ -281,37 +303,57 @@ func (dr *DailyReminder) getAbsentEmployeesToday(ctx context.Context, mskLocatio
logrus.Errorf("DailyReminder: getAbsentEmployeesToday: GetApprovalsListDB err=%v", err)
return nil
}
logrus.Infof("DailyReminder: getAbsentEmployeesToday: заявок со статусом approved найдено: %d (сегодня %04d-%02d-%02d)",
len(approvals), todayY, todayM, todayD)
seenUsers := make(map[uint64]bool)
var result []AbsentEmployeeInfo
for _, approval := range approvals {
approvalID := derefApprovalID(approval)
if approval.Metadata == nil || *approval.Metadata == "" || approval.Content == nil {
logrus.Infof("DailyReminder: заявка #%d пропущена — нет Metadata или Content", approvalID)
continue
}
var meta absenceMetadata
if err := json.Unmarshal([]byte(*approval.Metadata), &meta); err != nil {
logrus.Warnf("DailyReminder: заявка #%d — не удалось распарсить Metadata как JSON: %v (metadata=%q)",
approvalID, err, *approval.Metadata)
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 || seenUsers[*approval.InitiatorID] {
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
}
dates := parseAbsenceDates(*approval.Content)
if len(dates) == 0 {
logrus.Warnf("DailyReminder: не удалось разобрать даты в content заявки #%d: %q",
derefApprovalID(approval), *approval.Content)
logrus.Warnf("DailyReminder: заявка #%d — не удалось разобрать даты в content: %q",
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)
continue
}
logrus.Infof("DailyReminder: заявка #%d — покрывает сегодня, добавляем в сводку", approvalID)
name := "—"
if approval.Initiator != nil && approval.Initiator.FullName != nil {
@ -374,6 +416,8 @@ func (dr *DailyReminder) getAbsentEmployeesToday(ctx context.Context, mskLocatio
})
}
logrus.Infof("DailyReminder: getAbsentEmployeesToday: итоговый список отсутствующих сегодня (%d): %+v", len(result), result)
return result
}
@ -383,6 +427,7 @@ func derefApprovalID(a *typescore.Approval) uint64 {
}
return *a.ID
}
func parseAbsenceDates(content string) []time.Time {
matches := absenceDateRe.FindAllStringSubmatch(content, -1)
var dates []time.Time