fix-permissions #33

Merged
romanskijdev merged 3 commits from fix-permissions into main 2026-06-25 14:23:38 +03:00
4 changed files with 127 additions and 51 deletions

View File

@ -236,6 +236,7 @@ func (u *UserHierarchyDB) GetApproversDB(ctx context.Context, subordinateID, dep
}
return result, nil
}
func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts typescore.ListDbOptions) ([]*typescore.UserHierarchy, uint64, error) {
options, filter, err := dbutils.GetOptionsDB[typescore.UserHierarchy](opts)
if err != nil {
@ -243,7 +244,6 @@ func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts
}
query := squirrel.Select(
// Основные поля таблицы user_hierarchy (в порядке сканирования)
"uh.id",
"uh.subordinate_id",
"uh.approver_id",
@ -253,25 +253,13 @@ func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts
"uh.priority",
"uh.created_at",
"uh.updated_at",
// Поля Subordinate
"sub.id",
"sub.full_name",
"sub.username",
// Поля Approver
"app.id",
"app.full_name",
"app.username",
// Поля Department
"dep.id",
"dep.name",
// Поля Category
"cat.id",
"cat.name",
// Поля Topic
"top.id",
"top.name",
// Общее количество записей для пагинации
"COUNT(*) OVER() AS total_count").
"sub.id", "sub.full_name", "sub.username",
"app.id", "app.full_name", "app.username",
"dep.id", "dep.name",
"cat.id", "cat.name",
"top.id", "top.name",
"COUNT(*) OVER() AS total_count",
).
From("user_hierarchy uh").
LeftJoin("users sub ON uh.subordinate_id = sub.id").
LeftJoin("users app ON uh.approver_id = app.id").
@ -280,7 +268,24 @@ func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts
LeftJoin("approval_topics top ON uh.topic_id = top.id")
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
query = dbutils.ApplyFilters(query, filter, options.LikeFields, "uh")
// Явная обработка фильтров
if filter.SubordinateID != nil {
query = query.Where(squirrel.Eq{"uh.subordinate_id": *filter.SubordinateID})
}
if filter.ApproverID != nil {
query = query.Where(squirrel.Eq{"uh.approver_id": *filter.ApproverID})
}
if filter.DepartmentID != nil {
query = query.Where(squirrel.Eq{"uh.department_id": *filter.DepartmentID})
}
if filter.TopicCategoryID != nil {
query = query.Where(squirrel.Eq{"uh.topic_category_id": *filter.TopicCategoryID})
}
if filter.TopicID != nil {
query = query.Where(squirrel.Eq{"uh.topic_id": *filter.TopicID})
}
query = query.OrderBy("uh.created_at DESC")
sql, args, err := query.PlaceholderFormat(squirrel.Dollar).ToSql()
@ -306,34 +311,13 @@ func (u *UserHierarchyDB) GetHierarchiesWithRelations(ctx context.Context, opts
h.Topic = &typescore.ApprovalTopic{}
err := rows.Scan(
// Основные поля (9 полей)
&h.ID,
&h.SubordinateID,
&h.ApproverID,
&h.DepartmentID,
&h.TopicCategoryID,
&h.TopicID,
&h.Priority,
&h.CreatedAt,
&h.UpdatedAt,
// Subordinate (3 поля)
&h.Subordinate.ID,
&h.Subordinate.FullName,
&h.Subordinate.Username,
// Approver (3 поля)
&h.Approver.ID,
&h.Approver.FullName,
&h.Approver.Username,
// Department (2 поля)
&h.Department.ID,
&h.Department.Name,
// TopicCategory (2 поля)
&h.TopicCategory.ID,
&h.TopicCategory.Name,
// Topic (2 поля)
&h.Topic.ID,
&h.Topic.Name,
// Общее количество
&h.ID, &h.SubordinateID, &h.ApproverID, &h.DepartmentID,
&h.TopicCategoryID, &h.TopicID, &h.Priority, &h.CreatedAt, &h.UpdatedAt,
&h.Subordinate.ID, &h.Subordinate.FullName, &h.Subordinate.Username,
&h.Approver.ID, &h.Approver.FullName, &h.Approver.Username,
&h.Department.ID, &h.Department.Name,
&h.TopicCategory.ID, &h.TopicCategory.Name,
&h.Topic.ID, &h.Topic.Name,
&totalCount,
)
if err != nil {

View File

@ -0,0 +1,90 @@
package reportcore
import (
"github.com/xuri/excelize/v2"
"strings"
"unicode/utf8"
)
// autoFitColumns автоматически подгоняет ширину колонок под содержимое.
// Учитывает длину заголовка и всех ячеек, добавляет небольшой отступ.
func autoFitColumns(f *excelize.File, sheetName string, headers []string, dataRowCount int) {
for colIdx, header := range headers {
colLetter, _ := excelize.ColumnNumberToName(colIdx + 1)
// Начинаем с длины заголовка
maxWidth := stringWidth(header)
// Проверяем все строки данных в этой колонке
for row := 2; row <= dataRowCount+1; row++ {
cellName, _ := excelize.CoordinatesToCellName(colIdx+1, row)
cellValue, _ := f.GetCellValue(sheetName, cellName)
w := stringWidth(cellValue)
if w > maxWidth {
maxWidth = w
}
}
// Добавляем небольшой отступ для красоты
finalWidth := float64(maxWidth) + 2
// Ограничиваем минимальную и максимальную ширину
if finalWidth < 10 {
finalWidth = 10
}
if finalWidth > 60 {
finalWidth = 60
}
_ = f.SetColWidth(sheetName, colLetter, colLetter, finalWidth)
}
}
// stringWidth вычисляет "визуальную" ширину строки.
// Кириллица и другие широкие символы занимают больше места, чем латиница.
func stringWidth(s string) int {
width := 0
for _, r := range s {
if isWideRune(r) {
width += 2 // широкие символы (кириллица, CJK)
} else {
width += 1
}
}
// Учитываем переносы строк — берём самую длинную строку
lines := strings.Split(s, "\n")
maxLine := 0
for _, line := range lines {
lw := 0
for _, r := range line {
if isWideRune(r) {
lw += 2
} else {
lw += 1
}
}
if lw > maxLine {
maxLine = lw
}
}
if maxLine > width {
width = maxLine
}
return width
}
// isWideRune определяет, является ли символ "широким"
func isWideRune(r rune) bool {
// Кириллица
if r >= 0x0400 && r <= 0x04FF {
return true
}
// CJK (китайские, японские, корейские)
if r >= 0x4E00 && r <= 0x9FFF {
return true
}
return false
}
// _ используется, чтобы убрать предупреждение о неиспользуемом импорте
var _ = utf8.RuneCountInString

View File

@ -421,6 +421,8 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro
logrus.Warnf("reportcore: set panes: %v", err)
}
autoFitColumns(f, sheet, headers, len(approvals))
var buf bytes.Buffer
if err := f.Write(&buf); err != nil {
return nil, fmt.Errorf("write excel: %w", err)

View File

@ -90,8 +90,8 @@ func BuildObserverActions(approvalID uint64, topicCode string, status string, fi
if status != "approved" {
kb.Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)))
}
kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", fmt.Sprintf("obs_back:%s", topicCode)))
// К списку (наблюдатель)
//kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleBack, "К списку", fmt.Sprintf("obs_back:%s", topicCode)))
return kb.Build()
}