Fix deply script #3
|
|
@ -114,8 +114,8 @@ type SecretsConfig struct {
|
|||
AuthJWT AuthJWTConfig `yaml:"auth_jwt"`
|
||||
ApiPublicUser string `yaml:"access_code_user"`
|
||||
ApiPrivateUser string
|
||||
ApiPublicAdmin string `yaml:"access_code_admin"`
|
||||
ApiPrivateAdmin string
|
||||
ApiPublicAdmin string `yaml:"api_public_admin"`
|
||||
ApiPrivateAdmin string `yaml:"api_private_admin"`
|
||||
ApiPublicBase string `yaml:"api_public_base"`
|
||||
ApiPrivateBase string `yaml:"api_private_base"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -80,6 +80,7 @@ func copyConfigFields(options *ConfigLoadOptions, source, target *Config) {
|
|||
}
|
||||
if options.Secrets.AdminAccessCode {
|
||||
target.Secrets.ApiPublicAdmin = source.Secrets.ApiPublicAdmin
|
||||
target.Secrets.ApiPrivateAdmin = source.Secrets.ApiPrivateAdmin
|
||||
}
|
||||
if options.Secrets.UserAccessCode {
|
||||
target.Secrets.ApiPublicUser = source.Secrets.ApiPublicUser
|
||||
|
|
|
|||
|
|
@ -192,13 +192,13 @@ func (u *AdminDB) UpdateAdminDB(tx pgx.Tx, paramsUpdate *typescore.Admin, return
|
|||
}
|
||||
|
||||
func (u *AdminDB) DeleteAdminDB(params *typescore.Admin) error {
|
||||
if params != nil && params.Login != nil {
|
||||
if params != nil && params.ID != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), variables.ContextTimeoutBase)
|
||||
defer cancel()
|
||||
|
||||
query, args, err := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Delete(dbcoretablenames.TableNameAdmin.ToString()).
|
||||
Where(squirrel.Eq{"email": *params.Login}).
|
||||
Where(squirrel.Eq{"id": *params.ID}).
|
||||
ToSql()
|
||||
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"bitrix_balancer_api/core/typescore"
|
||||
dbutils "bitrix_balancer_api/core/utilscore/db"
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
|
@ -37,6 +38,69 @@ type ApprovalDBI interface {
|
|||
GetPendingApprovalsByApproverAndCategoryDB(ctx context.Context, approverID uint64, categoryCode string) ([]*typescore.Approval, error)
|
||||
GetApprovalsByCategoryDB(ctx context.Context, categoryCode string) ([]*typescore.Approval, error)
|
||||
GetClosedApprovalsByInitiatorDB(ctx context.Context, initiatorID uint64) ([]*typescore.Approval, error)
|
||||
SearchApprovalsByContentDB(ctx context.Context, content string, opts ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error)
|
||||
GetOldPendingApprovalsDB(ctx context.Context, since time.Time, limit int) ([]*typescore.Approval, error)
|
||||
CountApprovalsDB(ctx context.Context, filter *typescore.Approval) (int, error)
|
||||
CountApprovalsCreatedOnDB(ctx context.Context, date time.Time) (int, error)
|
||||
CountApprovalsApprovedOnDB(ctx context.Context, date time.Time) (int, error)
|
||||
GetTopTopicsDB(ctx context.Context, limit int) ([]map[string]interface{}, error)
|
||||
}
|
||||
|
||||
// SearchApprovalsByContentDB — поиск заявок по частичному совпадению в тексте
|
||||
func (u *ApprovalDB) SearchApprovalsByContentDB(ctx context.Context, content string, opts ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error) {
|
||||
fields := dbutils.GetStructFieldsDB(&typescore.Approval{}, "approvals")
|
||||
selectFields := append(fields, "COUNT(*) OVER() AS total_count")
|
||||
|
||||
options, filter, err := dbutils.GetOptionsDB[typescore.Approval](opts...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
query := dbutils.BuildSelectQuery("approvals", selectFields)
|
||||
query = dbutils.SetterLimitAndOffsetQuery(query, options.Offset, options.Limit)
|
||||
|
||||
// 🆕 Для collation "C" используем явное приведение
|
||||
// Вариант 1: Через CAST с collation
|
||||
query = query.Where(
|
||||
squirrel.Expr(
|
||||
"approvals.content::text ILIKE ? COLLATE \"ru_RU.UTF-8\"",
|
||||
"%"+content+"%",
|
||||
),
|
||||
)
|
||||
|
||||
// Применяем остальные фильтры
|
||||
query = dbutils.ApplyFilters(query, filter, nil, "approvals")
|
||||
query = query.OrderBy("approvals.created_at DESC")
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
logrus.Infof("🔍 SearchApprovalsByContentDB SQL: %s", sql)
|
||||
logrus.Infof("🔍 SearchApprovalsByContentDB Args: %v", args)
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
logrus.Errorf("❌ SearchApprovalsByContentDB error: %v", err)
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var approvals []*typescore.Approval
|
||||
var totalCount uint64
|
||||
for rows.Next() {
|
||||
approval := &typescore.Approval{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, approval, &totalCount); err != nil {
|
||||
logrus.Warn("SearchApprovalsByContentDB:ScanRowsToStructRows", err)
|
||||
continue
|
||||
}
|
||||
approvals = append(approvals, approval)
|
||||
}
|
||||
|
||||
logrus.Infof("✅ SearchApprovalsByContentDB found: %d approvals, total: %d", len(approvals), totalCount)
|
||||
|
||||
return approvals, totalCount, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalDB) GetApprovalsListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.Approval, uint64, error) {
|
||||
|
|
@ -422,3 +486,139 @@ func buildApprovalIdSubquery(role string, userID *uint64) squirrel.SelectBuilder
|
|||
return q.Where(squirrel.Expr("false"))
|
||||
}
|
||||
}
|
||||
|
||||
// CountApprovalsDB — подсчёт заявок с фильтром
|
||||
func (u *ApprovalDB) CountApprovalsDB(ctx context.Context, filter *typescore.Approval) (int, error) {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("COUNT(*)").
|
||||
From(dbcoretablenames.TableNameApprovals.ToString())
|
||||
|
||||
if filter != nil {
|
||||
if filter.Status != nil {
|
||||
query = query.Where(squirrel.Eq{"status": *filter.Status})
|
||||
}
|
||||
}
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var count int
|
||||
err = u.pool.QueryRow(ctx, sql, args...).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
// CountApprovalsCreatedOnDB — заявки, созданные в определённый день
|
||||
func (u *ApprovalDB) CountApprovalsCreatedOnDB(ctx context.Context, date time.Time) (int, error) {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("COUNT(*)").
|
||||
From(dbcoretablenames.TableNameApprovals.ToString()).
|
||||
Where("DATE(created_at) = ?", date.Format("2006-01-02"))
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var count int
|
||||
err = u.pool.QueryRow(ctx, sql, args...).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
// CountApprovalsApprovedOnDB — заявки, согласованные в определённый день
|
||||
func (u *ApprovalDB) CountApprovalsApprovedOnDB(ctx context.Context, date time.Time) (int, error) {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("COUNT(DISTINCT approval_id)").
|
||||
From(dbcoretablenames.TableNameApprovalSteps.ToString()).
|
||||
Where("DATE(acted_at) = ? AND status = 'approved'", date.Format("2006-01-02"))
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var count int
|
||||
err = u.pool.QueryRow(ctx, sql, args...).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
// GetTopTopicsDB — топ тем по количеству заявок
|
||||
func (u *ApprovalDB) GetTopTopicsDB(ctx context.Context, limit int) ([]map[string]interface{}, error) {
|
||||
query := `
|
||||
SELECT
|
||||
t.id,
|
||||
t.name,
|
||||
c.name as category_name,
|
||||
COUNT(a.id) as total_count,
|
||||
COUNT(CASE WHEN a.status = 'pending' THEN 1 END) as pending_count
|
||||
FROM approval_topics t
|
||||
LEFT JOIN approval_topic_categories c ON t.category_id = c.id
|
||||
LEFT JOIN approvals a ON a.topic_id = t.id
|
||||
GROUP BY t.id, t.name, c.name
|
||||
ORDER BY total_count DESC
|
||||
LIMIT $1
|
||||
`
|
||||
|
||||
rows, err := u.pool.Query(ctx, query, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []map[string]interface{}
|
||||
for rows.Next() {
|
||||
var id uint64
|
||||
var name, categoryName sql.NullString
|
||||
var totalCount, pendingCount int
|
||||
|
||||
if err := rows.Scan(&id, &name, &categoryName, &totalCount, &pendingCount); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
result = append(result, map[string]interface{}{
|
||||
"id": id,
|
||||
"name": name.String,
|
||||
"category_name": categoryName.String,
|
||||
"total_count": totalCount,
|
||||
"pending_count": pendingCount,
|
||||
})
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetOldPendingApprovalsDB — заявки, которые давно висят в pending
|
||||
func (u *ApprovalDB) GetOldPendingApprovalsDB(ctx context.Context, since time.Time, limit int) ([]*typescore.Approval, error) {
|
||||
query := squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar).
|
||||
Select("*").
|
||||
From(dbcoretablenames.TableNameApprovals.ToString()).
|
||||
Where(squirrel.And{
|
||||
squirrel.Eq{"status": "pending"},
|
||||
squirrel.Lt{"created_at": since},
|
||||
}).
|
||||
OrderBy("created_at ASC").
|
||||
Limit(uint64(limit))
|
||||
|
||||
sql, args, err := query.ToSql()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows, err := u.pool.Query(ctx, sql, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []*typescore.Approval
|
||||
for rows.Next() {
|
||||
a := &typescore.Approval{}
|
||||
if err := dbutils.ScanRowsToStructRows(rows, a, nil); err != nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, a)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ type ApprovalFileDBI interface {
|
|||
DeleteApprovalFileDB(ctx context.Context, params *typescore.ApprovalFile) error
|
||||
GetFilesByApprovalIDDB(ctx context.Context, id uint64) ([]*typescore.ApprovalFile, error)
|
||||
GetApprovalFileByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFile, error)
|
||||
GetFilesByTaskIDDB(ctx context.Context, taskID uint64) ([]*typescore.ApprovalFile, error)
|
||||
}
|
||||
|
||||
func (u *ApprovalFileDB) GetApprovalFilesListDB(ctx context.Context, opts ...typescore.ListDbOptions) ([]*typescore.ApprovalFile, uint64, error) {
|
||||
|
|
@ -184,16 +185,16 @@ func (u *ApprovalFileDB) GetFilesByApprovalIDDB(ctx context.Context, id uint64)
|
|||
}
|
||||
|
||||
func (u *ApprovalFileDB) GetApprovalFileByIDDB(ctx context.Context, id uint64) (*typescore.ApprovalFile, error) {
|
||||
approvals, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.Approval{ID: &id},
|
||||
files, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalFile{ID: &id},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(approvals) == 0 {
|
||||
if len(files) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return approvals[0], nil
|
||||
return files[0], nil
|
||||
}
|
||||
|
||||
// queryApprovalFiles — общий сканер строк
|
||||
|
|
@ -215,3 +216,13 @@ func (u *ApprovalFileDB) queryApprovalFiles(ctx context.Context, sql string, arg
|
|||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (u *ApprovalFileDB) GetFilesByTaskIDDB(ctx context.Context, taskID uint64) ([]*typescore.ApprovalFile, error) {
|
||||
files, _, err := u.GetApprovalFilesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalFile{TaskID: &taskID},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,429 @@
|
|||
package reportcore
|
||||
|
||||
import (
|
||||
database "bitrix_balancer_api/core/db"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/xuri/excelize/v2"
|
||||
)
|
||||
|
||||
// BuildExcelApprovalsReport — строит xlsx-файл отчёта по согласованиям и возвращает байты.
|
||||
// Универсальная функция, используется и из админки, и из телеграм-бота.
|
||||
func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, approvals []*typescore.Approval) ([]byte, error) {
|
||||
f := excelize.NewFile()
|
||||
sheet := "Согласования"
|
||||
if err := f.SetSheetName("Sheet1", sheet); err != nil {
|
||||
return nil, fmt.Errorf("set sheet name: %w", err)
|
||||
}
|
||||
|
||||
headers := []string{
|
||||
"ФИО инициатора", // A
|
||||
"Тема согласования", // B
|
||||
"Дата создания", // C
|
||||
"Согласующие", // D
|
||||
"Наблюдатели", // E
|
||||
"Статус", // F
|
||||
"Текст согласования", // G
|
||||
"Отдел сотрудника", // H
|
||||
"Комментарии", // I
|
||||
"Дата согласования", // J
|
||||
"Текст задачи", // K
|
||||
"Исполнитель", // L
|
||||
"Статус задачи", // M
|
||||
"Дата исполнения", // N
|
||||
}
|
||||
|
||||
cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"}
|
||||
|
||||
colWidths := map[string]float64{
|
||||
"A": 25, "B": 40, "C": 18, "D": 30,
|
||||
"E": 30, "F": 16, "G": 40, "H": 25,
|
||||
"I": 30, "J": 18, "K": 40, "L": 25,
|
||||
"M": 18, "N": 18,
|
||||
}
|
||||
|
||||
headerStyle, err := f.NewStyle(&excelize.Style{
|
||||
Font: &excelize.Font{Bold: true, Color: "FFFFFF"},
|
||||
Fill: excelize.Fill{Type: "pattern", Color: []string{"2E75B6"}, Pattern: 1},
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Color: "000000", Style: 1},
|
||||
{Type: "right", Color: "000000", Style: 1},
|
||||
{Type: "top", Color: "000000", Style: 1},
|
||||
{Type: "bottom", Color: "000000", Style: 1},
|
||||
},
|
||||
Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center", WrapText: true},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create header style: %w", err)
|
||||
}
|
||||
|
||||
dataStyle, err := f.NewStyle(&excelize.Style{
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Color: "CCCCCC", Style: 1},
|
||||
{Type: "right", Color: "CCCCCC", Style: 1},
|
||||
{Type: "top", Color: "CCCCCC", Style: 1},
|
||||
{Type: "bottom", Color: "CCCCCC", Style: 1},
|
||||
},
|
||||
Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create data style: %w", err)
|
||||
}
|
||||
|
||||
rejectedStyle, err := f.NewStyle(&excelize.Style{
|
||||
Fill: excelize.Fill{Type: "pattern", Color: []string{"FFE0E0"}, Pattern: 1},
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Color: "CCCCCC", Style: 1},
|
||||
{Type: "right", Color: "CCCCCC", Style: 1},
|
||||
{Type: "top", Color: "CCCCCC", Style: 1},
|
||||
{Type: "bottom", Color: "CCCCCC", Style: 1},
|
||||
},
|
||||
Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create rejected style: %w", err)
|
||||
}
|
||||
|
||||
errorStyle, err := f.NewStyle(&excelize.Style{
|
||||
Fill: excelize.Fill{Type: "pattern", Color: []string{"FFCCCC"}, Pattern: 1},
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Color: "CCCCCC", Style: 1},
|
||||
{Type: "right", Color: "CCCCCC", Style: 1},
|
||||
{Type: "top", Color: "CCCCCC", Style: 1},
|
||||
{Type: "bottom", Color: "CCCCCC", Style: 1},
|
||||
},
|
||||
Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create error style: %w", err)
|
||||
}
|
||||
|
||||
for col, width := range colWidths {
|
||||
if err := f.SetColWidth(sheet, col, col, width); err != nil {
|
||||
return nil, fmt.Errorf("set col width %s: %w", col, err)
|
||||
}
|
||||
}
|
||||
|
||||
for i, header := range headers {
|
||||
cell := fmt.Sprintf("%s1", cols[i])
|
||||
if err := f.SetCellValue(sheet, cell, header); err != nil {
|
||||
return nil, fmt.Errorf("set cell value %s: %w", cell, err)
|
||||
}
|
||||
if err := f.SetCellStyle(sheet, cell, cell, headerStyle); err != nil {
|
||||
return nil, fmt.Errorf("set cell style %s: %w", cell, err)
|
||||
}
|
||||
}
|
||||
if err := f.SetRowHeight(sheet, 1, 36); err != nil {
|
||||
return nil, fmt.Errorf("set row height: %w", err)
|
||||
}
|
||||
|
||||
for rowIdx, a := range approvals {
|
||||
row := rowIdx + 2
|
||||
|
||||
// === ФИО инициатора ===
|
||||
initiatorName := ""
|
||||
if a.Initiator != nil && a.Initiator.FullName != nil {
|
||||
initiatorName = *a.Initiator.FullName
|
||||
} else if a.InitiatorID != nil {
|
||||
if u, err := db.User.GetUserByIDDB(ctx, *a.InitiatorID); err == nil && u != nil && u.FullName != nil {
|
||||
initiatorName = *u.FullName
|
||||
}
|
||||
}
|
||||
|
||||
// === Тема согласования ===
|
||||
topicName := ""
|
||||
if a.Topic != nil {
|
||||
if a.Topic.Category != nil && a.Topic.Category.Name != nil {
|
||||
topicName = *a.Topic.Category.Name + ": "
|
||||
} else if a.Topic.CategoryID != nil {
|
||||
if c, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *a.Topic.CategoryID); err == nil && c != nil && c.Name != nil {
|
||||
topicName = *c.Name + ": "
|
||||
}
|
||||
}
|
||||
if a.Topic.Name != nil {
|
||||
topicName += *a.Topic.Name
|
||||
}
|
||||
} else if a.TopicID != nil {
|
||||
if t, err := db.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); err == nil && t != nil {
|
||||
if t.CategoryID != nil {
|
||||
if c, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *t.CategoryID); err == nil && c != nil && c.Name != nil {
|
||||
topicName = *c.Name + ": "
|
||||
}
|
||||
}
|
||||
if t.Name != nil {
|
||||
topicName += *t.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === Дата создания ===
|
||||
createdAt := ""
|
||||
if a.CreatedAt != nil {
|
||||
createdAt = a.CreatedAt.Format("02.01.2006 15:04")
|
||||
}
|
||||
|
||||
// === Согласующие и комментарии ===
|
||||
var approverParts []string
|
||||
var commentFromStep string
|
||||
lastApprovedAt := ""
|
||||
|
||||
steps, _, _ := db.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalStep{ApprovalID: a.ID},
|
||||
})
|
||||
sort.Slice(steps, func(i, j int) bool {
|
||||
if steps[i].StepOrder == nil || steps[j].StepOrder == nil {
|
||||
return false
|
||||
}
|
||||
return *steps[i].StepOrder < *steps[j].StepOrder
|
||||
})
|
||||
for _, s := range steps {
|
||||
name := ""
|
||||
if s.ApproverNameSnapshot != nil && *s.ApproverNameSnapshot != "" {
|
||||
name = *s.ApproverNameSnapshot
|
||||
} else if s.ApproverID != nil {
|
||||
if u, err := db.User.GetUserByIDDB(ctx, *s.ApproverID); err == nil && u != nil && u.FullName != nil {
|
||||
name = *u.FullName
|
||||
}
|
||||
}
|
||||
if name != "" {
|
||||
approverParts = append(approverParts, name)
|
||||
}
|
||||
if s.Status != nil && *s.Status == "rejected" && s.Comment != nil && *s.Comment != "" {
|
||||
commentFromStep = *s.Comment
|
||||
}
|
||||
if s.Status != nil && *s.Status == "approved" && s.ActedAt != nil {
|
||||
lastApprovedAt = s.ActedAt.Format("02.01.2006 15:04")
|
||||
}
|
||||
}
|
||||
approversCell := strings.Join(approverParts, "\n")
|
||||
|
||||
// === Наблюдатели ===
|
||||
var observerParts []string
|
||||
categoryCode := GetTopicCategoryCodeByApproval(ctx, db, a)
|
||||
if categoryCode != "" {
|
||||
observers, _ := db.User.GetObserversForCategoryDB(ctx, categoryCode)
|
||||
for _, obs := range observers {
|
||||
if obs.FullName != nil {
|
||||
observerParts = append(observerParts, *obs.FullName)
|
||||
}
|
||||
}
|
||||
}
|
||||
observersCell := strings.Join(observerParts, "\n")
|
||||
|
||||
// === Статус ===
|
||||
status := "—"
|
||||
if a.Status != nil {
|
||||
switch *a.Status {
|
||||
case "pending":
|
||||
status = "На согласовании"
|
||||
case "approved":
|
||||
status = "Согласовано"
|
||||
case "rejected":
|
||||
status = "Отклонено"
|
||||
case "revoked":
|
||||
status = "Отозвано"
|
||||
case "revision":
|
||||
status = "На доработке"
|
||||
case "draft":
|
||||
status = "Черновик"
|
||||
}
|
||||
}
|
||||
|
||||
// === Текст заявки ===
|
||||
content := ""
|
||||
if a.Content != nil {
|
||||
content = *a.Content
|
||||
}
|
||||
|
||||
// === Отдел ===
|
||||
deptName := ""
|
||||
if a.Department != nil && a.Department.Name != nil {
|
||||
deptName = *a.Department.Name
|
||||
} else if a.DepartmentID != nil {
|
||||
if d, err := db.Department.GetDepartmentByIDDB(ctx, *a.DepartmentID); err == nil && d != nil && d.Name != nil {
|
||||
deptName = *d.Name
|
||||
}
|
||||
}
|
||||
|
||||
// === Комментарий ===
|
||||
comment := ""
|
||||
if a.Status != nil && *a.Status == "rejected" {
|
||||
comment = commentFromStep
|
||||
}
|
||||
|
||||
// === Задачи и исполнители ===
|
||||
taskText := "Не предусмотрено"
|
||||
executorName := "Не предусмотрено"
|
||||
taskStatus := "Не предусмотрено"
|
||||
taskCompletedAt := ""
|
||||
hasTaskError := false
|
||||
|
||||
if a.TopicID != nil {
|
||||
topicExecutors, _ := db.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, *a.TopicID)
|
||||
|
||||
if len(topicExecutors) == 0 {
|
||||
taskText = "Не предусмотрено"
|
||||
executorName = "Не предусмотрено"
|
||||
taskStatus = "Не предусмотрено"
|
||||
} else {
|
||||
tasks, _, _ := db.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTask{ApprovalID: a.ID},
|
||||
})
|
||||
|
||||
if len(tasks) == 0 {
|
||||
if a.Status == nil {
|
||||
taskText = "Не предусмотрено"
|
||||
executorName = "Не предусмотрено"
|
||||
taskStatus = "Не предусмотрено"
|
||||
} else {
|
||||
switch *a.Status {
|
||||
case "approved":
|
||||
taskText = "Ошибка: задачи не созданы"
|
||||
executorName = "Ошибка"
|
||||
taskStatus = "Ошибка"
|
||||
hasTaskError = true
|
||||
case "pending":
|
||||
taskText = "Ожидает согласования"
|
||||
executorName = "Ожидает согласования"
|
||||
taskStatus = "Ожидает согласования"
|
||||
case "rejected":
|
||||
taskText = "Не выполнено (заявка отклонена)"
|
||||
executorName = "Не выполнено (заявка отклонена)"
|
||||
taskStatus = "Не выполнено (заявка отклонена)"
|
||||
case "revoked":
|
||||
taskText = "Не выполнено (заявка отозвана)"
|
||||
executorName = "Не выполнено (заявка отозвана)"
|
||||
taskStatus = "Не выполнено (заявка отозвана)"
|
||||
default:
|
||||
taskText = "Не предусмотрено"
|
||||
executorName = "Не предусмотрено"
|
||||
taskStatus = "Не предусмотрено"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
var taskTexts []string
|
||||
var executorNames []string
|
||||
var taskStatuses []string
|
||||
|
||||
sort.Slice(tasks, func(i, j int) bool {
|
||||
if tasks[i].StepOrder == nil || tasks[j].StepOrder == nil {
|
||||
return false
|
||||
}
|
||||
return *tasks[i].StepOrder < *tasks[j].StepOrder
|
||||
})
|
||||
|
||||
for _, task := range tasks {
|
||||
if task.TaskText != nil {
|
||||
taskTexts = append(taskTexts, *task.TaskText)
|
||||
} else {
|
||||
taskTexts = append(taskTexts, "—")
|
||||
}
|
||||
|
||||
eName := ""
|
||||
if task.ExecutorID != nil {
|
||||
if u, err := db.User.GetUserByIDDB(ctx, *task.ExecutorID); err == nil && u != nil && u.FullName != nil {
|
||||
eName = *u.FullName
|
||||
}
|
||||
}
|
||||
executorNames = append(executorNames, eName)
|
||||
|
||||
ts := "—"
|
||||
if task.Status != nil {
|
||||
switch *task.Status {
|
||||
case "pending":
|
||||
ts = "В работе"
|
||||
case "waiting":
|
||||
ts = "Ожидает"
|
||||
case "completed":
|
||||
ts = "Выполнено"
|
||||
case "cancelled":
|
||||
ts = "Отменено"
|
||||
}
|
||||
}
|
||||
taskStatuses = append(taskStatuses, ts)
|
||||
|
||||
if taskCompletedAt == "" && task.CompletedAt != nil {
|
||||
taskCompletedAt = task.CompletedAt.Format("02.01.2006 15:04")
|
||||
}
|
||||
}
|
||||
|
||||
taskText = strings.Join(taskTexts, "\n")
|
||||
executorName = strings.Join(executorNames, "\n")
|
||||
taskStatus = strings.Join(taskStatuses, "\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
values := []interface{}{
|
||||
initiatorName, topicName, createdAt,
|
||||
approversCell, observersCell,
|
||||
status, content, deptName, comment,
|
||||
lastApprovedAt,
|
||||
taskText, executorName, taskStatus,
|
||||
taskCompletedAt,
|
||||
}
|
||||
|
||||
// Базовый стиль строки
|
||||
style := dataStyle
|
||||
if a.Status != nil && *a.Status == "rejected" {
|
||||
style = rejectedStyle
|
||||
}
|
||||
|
||||
// Заполняем ячейки с индивидуальными стилями
|
||||
for colIdx, val := range values {
|
||||
cell := fmt.Sprintf("%s%d", cols[colIdx], row)
|
||||
if err := f.SetCellValue(sheet, cell, val); err != nil {
|
||||
logrus.Warnf("reportcore: set cell value %s: %v", cell, err)
|
||||
continue
|
||||
}
|
||||
|
||||
cellStyle := style
|
||||
if hasTaskError && colIdx >= 10 && colIdx <= 12 {
|
||||
cellStyle = errorStyle
|
||||
}
|
||||
if err := f.SetCellStyle(sheet, cell, cell, cellStyle); err != nil {
|
||||
logrus.Warnf("reportcore: set cell style %s: %v", cell, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Высота строки
|
||||
rowHeight := 20.0
|
||||
maxLines := len(approverParts)
|
||||
if len(strings.Split(taskText, "\n")) > maxLines {
|
||||
maxLines = len(strings.Split(taskText, "\n"))
|
||||
}
|
||||
if maxLines > 1 {
|
||||
rowHeight = float64(maxLines) * 18
|
||||
}
|
||||
if err := f.SetRowHeight(sheet, row, rowHeight); err != nil {
|
||||
logrus.Warnf("reportcore: set row height %d: %v", row, err)
|
||||
}
|
||||
}
|
||||
|
||||
lastCol := cols[len(headers)-1]
|
||||
lastRow := len(approvals) + 1
|
||||
if err := f.AutoFilter(sheet, fmt.Sprintf("A1:%s%d", lastCol, lastRow), []excelize.AutoFilterOptions{}); err != nil {
|
||||
logrus.Warnf("reportcore: auto filter: %v", err)
|
||||
}
|
||||
|
||||
if err := f.SetPanes(sheet, &excelize.Panes{
|
||||
Freeze: true,
|
||||
YSplit: 1,
|
||||
TopLeftCell: "A2",
|
||||
ActivePane: "bottomLeft",
|
||||
}); err != nil {
|
||||
logrus.Warnf("reportcore: set panes: %v", err)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := f.Write(&buf); err != nil {
|
||||
return nil, fmt.Errorf("write excel: %w", err)
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
package reportcore
|
||||
|
||||
import (
|
||||
database "bitrix_balancer_api/core/db"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"context"
|
||||
)
|
||||
|
||||
// GetTopicCategoryCodeByApproval возвращает код категории темы для заявки.
|
||||
func GetTopicCategoryCodeByApproval(ctx context.Context, db *database.ModuleDB, a *typescore.Approval) string {
|
||||
if a == nil || a.TopicID == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Если тема уже загружена
|
||||
if a.Topic != nil && a.Topic.CategoryID != nil {
|
||||
if a.Topic.Category != nil && a.Topic.Category.Code != nil {
|
||||
return *a.Topic.Category.Code
|
||||
}
|
||||
if cat, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *a.Topic.CategoryID); err == nil && cat != nil && cat.Code != nil {
|
||||
return *cat.Code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Загружаем тему
|
||||
topic, err := db.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID)
|
||||
if err != nil || topic == nil || topic.CategoryID == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
cat, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
|
||||
if err != nil || cat == nil || cat.Code == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return *cat.Code
|
||||
}
|
||||
|
||||
// GetReportCategoryCodes — объединяет категории согласующего и наблюдателя.
|
||||
// Используется для определения, какие категории доступны пользователю для отчёта.
|
||||
func GetReportCategoryCodes(ctx context.Context, db *database.ModuleDB, user *typescore.User) []string {
|
||||
if user == nil || user.ID == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
var codes []string
|
||||
|
||||
addCodes := func(action string) {
|
||||
perms, err := db.Permission.GetUserPermissionsDB(ctx, *user.ID, action)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, p := range perms {
|
||||
if p.TopicCategoryID == nil {
|
||||
continue
|
||||
}
|
||||
cat, err := db.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *p.TopicCategoryID)
|
||||
if err != nil || cat == nil || cat.Code == nil {
|
||||
continue
|
||||
}
|
||||
if !seen[*cat.Code] {
|
||||
seen[*cat.Code] = true
|
||||
codes = append(codes, *cat.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addCodes("create") // согласующий
|
||||
addCodes("observe") // наблюдатель
|
||||
|
||||
return codes
|
||||
}
|
||||
|
|
@ -6,16 +6,22 @@ import (
|
|||
|
||||
// Admin - структура для хранения данных о администраторах.
|
||||
type Admin struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"` // Автоматически заполняемое уникальное поле для большого числа записей
|
||||
Login *string `gorm:"type:text;not null;unique;column:login" json:"login" db:"login" mapstructure:"login"` // Логин администратора
|
||||
PasswordHash *string `gorm:"type:text;not null;column:password_hash" json:"-" db:"password_hash" mapstructure:"password_hash"` // Пароль администратора
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"` // Дата создания записи
|
||||
LastLogin *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:last_login" json:"last_login" db:"last_login"` // Дата входа
|
||||
LastIPLogin *string `gorm:"type:text;column:last_ip_login" json:"last_ip_login" db:"last_ip_login" mapstructure:"last_ip_login"` // Последний IP входа
|
||||
IsBlocked *bool `gorm:"type:boolean;not null;index;default:false;column:is_blocked" json:"is_blocked" db:"is_blocked" mapstructure:"is_blocked"` // Заблокирован ли администратор
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" ignore_update_db:"true" json:"id" db:"id" mapstructure:"id"`
|
||||
Login *string `gorm:"type:text;not null;unique;column:login" json:"login" db:"login" mapstructure:"login"`
|
||||
Name *string `gorm:"type:text;column:name" json:"name,omitempty" db:"name" mapstructure:"name"`
|
||||
PasswordHash *string `gorm:"type:text;not null;column:password_hash" json:"-" db:"password_hash" mapstructure:"password_hash"`
|
||||
IsRoot *bool `gorm:"type:boolean;not null;default:false;column:is_root" json:"is_root" db:"is_root" mapstructure:"is_root"`
|
||||
CreatedAt *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:created_at" json:"created_at" db:"created_at"`
|
||||
LastLogin *time.Time `gorm:"type:timestamp;default:CURRENT_TIMESTAMP;column:last_login" json:"last_login" db:"last_login"`
|
||||
LastIPLogin *string `gorm:"type:text;column:last_ip_login" json:"last_ip_login" db:"last_ip_login" mapstructure:"last_ip_login"`
|
||||
IsBlocked *bool `gorm:"type:boolean;not null;index;default:false;column:is_blocked" json:"is_blocked" db:"is_blocked" mapstructure:"is_blocked"`
|
||||
|
||||
Password *string `gorm:"-" json:"password,omitempty"`
|
||||
}
|
||||
|
||||
type AdminReq struct {
|
||||
Login *string `json:"login"`
|
||||
Name *string `json:"name"`
|
||||
Password *string `json:"password"` // Пароль пользователя
|
||||
IsRoot *bool `json:"is_root"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ type Approval struct {
|
|||
InitiatorID *uint64 `gorm:"type:bigint;not null;index;column:initiator_id" json:"initiator_id" db:"initiator_id" mapstructure:"initiator_id"`
|
||||
TopicID *uint64 `gorm:"type:bigint;not null;index;column:topic_id" json:"topic_id" db:"topic_id" mapstructure:"topic_id"`
|
||||
DepartmentID *uint64 `gorm:"type:bigint;not null;index;column:department_id" json:"department_id" db:"department_id" mapstructure:"department_id"` // снимок отдела на момент создания
|
||||
Content *string `gorm:"type:text;not null;column:content" json:"content" db:"content" mapstructure:"content"` // введённые пользователем данные по шаблону
|
||||
Content *string `gorm:"type:text;not null;column:content" json:"content" db:"content" mapstructure:"content" mapstructure:"content"` // введённые пользователем данные по шаблону
|
||||
Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status" mapstructure:"status"`
|
||||
RevokedByID *uint64 `gorm:"type:bigint;index;column:revoked_by_id" json:"revoked_by_id,omitempty" db:"revoked_by_id" mapstructure:"revoked_by_id"`
|
||||
RevokedAt *time.Time `gorm:"type:timestamp;column:revoked_at" json:"revoked_at,omitempty" db:"revoked_at"`
|
||||
|
|
|
|||
|
|
@ -3,18 +3,19 @@ package typescore
|
|||
import "time"
|
||||
|
||||
type ApprovalTask struct {
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id"`
|
||||
ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id"`
|
||||
ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id" json:"executor_id" db:"executor_id"`
|
||||
ID *uint64 `gorm:"column:id;index;type:bigint;autoIncrement;not null;unique" json:"id" db:"id" mapstructure:"id"`
|
||||
ApprovalID *uint64 `gorm:"type:bigint;not null;index;column:approval_id" json:"approval_id" db:"approval_id" mapstructure:"approval_id"`
|
||||
ExecutorID *uint64 `gorm:"type:bigint;not null;index;column:executor_id" json:"executor_id" db:"executor_id" mapstructure:"executor_id"`
|
||||
TaskText *string `gorm:"type:text;not null;column:task_text" json:"task_text" db:"task_text"`
|
||||
Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status"`
|
||||
Status *string `gorm:"type:text;not null;default:'pending';index;column:status" json:"status" db:"status" mapstructure:"status"`
|
||||
StepOrder *int `gorm:"type:int;default:0;column:step_order" json:"step_order" db:"step_order"`
|
||||
RequireFile *bool `gorm:"type:boolean;default:false;column:require_file" json:"require_file" db:"require_file"`
|
||||
TopicExecutorID *uint64 `gorm:"type:bigint;column:topic_executor_id" json:"topic_executor_id,omitempty" db:"topic_executor_id"`
|
||||
RequireFile *bool `gorm:"type:boolean;default:false;column:require_file" json:"require_file" db:"require_file" mapstructure:"require_file"`
|
||||
TopicExecutorID *uint64 `gorm:"type:bigint;column:topic_executor_id" json:"topic_executor_id,omitempty" db:"topic_executor_id" mapstructure:"topic_executor_id"`
|
||||
CompletedAt *time.Time `gorm:"type:timestamp;column:completed_at" json:"completed_at,omitempty" db:"completed_at"`
|
||||
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"`
|
||||
|
||||
Approval *Approval `gorm:"-" json:"approval,omitempty"`
|
||||
Executor *User `gorm:"-" json:"executor,omitempty"`
|
||||
Approval *Approval `gorm:"-" json:"approval,omitempty"`
|
||||
Executor *User `gorm:"-" json:"executor,omitempty"`
|
||||
Files []*ApprovalFile `gorm:"-" json:"files,omitempty"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,7 +16,9 @@ type UserHierarchy struct {
|
|||
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"`
|
||||
|
||||
Subordinate *User `gorm:"-" json:"subordinate,omitempty"`
|
||||
Approver *User `gorm:"-" json:"approver,omitempty"`
|
||||
Department *Department `gorm:"-" json:"department,omitempty"`
|
||||
Subordinate *User `gorm:"-" json:"subordinate,omitempty"`
|
||||
Approver *User `gorm:"-" json:"approver,omitempty"`
|
||||
Department *Department `gorm:"-" json:"department,omitempty"`
|
||||
TopicCategory *ApprovalTopicCategory `gorm:"-" json:"topic_category,omitempty"`
|
||||
Topic *ApprovalTopic `gorm:"-" json:"topic,omitempty"`
|
||||
}
|
||||
|
|
|
|||
11
deploy.sh
11
deploy.sh
|
|
@ -65,24 +65,27 @@ if [ "$SERVICE_TYPE" = "all" ]; then
|
|||
log_info "Deploying all services..."
|
||||
echo ""
|
||||
|
||||
# Полный путь к скрипту для рекурсивных вызовов
|
||||
SELF="$THIS_PATH/deploy.sh"
|
||||
|
||||
# 1. Сначала миграции
|
||||
log_service "Step 1/4: Database migrations"
|
||||
"$0" migrations
|
||||
"$SELF" migrations # ✅ Используем полный путь
|
||||
echo ""
|
||||
|
||||
# 2. Потом Telegram бот
|
||||
log_service "Step 2/4: Telegram bot"
|
||||
"$0" telegram
|
||||
"$SELF" telegram # ✅
|
||||
echo ""
|
||||
|
||||
# 3. Потом балансировщик
|
||||
log_service "Step 3/4: REST balancer"
|
||||
"$0" balancer
|
||||
"$SELF" balancer # ✅
|
||||
echo ""
|
||||
|
||||
# 4. В конце админка (с Swagger если нужно)
|
||||
log_service "Step 4/4: REST admin"
|
||||
"$0" admin "$GENERATE_SWAGGER"
|
||||
"$SELF" admin "$GENERATE_SWAGGER" # ✅
|
||||
|
||||
echo ""
|
||||
log_success "All services deployed successfully!"
|
||||
|
|
|
|||
|
|
@ -6,8 +6,10 @@ import (
|
|||
_ "bitrix_balancer_api/rest_admin_service/docs"
|
||||
adminhandler "bitrix_balancer_api/rest_admin_service/handlers/admin"
|
||||
approvalstepshandler "bitrix_balancer_api/rest_admin_service/handlers/approval_steps"
|
||||
approvaltaskshandler "bitrix_balancer_api/rest_admin_service/handlers/approval_tasks"
|
||||
approvalshandler "bitrix_balancer_api/rest_admin_service/handlers/approvals"
|
||||
authhandler "bitrix_balancer_api/rest_admin_service/handlers/auth"
|
||||
dashboardhandler "bitrix_balancer_api/rest_admin_service/handlers/dashboard"
|
||||
departmentshandler "bitrix_balancer_api/rest_admin_service/handlers/departments"
|
||||
permissionshandler "bitrix_balancer_api/rest_admin_service/handlers/permission"
|
||||
profilehandler "bitrix_balancer_api/rest_admin_service/handlers/profile"
|
||||
|
|
@ -213,6 +215,8 @@ func registerRoutes(router chi.Router, ipc *typesm.InternalProviderControl) erro
|
|||
{"approvals", approvalshandler.RegisterApprovalRoutes},
|
||||
{"approval-steps", approvalstepshandler.RegisterApprovalStepRoutes},
|
||||
{"permissions", permissionshandler.RegisterPermissionRoutes},
|
||||
{"approval-tasks", approvaltaskshandler.RegisterApprovalTasksRoutes},
|
||||
{"dashboard", dashboardhandler.RegisterDashboardRoutes},
|
||||
}
|
||||
|
||||
// Регистрация всех маршрутов
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"bitrix_balancer_api/core/securecore"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/core/utilscore"
|
||||
"bitrix_balancer_api/rest_admin_service/handlers"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
|
|
@ -51,19 +52,27 @@ func (s *AdminsReg) GetAdminsListHandler(w http.ResponseWriter, r *http.Request)
|
|||
}
|
||||
|
||||
// CreateAdminHandler Создание администратора
|
||||
// @Summary Создание администратора
|
||||
// @Description Создание администратора
|
||||
// @Tags admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body typescore.AdminReq true "Запрос"
|
||||
// @Success 200 {object} typescore.Admin
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/admin [post]
|
||||
func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
defer r.Body.Close()
|
||||
|
||||
// Проверка, что текущий админ — root
|
||||
currentUserID, err := handlers.GetIDFromContext(r.Context())
|
||||
if err != nil {
|
||||
return nil, errors.New("user not authenticated")
|
||||
}
|
||||
|
||||
currentAdmins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
|
||||
Filtering: &typescore.Admin{ID: ¤tUserID},
|
||||
})
|
||||
if err != nil || len(currentAdmins) == 0 {
|
||||
return nil, errors.New("current admin not found")
|
||||
}
|
||||
|
||||
// 🆕 Проверяем is_root, а не login
|
||||
if currentAdmins[0].IsRoot == nil || !*currentAdmins[0].IsRoot {
|
||||
return nil, errors.New("only_root_can_create_admins")
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
@ -74,7 +83,14 @@ func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (
|
|||
return nil, err
|
||||
}
|
||||
|
||||
usersList, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{Filtering: &typescore.Admin{Login: req.Login}})
|
||||
if req.Login == nil || *req.Login == "" {
|
||||
return nil, errors.New("login is required")
|
||||
}
|
||||
|
||||
// Проверка уникальности логина
|
||||
usersList, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
|
||||
Filtering: &typescore.Admin{Login: req.Login},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -94,7 +110,9 @@ func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (
|
|||
|
||||
newAdminObj := &typescore.Admin{
|
||||
Login: req.Login,
|
||||
Name: req.Name,
|
||||
PasswordHash: tempPasswordHash,
|
||||
IsRoot: req.IsRoot,
|
||||
}
|
||||
|
||||
newAdmin, _, err := s.ipc.Database.Admin.CreateAdminDB(nil, newAdminObj, true)
|
||||
|
|
@ -102,20 +120,109 @@ func (s *AdminsReg) CreateAdminHandler(w http.ResponseWriter, r *http.Request) (
|
|||
return nil, err
|
||||
}
|
||||
|
||||
newAdmin.PasswordHash = &tempPassword
|
||||
newAdmin.Password = &tempPassword
|
||||
return newAdmin, nil
|
||||
}
|
||||
|
||||
// UpdateAdminHandler Обновление администратора
|
||||
func (s *AdminsReg) UpdateAdminHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var req typescore.Admin
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return nil, errors.New("invalid request body")
|
||||
}
|
||||
|
||||
if req.ID == nil {
|
||||
return nil, errors.New("admin id is required")
|
||||
}
|
||||
|
||||
// Получаем существующего админа
|
||||
existingAdmins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
|
||||
Filtering: &typescore.Admin{ID: req.ID},
|
||||
})
|
||||
if err != nil || len(existingAdmins) == 0 {
|
||||
return nil, errors.New("admin not found")
|
||||
}
|
||||
existing := existingAdmins[0]
|
||||
|
||||
// Получаем текущего админа
|
||||
currentUserID, err := handlers.GetIDFromContext(r.Context())
|
||||
if err != nil {
|
||||
return nil, errors.New("user not authenticated")
|
||||
}
|
||||
currentAdmins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
|
||||
Filtering: &typescore.Admin{ID: ¤tUserID},
|
||||
})
|
||||
if err != nil || len(currentAdmins) == 0 {
|
||||
return nil, errors.New("current admin not found")
|
||||
}
|
||||
currentIsRoot := currentAdmins[0].IsRoot != nil && *currentAdmins[0].IsRoot
|
||||
|
||||
if req.IsRoot != nil {
|
||||
if !currentIsRoot {
|
||||
return nil, errors.New("only_root_can_manage_root_rights")
|
||||
}
|
||||
|
||||
if *req.ID == currentUserID && !*req.IsRoot {
|
||||
return nil, errors.New("cannot_remove_root_from_self")
|
||||
}
|
||||
if !*req.IsRoot && existing.IsRoot != nil && *existing.IsRoot {
|
||||
allAdmins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
|
||||
Filtering: &typescore.Admin{},
|
||||
})
|
||||
if err == nil {
|
||||
rootCount := 0
|
||||
for _, a := range allAdmins {
|
||||
if a.IsRoot != nil && *a.IsRoot {
|
||||
rootCount++
|
||||
}
|
||||
}
|
||||
if rootCount <= 1 {
|
||||
return nil, errors.New("cannot_remove_last_root")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if req.IsBlocked != nil && *req.IsBlocked {
|
||||
if existing.IsRoot != nil && *existing.IsRoot && !currentIsRoot {
|
||||
return nil, errors.New("cannot_block_root")
|
||||
}
|
||||
}
|
||||
|
||||
if *req.ID == currentUserID && req.IsBlocked != nil && *req.IsBlocked {
|
||||
return nil, errors.New("cannot_block_self")
|
||||
}
|
||||
|
||||
// Создаём объект для обновления
|
||||
updateObj := &typescore.Admin{
|
||||
ID: req.ID,
|
||||
}
|
||||
if req.Name != nil {
|
||||
updateObj.Name = req.Name
|
||||
}
|
||||
if req.IsBlocked != nil {
|
||||
updateObj.IsBlocked = req.IsBlocked
|
||||
}
|
||||
if req.IsRoot != nil {
|
||||
updateObj.IsRoot = req.IsRoot
|
||||
}
|
||||
|
||||
updated, _, err := s.ipc.Database.Admin.UpdateAdminDB(nil, updateObj, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
// DeleteAdminHandler Удаление администратора
|
||||
// @Summary Удаление администратора
|
||||
// @Description Удаление администратора
|
||||
// @Tags admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body typescore.AdminReq true "Запрос"
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/admin [delete]
|
||||
func (s *AdminsReg) DeleteAdminHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
defer r.Body.Close()
|
||||
|
||||
|
|
@ -126,7 +233,39 @@ func (s *AdminsReg) DeleteAdminHandler(w http.ResponseWriter, r *http.Request) (
|
|||
|
||||
var req typescore.Admin
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return nil, err
|
||||
return nil, errors.New("invalid request body")
|
||||
}
|
||||
|
||||
if req.ID == nil {
|
||||
return nil, errors.New("admin id is required")
|
||||
}
|
||||
|
||||
// Нельзя удалить себя
|
||||
currentUserID, err := handlers.GetIDFromContext(r.Context())
|
||||
if err != nil {
|
||||
return nil, errors.New("user not authenticated")
|
||||
}
|
||||
if *req.ID == currentUserID {
|
||||
return nil, errors.New("cannot_delete_self")
|
||||
}
|
||||
|
||||
// Получаем удаляемого админа
|
||||
admins, _, err := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
|
||||
Filtering: &typescore.Admin{ID: req.ID},
|
||||
})
|
||||
if err != nil || len(admins) == 0 {
|
||||
return nil, errors.New("admin not found")
|
||||
}
|
||||
|
||||
// 🆕 Нельзя удалить root (если текущий не root)
|
||||
currentAdmins, _, _ := s.ipc.Database.Admin.GetAdminsListDB(typescore.ListDbOptions{
|
||||
Filtering: &typescore.Admin{ID: ¤tUserID},
|
||||
})
|
||||
currentIsRoot := len(currentAdmins) > 0 && currentAdmins[0].IsRoot != nil && *currentAdmins[0].IsRoot
|
||||
|
||||
targetIsRoot := admins[0].IsRoot != nil && *admins[0].IsRoot
|
||||
if targetIsRoot && !currentIsRoot {
|
||||
return nil, errors.New("cannot_delete_root")
|
||||
}
|
||||
|
||||
err = s.ipc.Database.Admin.DeleteAdminDB(&req)
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ func RegisterAdminRoutes(
|
|||
handlers.RegisterRoute(r, http.MethodGet, adminURL, s.GetAdminsListHandler)
|
||||
handlers.RegisterRoute(r, http.MethodPost, adminURL, s.CreateAdminHandler)
|
||||
handlers.RegisterRoute(r, http.MethodDelete, adminURL, s.DeleteAdminHandler)
|
||||
handlers.RegisterRoute(r, http.MethodPut, adminURL, s.UpdateAdminHandler)
|
||||
})
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -0,0 +1,403 @@
|
|||
package approvaltaskshandler
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/core/utilscore"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// GetApprovalTasksListHandler Получение списка задач
|
||||
func (s *ApprovalTasksReg) GetApprovalTasksListHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
queryParams := r.URL.Query()
|
||||
|
||||
taskParams := &typescore.ApprovalTask{}
|
||||
offset, limit, likeFields, errW := utilscore.ParseParamsGetRequest(queryParams, taskParams)
|
||||
if errW != nil {
|
||||
return nil, errW
|
||||
}
|
||||
|
||||
options := typescore.ListDbOptions{
|
||||
Filtering: taskParams,
|
||||
Offset: offset,
|
||||
Limit: limit,
|
||||
LikeFields: likeFields,
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
tasks, total, errW := s.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, options)
|
||||
if errW != nil {
|
||||
return nil, errW
|
||||
}
|
||||
|
||||
// 🆕 Обогащаем данные
|
||||
for _, task := range tasks {
|
||||
s.enrichTask(ctx, task)
|
||||
}
|
||||
|
||||
return &typescore.ApiResponseBase{
|
||||
TotalCount: total,
|
||||
Data: tasks,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetApprovalTaskByIDHandler Получение задачи по ID
|
||||
func (s *ApprovalTasksReg) GetApprovalTaskByIDHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
idStr := chi.URLParam(r, "id")
|
||||
if idStr == "" {
|
||||
return nil, errors.New("task id is required")
|
||||
}
|
||||
|
||||
id, err := strconv.ParseUint(idStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid task id")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
task, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if task == nil {
|
||||
return nil, errors.New("task not found")
|
||||
}
|
||||
|
||||
s.enrichTask(ctx, task)
|
||||
|
||||
return task, nil
|
||||
}
|
||||
|
||||
// UpdateApprovalTaskHandler Обновление задачи
|
||||
func (s *ApprovalTasksReg) UpdateApprovalTaskHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
logrus.Error("🛑 UpdateApprovalTaskHandler: ReadAll error:", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var req typescore.ApprovalTask
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return nil, errors.New("invalid request body")
|
||||
}
|
||||
|
||||
if req.ID == nil {
|
||||
return nil, errors.New("task id is required")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Проверяем существование
|
||||
existingTask, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, *req.ID)
|
||||
if err != nil || existingTask == nil {
|
||||
return nil, errors.New("task not found")
|
||||
}
|
||||
|
||||
// 🆕 Валидация статуса
|
||||
if req.Status != nil {
|
||||
validStatuses := map[string]bool{
|
||||
"pending": true,
|
||||
"waiting": true,
|
||||
"completed": true,
|
||||
"cancelled": true,
|
||||
}
|
||||
if !validStatuses[*req.Status] {
|
||||
return nil, errors.New("invalid status")
|
||||
}
|
||||
}
|
||||
|
||||
updated, _, err := s.ipc.Database.ApprovalTasks.UpdateApprovalTaskDB(ctx, nil, &req, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.enrichTask(ctx, updated)
|
||||
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
// DeleteApprovalTaskHandler Удаление задачи
|
||||
func (s *ApprovalTasksReg) DeleteApprovalTaskHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var req typescore.ApprovalTask
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return nil, errors.New("invalid request body")
|
||||
}
|
||||
|
||||
if req.ID == nil {
|
||||
return nil, errors.New("task id is required")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
err = s.ipc.Database.ApprovalTasks.DeleteApprovalTaskDB(ctx, &req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// enrichTask подгружает связанные данные для задачи
|
||||
func (s *ApprovalTasksReg) enrichTask(ctx context.Context, task *typescore.ApprovalTask) {
|
||||
if task == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Подгружаем заявку
|
||||
if task.ApprovalID != nil {
|
||||
approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, *task.ApprovalID)
|
||||
if err == nil && approval != nil {
|
||||
task.Approval = approval
|
||||
s.enrichApproval(ctx, approval)
|
||||
}
|
||||
}
|
||||
|
||||
// Подгружаем исполнителя
|
||||
if task.ExecutorID != nil {
|
||||
executor, err := s.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID)
|
||||
if err == nil && executor != nil {
|
||||
task.Executor = executor
|
||||
if executor.DepartmentID != nil {
|
||||
department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *executor.DepartmentID)
|
||||
if err == nil && department != nil {
|
||||
executor.Department = department
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if task.ID != nil {
|
||||
files, err := s.ipc.Database.ApprovalFile.GetFilesByTaskIDDB(ctx, *task.ID)
|
||||
if err == nil {
|
||||
task.Files = files
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ApprovalTasksReg) enrichApproval(ctx context.Context, approval *typescore.Approval) {
|
||||
if approval == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Подгружаем инициатора
|
||||
if approval.InitiatorID != nil {
|
||||
initiator, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.InitiatorID)
|
||||
if err == nil && initiator != nil {
|
||||
approval.Initiator = initiator
|
||||
|
||||
// Подгружаем отдел инициатора
|
||||
if initiator.DepartmentID != nil {
|
||||
department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *initiator.DepartmentID)
|
||||
if err == nil && department != nil {
|
||||
initiator.Department = department
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Подгружаем тему
|
||||
if approval.TopicID != nil {
|
||||
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
|
||||
if err == nil && topic != nil {
|
||||
approval.Topic = topic
|
||||
|
||||
// Подгружаем категорию темы
|
||||
if topic.CategoryID != nil {
|
||||
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
|
||||
if err == nil && category != nil {
|
||||
topic.Category = category
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Подгружаем отдел
|
||||
if approval.DepartmentID != nil {
|
||||
department, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *approval.DepartmentID)
|
||||
if err == nil && department != nil {
|
||||
approval.Department = department
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetApprovalTaskFileHandler Получение файла задачи (для предпросмотра)
|
||||
func (s *ApprovalTasksReg) GetApprovalTaskFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
ctx := r.Context()
|
||||
|
||||
taskIDStr := chi.URLParam(r, "task_id")
|
||||
fileIDStr := chi.URLParam(r, "file_id")
|
||||
|
||||
if taskIDStr == "" || fileIDStr == "" {
|
||||
return nil, errors.New("task_id and file_id are required")
|
||||
}
|
||||
|
||||
taskID, err := strconv.ParseUint(taskIDStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid task_id")
|
||||
}
|
||||
|
||||
fileID, err := strconv.ParseUint(fileIDStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid file_id")
|
||||
}
|
||||
|
||||
// Проверяем, что задача существует
|
||||
task, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID)
|
||||
if err != nil || task == nil {
|
||||
return nil, errors.New("task not found")
|
||||
}
|
||||
|
||||
// Получаем файл
|
||||
file, err := s.ipc.Database.ApprovalFile.GetApprovalFileByIDDB(ctx, fileID)
|
||||
if err != nil || file == nil {
|
||||
return nil, errors.New("file not found")
|
||||
}
|
||||
|
||||
// Проверяем, что файл принадлежит задаче
|
||||
if file.TaskID == nil || *file.TaskID != taskID {
|
||||
return nil, errors.New("file does not belong to this task")
|
||||
}
|
||||
|
||||
if file.FileBase64 == nil || *file.FileBase64 == "" {
|
||||
return nil, errors.New("file content is empty")
|
||||
}
|
||||
|
||||
fileData, err := base64.StdEncoding.DecodeString(*file.FileBase64)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decode file")
|
||||
}
|
||||
|
||||
fileName := ""
|
||||
if file.FileName != nil {
|
||||
fileName = *file.FileName
|
||||
}
|
||||
mimeType := getMimeType(fileName)
|
||||
|
||||
w.Header().Set("Content-Type", mimeType)
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, fileName))
|
||||
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileData)))
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000")
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, err = w.Write(fileData)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to send file")
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// DownloadApprovalTaskFileHandler Скачивание файла задачи
|
||||
func (s *ApprovalTasksReg) DownloadApprovalTaskFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
ctx := r.Context()
|
||||
|
||||
taskIDStr := chi.URLParam(r, "task_id")
|
||||
fileIDStr := chi.URLParam(r, "file_id")
|
||||
|
||||
if taskIDStr == "" || fileIDStr == "" {
|
||||
return nil, errors.New("task_id and file_id are required")
|
||||
}
|
||||
|
||||
taskID, err := strconv.ParseUint(taskIDStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid task_id")
|
||||
}
|
||||
|
||||
fileID, err := strconv.ParseUint(fileIDStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid file_id")
|
||||
}
|
||||
|
||||
task, err := s.ipc.Database.ApprovalTasks.GetApprovalTaskByIDDB(ctx, taskID)
|
||||
if err != nil || task == nil {
|
||||
return nil, errors.New("task not found")
|
||||
}
|
||||
|
||||
file, err := s.ipc.Database.ApprovalFile.GetApprovalFileByIDDB(ctx, fileID)
|
||||
if err != nil || file == nil {
|
||||
return nil, errors.New("file not found")
|
||||
}
|
||||
|
||||
if file.TaskID == nil || *file.TaskID != taskID {
|
||||
return nil, errors.New("file does not belong to this task")
|
||||
}
|
||||
|
||||
if file.FileBase64 == nil || *file.FileBase64 == "" {
|
||||
return nil, errors.New("file content is empty")
|
||||
}
|
||||
|
||||
fileData, err := base64.StdEncoding.DecodeString(*file.FileBase64)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decode file")
|
||||
}
|
||||
|
||||
fileName := ""
|
||||
if file.FileName != nil {
|
||||
fileName = *file.FileName
|
||||
}
|
||||
mimeType := getMimeType(fileName)
|
||||
|
||||
w.Header().Set("Content-Type", mimeType)
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
|
||||
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileData)))
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, err = w.Write(fileData)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to send file")
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 🆕 getMimeType определяет MIME тип по расширению файла
|
||||
func getMimeType(fileName string) string {
|
||||
ext := strings.ToLower(filepath.Ext(fileName))
|
||||
|
||||
mimeTypes := map[string]string{
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
".gif": "image/gif",
|
||||
".webp": "image/webp",
|
||||
".svg": "image/svg+xml",
|
||||
".bmp": "image/bmp",
|
||||
".pdf": "application/pdf",
|
||||
".txt": "text/plain",
|
||||
".doc": "application/msword",
|
||||
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
".xls": "application/vnd.ms-excel",
|
||||
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
".csv": "text/csv",
|
||||
".zip": "application/zip",
|
||||
".json": "application/json",
|
||||
".xml": "application/xml",
|
||||
".html": "text/html",
|
||||
".mp3": "audio/mpeg",
|
||||
".mp4": "video/mp4",
|
||||
}
|
||||
|
||||
if mimeType, ok := mimeTypes[ext]; ok {
|
||||
return mimeType
|
||||
}
|
||||
|
||||
return "application/octet-stream"
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
package approvaltaskshandler
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/rest_admin_service/handlers"
|
||||
typesm "bitrix_balancer_api/rest_admin_service/types"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type ApprovalTasksReg struct {
|
||||
ipc *typesm.InternalProviderControl
|
||||
}
|
||||
|
||||
// RegisterApprovalTasksRoutes регистрирует маршруты для группы approvals
|
||||
func RegisterApprovalTasksRoutes(
|
||||
r chi.Router,
|
||||
ipc *typesm.InternalProviderControl,
|
||||
) error {
|
||||
s := &ApprovalTasksReg{
|
||||
ipc: ipc,
|
||||
}
|
||||
|
||||
r.Route("/api/approval-tasks", func(r chi.Router) {
|
||||
r.Use(handlers.AccessCodeVerifier(ipc.Config))
|
||||
r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient))
|
||||
|
||||
handlers.RegisterRoute(r, http.MethodGet, "/", s.GetApprovalTasksListHandler)
|
||||
handlers.RegisterRoute(r, http.MethodPut, "/", s.UpdateApprovalTaskHandler)
|
||||
handlers.RegisterRoute(r, http.MethodDelete, "/", s.DeleteApprovalTaskHandler)
|
||||
|
||||
r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
|
||||
HandlerFunc: s.GetApprovalTaskByIDHandler,
|
||||
}))
|
||||
r.Get("/{task_id}/files/{file_id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
|
||||
HandlerFunc: s.GetApprovalTaskFileHandler,
|
||||
}))
|
||||
r.Get("/{task_id}/files/{file_id}/download", handlers.WrapHandlerF(handlers.WrapHandlerParams{
|
||||
HandlerFunc: s.DownloadApprovalTaskFileHandler,
|
||||
}))
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,278 @@
|
|||
package approvalshandler
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// GetApprovalFileHandler Получение файла заявки
|
||||
// @Summary Получение файла заявки
|
||||
// @Description Возвращает файл по ID заявки и ID файла
|
||||
// @Tags approvals
|
||||
// @Produce application/octet-stream
|
||||
// @Param approval_id path integer true "ID заявки"
|
||||
// @Param file_id path integer true "ID файла"
|
||||
// @Success 200 {file} binary "Файл"
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 404 {object} handlers.ErrorResponse "Файл не найден"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/approvals/{approval_id}/files/{file_id} [get]
|
||||
func (s *ApprovalsReg) GetApprovalFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
ctx := r.Context()
|
||||
|
||||
// Получаем ID из URL
|
||||
approvalIDStr := chi.URLParam(r, "approval_id")
|
||||
fileIDStr := chi.URLParam(r, "file_id")
|
||||
|
||||
if approvalIDStr == "" || fileIDStr == "" {
|
||||
return nil, fmt.Errorf("approval_id and file_id are required")
|
||||
}
|
||||
|
||||
approvalID, err := parseUint64(approvalIDStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid approval_id: %w", err)
|
||||
}
|
||||
|
||||
fileID, err := parseUint64(fileIDStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid file_id: %w", err)
|
||||
}
|
||||
|
||||
// Получаем заявку
|
||||
approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get approval: %w", err)
|
||||
}
|
||||
if approval == nil {
|
||||
return nil, fmt.Errorf("approval not found")
|
||||
}
|
||||
|
||||
// Ищем файл в заявке
|
||||
var targetFile *typescore.ApprovalFile
|
||||
if approval.Files != nil {
|
||||
for i := range approval.Files {
|
||||
if approval.Files[i].ID != nil && *approval.Files[i].ID == fileID {
|
||||
targetFile = approval.Files[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Если файл не найден в кэше, загружаем все файлы заявки
|
||||
if targetFile == nil {
|
||||
files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get files: %w", err)
|
||||
}
|
||||
|
||||
for i := range files {
|
||||
if files[i].ID != nil && *files[i].ID == fileID {
|
||||
targetFile = files[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if targetFile == nil {
|
||||
return nil, fmt.Errorf("file not found")
|
||||
}
|
||||
|
||||
// Проверяем, что файл существует
|
||||
if targetFile.FileBase64 == nil || *targetFile.FileBase64 == "" {
|
||||
return nil, fmt.Errorf("file content is empty")
|
||||
}
|
||||
|
||||
// Декодируем base64
|
||||
fileData, err := base64.StdEncoding.DecodeString(*targetFile.FileBase64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode file: %w", err)
|
||||
}
|
||||
|
||||
// Определяем MIME тип
|
||||
fileName := ""
|
||||
if targetFile.FileName != nil {
|
||||
fileName = *targetFile.FileName
|
||||
}
|
||||
mimeType := getMimeType(fileName)
|
||||
|
||||
// Устанавливаем заголовки
|
||||
w.Header().Set("Content-Type", mimeType)
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, fileName))
|
||||
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileData)))
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000")
|
||||
|
||||
// Отправляем файл
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, err = w.Write(fileData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send file: %w", err)
|
||||
}
|
||||
|
||||
return nil, nil // nil означает, что мы уже отправили ответ
|
||||
}
|
||||
|
||||
// DownloadApprovalFileHandler Скачивание файла заявки
|
||||
// @Summary Скачивание файла заявки
|
||||
// @Description Скачивает файл по ID заявки и ID файла
|
||||
// @Tags approvals
|
||||
// @Produce application/octet-stream
|
||||
// @Param approval_id path integer true "ID заявки"
|
||||
// @Param file_id path integer true "ID файла"
|
||||
// @Success 200 {file} binary "Файл"
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 404 {object} handlers.ErrorResponse "Файл не найден"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/approvals/{approval_id}/files/{file_id}/download [get]
|
||||
func (s *ApprovalsReg) DownloadApprovalFileHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
ctx := r.Context()
|
||||
|
||||
approvalIDStr := chi.URLParam(r, "approval_id")
|
||||
fileIDStr := chi.URLParam(r, "file_id")
|
||||
|
||||
if approvalIDStr == "" || fileIDStr == "" {
|
||||
return nil, fmt.Errorf("approval_id and file_id are required")
|
||||
}
|
||||
|
||||
approvalID, err := parseUint64(approvalIDStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid approval_id: %w", err)
|
||||
}
|
||||
|
||||
fileID, err := parseUint64(fileIDStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid file_id: %w", err)
|
||||
}
|
||||
|
||||
approval, err := s.ipc.Database.Approval.GetApprovalByIDDB(ctx, approvalID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get approval: %w", err)
|
||||
}
|
||||
if approval == nil {
|
||||
return nil, fmt.Errorf("approval not found")
|
||||
}
|
||||
|
||||
var targetFile *typescore.ApprovalFile
|
||||
if approval.Files != nil {
|
||||
for i := range approval.Files {
|
||||
if approval.Files[i].ID != nil && *approval.Files[i].ID == fileID {
|
||||
targetFile = approval.Files[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if targetFile == nil {
|
||||
files, err := s.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, approvalID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get files: %w", err)
|
||||
}
|
||||
|
||||
for i := range files {
|
||||
if files[i].ID != nil && *files[i].ID == fileID {
|
||||
targetFile = files[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if targetFile == nil {
|
||||
return nil, fmt.Errorf("file not found")
|
||||
}
|
||||
|
||||
if targetFile.FileBase64 == nil || *targetFile.FileBase64 == "" {
|
||||
return nil, fmt.Errorf("file content is empty")
|
||||
}
|
||||
|
||||
fileData, err := base64.StdEncoding.DecodeString(*targetFile.FileBase64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode file: %w", err)
|
||||
}
|
||||
|
||||
fileName := ""
|
||||
if targetFile.FileName != nil {
|
||||
fileName = *targetFile.FileName
|
||||
}
|
||||
mimeType := getMimeType(fileName)
|
||||
|
||||
w.Header().Set("Content-Type", mimeType)
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
|
||||
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(fileData)))
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, err = w.Write(fileData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send file: %w", err)
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// getMimeType определяет MIME тип по расширению файла
|
||||
func getMimeType(fileName string) string {
|
||||
ext := strings.ToLower(filepath.Ext(fileName))
|
||||
|
||||
mimeTypes := map[string]string{
|
||||
// Images
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
".gif": "image/gif",
|
||||
".webp": "image/webp",
|
||||
".svg": "image/svg+xml",
|
||||
".bmp": "image/bmp",
|
||||
".ico": "image/x-icon",
|
||||
|
||||
// PDF
|
||||
".pdf": "application/pdf",
|
||||
|
||||
// Documents
|
||||
".txt": "text/plain",
|
||||
".doc": "application/msword",
|
||||
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
".xls": "application/vnd.ms-excel",
|
||||
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
".csv": "text/csv",
|
||||
|
||||
// Archives
|
||||
".zip": "application/zip",
|
||||
".rar": "application/vnd.rar",
|
||||
".7z": "application/x-7z-compressed",
|
||||
".tar": "application/x-tar",
|
||||
".gz": "application/gzip",
|
||||
|
||||
// Code
|
||||
".json": "application/json",
|
||||
".xml": "application/xml",
|
||||
".html": "text/html",
|
||||
".css": "text/css",
|
||||
".js": "application/javascript",
|
||||
|
||||
// Audio/Video
|
||||
".mp3": "audio/mpeg",
|
||||
".mp4": "video/mp4",
|
||||
".avi": "video/x-msvideo",
|
||||
".mov": "video/quicktime",
|
||||
".wmv": "video/x-ms-wmv",
|
||||
".flv": "video/x-flv",
|
||||
".webm": "video/webm",
|
||||
}
|
||||
|
||||
if mimeType, ok := mimeTypes[ext]; ok {
|
||||
return mimeType
|
||||
}
|
||||
|
||||
return "application/octet-stream"
|
||||
}
|
||||
|
||||
// parseUint64 парсит строку в uint64
|
||||
func parseUint64(s string) (uint64, error) {
|
||||
var result uint64
|
||||
_, err := fmt.Sscanf(s, "%d", &result)
|
||||
return result, err
|
||||
}
|
||||
|
|
@ -40,6 +40,17 @@ func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Re
|
|||
return nil, errW
|
||||
}
|
||||
|
||||
logrus.Infof("📥 GetApprovalsListHandler params: content=%v, status=%v",
|
||||
queryParams.Get("content"), queryParams.Get("status"))
|
||||
|
||||
contentSearch := queryParams.Get("content")
|
||||
|
||||
approvalParams.Content = nil
|
||||
|
||||
if contentSearch != "" && len(contentSearch) < 2 {
|
||||
return nil, errors.New("search query must be at least 2 characters")
|
||||
}
|
||||
|
||||
options := typescore.ListDbOptions{
|
||||
Filtering: approvalParams,
|
||||
Offset: offset,
|
||||
|
|
@ -48,12 +59,25 @@ func (s *ApprovalsReg) GetApprovalsListHandler(w http.ResponseWriter, r *http.Re
|
|||
}
|
||||
|
||||
ctx := context.Background()
|
||||
approvalsDbLst, total, errW := s.ipc.Database.Approval.GetApprovalsListDB(ctx, options)
|
||||
|
||||
var approvalsDbLst []*typescore.Approval
|
||||
var total uint64
|
||||
|
||||
if contentSearch != "" {
|
||||
approvalsDbLst, total, errW = s.ipc.Database.Approval.SearchApprovalsByContentDB(ctx, contentSearch, options)
|
||||
} else {
|
||||
approvalsDbLst, total, errW = s.ipc.Database.Approval.GetApprovalsListDB(ctx, options)
|
||||
}
|
||||
|
||||
if errW != nil {
|
||||
logrus.Errorf("❌ GetApprovalsListHandler error: %v", errW)
|
||||
return nil, errW
|
||||
}
|
||||
|
||||
// 🚀 Подгружаем связанные данные
|
||||
if approvalsDbLst == nil {
|
||||
approvalsDbLst = []*typescore.Approval{}
|
||||
}
|
||||
|
||||
for _, approval := range approvalsDbLst {
|
||||
s.enrichApproval(ctx, approval, false)
|
||||
}
|
||||
|
|
@ -301,6 +325,14 @@ func (s *ApprovalsReg) enrichApproval(ctx context.Context, approval *typescore.A
|
|||
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
|
||||
if err == nil && topic != nil {
|
||||
approval.Topic = topic
|
||||
|
||||
// 🆕 Подгружаем категорию темы
|
||||
if topic.CategoryID != nil {
|
||||
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
|
||||
if err == nil && category != nil {
|
||||
topic.Category = category
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -312,7 +344,7 @@ func (s *ApprovalsReg) enrichApproval(ctx context.Context, approval *typescore.A
|
|||
}
|
||||
}
|
||||
|
||||
// Подгружаем того, кто отозвал (если есть)
|
||||
// Подгружаем того, кто отозвал
|
||||
if approval.RevokedByID != nil {
|
||||
revokedBy, err := s.ipc.Database.User.GetUserByIDDB(ctx, *approval.RevokedByID)
|
||||
if err == nil && revokedBy != nil {
|
||||
|
|
@ -332,7 +364,6 @@ func (s *ApprovalsReg) enrichApproval(ctx context.Context, approval *typescore.A
|
|||
Filtering: &typescore.ApprovalStep{ApprovalID: approval.ID},
|
||||
})
|
||||
if err == nil {
|
||||
// Подгружаем информацию о согласующих для каждого шага
|
||||
for _, step := range steps {
|
||||
if step.ApproverID != nil {
|
||||
approver, err := s.ipc.Database.User.GetUserByIDDB(ctx, *step.ApproverID)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,73 @@
|
|||
package approvalshandler
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/reportcore"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/rest_admin_service/handlers"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DownloadApprovalsReportHandler Скачивание отчёта по заявкам в формате XLSX
|
||||
// @Summary Скачивание отчёта по заявкам
|
||||
// @Description Формирует и возвращает XLSX-файл отчёта по заявкам за указанный период
|
||||
// @Tags approvals
|
||||
// @Accept json
|
||||
// @Produce application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
|
||||
// @Param date_from query string false "Начальная дата (YYYY-MM-DD)"
|
||||
// @Param date_to query string false "Конечная дата (YYYY-MM-DD)"
|
||||
// @Param all_access query boolean false "Полный доступ (игнорировать фильтрацию по пользователю)"
|
||||
// @Success 200 {file} binary "XLSX файл"
|
||||
// @Failure 400 {object} handlers.ErrorResponse "Некорректный запрос"
|
||||
// @Failure 500 {object} handlers.ErrorResponse "Ошибка сервера"
|
||||
// @Router /api/approvals/report/download [get]
|
||||
func (s *ApprovalsReg) DownloadApprovalsReportHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
queryParams := r.URL.Query()
|
||||
|
||||
filter := typescore.ReportFilter{}
|
||||
|
||||
// Парсим даты
|
||||
if dateFromStr := queryParams.Get("date_from"); dateFromStr != "" {
|
||||
dateFrom, err := time.Parse("2006-01-02", dateFromStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid date_from format, use YYYY-MM-DD")
|
||||
}
|
||||
filter.DateFrom = &dateFrom
|
||||
}
|
||||
|
||||
if dateToStr := queryParams.Get("date_to"); dateToStr != "" {
|
||||
dateTo, err := time.Parse("2006-01-02", dateToStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid date_to format, use YYYY-MM-DD")
|
||||
}
|
||||
filter.DateTo = &dateTo
|
||||
}
|
||||
|
||||
// В админке всегда all_access = true (админ видит все заявки)
|
||||
filter.AllAccess = true
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
// Получаем заявки для отчёта
|
||||
approvals, err := s.ipc.Database.Approval.GetApprovalsForReportDB(ctx, filter)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get approvals for report: %w", err)
|
||||
}
|
||||
|
||||
if len(approvals) == 0 {
|
||||
return nil, fmt.Errorf("no approvals found for the specified period")
|
||||
}
|
||||
|
||||
excelBytes, err := reportcore.BuildExcelApprovalsReport(ctx, s.ipc.Database, approvals)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to build excel report: %w", err)
|
||||
}
|
||||
|
||||
fileName := fmt.Sprintf("Согласования_%s.xlsx", time.Now().Format("02.01.2006_15-04"))
|
||||
|
||||
return &handlers.ExcelFileResponse{
|
||||
Data: excelBytes,
|
||||
FileName: fileName,
|
||||
}, nil
|
||||
}
|
||||
|
|
@ -31,10 +31,17 @@ func RegisterApprovalRoutes(
|
|||
|
||||
// Отчёты
|
||||
handlers.RegisterRoute(r, http.MethodGet, "/report", s.GetApprovalsForReportHandler)
|
||||
handlers.RegisterRoute(r, http.MethodGet, "/report/download", s.DownloadApprovalsReportHandler)
|
||||
|
||||
r.Get("/{id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
|
||||
HandlerFunc: s.GetApprovalByIDHandler,
|
||||
}))
|
||||
r.Get("/{approval_id}/files/{file_id}", handlers.WrapHandlerF(handlers.WrapHandlerParams{
|
||||
HandlerFunc: s.GetApprovalFileHandler,
|
||||
}))
|
||||
r.Get("/{approval_id}/files/{file_id}/download", handlers.WrapHandlerF(handlers.WrapHandlerParams{
|
||||
HandlerFunc: s.DownloadApprovalFileHandler,
|
||||
}))
|
||||
})
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
|
@ -135,14 +136,13 @@ func (s *AuthReg) loginAcc(ctx context.Context, login, password *string, ip, dev
|
|||
|
||||
keyPath := fmt.Sprintf("%s:admin:%d", variables.RedisPathUserAuthSessions, *loggedUser.ID)
|
||||
sessionJSON, err := s.ipc.RedisClient.Get(ctx, keyPath)
|
||||
if err != nil {
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
return nil, err
|
||||
}
|
||||
// Создаем переменную для десериализации
|
||||
|
||||
var session typescore.UsersSessions
|
||||
|
||||
if sessionJSON != "" {
|
||||
// Парсим JSON
|
||||
if err := json.Unmarshal([]byte(sessionJSON), &session); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -161,9 +161,14 @@ func (s *AuthReg) loginAcc(ctx context.Context, login, password *string, ip, dev
|
|||
CreatedAt: &now,
|
||||
})
|
||||
|
||||
err := s.ipc.RedisClient.Set(ctx, fmt.Sprintf("%s:admin:%d", variables.RedisPathUserAuthSessions, *loggedUser.ID), session, 0)
|
||||
sessionJSONBytes, err := json.Marshal(session)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("failed to marshal session: %w", err)
|
||||
}
|
||||
|
||||
err = s.ipc.RedisClient.Set(ctx, keyPath, string(sessionJSONBytes), 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to save session to Redis: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,439 @@
|
|||
package dashboardhandler
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/core/utilscore"
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// GetDashboardStatsHandler — возвращает все данные для дашборда одним запросом
|
||||
func (s *DashboardReg) GetDashboardStatsHandler(w http.ResponseWriter, r *http.Request) (interface{}, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
// === 1. KPI: считаем сущности ===
|
||||
totalUsers := s.countUsers(ctx, &typescore.User{})
|
||||
activeUsers := s.countUsers(ctx, &typescore.User{IsBlocked: boolPtr(false), IsFired: boolPtr(false)})
|
||||
blockedUsers := s.countUsers(ctx, &typescore.User{IsBlocked: boolPtr(true)})
|
||||
|
||||
totalApprovals := s.countApprovals(ctx, &typescore.Approval{})
|
||||
pendingApprovals := s.countApprovalsByStatus(ctx, "pending")
|
||||
revisionApprovals := s.countApprovalsByStatus(ctx, "revision")
|
||||
approvedToday := s.countApprovalsByStatusAndDate(ctx, "approved", time.Now())
|
||||
|
||||
totalTopics := s.countTopics(ctx, &typescore.ApprovalTopic{})
|
||||
activeTopics := s.countTopics(ctx, &typescore.ApprovalTopic{IsActive: boolPtr(true)})
|
||||
totalCategories := s.countCategories(ctx)
|
||||
totalDepartments := s.countDepartments(ctx)
|
||||
totalRoles := s.countRoles(ctx)
|
||||
totalExecutors := s.countExecutors(ctx)
|
||||
|
||||
// === 2. Распределение заявок по статусам ===
|
||||
statuses := []string{"draft", "pending", "approved", "rejected", "revoked", "revision"}
|
||||
statusData := make([]map[string]interface{}, 0, len(statuses))
|
||||
for _, status := range statuses {
|
||||
count := s.countApprovalsByStatus(ctx, status)
|
||||
statusData = append(statusData, map[string]interface{}{
|
||||
"status": status,
|
||||
"count": count,
|
||||
})
|
||||
}
|
||||
|
||||
// === 3. Динамика за последние 7 дней ===
|
||||
dailyData := make([]map[string]interface{}, 0, 7)
|
||||
now := time.Now()
|
||||
for i := 6; i >= 0; i-- {
|
||||
date := now.AddDate(0, 0, -i)
|
||||
created := s.countApprovalsCreatedOn(ctx, date)
|
||||
approved := s.countApprovalsApprovedOn(ctx, date)
|
||||
|
||||
dailyData = append(dailyData, map[string]interface{}{
|
||||
"date": date.Format("2006-01-02"),
|
||||
"created": created,
|
||||
"approved": approved,
|
||||
})
|
||||
}
|
||||
|
||||
// === 4. Топ-5 тем по количеству заявок ===
|
||||
topTopics := s.getTopTopics(ctx, 5)
|
||||
|
||||
// === 5. Топ-5 согласующих ===
|
||||
topApprovers := s.getTopApprovers(ctx, 5)
|
||||
|
||||
// === 6. Старые pending заявки (>7 дней) ===
|
||||
oldPendingCount := s.countOldPendingApprovals(ctx, 7)
|
||||
|
||||
return map[string]interface{}{
|
||||
"users": map[string]int{
|
||||
"total": totalUsers,
|
||||
"active": activeUsers,
|
||||
"blocked": blockedUsers,
|
||||
},
|
||||
"approvals": map[string]int{
|
||||
"total": totalApprovals,
|
||||
"pending": pendingApprovals,
|
||||
"revision": revisionApprovals,
|
||||
"today": approvedToday,
|
||||
},
|
||||
"topics": map[string]int{
|
||||
"total": totalTopics,
|
||||
"active": activeTopics,
|
||||
},
|
||||
"categories": totalCategories,
|
||||
"departments": totalDepartments,
|
||||
"roles": totalRoles,
|
||||
"executors": totalExecutors,
|
||||
"statusData": statusData,
|
||||
"dailyData": dailyData,
|
||||
"topTopics": topTopics,
|
||||
"topApprovers": topApprovers,
|
||||
"oldPendingCount": oldPendingCount,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Вспомогательные методы для подсчёта
|
||||
// ============================================================
|
||||
|
||||
func (s *DashboardReg) countUsers(ctx context.Context, filter *typescore.User) int {
|
||||
opts := typescore.ListDbOptions{
|
||||
Filtering: filter,
|
||||
Limit: utilscore.PointerToUint64(10000), // считаем через len
|
||||
}
|
||||
list, _, err := s.ipc.Database.User.GetUsersListDB(ctx, opts)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return len(list)
|
||||
}
|
||||
|
||||
func (s *DashboardReg) countApprovals(ctx context.Context, filter *typescore.Approval) int {
|
||||
opts := typescore.ListDbOptions{
|
||||
Filtering: filter,
|
||||
Limit: utilscore.PointerToUint64(10000),
|
||||
}
|
||||
list, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return len(list)
|
||||
}
|
||||
|
||||
func (s *DashboardReg) countApprovalsByStatus(ctx context.Context, status string) int {
|
||||
return s.countApprovals(ctx, &typescore.Approval{Status: &status})
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
list, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
count := 0
|
||||
today := date.Format("2006-01-02")
|
||||
for _, a := range list {
|
||||
if a.CreatedAt != nil && a.CreatedAt.Format("2006-01-02") == today {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func (s *DashboardReg) countApprovalsCreatedOn(ctx context.Context, date time.Time) int {
|
||||
opts := typescore.ListDbOptions{
|
||||
Filtering: &typescore.Approval{},
|
||||
Limit: utilscore.PointerToUint64(10000),
|
||||
}
|
||||
list, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
count := 0
|
||||
target := date.Format("2006-01-02")
|
||||
for _, a := range list {
|
||||
if a.CreatedAt != nil && a.CreatedAt.Format("2006-01-02") == target {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
steps, _, err := s.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, opts)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
// Считаем уникальные заявки
|
||||
uniqueApprovals := make(map[uint64]bool)
|
||||
target := date.Format("2006-01-02")
|
||||
for _, step := range steps {
|
||||
if step.ActedAt != nil && step.ActedAt.Format("2006-01-02") == target && step.ApprovalID != nil {
|
||||
uniqueApprovals[*step.ApprovalID] = true
|
||||
}
|
||||
}
|
||||
return len(uniqueApprovals)
|
||||
}
|
||||
|
||||
func (s *DashboardReg) countTopics(ctx context.Context, filter *typescore.ApprovalTopic) int {
|
||||
opts := typescore.ListDbOptions{
|
||||
Filtering: filter,
|
||||
Limit: utilscore.PointerToUint64(10000),
|
||||
}
|
||||
list, _, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicsListDB(ctx, opts)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return len(list)
|
||||
}
|
||||
|
||||
func (s *DashboardReg) countCategories(ctx context.Context) int {
|
||||
opts := typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTopicCategory{},
|
||||
Limit: utilscore.PointerToUint64(10000),
|
||||
}
|
||||
list, _, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryListDB(ctx, opts)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return len(list)
|
||||
}
|
||||
|
||||
func (s *DashboardReg) countDepartments(ctx context.Context) int {
|
||||
opts := typescore.ListDbOptions{
|
||||
Filtering: &typescore.Department{},
|
||||
Limit: utilscore.PointerToUint64(10000),
|
||||
}
|
||||
list, _, err := s.ipc.Database.Department.GetDepartmentsListDB(ctx, opts)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return len(list)
|
||||
}
|
||||
|
||||
func (s *DashboardReg) countRoles(ctx context.Context) int {
|
||||
opts := typescore.ListDbOptions{
|
||||
Filtering: &typescore.Role{},
|
||||
Limit: utilscore.PointerToUint64(10000),
|
||||
}
|
||||
list, _, err := s.ipc.Database.Role.GetRolesListDB(ctx, opts)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return len(list)
|
||||
}
|
||||
|
||||
func (s *DashboardReg) countExecutors(ctx context.Context) int {
|
||||
opts := typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTopicExecutor{},
|
||||
Limit: utilscore.PointerToUint64(10000),
|
||||
}
|
||||
list, _, err := s.ipc.Database.ApprovalTopicExecutor.GetApprovalTopicExecutorListDB(ctx, opts)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return len(list)
|
||||
}
|
||||
|
||||
func (s *DashboardReg) countOldPendingApprovals(ctx context.Context, days int) int {
|
||||
opts := typescore.ListDbOptions{
|
||||
Filtering: &typescore.Approval{Status: strPtr("pending")},
|
||||
Limit: utilscore.PointerToUint64(10000),
|
||||
}
|
||||
list, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
cutoff := time.Now().AddDate(0, 0, -days)
|
||||
count := 0
|
||||
for _, a := range list {
|
||||
if a.CreatedAt != nil && a.CreatedAt.Before(cutoff) {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Топ-5 тем по количеству заявок
|
||||
// ============================================================
|
||||
|
||||
func (s *DashboardReg) getTopTopics(ctx context.Context, limit int) []map[string]interface{} {
|
||||
// Получаем все заявки
|
||||
opts := typescore.ListDbOptions{
|
||||
Filtering: &typescore.Approval{},
|
||||
Limit: utilscore.PointerToUint64(10000),
|
||||
}
|
||||
approvals, _, err := s.ipc.Database.Approval.GetApprovalsListDB(ctx, opts)
|
||||
if err != nil {
|
||||
return []map[string]interface{}{}
|
||||
}
|
||||
|
||||
// Считаем количество заявок по topic_id
|
||||
topicCounts := make(map[uint64]int)
|
||||
topicPending := make(map[uint64]int)
|
||||
for _, a := range approvals {
|
||||
if a.TopicID == nil {
|
||||
continue
|
||||
}
|
||||
topicCounts[*a.TopicID]++
|
||||
if a.Status != nil && *a.Status == "pending" {
|
||||
topicPending[*a.TopicID]++
|
||||
}
|
||||
}
|
||||
|
||||
// Сортируем по количеству (вручную, без 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 {
|
||||
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})
|
||||
}
|
||||
for i := 0; i < len(entries); i++ {
|
||||
for j := i + 1; j < len(entries); j++ {
|
||||
if entries[j].total > entries[i].total {
|
||||
entries[i], entries[j] = entries[j], entries[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Берём топ-N
|
||||
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)
|
||||
if err != nil || user == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
fullName := ""
|
||||
if user.FullName != nil {
|
||||
fullName = *user.FullName
|
||||
}
|
||||
|
||||
deptName := ""
|
||||
if user.DepartmentID != nil {
|
||||
dept, err := s.ipc.Database.Department.GetDepartmentByIDDB(ctx, *user.DepartmentID)
|
||||
if err == nil && dept != nil && dept.Name != nil {
|
||||
deptName = *dept.Name
|
||||
}
|
||||
}
|
||||
|
||||
result = append(result, map[string]interface{}{
|
||||
"user_id": entry.id,
|
||||
"full_name": fullName,
|
||||
"department_name": deptName,
|
||||
"total_steps": entry.total,
|
||||
"pending_steps": entry.pending,
|
||||
})
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func boolPtr(b bool) *bool { return &b }
|
||||
func strPtr(s string) *string { return &s }
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package dashboardhandler
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/rest_admin_service/handlers"
|
||||
typesm "bitrix_balancer_api/rest_admin_service/types"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type DashboardReg struct {
|
||||
ipc *typesm.InternalProviderControl
|
||||
}
|
||||
|
||||
// RegisterDashboardRoutes регистрирует маршруты для дашборда
|
||||
func RegisterDashboardRoutes(
|
||||
r chi.Router,
|
||||
ipc *typesm.InternalProviderControl,
|
||||
) error {
|
||||
s := &DashboardReg{
|
||||
ipc: ipc,
|
||||
}
|
||||
|
||||
r.Route("/api/dashboard", func(r chi.Router) {
|
||||
r.Use(handlers.AccessCodeVerifier(ipc.Config))
|
||||
r.Use(handlers.JWTVerifier(ipc.Config, ipc.Database.Admin, ipc.RedisClient))
|
||||
|
||||
// 📊 Основная статистика (всё сразу одним запросом)
|
||||
handlers.RegisterRoute(r, http.MethodGet, "/stats", s.GetDashboardStatsHandler)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -12,11 +12,12 @@ import (
|
|||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func BasicAuthMiddleware(username, password string) func(http.Handler) http.Handler {
|
||||
|
|
@ -42,29 +43,43 @@ func JWTVerifier(cfg *configcore.Config, adminDB dbcore.AdminDBI, redisModule *r
|
|||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if cfg.Secrets.AuthJWT.AdminSecret == "" {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
}).Error("JWTVerifier: AdminSecret is empty")
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
}).Warn("JWTVerifier: Authorization header is empty")
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
deviceID := r.Header.Get("x-device-id")
|
||||
if deviceID == "" {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
}).Warn("JWTVerifier: x-device-id header is empty")
|
||||
http.Error(w, "Unauthorized device", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if redisModule == nil {
|
||||
logrus.Error("JWTVerifier: Redis storage not initialized")
|
||||
http.Error(w, "Internal server error: Redis storage not initialized", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.Split(authHeader, " ")
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"auth_header": authHeader,
|
||||
}).Warn("JWTVerifier: Invalid authorization header format")
|
||||
http.Error(w, "Invalid authorization header", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
|
@ -72,12 +87,19 @@ func JWTVerifier(cfg *configcore.Config, adminDB dbcore.AdminDBI, redisModule *r
|
|||
|
||||
_, claims, err := securecore.VerifyToken(tokenString, cfg.Secrets.AuthJWT.AdminSecret)
|
||||
if err != nil {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"error": err.Error(),
|
||||
}).Warn("JWTVerifier: Token verification failed")
|
||||
http.Error(w, "Invalid token", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
userIDFloat, ok := claims[securecore.IDContextKey.String()].(float64)
|
||||
if !ok {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
}).Warn("JWTVerifier: Missing user_id in token claims")
|
||||
http.Error(w, "Invalid token: missing user_id", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
|
@ -90,11 +112,20 @@ func JWTVerifier(cfg *configcore.Config, adminDB dbcore.AdminDBI, redisModule *r
|
|||
},
|
||||
})
|
||||
if errW != nil || len(adminList) == 0 {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"user_id": userID,
|
||||
"error": errW,
|
||||
}).Warn("JWTVerifier: Admin not found or blocked")
|
||||
http.Error(w, "Admin not found or blocked", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if adminList[0].IsBlocked == nil || *adminList[0].IsBlocked {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"user_id": userID,
|
||||
}).Warn("JWTVerifier: Account is blocked")
|
||||
http.Error(w, "Forbidden: account is blocked", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
|
@ -103,21 +134,42 @@ func JWTVerifier(cfg *configcore.Config, adminDB dbcore.AdminDBI, redisModule *r
|
|||
|
||||
sessionJSON, err := redisModule.Get(ctx, fmt.Sprintf("%s:admin:%d", variables.RedisPathUserAuthSessions, userID))
|
||||
if err != nil || sessionJSON == "" {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"user_id": userID,
|
||||
"error": err,
|
||||
}).Warn("JWTVerifier: User session not found in Redis")
|
||||
http.Error(w, "User session not found. Please authorize again", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var session typescore.UsersSessions
|
||||
if err := json.Unmarshal([]byte(sessionJSON), &session); err != nil {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"user_id": userID,
|
||||
"error": err.Error(),
|
||||
}).Warn("JWTVerifier: Failed to unmarshal session")
|
||||
http.Error(w, "Failed to get user session data. Please authorize again", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if !securecore.FindDeviceID(session.AuthorizedDevices, deviceID) {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"user_id": userID,
|
||||
"device_id": deviceID,
|
||||
}).Warn("JWTVerifier: Device not authorized")
|
||||
http.Error(w, "Unauthorized device", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"user_id": userID,
|
||||
"device_id": deviceID,
|
||||
}).Debug("JWTVerifier: Request authorized")
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
|
@ -127,33 +179,65 @@ func JWTVerifier(cfg *configcore.Config, adminDB dbcore.AdminDBI, redisModule *r
|
|||
func AccessCodeVerifier(cfg *configcore.Config) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// 🆕 Логируем начало проверки
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"method": r.Method,
|
||||
"remote": r.RemoteAddr,
|
||||
}).Debug("AccessCodeVerifier: Starting verification")
|
||||
|
||||
// Проверка 1: Секреты в конфиге
|
||||
if cfg.Secrets.ApiPublicAdmin == "" || cfg.Secrets.ApiPrivateAdmin == "" {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"api_public_empty": cfg.Secrets.ApiPublicAdmin == "",
|
||||
"api_private_empty": cfg.Secrets.ApiPrivateAdmin == "",
|
||||
}).Error("AccessCodeVerifier: API secrets not configured")
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Получаем заголовки
|
||||
authHeader := r.Header.Get("ApiKey")
|
||||
timestampStr := r.Header.Get("X-Timestamp")
|
||||
deviceID := r.Header.Get("x-device-id")
|
||||
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"has_api_key": authHeader != "",
|
||||
"has_timestamp": timestampStr != "",
|
||||
"device_id": deviceID,
|
||||
}).Debug("AccessCodeVerifier: Headers received")
|
||||
|
||||
// Проверка 2: Наличие заголовков
|
||||
if authHeader == "" || timestampStr == "" {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"api_key_empty": authHeader == "",
|
||||
"timestamp_empty": timestampStr == "",
|
||||
"all_headers": r.Header,
|
||||
}).Warn("AccessCodeVerifier: Missing required headers")
|
||||
http.Error(w, "Unauthorized client", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Парсим timestamp как Unix timestamp
|
||||
// Проверка 3: Парсинг timestamp
|
||||
timestampUnix, err := strconv.ParseInt(timestampStr, 10, 64)
|
||||
if err != nil {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"timestamp": timestampStr,
|
||||
"error": err.Error(),
|
||||
}).Warn("AccessCodeVerifier: Invalid timestamp format")
|
||||
http.Error(w, "Invalid timestamp", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Конвертируем Unix timestamp в time.Time
|
||||
// Unix timestamp всегда представляет время в UTC
|
||||
timestampTime := time.Unix(timestampUnix, 0).UTC()
|
||||
now := time.Now().UTC()
|
||||
|
||||
// Округляем время до минут, игнорируя секунды и миллисекунды
|
||||
// Используем time.Date для явного обнуления секунд и наносекунд
|
||||
// Округляем время до минут
|
||||
timestampTimeRounded := time.Date(
|
||||
timestampTime.Year(), timestampTime.Month(), timestampTime.Day(),
|
||||
timestampTime.Hour(), timestampTime.Minute(), 0, 0, time.UTC,
|
||||
|
|
@ -163,35 +247,72 @@ func AccessCodeVerifier(cfg *configcore.Config) func(http.Handler) http.Handler
|
|||
now.Hour(), now.Minute(), 0, 0, time.UTC,
|
||||
)
|
||||
|
||||
// Проверяем, что timestamp не старше 3 минут и не в будущем
|
||||
// Используем Before/After для более точной проверки времени
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"timestamp_received": timestampTime.Format(time.RFC3339),
|
||||
"timestamp_rounded": timestampTimeRounded.Format(time.RFC3339),
|
||||
"now": now.Format(time.RFC3339),
|
||||
"now_rounded": nowRounded.Format(time.RFC3339),
|
||||
}).Debug("AccessCodeVerifier: Timestamp parsed")
|
||||
|
||||
// Проверка 4: Timestamp не старше 3 минут
|
||||
threeMinutesAgo := nowRounded.Add(-3 * time.Minute)
|
||||
|
||||
// Проверяем, что timestamp не не старше 3 минут
|
||||
if timestampTimeRounded.Before(threeMinutesAgo) {
|
||||
log.Printf("Timestamp expired - received: %v (rounded: %v), current: %v (rounded: %v), 3min ago: %v",
|
||||
timestampTime, timestampTimeRounded, now, nowRounded, threeMinutesAgo)
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"timestamp": timestampTimeRounded.Format(time.RFC3339),
|
||||
"three_minutes_ago": threeMinutesAgo.Format(time.RFC3339),
|
||||
"now": nowRounded.Format(time.RFC3339),
|
||||
}).Warn("AccessCodeVerifier: Timestamp expired")
|
||||
http.Error(w, "Timestamp expired", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Проверяем, что timestamp не в будущем
|
||||
// Проверка 5: Timestamp не в будущем
|
||||
if timestampTimeRounded.After(nowRounded) {
|
||||
log.Printf("Timestamp in future - received: %v (rounded: %v), current: %v (rounded: %v)",
|
||||
timestampTime, timestampTimeRounded, now, nowRounded)
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"timestamp": timestampTimeRounded.Format(time.RFC3339),
|
||||
"now": nowRounded.Format(time.RFC3339),
|
||||
}).Warn("AccessCodeVerifier: Timestamp in future")
|
||||
http.Error(w, "Timestamp in future", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Генерируем ожидаемую подпись
|
||||
expectedSignature := utilscore.GenerateHMACSignature(cfg.Secrets.ApiPublicAdmin, timestampStr, cfg.Secrets.ApiPrivateAdmin)
|
||||
// Проверка 6: Генерация и сравнение подписи
|
||||
expectedSignature := utilscore.GenerateHMACSignature(
|
||||
cfg.Secrets.ApiPublicAdmin,
|
||||
timestampStr,
|
||||
cfg.Secrets.ApiPrivateAdmin,
|
||||
)
|
||||
|
||||
// Сравниваем безопасно
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"public_key": cfg.Secrets.ApiPublicAdmin[:min(10, len(cfg.Secrets.ApiPublicAdmin))] + "...",
|
||||
"timestamp": timestampStr,
|
||||
"expected_signature": expectedSignature[:min(20, len(expectedSignature))] + "...",
|
||||
"received_signature": authHeader[:min(20, len(authHeader))] + "...",
|
||||
"signatures_match": expectedSignature == authHeader,
|
||||
}).Debug("AccessCodeVerifier: Comparing signatures")
|
||||
|
||||
// Безопасное сравнение
|
||||
if !utilscore.HmacEquals(expectedSignature, authHeader) {
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
"expected_signature": expectedSignature,
|
||||
"received_signature": authHeader,
|
||||
"expected_length": len(expectedSignature),
|
||||
"received_length": len(authHeader),
|
||||
}).Warn("AccessCodeVerifier: Signature mismatch")
|
||||
http.Error(w, "Unauthorized client", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
logrus.WithFields(logrus.Fields{
|
||||
"path": r.URL.Path,
|
||||
}).Debug("AccessCodeVerifier: Verification successful")
|
||||
|
||||
ctx := context.WithValue(r.Context(), securecore.AccessContextKey, authHeader)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
|
|
@ -215,3 +336,11 @@ func GetIPFromContext(ctx context.Context) (string, error) {
|
|||
}
|
||||
return address, nil
|
||||
}
|
||||
|
||||
// min возвращает минимальное из двух int
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,15 +3,23 @@ package handlers
|
|||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// ErrorResponse структура для возврата ошибок
|
||||
type ErrorResponse struct {
|
||||
ErrorCode int `json:"error_code"` // Код ошибки
|
||||
ErrorDescription string `json:"error_description"` // Описание ошибки
|
||||
ErrorCode int `json:"error_code"`
|
||||
ErrorDescription string `json:"error_description"`
|
||||
}
|
||||
|
||||
// 🆕 ExcelFileResponse — специальный тип ответа для скачивания файлов
|
||||
type ExcelFileResponse struct {
|
||||
Data []byte // Содержимое файла
|
||||
FileName string // Имя файла для скачивания
|
||||
}
|
||||
|
||||
// WrapHandlerParams структура для параметров обертки
|
||||
|
|
@ -25,7 +33,6 @@ type responseWriterWrapper struct {
|
|||
wroteHeader bool
|
||||
}
|
||||
|
||||
// WriteHeader перехватывает вызов WriteHeader
|
||||
func (rw *responseWriterWrapper) WriteHeader(statusCode int) {
|
||||
if !rw.wroteHeader {
|
||||
rw.ResponseWriter.WriteHeader(statusCode)
|
||||
|
|
@ -33,10 +40,9 @@ func (rw *responseWriterWrapper) WriteHeader(statusCode int) {
|
|||
}
|
||||
}
|
||||
|
||||
// Write перехватывает вызов Write
|
||||
func (rw *responseWriterWrapper) Write(b []byte) (int, error) {
|
||||
if !rw.wroteHeader {
|
||||
rw.WriteHeader(http.StatusOK) // Устанавливаем статус по умолчанию
|
||||
rw.WriteHeader(http.StatusOK)
|
||||
}
|
||||
return rw.ResponseWriter.Write(b)
|
||||
}
|
||||
|
|
@ -46,10 +52,36 @@ func WrapHandlerF(p WrapHandlerParams) http.HandlerFunc {
|
|||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
rw := &responseWriterWrapper{ResponseWriter: w}
|
||||
payload, err := p.HandlerFunc(rw, r)
|
||||
|
||||
// 🆕 Проверяем, не файл ли это
|
||||
if fileResp, ok := payload.(*ExcelFileResponse); ok && err == nil {
|
||||
serveExcelFile(rw, fileResp)
|
||||
return
|
||||
}
|
||||
|
||||
// Обычный JSON ответ
|
||||
respondWithJSON(rw, err, payload)
|
||||
}
|
||||
}
|
||||
|
||||
// 🆕 serveExcelFile отправляет файл как бинарный ответ
|
||||
func serveExcelFile(w http.ResponseWriter, fileResp *ExcelFileResponse) {
|
||||
// Устанавливаем заголовки ДО отправки тела
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileResp.FileName))
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(fileResp.Data)))
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
// Отправляем содержимое файла
|
||||
if _, err := w.Write(fileResp.Data); err != nil {
|
||||
// Логируем ошибку, но заголовки уже отправлены
|
||||
// Можно добавить логгер здесь
|
||||
_ = err
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterRoute вспомогательная функция для регистрации маршрутов
|
||||
func RegisterRoute(r chi.Router, method, path string, handlerFunc func(http.ResponseWriter, *http.Request) (interface{}, error)) {
|
||||
wrappedHandler := WrapHandlerF(WrapHandlerParams{
|
||||
|
|
@ -70,7 +102,7 @@ func RegisterRoute(r chi.Router, method, path string, handlerFunc func(http.Resp
|
|||
}
|
||||
}
|
||||
|
||||
// ParseRequestBodyPost обрабатывает тело запроса и заполняет структуру запроса
|
||||
// ParseRequestBodyPost обрабатывает тело запроса
|
||||
func ParseRequestBodyPost(r *http.Request, v interface{}) error {
|
||||
defer r.Body.Close()
|
||||
|
||||
|
|
@ -118,7 +150,6 @@ func respondWithJSON(w http.ResponseWriter, err error, payload interface{}) {
|
|||
}
|
||||
}
|
||||
|
||||
// Проверяем, является ли w нашим responseWriterWrapper
|
||||
if rw, ok := w.(*responseWriterWrapper); ok {
|
||||
if !rw.wroteHeader {
|
||||
rw.WriteHeader(status)
|
||||
|
|
|
|||
|
|
@ -438,4 +438,19 @@ func (s *HierarchiesReg) enrichHierarchy(ctx context.Context, h *typescore.UserH
|
|||
h.Department = department
|
||||
}
|
||||
}
|
||||
|
||||
if h.TopicCategoryID != nil {
|
||||
category, err := s.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *h.TopicCategoryID)
|
||||
if err == nil && category != nil {
|
||||
h.TopicCategory = category
|
||||
}
|
||||
}
|
||||
|
||||
// 🆕 Подгружаем тему
|
||||
if h.TopicID != nil {
|
||||
topic, err := s.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *h.TopicID)
|
||||
if err == nil && topic != nil {
|
||||
h.Topic = topic
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -342,7 +342,7 @@ func (h *Handler) HandleRevokeWithComment(bot *tgbotapi.BotAPI, chatID int64, te
|
|||
return
|
||||
}
|
||||
|
||||
h.handleRevokeCancellationTask(bot, ctx, approval, revoker, comment)
|
||||
h.handleRevokeCancellationTask(bot, ctx, approval)
|
||||
|
||||
revokerName := "—"
|
||||
if revoker.FullName != nil {
|
||||
|
|
|
|||
|
|
@ -109,7 +109,7 @@ func (h *Handler) sendTaskCard(bot *tgbotapi.BotAPI, chatID int64, approval *typ
|
|||
}
|
||||
}
|
||||
if len(taskFiles) > 0 {
|
||||
text += "\n\n📎 <b>Прикреплённые файлы:</b>\n"
|
||||
text += "\n\n📎 <b>Прикреплённые файлы к задаче:</b>\n"
|
||||
for i, name := range taskFiles {
|
||||
text += fmt.Sprintf("%d. %s\n", i+1, name)
|
||||
}
|
||||
|
|
@ -120,7 +120,7 @@ func (h *Handler) sendTaskCard(bot *tgbotapi.BotAPI, chatID int64, approval *typ
|
|||
|
||||
msg := tgbotapi.NewMessage(chatID, text)
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID)
|
||||
msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, len(allFiles))
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
}
|
||||
|
||||
|
|
@ -162,7 +162,6 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback
|
|||
}
|
||||
}
|
||||
|
||||
// 🚀 Проверка обязательности файла — ищем файлы, привязанные именно к этой задаче
|
||||
requireFile := task.RequireFile != nil && *task.RequireFile
|
||||
if requireFile {
|
||||
files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *task.ApprovalID)
|
||||
|
|
@ -175,17 +174,18 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback
|
|||
}
|
||||
}
|
||||
if !hasExecutorFile {
|
||||
files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *task.ApprovalID)
|
||||
|
||||
msg := tgbotapi.NewMessage(chatID,
|
||||
"⚠️ <b>Для завершения необходимо прикрепить файл.</b>\n\n"+
|
||||
"Нажмите «📎 Прикрепить файл», прикрепите документ, затем нажмите «Выполнено».")
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID)
|
||||
msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, len(files))
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Обновляем статус текущей задачи
|
||||
now := time.Now()
|
||||
completedStatus := "completed"
|
||||
task.Status = &completedStatus
|
||||
|
|
@ -235,7 +235,6 @@ func (h *Handler) HandleCompleteTask(bot *tgbotapi.BotAPI, cq *tgbotapi.Callback
|
|||
approvalTopic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
|
||||
if approvalTopic != nil && approvalTopic.Code != nil {
|
||||
topicCode := *approvalTopic.Code
|
||||
// Проверяем, что тема относится к "Заказу товаров"
|
||||
if strings.HasPrefix(topicCode, "goods_order_") {
|
||||
hintMsg := tgbotapi.NewMessage(*initiator.TelegramID,
|
||||
"📦 <i>Следи за выполнением заказа</i>")
|
||||
|
|
@ -296,13 +295,7 @@ func (h *Handler) activateNextTask(bot *tgbotapi.BotAPI, ctx context.Context, ap
|
|||
// handleRevokeCancellationTask — вызывается при отзыве заявки.
|
||||
// Если задача выполнена — создаём задачу на обращение изменений.
|
||||
// Если задача ожидает — спрашиваем исполнителя, вносил ли он изменения.
|
||||
func (h *Handler) handleRevokeCancellationTask(
|
||||
bot *tgbotapi.BotAPI,
|
||||
ctx context.Context,
|
||||
approval *typescore.Approval,
|
||||
revoker *typescore.User,
|
||||
revokeComment string,
|
||||
) {
|
||||
func (h *Handler) handleRevokeCancellationTask(bot *tgbotapi.BotAPI, ctx context.Context, approval *typescore.Approval) {
|
||||
if approval.ID == nil {
|
||||
return
|
||||
}
|
||||
|
|
@ -395,6 +388,8 @@ func (h *Handler) createReversalTask(
|
|||
return
|
||||
}
|
||||
|
||||
files, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
|
||||
|
||||
msg := tgbotapi.NewMessage(*executor.TelegramID, fmt.Sprintf(
|
||||
"⚠️ <b>Заявка #%d отозвана — требуется обратить изменения</b>\n\n"+
|
||||
"📋 <b>Тема:</b> %s\n"+
|
||||
|
|
@ -403,7 +398,7 @@ func (h *Handler) createReversalTask(
|
|||
*approval.ID, topicFullName, content, reversalText,
|
||||
))
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*created.ID, *approval.ID)
|
||||
msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*created.ID, *approval.ID, len(files))
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
}
|
||||
|
||||
|
|
@ -444,7 +439,6 @@ func (h *Handler) askExecutorAboutChanges(
|
|||
}
|
||||
|
||||
// HandleRevokeTaskNoChanges — исполнитель подтвердил, что изменений не вносил.
|
||||
// Задача отменяется.
|
||||
func (h *Handler) HandleRevokeTaskNoChanges(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64, approvalID uint64) {
|
||||
ctx := context.Background()
|
||||
chatID := cq.Message.Chat.ID
|
||||
|
|
@ -475,7 +469,6 @@ func (h *Handler) HandleRevokeTaskNoChanges(bot *tgbotapi.BotAPI, cq *tgbotapi.C
|
|||
}
|
||||
|
||||
// HandleRevokeTaskHasChanges — исполнитель подтвердил, что уже вносил изменения.
|
||||
// Исходная задача отменяется, создаётся задача на обращение изменений.
|
||||
func (h *Handler) HandleRevokeTaskHasChanges(bot *tgbotapi.BotAPI, cq *tgbotapi.CallbackQuery, taskID uint64, approvalID uint64) {
|
||||
ctx := context.Background()
|
||||
chatID := cq.Message.Chat.ID
|
||||
|
|
|
|||
|
|
@ -1,15 +1,12 @@
|
|||
package approval
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/reportcore"
|
||||
"bitrix_balancer_api/core/typescore"
|
||||
"bitrix_balancer_api/telegram_service/keyboard"
|
||||
"bitrix_balancer_api/telegram_service/state"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/xuri/excelize/v2"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
|
|
@ -18,389 +15,16 @@ import (
|
|||
|
||||
// getReportCategoryCodes — объединяет категории согласующего и наблюдателя.
|
||||
func (h *Handler) getReportCategoryCodes(ctx context.Context, user *typescore.User) []string {
|
||||
seen := map[string]bool{}
|
||||
var codes []string
|
||||
|
||||
addCodes := func(action string) {
|
||||
perms, err := h.ipc.Database.Permission.GetUserPermissionsDB(ctx, *user.ID, action)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, p := range perms {
|
||||
if p.TopicCategoryID == nil {
|
||||
continue
|
||||
}
|
||||
cat, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *p.TopicCategoryID)
|
||||
if err != nil || cat == nil || cat.Code == nil {
|
||||
continue
|
||||
}
|
||||
if !seen[*cat.Code] {
|
||||
seen[*cat.Code] = true
|
||||
codes = append(codes, *cat.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addCodes("create") // согласующий видит то, что сам может согласовывать
|
||||
addCodes("observe") // наблюдатель видит свои категории
|
||||
|
||||
return codes
|
||||
return reportcore.GetReportCategoryCodes(ctx, h.ipc.Database, user)
|
||||
}
|
||||
|
||||
// buildExcelApprovalsReport — строит xlsx-файл отчёта по согласованиям и возвращает байты.
|
||||
func (h *Handler) buildExcelApprovalsReport(ctx context.Context, approvals []*typescore.Approval) ([]byte, error) {
|
||||
f := excelize.NewFile()
|
||||
sheet := "Согласования"
|
||||
f.SetSheetName("Sheet1", sheet)
|
||||
return reportcore.BuildExcelApprovalsReport(ctx, h.ipc.Database, approvals)
|
||||
}
|
||||
|
||||
headers := []string{
|
||||
"ФИО инициатора", // A
|
||||
"Тема согласования", // B
|
||||
"Дата создания", // C
|
||||
"Согласующие", // D
|
||||
"Наблюдатели", // E
|
||||
"Статус", // F
|
||||
"Текст согласования", // G
|
||||
"Отдел сотрудника", // H
|
||||
"Комментарии", // I
|
||||
"Дата согласования", // J
|
||||
"Текст задачи", // K
|
||||
"Исполнитель", // L
|
||||
"Статус задачи", // M
|
||||
"Дата исполнения", // N
|
||||
}
|
||||
|
||||
cols := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"}
|
||||
|
||||
colWidths := map[string]float64{
|
||||
"A": 25, "B": 40, "C": 18, "D": 30,
|
||||
"E": 30, "F": 16, "G": 40, "H": 25,
|
||||
"I": 30, "J": 18, "K": 40, "L": 25,
|
||||
"M": 18, "N": 18,
|
||||
}
|
||||
|
||||
headerStyle, _ := f.NewStyle(&excelize.Style{
|
||||
Font: &excelize.Font{Bold: true, Color: "FFFFFF"},
|
||||
Fill: excelize.Fill{Type: "pattern", Color: []string{"2E75B6"}, Pattern: 1},
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Color: "000000", Style: 1},
|
||||
{Type: "right", Color: "000000", Style: 1},
|
||||
{Type: "top", Color: "000000", Style: 1},
|
||||
{Type: "bottom", Color: "000000", Style: 1},
|
||||
},
|
||||
Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center", WrapText: true},
|
||||
})
|
||||
|
||||
dataStyle, _ := f.NewStyle(&excelize.Style{
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Color: "CCCCCC", Style: 1},
|
||||
{Type: "right", Color: "CCCCCC", Style: 1},
|
||||
{Type: "top", Color: "CCCCCC", Style: 1},
|
||||
{Type: "bottom", Color: "CCCCCC", Style: 1},
|
||||
},
|
||||
Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
|
||||
})
|
||||
|
||||
rejectedStyle, _ := f.NewStyle(&excelize.Style{
|
||||
Fill: excelize.Fill{Type: "pattern", Color: []string{"FFE0E0"}, Pattern: 1},
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Color: "CCCCCC", Style: 1},
|
||||
{Type: "right", Color: "CCCCCC", Style: 1},
|
||||
{Type: "top", Color: "CCCCCC", Style: 1},
|
||||
{Type: "bottom", Color: "CCCCCC", Style: 1},
|
||||
},
|
||||
Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
|
||||
})
|
||||
|
||||
errorStyle, _ := f.NewStyle(&excelize.Style{
|
||||
Fill: excelize.Fill{Type: "pattern", Color: []string{"FFCCCC"}, Pattern: 1},
|
||||
Border: []excelize.Border{
|
||||
{Type: "left", Color: "CCCCCC", Style: 1},
|
||||
{Type: "right", Color: "CCCCCC", Style: 1},
|
||||
{Type: "top", Color: "CCCCCC", Style: 1},
|
||||
{Type: "bottom", Color: "CCCCCC", Style: 1},
|
||||
},
|
||||
Alignment: &excelize.Alignment{Vertical: "center", WrapText: true},
|
||||
})
|
||||
|
||||
for col, width := range colWidths {
|
||||
f.SetColWidth(sheet, col, col, width) //nolint:errcheck
|
||||
}
|
||||
|
||||
for i, header := range headers {
|
||||
cell := fmt.Sprintf("%s1", cols[i])
|
||||
f.SetCellValue(sheet, cell, header) //nolint:errcheck
|
||||
f.SetCellStyle(sheet, cell, cell, headerStyle) //nolint:errcheck
|
||||
}
|
||||
f.SetRowHeight(sheet, 1, 36) //nolint:errcheck
|
||||
|
||||
for rowIdx, a := range approvals {
|
||||
row := rowIdx + 2
|
||||
|
||||
initiatorName := ""
|
||||
if a.InitiatorID != nil {
|
||||
if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *a.InitiatorID); u != nil && u.FullName != nil {
|
||||
initiatorName = *u.FullName
|
||||
}
|
||||
}
|
||||
|
||||
topicName := ""
|
||||
if a.TopicID != nil {
|
||||
if t, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *a.TopicID); t != nil {
|
||||
if t.CategoryID != nil {
|
||||
if c, _ := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *t.CategoryID); c != nil && c.Name != nil {
|
||||
topicName = *c.Name + ": "
|
||||
}
|
||||
}
|
||||
if t.Name != nil {
|
||||
topicName += *t.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
createdAt := ""
|
||||
if a.CreatedAt != nil {
|
||||
createdAt = a.CreatedAt.Format("02.01.2006 15:04")
|
||||
}
|
||||
|
||||
var approverParts []string
|
||||
var commentFromStep string
|
||||
lastApprovedAt := ""
|
||||
|
||||
steps, _, _ := h.ipc.Database.ApprovalStep.GetApprovalStepsListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalStep{ApprovalID: a.ID},
|
||||
})
|
||||
sort.Slice(steps, func(i, j int) bool {
|
||||
if steps[i].StepOrder == nil || steps[j].StepOrder == nil {
|
||||
return false
|
||||
}
|
||||
return *steps[i].StepOrder < *steps[j].StepOrder
|
||||
})
|
||||
for _, s := range steps {
|
||||
name := ""
|
||||
if s.ApproverNameSnapshot != nil && *s.ApproverNameSnapshot != "" {
|
||||
name = *s.ApproverNameSnapshot
|
||||
} else if s.ApproverID != nil {
|
||||
if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *s.ApproverID); u != nil && u.FullName != nil {
|
||||
name = *u.FullName
|
||||
}
|
||||
}
|
||||
if name != "" {
|
||||
approverParts = append(approverParts, name)
|
||||
}
|
||||
if s.Status != nil && *s.Status == "rejected" && s.Comment != nil && *s.Comment != "" {
|
||||
commentFromStep = *s.Comment
|
||||
}
|
||||
if s.Status != nil && *s.Status == "approved" && s.ActedAt != nil {
|
||||
lastApprovedAt = s.ActedAt.Format("02.01.2006 15:04")
|
||||
}
|
||||
}
|
||||
approversCell := strings.Join(approverParts, "\n")
|
||||
|
||||
var observerParts []string
|
||||
categoryCode := h.getTopicCodeByApproval(ctx, a)
|
||||
if categoryCode != "" {
|
||||
observers, _ := h.ipc.Database.User.GetObserversForCategoryDB(ctx, categoryCode)
|
||||
for _, obs := range observers {
|
||||
if obs.FullName != nil {
|
||||
observerParts = append(observerParts, *obs.FullName)
|
||||
}
|
||||
}
|
||||
}
|
||||
observersCell := strings.Join(observerParts, "\n")
|
||||
|
||||
status := "—"
|
||||
if a.Status != nil {
|
||||
switch *a.Status {
|
||||
case "pending":
|
||||
status = "На согласовании"
|
||||
case "approved":
|
||||
status = "Согласовано"
|
||||
case "rejected":
|
||||
status = "Отклонено"
|
||||
case "revoked":
|
||||
status = "Отозвано"
|
||||
}
|
||||
}
|
||||
|
||||
content := ""
|
||||
if a.Content != nil {
|
||||
content = *a.Content
|
||||
}
|
||||
|
||||
deptName := ""
|
||||
if a.DepartmentID != nil {
|
||||
if d, _ := h.ipc.Database.Department.GetDepartmentByIDDB(ctx, *a.DepartmentID); d != nil && d.Name != nil {
|
||||
deptName = *d.Name
|
||||
}
|
||||
}
|
||||
|
||||
comment := ""
|
||||
if a.Status != nil && *a.Status == "rejected" {
|
||||
comment = commentFromStep
|
||||
}
|
||||
|
||||
taskText := "Не предусмотрено"
|
||||
executorName := "Не предусмотрено"
|
||||
taskStatus := "Не предусмотрено"
|
||||
taskCompletedAt := ""
|
||||
hasTaskError := false
|
||||
|
||||
if a.TopicID != nil {
|
||||
topicExecutors, _ := h.ipc.Database.ApprovalTopicExecutor.GetExecutorsByTopicIDDB(ctx, *a.TopicID)
|
||||
|
||||
if len(topicExecutors) == 0 {
|
||||
taskText = "Не предусмотрено"
|
||||
executorName = "Не предусмотрено"
|
||||
taskStatus = "Не предусмотрено"
|
||||
} else {
|
||||
tasks, _, _ := h.ipc.Database.ApprovalTasks.GetApprovalTasksListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.ApprovalTask{ApprovalID: a.ID},
|
||||
})
|
||||
|
||||
if len(tasks) == 0 {
|
||||
if a.Status == nil {
|
||||
taskText = "Не предусмотрено"
|
||||
executorName = "Не предусмотрено"
|
||||
taskStatus = "Не предусмотрено"
|
||||
} else {
|
||||
switch *a.Status {
|
||||
case "approved":
|
||||
taskText = "Ошибка: задачи не созданы"
|
||||
executorName = "Ошибка"
|
||||
taskStatus = "Ошибка"
|
||||
hasTaskError = true
|
||||
case "pending":
|
||||
taskText = "Ожидает согласования"
|
||||
executorName = "Ожидает согласования"
|
||||
taskStatus = "Ожидает согласования"
|
||||
case "rejected":
|
||||
taskText = "Не выполнено (заявка отклонена)"
|
||||
executorName = "Не выполнено (заявка отклонена)"
|
||||
taskStatus = "Не выполнено (заявка отклонена)"
|
||||
case "revoked":
|
||||
taskText = "Не выполнено (заявка отозвана)"
|
||||
executorName = "Не выполнено (заявка отозвана)"
|
||||
taskStatus = "Не выполнено (заявка отозвана)"
|
||||
default:
|
||||
taskText = "Не предусмотрено"
|
||||
executorName = "Не предусмотрено"
|
||||
taskStatus = "Не предусмотрено"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
var taskTexts []string
|
||||
var executorNames []string
|
||||
var taskStatuses []string
|
||||
|
||||
sort.Slice(tasks, func(i, j int) bool {
|
||||
if tasks[i].StepOrder == nil || tasks[j].StepOrder == nil {
|
||||
return false
|
||||
}
|
||||
return *tasks[i].StepOrder < *tasks[j].StepOrder
|
||||
})
|
||||
|
||||
for _, task := range tasks {
|
||||
if task.TaskText != nil {
|
||||
taskTexts = append(taskTexts, *task.TaskText)
|
||||
} else {
|
||||
taskTexts = append(taskTexts, "—")
|
||||
}
|
||||
|
||||
eName := ""
|
||||
if task.ExecutorID != nil {
|
||||
if u, _ := h.ipc.Database.User.GetUserByIDDB(ctx, *task.ExecutorID); u != nil && u.FullName != nil {
|
||||
eName = *u.FullName
|
||||
}
|
||||
}
|
||||
executorNames = append(executorNames, eName)
|
||||
|
||||
ts := "—"
|
||||
if task.Status != nil {
|
||||
switch *task.Status {
|
||||
case "pending":
|
||||
ts = "В работе"
|
||||
case "waiting":
|
||||
ts = "Ожидает"
|
||||
case "completed":
|
||||
ts = "Выполнено"
|
||||
case "cancelled":
|
||||
ts = "Отменено"
|
||||
}
|
||||
}
|
||||
taskStatuses = append(taskStatuses, ts)
|
||||
|
||||
if taskCompletedAt == "" && task.CompletedAt != nil {
|
||||
taskCompletedAt = task.CompletedAt.Format("02.01.2006 15:04")
|
||||
}
|
||||
}
|
||||
|
||||
taskText = strings.Join(taskTexts, "\n")
|
||||
executorName = strings.Join(executorNames, "\n")
|
||||
taskStatus = strings.Join(taskStatuses, "\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
values := []interface{}{
|
||||
initiatorName, topicName, createdAt,
|
||||
approversCell, observersCell,
|
||||
status, content, deptName, comment,
|
||||
lastApprovedAt,
|
||||
taskText, executorName, taskStatus,
|
||||
taskCompletedAt,
|
||||
}
|
||||
|
||||
// Базовый стиль строки
|
||||
style := dataStyle
|
||||
if a.Status != nil && *a.Status == "rejected" {
|
||||
style = rejectedStyle
|
||||
}
|
||||
|
||||
// 🚀 Заполняем ячейки с индивидуальными стилями для задач
|
||||
for colIdx, val := range values {
|
||||
cell := fmt.Sprintf("%s%d", cols[colIdx], row)
|
||||
f.SetCellValue(sheet, cell, val) //nolint:errcheck
|
||||
|
||||
// 🚀 Для ячеек задач (K, L, M) применяем errorStyle при ошибке
|
||||
cellStyle := style
|
||||
if hasTaskError && colIdx >= 10 && colIdx <= 12 {
|
||||
cellStyle = errorStyle
|
||||
}
|
||||
f.SetCellStyle(sheet, cell, cell, cellStyle) //nolint:errcheck
|
||||
}
|
||||
|
||||
// Высота строки
|
||||
rowHeight := 20.0
|
||||
maxLines := len(approverParts)
|
||||
if len(strings.Split(taskText, "\n")) > maxLines {
|
||||
maxLines = len(strings.Split(taskText, "\n"))
|
||||
}
|
||||
if maxLines > 1 {
|
||||
rowHeight = float64(maxLines) * 18
|
||||
}
|
||||
f.SetRowHeight(sheet, row, rowHeight) //nolint:errcheck
|
||||
}
|
||||
|
||||
lastCol := cols[len(headers)-1]
|
||||
lastRow := len(approvals) + 1
|
||||
f.AutoFilter(sheet, //nolint:errcheck
|
||||
fmt.Sprintf("A1:%s%d", lastCol, lastRow),
|
||||
[]excelize.AutoFilterOptions{},
|
||||
)
|
||||
|
||||
f.SetPanes(sheet, &excelize.Panes{ //nolint:errcheck
|
||||
Freeze: true,
|
||||
YSplit: 1,
|
||||
TopLeftCell: "A2",
|
||||
ActivePane: "bottomLeft",
|
||||
})
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := f.Write(&buf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
func (h *Handler) getTopicCodeByApproval(ctx context.Context, a *typescore.Approval) string {
|
||||
return reportcore.GetTopicCategoryCodeByApproval(ctx, h.ipc.Database, a)
|
||||
}
|
||||
|
||||
const reportDateLayout = "02.01.2006"
|
||||
|
|
|
|||
|
|
@ -292,36 +292,6 @@ func (h *Handler) submitApproval(ctx context.Context, bot *tgbotapi.BotAPI, tele
|
|||
return created, nil
|
||||
}
|
||||
|
||||
func (h *Handler) getTopicCodeByApproval(ctx context.Context, approval *typescore.Approval) string {
|
||||
if approval.TopicID == nil {
|
||||
return ""
|
||||
}
|
||||
topic, err := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
|
||||
if err != nil || topic == nil {
|
||||
return ""
|
||||
}
|
||||
category, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID)
|
||||
if err != nil || category == nil || category.Code == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
categoryCode := *category.Code
|
||||
|
||||
_, err = h.Registry.Get(categoryCode)
|
||||
if err == nil {
|
||||
return categoryCode
|
||||
}
|
||||
|
||||
absenceCategories := map[string]bool{
|
||||
"timeoff": true, "vacation": true, "sickleave": true,
|
||||
}
|
||||
if absenceCategories[categoryCode] {
|
||||
return "absence"
|
||||
}
|
||||
|
||||
return categoryCode
|
||||
}
|
||||
|
||||
func (h *Handler) getTopicNameByApproval(ctx context.Context, approval *typescore.Approval) string {
|
||||
if approval.TopicID == nil {
|
||||
return "—"
|
||||
|
|
|
|||
|
|
@ -57,12 +57,55 @@ func (h *Handler) notifyExecutor(bot *tgbotapi.BotAPI, ctx context.Context, exec
|
|||
commentsSection := h.formatCommentsSection(ctx, *approval.ID)
|
||||
text += commentsSection
|
||||
|
||||
// 🆕 Получаем все файлы заявки
|
||||
allFiles, _ := h.ipc.Database.ApprovalFile.GetFilesByApprovalIDDB(ctx, *approval.ID)
|
||||
filesCount := len(allFiles)
|
||||
|
||||
// 🆕 Информация о файлах, приложенных к этой задаче
|
||||
var taskFiles []string
|
||||
for _, f := range allFiles {
|
||||
if f.TaskID != nil && *f.TaskID == *task.ID && f.FileName != nil {
|
||||
taskFiles = append(taskFiles, *f.FileName)
|
||||
}
|
||||
}
|
||||
if len(taskFiles) > 0 {
|
||||
text += "\n\n📎 <b>Файлы к этой задаче:</b>\n"
|
||||
for i, name := range taskFiles {
|
||||
text += fmt.Sprintf("%d. %s\n", i+1, name)
|
||||
}
|
||||
} else if filesCount > 0 {
|
||||
// 🆕 Если есть файлы заявки, но не к этой задаче — показываем кнопку
|
||||
text += fmt.Sprintf("\n\n📂 <b>В заявке есть файлы (%d шт.) — см. кнопку ниже</b>", filesCount)
|
||||
}
|
||||
|
||||
// 🆕 Передаём filesCount в клавиатуру
|
||||
msg := tgbotapi.NewMessage(*executor.TelegramID, text)
|
||||
msg.ParseMode = "HTML"
|
||||
msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID)
|
||||
msg.ReplyMarkup = keyboard.BuildExecutorTaskActions(*task.ID, *approval.ID, filesCount)
|
||||
bot.Send(msg) //nolint:errcheck
|
||||
}
|
||||
|
||||
func (n *Notifier) ensureInstructions(ctx context.Context, approval *typescore.Approval, collected map[string]string) map[string]string {
|
||||
if collected == nil {
|
||||
collected = make(map[string]string)
|
||||
}
|
||||
|
||||
// Если инструкция уже есть — ничего не делаем
|
||||
if _, ok := collected["instructions"]; ok && collected["instructions"] != "" {
|
||||
return collected
|
||||
}
|
||||
|
||||
// Подгружаем тему из БД и берём инструкцию
|
||||
if approval != nil && approval.TopicID != nil {
|
||||
topic, err := n.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID)
|
||||
if err == nil && topic != nil && topic.Instructions != nil && *topic.Instructions != "" {
|
||||
collected["instructions"] = *topic.Instructions
|
||||
}
|
||||
}
|
||||
|
||||
return collected
|
||||
}
|
||||
|
||||
// NotifyApprover отправляет уведомление согласующему с кнопками Да/Нет.
|
||||
func (n *Notifier) NotifyApprover(
|
||||
bot *tgbotapi.BotAPI,
|
||||
|
|
@ -77,7 +120,8 @@ func (n *Notifier) NotifyApprover(
|
|||
|
||||
ctx := context.Background()
|
||||
|
||||
// Формируем основное сообщение
|
||||
collected = n.ensureInstructions(ctx, approval, collected)
|
||||
|
||||
msgText := fmt.Sprintf("📬 <b>Новая заявка #%d на согласование</b>\n\n", *approval.ID) +
|
||||
n.topic.FormatApproverMessage(initiator, collected)
|
||||
|
||||
|
|
|
|||
|
|
@ -23,10 +23,15 @@ import (
|
|||
type Registry struct {
|
||||
topics map[string]approvalflow.Topic
|
||||
order []string
|
||||
|
||||
topicCodeToCategory map[string]string
|
||||
}
|
||||
|
||||
func NewRegistry() *Registry {
|
||||
r := &Registry{topics: make(map[string]approvalflow.Topic)}
|
||||
r := &Registry{
|
||||
topics: make(map[string]approvalflow.Topic),
|
||||
topicCodeToCategory: make(map[string]string),
|
||||
}
|
||||
r.registerAll()
|
||||
return r
|
||||
}
|
||||
|
|
@ -47,7 +52,10 @@ func (r *Registry) registerAll() {
|
|||
r.register(nonstandardcontract.NewNonstandardContractTopic())
|
||||
r.register(otkconditions.NewOtkConditionsTopic())
|
||||
|
||||
// Свободные темы (без подтем)
|
||||
r.mapTopicToCategory("timeoff", "absence")
|
||||
r.mapTopicToCategory("vacation", "absence")
|
||||
r.mapTopicToCategory("sickleave", "absence")
|
||||
|
||||
freeTopics := []struct{ code, name, template, instructions string }{
|
||||
{"delivery_clients", "Доставка клиентам/на склад", "Иванов Иван Иванович\nТел 89781234567\nПаспорт 1234 567890\nДАФ н862нн46 п/п АА8473|46\n\n61 бц с ад - 52 кор\nЧП000001676\n\nЕПР-СтройКрым", ""},
|
||||
{"v_shipments", "В. Отгрузки", "ООО Нива на 370 тыс. руб. под 19%", ""},
|
||||
|
|
@ -55,7 +63,7 @@ func (r *Registry) registerAll() {
|
|||
{"vacancies", "Вакансии", "", ""},
|
||||
{"delivery_rates_ap", "Ставки доставки АП", "Прошу согласовать доставку 14 кор преформы клиенту Олег-Выдув-Сочи за 34 000 руб.", ""},
|
||||
{"freelancers_approval", "Утверждение фрилансеров", "Одного помощника на выгрузку полной фуры с крышкой ручкой с КТ на 23.04.2026 на весь день", ""},
|
||||
{"non_working_day", "Выход в нерабочий день", "Прошу вывести склад для учета c 25.04 по 26.04", ""},
|
||||
{"non_working_day", "Выход в нерабочий день", "Прошу вывести склад для учета c 25.04 по 26.04", ""},
|
||||
{"suggestions", "Предложения и пожелания", "", ""},
|
||||
{"cash_balance", "Остаток в кассах", "", ""},
|
||||
{"client_sales", "Продажи по клиенту", "", ""},
|
||||
|
|
@ -67,17 +75,27 @@ func (r *Registry) registerAll() {
|
|||
}
|
||||
}
|
||||
|
||||
func (r *Registry) mapTopicToCategory(topicCode, categoryCode string) {
|
||||
r.topicCodeToCategory[topicCode] = categoryCode
|
||||
}
|
||||
|
||||
func (r *Registry) register(t approvalflow.Topic) {
|
||||
r.topics[t.Code()] = t
|
||||
r.order = append(r.order, t.Code())
|
||||
}
|
||||
|
||||
func (r *Registry) Get(code string) (approvalflow.Topic, error) {
|
||||
t, ok := r.topics[code]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown topic code: %s", code)
|
||||
if t, ok := r.topics[code]; ok {
|
||||
return t, nil
|
||||
}
|
||||
return t, nil
|
||||
|
||||
if categoryCode, mapped := r.topicCodeToCategory[code]; mapped {
|
||||
if t, ok := r.topics[categoryCode]; ok {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("unknown topic code: %s", code)
|
||||
}
|
||||
|
||||
func (r *Registry) All() []approvalflow.Topic {
|
||||
|
|
|
|||
|
|
@ -114,6 +114,25 @@ func (h *Handler) handleFullNameInput(ctx context.Context, bot *tgbotapi.BotAPI,
|
|||
|
||||
logrus.Infof("✅ Новый пользователь зарегистрирован: %s (tg_id=%d)", fullName, telegramID)
|
||||
|
||||
defaultRoles, _, err := h.ipc.Database.Role.GetRolesListDB(ctx, typescore.ListDbOptions{
|
||||
Filtering: &typescore.Role{IsDefault: utilscore.PointerToBool(true)},
|
||||
})
|
||||
if err != nil {
|
||||
logrus.Error("start.handleFullNameInput: GetRolesListDB: ", err)
|
||||
utilscore.SendBotMessage(bot, msg.Chat.ID, "Произошла ошибка при регистрации. Попробуйте ещё раз — /start")
|
||||
return
|
||||
}
|
||||
if len(defaultRoles) > 0 {
|
||||
for _, role := range defaultRoles {
|
||||
_, _, err = h.ipc.Database.UserRole.CreateUserRoleDB(ctx, nil, &typescore.UserRole{
|
||||
UserID: created.ID,
|
||||
RoleID: role.ID,
|
||||
})
|
||||
if err != nil {
|
||||
logrus.Error("start.handleFullNameInput: CreateUserRoleDB: ", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
h.sendRegistrationDone(bot, msg.Chat.ID, created)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -95,15 +95,6 @@ func BuildObserverActions(approvalID uint64, topicCode string, status string, fi
|
|||
return kb.Build()
|
||||
}
|
||||
|
||||
// BuildExecutorTaskActions — кнопки исполнителя
|
||||
func BuildExecutorTaskActions(taskID, approvalID uint64) interface{} {
|
||||
return tgkit.NewInlineKeyboard().
|
||||
Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Выполнено", fmt.Sprintf("task_complete:%d", taskID))).
|
||||
Row(tgkit.Btn("📎 Прикрепить файл", fmt.Sprintf("executor_attach:%d:%d", taskID, approvalID))).
|
||||
Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID))).
|
||||
Build()
|
||||
}
|
||||
|
||||
// BuildApprovalMenu — список тем для создания заявки
|
||||
func BuildApprovalMenu(topics []approvalflow.Topic, page int) interface{} {
|
||||
const perPage = 6
|
||||
|
|
@ -335,3 +326,21 @@ func BuildAttachSessionKeyboard(approvalID uint64, fileCount int) tgbotapi.Inlin
|
|||
|
||||
return kb.Build()
|
||||
}
|
||||
|
||||
// BuildExecutorTaskActions — кнопки исполнителя
|
||||
func BuildExecutorTaskActions(taskID, approvalID uint64, filesCount int) interface{} {
|
||||
kb := tgkit.NewInlineKeyboard()
|
||||
|
||||
if filesCount > 0 {
|
||||
kb.Row(tgkit.Btn(
|
||||
fmt.Sprintf("📎 Файлы заявки (%d)", filesCount),
|
||||
fmt.Sprintf("appr_view_files:%d", approvalID),
|
||||
))
|
||||
}
|
||||
|
||||
kb.Row(tgkit.BtnStyled(tgkit.ButtonStyleSuccess, "Выполнено", fmt.Sprintf("task_complete:%d", taskID))).
|
||||
Row(tgkit.Btn("📎 Прикрепить файл к задаче", fmt.Sprintf("executor_attach:%d:%d", taskID, approvalID))).
|
||||
Row(tgkit.Btn("💬 Комментировать", fmt.Sprintf("appr_comment:%d", approvalID)))
|
||||
|
||||
return kb.Build()
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue