group_detail_stats.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package service
  2. import (
  3. "context"
  4. infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
  5. "time"
  6. )
  7. type GroupDetailStats struct {
  8. GroupID int64 `json:"group_id"`
  9. GroupName string `json:"group_name"`
  10. TotalAPIKeys int64 `json:"total_api_keys"`
  11. ActiveAPIKeys int64 `json:"active_api_keys"`
  12. TotalAccounts int64 `json:"total_accounts"`
  13. TotalRequests int64 `json:"total_requests"`
  14. TotalTokens int64 `json:"total_tokens"`
  15. TotalCost float64 `json:"total_cost"`
  16. TotalActualCost float64 `json:"total_actual_cost"`
  17. TotalAccountCost float64 `json:"total_account_cost"`
  18. BalanceCost float64 `json:"balance_cost"`
  19. SubscriptionCost float64 `json:"subscription_cost"`
  20. ZeroChargeRequests int64 `json:"zero_charge_requests"`
  21. AverageDurationMS float64 `json:"average_duration_ms"`
  22. From *time.Time `json:"from"`
  23. To *time.Time `json:"to"`
  24. GeneratedAt time.Time `json:"generated_at"`
  25. }
  26. type GroupDetailStatsProvider interface {
  27. GetGroupDetailStats(context.Context, int64, *time.Time, *time.Time) (*GroupDetailStats, error)
  28. }
  29. func (s *DashboardService) GetGroupDetailStats(ctx context.Context, id int64, from, to *time.Time) (*GroupDetailStats, error) {
  30. if id <= 0 || (from != nil && to != nil && !from.Before(*to)) {
  31. return nil, infraerrors.BadRequest("GROUP_STATS_INVALID_RANGE", "统计时间范围无效")
  32. }
  33. if s == nil {
  34. return nil, infraerrors.ServiceUnavailable("GROUP_STATS_UNAVAILABLE", "统计服务暂不可用")
  35. }
  36. provider, ok := s.usageRepo.(GroupDetailStatsProvider)
  37. if !ok {
  38. return nil, infraerrors.ServiceUnavailable("GROUP_STATS_UNAVAILABLE", "统计服务暂不可用")
  39. }
  40. ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
  41. defer cancel()
  42. return provider.GetGroupDetailStats(ctx, id, from, to)
  43. }