78 lines
2.1 KiB
Go
78 lines
2.1 KiB
Go
|
|
package dashboard
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"errors"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"gorm.io/gorm"
|
||
|
|
|
||
|
|
"git.apinb.com/ops/license/internal/issuance"
|
||
|
|
)
|
||
|
|
|
||
|
|
var ErrInvalidInput = errors.New("invalid dashboard input")
|
||
|
|
|
||
|
|
type Overview struct {
|
||
|
|
SubjectCount int64
|
||
|
|
IssuanceCount int64
|
||
|
|
ExpiringSoonCount int64
|
||
|
|
RecentIssuances []issuance.RecordSummary
|
||
|
|
}
|
||
|
|
|
||
|
|
type Service struct {
|
||
|
|
db *gorm.DB
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewService(db *gorm.DB) (*Service, error) {
|
||
|
|
if db == nil {
|
||
|
|
return nil, ErrInvalidInput
|
||
|
|
}
|
||
|
|
return &Service{db: db}, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func (s *Service) Get(ctx context.Context) (Overview, error) {
|
||
|
|
if s == nil || s.db == nil || ctx == nil {
|
||
|
|
return Overview{}, ErrInvalidInput
|
||
|
|
}
|
||
|
|
|
||
|
|
var result Overview
|
||
|
|
db := s.db.WithContext(ctx)
|
||
|
|
if err := db.Raw("SELECT COUNT(*) FROM authorization_subjects").Scan(&result.SubjectCount).Error; err != nil {
|
||
|
|
return Overview{}, err
|
||
|
|
}
|
||
|
|
if err := db.Raw("SELECT COUNT(*) FROM licence_issuances").Scan(&result.IssuanceCount).Error; err != nil {
|
||
|
|
return Overview{}, err
|
||
|
|
}
|
||
|
|
|
||
|
|
shanghai := time.FixedZone("Asia/Shanghai", 8*60*60)
|
||
|
|
now := time.Now().In(shanghai)
|
||
|
|
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, shanghai)
|
||
|
|
endDate := today.AddDate(0, 0, 30)
|
||
|
|
if err := db.Raw(`
|
||
|
|
SELECT COUNT(*)
|
||
|
|
FROM (
|
||
|
|
SELECT DISTINCT ON (subject_id) subject_id, expires_on
|
||
|
|
FROM licence_issuances
|
||
|
|
ORDER BY subject_id, issued_at DESC, id DESC
|
||
|
|
) AS latest
|
||
|
|
WHERE latest.expires_on BETWEEN ? AND ?`, today, endDate).
|
||
|
|
Scan(&result.ExpiringSoonCount).Error; err != nil {
|
||
|
|
return Overview{}, err
|
||
|
|
}
|
||
|
|
|
||
|
|
if err := db.Raw(`
|
||
|
|
SELECT issuances.id, issuances.subject_id, subjects.platform_name, subjects.workspace,
|
||
|
|
issuances.issuance_type, issuances.previous_licence_id, issuances.valid_from,
|
||
|
|
issuances.expires_on, issuances.issued_at
|
||
|
|
FROM licence_issuances AS issuances
|
||
|
|
JOIN authorization_subjects AS subjects ON subjects.id = issuances.subject_id
|
||
|
|
ORDER BY issuances.issued_at DESC, issuances.id DESC
|
||
|
|
LIMIT 10`).Scan(&result.RecentIssuances).Error; err != nil {
|
||
|
|
return Overview{}, err
|
||
|
|
}
|
||
|
|
if result.RecentIssuances == nil {
|
||
|
|
result.RecentIssuances = make([]issuance.RecordSummary, 0)
|
||
|
|
}
|
||
|
|
return result, nil
|
||
|
|
}
|