From 3d14bc8797ac3672bbb600ceb98dffe97b508aa8 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Tue, 28 Jul 2026 00:31:27 +0300 Subject: [PATCH] Updated dashboard stats route --- .../handlers/dashboard/handlers.go | 493 +++++++++++++----- 1 file changed, 368 insertions(+), 125 deletions(-) diff --git a/service/rest_admin_service/handlers/dashboard/handlers.go b/service/rest_admin_service/handlers/dashboard/handlers.go index 4cc2cbe..63cd56b 100644 --- a/service/rest_admin_service/handlers/dashboard/handlers.go +++ b/service/rest_admin_service/handlers/dashboard/handlers.go @@ -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 }