package httpapi import ( "database/sql" "time" "github.com/gin-gonic/gin" ) type licenseTrendPoint struct { Month string `json:"month"` Issued int64 `json:"issued"` Expired int64 `json:"expired"` } type dashboardSummaryRecord struct { ActiveLicenses int64 `json:"active_licenses"` NewCustomers int64 `json:"new_customers"` PaidRevenueCents int64 `json:"paid_revenue_cents"` Currency string `json:"currency"` ExpiringLicenses int64 `json:"expiring_licenses"` LicenseTrend []licenseTrendPoint `json:"license_trend"` UpcomingExpirations []licenseRecord `json:"upcoming_expirations"` RecentLicenses []licenseRecord `json:"recent_licenses"` GeneratedAt time.Time `json:"generated_at"` } func dashboardMonths(c *gin.Context) (int, bool) { switch c.DefaultQuery("months", "6") { case "6": return 6, true case "12": return 12, true default: apiError(c, 400, "invalid_request", "months 必须为 6 或 12") return 0, false } } func (a *BusinessAPI) dashboardSummary(c *gin.Context) { months, ok := dashboardMonths(c) if !ok { return } now := time.Now().UTC() out, err := a.loadDashboardSummary(c, now, months) if err != nil { apiError(c, 500, "internal_error", "服务暂时不可用") return } c.JSON(200, gin.H{"data": out}) } // A read-only consistent snapshot prevents concurrent issuance/payment from making // the summary counts and its lists disagree. No application rows are changed. func (a *BusinessAPI) loadDashboardSummary(c *gin.Context, now time.Time, months int) (dashboardSummaryRecord, error) { now = now.UTC() monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC) nextMonth := monthStart.AddDate(0, 1, 0) out := dashboardSummaryRecord{Currency: "CNY", GeneratedAt: now, LicenseTrend: make([]licenseTrendPoint, months), UpcomingExpirations: []licenseRecord{}, RecentLicenses: []licenseRecord{}} tx, err := a.db.BeginTx(c, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true}) if err != nil { return out, err } defer tx.Rollback() err = tx.QueryRowContext(c, `SELECT (SELECT COUNT(*) FROM licenses WHERE status<>'revoked' AND starts_at<=? AND expires_at>?), (SELECT COUNT(*) FROM customers WHERE created_at>=? AND created_at=? AND paid_at'revoked' AND starts_at<=? AND expires_at>? AND expires_at<=?)`, now, now, monthStart, nextMonth, monthStart, nextMonth, now, now, now.Add(30*24*time.Hour)).Scan( &out.ActiveLicenses, &out.NewCustomers, &out.PaidRevenueCents, &out.ExpiringLicenses) if err != nil { return out, err } // Range aggregates use UTC boundaries rather than the database session's date // formatting/timezone. Each bucket includes its start and excludes its end. for i := range out.LicenseTrend { start := monthStart.AddDate(0, i-months+1, 0) end := start.AddDate(0, 1, 0) point := &out.LicenseTrend[i] point.Month = start.Format("2006-01") err = tx.QueryRowContext(c, `SELECT (SELECT COUNT(*) FROM licenses WHERE created_at>=? AND created_at'revoked' AND expires_at>=? AND expires_at