Updated dashboard stats route #86

Merged
romanskijdev merged 1 commits from fix-permissions into main 2026-07-28 09:47:29 +03:00
1 changed files with 239 additions and 13 deletions

View File

@ -5,6 +5,7 @@ import (
"bitrix_balancer_api/core/utilscore"
"context"
"encoding/json"
"fmt"
"net/http"
"regexp"
"strconv"
@ -75,6 +76,11 @@ func (s *DashboardReg) GetDashboardStatsHandler(w http.ResponseWriter, r *http.R
// === 8. 🆕 Кто отсутствует сегодня (отгул/отпуск/больничный) ===
absentToday := s.getAbsentToday(ctx)
// === 9. 🆕 Проблемы конфигурации: темы без назначенного порядка
// согласования для конкретного пользователя + пользователи вообще
// без иерархии в своём отделе ===
topicGaps, usersWithoutHierarchy := s.getInitiatorConfigWarnings(ctx)
return map[string]interface{}{
"users": map[string]int{
"total": totalUsers,
@ -91,19 +97,21 @@ 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,
"categoryBreakdown": categoryBreakdown,
"bottleneckApprovers": bottleneckApprovers,
"oldPendingCount": oldPendingCount,
"oldPendingDays": 7,
"taskStatusData": taskStatusData,
"taskDailyData": taskDailyData,
"absentToday": absentToday,
"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,
"topicGaps": topicGaps,
"usersWithoutHierarchy": usersWithoutHierarchy,
}, nil
}
@ -678,5 +686,223 @@ func maxDashboardAbsenceDate(dates []time.Time) time.Time {
return max
}
// ============================================================
// 🆕 Проблемы конфигурации инициаторов.
//
// Воспроизводит ТУ ЖЕ логику резолва согласующих, что и сам бот при
// реальной отправке заявки (submitApproval → UserHierarchy по
// SubordinateID+DepartmentID, с приоритетом TopicID → TopicCategoryID →
// глобальное правило) — но заранее, для ВСЕХ пользователей и ВСЕХ тем,
// на которые у них есть право "create", чтобы найти дыры ДО того, как
// сотрудник наткнётся на них в боте ("⚠️ Для вас в данной теме не
// настроены согласующие").
//
// Возвращает два среза:
// 1. topicGaps — точечные пробелы: у пользователя ЕСТЬ право создавать
// заявку по теме, но НИ ОДНО правило иерархии её не покрывает.
// 2. usersWithoutHierarchy — более базовый случай: у пользователя нет
// вообще ни одной строки UserHierarchy для его отдела (полностью
// не настроен, даже глобального правила нет).
//
// ⚠️ Предположения, которые стоит проверить при первом запуске:
// - Permission.GetUserPermissionsDB(ctx, userID, "create") доступен
// из rest_admin_service так же, как используется ботом
// (telegram_service/handlers/approval, getAllowedTopicCodes) —
// сама структура Permission (поля TopicID/TopicCategoryID) взята
// оттуда же, полностью структуру Permission я не видел.
// - Пользователи без DepartmentID пропускаются целиком (это отдельная,
// более базовая проблема — некому резолвить иерархию в принципе,
// не про конкретные темы).
// ============================================================
func (s *DashboardReg) getInitiatorConfigWarnings(ctx context.Context) ([]map[string]interface{}, []map[string]interface{}) {
users, _, err := s.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.User{IsBlocked: boolPtr(false), IsFired: boolPtr(false)},
Limit: utilscore.PointerToUint64(10000),
})
if err != nil {
return []map[string]interface{}{}, []map[string]interface{}{}
}
topics, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, typescore.ListDbOptions{
Filtering: &typescore.ApprovalTopic{IsActive: boolPtr(true)},
Limit: utilscore.PointerToUint64(10000),
})
if err != nil {
return []map[string]interface{}{}, []map[string]interface{}{}
}
categories, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(10000),
})
categoryNames := make(map[uint64]string, len(categories))
if err == nil {
for _, c := range categories {
if c.ID != nil && c.Name != nil {
categoryNames[*c.ID] = *c.Name
}
}
}
departments, _, err := s.ipc.Database.Department.GetDepartmentsListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(10000),
})
departmentNames := make(map[uint64]string, len(departments))
if err == nil {
for _, d := range departments {
if d.ID != nil && d.Name != nil {
departmentNames[*d.ID] = *d.Name
}
}
}
topicByID := make(map[uint64]*typescore.ApprovalTopic, len(topics))
topicsByCategory := make(map[uint64][]*typescore.ApprovalTopic)
for _, t := range topics {
if t.ID == nil {
continue
}
topicByID[*t.ID] = t
if t.CategoryID != nil {
topicsByCategory[*t.CategoryID] = append(topicsByCategory[*t.CategoryID], t)
}
}
hierarchies, _, err := s.ipc.Database.UserHierarchy.GetUserHierarchyListDB(ctx, typescore.ListDbOptions{
Limit: utilscore.PointerToUint64(10000),
})
if err != nil {
return []map[string]interface{}{}, []map[string]interface{}{}
}
type coverage struct {
topics map[uint64]bool
categories map[uint64]bool
global bool
}
coverageKey := func(userID, deptID uint64) string {
return fmt.Sprintf("%d:%d", userID, deptID)
}
coverageByUserDept := make(map[string]*coverage)
for _, h := range hierarchies {
if h.SubordinateID == nil || h.DepartmentID == nil {
continue
}
k := coverageKey(*h.SubordinateID, *h.DepartmentID)
cov, ok := coverageByUserDept[k]
if !ok {
cov = &coverage{topics: map[uint64]bool{}, categories: map[uint64]bool{}}
coverageByUserDept[k] = cov
}
switch {
case h.TopicID != nil:
cov.topics[*h.TopicID] = true
case h.TopicCategoryID != nil:
cov.categories[*h.TopicCategoryID] = true
default:
cov.global = true
}
}
isCovered := func(userID, deptID, topicID uint64, categoryID *uint64) bool {
cov, ok := coverageByUserDept[coverageKey(userID, deptID)]
if !ok {
return false
}
if cov.global {
return true
}
if cov.topics[topicID] {
return true
}
if categoryID != nil && cov.categories[*categoryID] {
return true
}
return false
}
var topicGaps []map[string]interface{}
var usersWithoutHierarchy []map[string]interface{}
for _, user := range users {
if user.ID == nil || user.DepartmentID == nil {
continue
}
perms, err := s.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, "create")
if err != nil || len(perms) == 0 {
continue // нет права создавать ничего — не наша забота здесь
}
userName := ""
if user.FullName != nil {
userName = *user.FullName
}
deptName := departmentNames[*user.DepartmentID]
// --- Проверка "вообще нет иерархии для этого отдела" ---
if _, hasAny := coverageByUserDept[coverageKey(*user.ID, *user.DepartmentID)]; !hasAny {
usersWithoutHierarchy = append(usersWithoutHierarchy, map[string]interface{}{
"user_id": *user.ID,
"full_name": userName,
"department_name": deptName,
})
continue // если вообще ничего нет — детальный разбор по темам избыточен
}
// --- Точечные пробелы по темам ---
allowedTopicIDs := make(map[uint64]bool)
for _, p := range perms {
if p.TopicID != nil {
allowedTopicIDs[*p.TopicID] = true
}
if p.TopicCategoryID != nil {
for _, t := range topicsByCategory[*p.TopicCategoryID] {
if t.ID != nil {
allowedTopicIDs[*t.ID] = true
}
}
}
}
for topicID := range allowedTopicIDs {
topic := topicByID[topicID]
if topic == nil {
continue
}
if isCovered(*user.ID, *user.DepartmentID, topicID, topic.CategoryID) {
continue
}
topicName := ""
if topic.Name != nil {
topicName = *topic.Name
}
categoryName := ""
if topic.CategoryID != nil {
categoryName = categoryNames[*topic.CategoryID]
}
topicGaps = append(topicGaps, map[string]interface{}{
"user_id": *user.ID,
"full_name": userName,
"department_name": deptName,
"topic_id": topicID,
"topic_name": topicName,
"category_name": categoryName,
})
}
}
if topicGaps == nil {
topicGaps = []map[string]interface{}{}
}
if usersWithoutHierarchy == nil {
usersWithoutHierarchy = []map[string]interface{}{}
}
return topicGaps, usersWithoutHierarchy
}
func boolPtr(b bool) *bool { return &b }
func strPtr(s string) *string { return &s }