mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-10-27 08:05:33 +00:00
Merge pull request #4878 from StarryKira/codex/fix-payment-dashboard-currencies
fix(payment): group dashboard stats by currency
This commit is contained in:
@@ -144,28 +144,32 @@ type RefundResult struct {
|
||||
}
|
||||
|
||||
type DashboardStats struct {
|
||||
TodayAmount float64 `json:"today_amount"`
|
||||
TotalAmount float64 `json:"total_amount"`
|
||||
TodayCount int `json:"today_count"`
|
||||
TotalCount int `json:"total_count"`
|
||||
AvgAmount float64 `json:"avg_amount"`
|
||||
PendingOrders int `json:"pending_orders"`
|
||||
TodayAmount CurrencyAmounts `json:"today_amount"`
|
||||
TotalAmount CurrencyAmounts `json:"total_amount"`
|
||||
TodayCount int `json:"today_count"`
|
||||
TotalCount int `json:"total_count"`
|
||||
AvgAmount CurrencyAmounts `json:"avg_amount"`
|
||||
PendingOrders int `json:"pending_orders"`
|
||||
|
||||
DailySeries []DailyStats `json:"daily_series"`
|
||||
PaymentMethods []PaymentMethodStat `json:"payment_methods"`
|
||||
TopUsers []TopUserStat `json:"top_users"`
|
||||
TopUsers TopUsersByCurrency `json:"top_users"`
|
||||
}
|
||||
|
||||
// CurrencyAmounts holds payment amounts keyed by their ISO 4217 currency.
|
||||
// Amounts in different currencies must never be added together.
|
||||
type CurrencyAmounts map[string]float64
|
||||
|
||||
type DailyStats struct {
|
||||
Date string `json:"date"`
|
||||
Amount float64 `json:"amount"`
|
||||
Count int `json:"count"`
|
||||
Date string `json:"date"`
|
||||
Amount CurrencyAmounts `json:"amount"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type PaymentMethodStat struct {
|
||||
Type string `json:"type"`
|
||||
Amount float64 `json:"amount"`
|
||||
Count int `json:"count"`
|
||||
Type string `json:"type"`
|
||||
Amount CurrencyAmounts `json:"amount"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type TopUserStat struct {
|
||||
@@ -174,6 +178,10 @@ type TopUserStat struct {
|
||||
Amount float64 `json:"amount"`
|
||||
}
|
||||
|
||||
// TopUsersByCurrency contains an independent ranked user list for each
|
||||
// currency. A single cross-currency leaderboard would be misleading.
|
||||
type TopUsersByCurrency map[string][]TopUserStat
|
||||
|
||||
// --- Service ---
|
||||
|
||||
type PaymentService struct {
|
||||
|
||||
@@ -54,22 +54,27 @@ func (s *PaymentService) GetDashboardStats(ctx context.Context, days int) (*Dash
|
||||
}
|
||||
|
||||
func computeBasicStats(st *DashboardStats, orders []*dbent.PaymentOrder, todayStart time.Time) {
|
||||
var totalAmount, todayAmount float64
|
||||
st.TotalAmount = make(CurrencyAmounts)
|
||||
st.TodayAmount = make(CurrencyAmounts)
|
||||
st.AvgAmount = make(CurrencyAmounts)
|
||||
currencyCounts := make(map[string]int)
|
||||
var todayCount int
|
||||
for _, o := range orders {
|
||||
totalAmount += o.PayAmount
|
||||
currency := PaymentOrderCurrency(o)
|
||||
st.TotalAmount[currency] += o.PayAmount
|
||||
currencyCounts[currency]++
|
||||
if o.PaidAt != nil && !o.PaidAt.Before(todayStart) {
|
||||
todayAmount += o.PayAmount
|
||||
st.TodayAmount[currency] += o.PayAmount
|
||||
todayCount++
|
||||
}
|
||||
}
|
||||
st.TotalAmount = math.Round(totalAmount*100) / 100
|
||||
st.TodayAmount = math.Round(todayAmount*100) / 100
|
||||
st.TotalCount = len(orders)
|
||||
st.TodayCount = todayCount
|
||||
if st.TotalCount > 0 {
|
||||
st.AvgAmount = math.Round(totalAmount/float64(st.TotalCount)*100) / 100
|
||||
for currency, totalAmount := range st.TotalAmount {
|
||||
st.AvgAmount[currency] = roundAmount(totalAmount / float64(currencyCounts[currency]))
|
||||
}
|
||||
roundCurrencyAmounts(st.TotalAmount)
|
||||
roundCurrencyAmounts(st.TodayAmount)
|
||||
}
|
||||
|
||||
func buildDailySeries(orders []*dbent.PaymentOrder, since time.Time, days int) []DailyStats {
|
||||
@@ -81,20 +86,20 @@ func buildDailySeries(orders []*dbent.PaymentOrder, since time.Time, days int) [
|
||||
date := o.PaidAt.Format("2006-01-02")
|
||||
ds, ok := dailyMap[date]
|
||||
if !ok {
|
||||
ds = &DailyStats{Date: date}
|
||||
ds = &DailyStats{Date: date, Amount: make(CurrencyAmounts)}
|
||||
dailyMap[date] = ds
|
||||
}
|
||||
ds.Amount += o.PayAmount
|
||||
ds.Amount[PaymentOrderCurrency(o)] += o.PayAmount
|
||||
ds.Count++
|
||||
}
|
||||
series := make([]DailyStats, 0, days)
|
||||
for i := 0; i < days; i++ {
|
||||
date := since.AddDate(0, 0, i+1).Format("2006-01-02")
|
||||
if ds, ok := dailyMap[date]; ok {
|
||||
ds.Amount = math.Round(ds.Amount*100) / 100
|
||||
roundCurrencyAmounts(ds.Amount)
|
||||
series = append(series, *ds)
|
||||
} else {
|
||||
series = append(series, DailyStats{Date: date})
|
||||
series = append(series, DailyStats{Date: date, Amount: make(CurrencyAmounts)})
|
||||
}
|
||||
}
|
||||
return series
|
||||
@@ -105,49 +110,71 @@ func buildMethodDistribution(orders []*dbent.PaymentOrder) []PaymentMethodStat {
|
||||
for _, o := range orders {
|
||||
ms, ok := methodMap[o.PaymentType]
|
||||
if !ok {
|
||||
ms = &PaymentMethodStat{Type: o.PaymentType}
|
||||
ms = &PaymentMethodStat{Type: o.PaymentType, Amount: make(CurrencyAmounts)}
|
||||
methodMap[o.PaymentType] = ms
|
||||
}
|
||||
ms.Amount += o.PayAmount
|
||||
ms.Amount[PaymentOrderCurrency(o)] += o.PayAmount
|
||||
ms.Count++
|
||||
}
|
||||
methods := make([]PaymentMethodStat, 0, len(methodMap))
|
||||
for _, ms := range methodMap {
|
||||
ms.Amount = math.Round(ms.Amount*100) / 100
|
||||
roundCurrencyAmounts(ms.Amount)
|
||||
methods = append(methods, *ms)
|
||||
}
|
||||
sort.Slice(methods, func(i, j int) bool {
|
||||
return methods[i].Type < methods[j].Type
|
||||
})
|
||||
return methods
|
||||
}
|
||||
|
||||
func buildTopUsers(orders []*dbent.PaymentOrder) []TopUserStat {
|
||||
userMap := make(map[int64]*TopUserStat)
|
||||
func buildTopUsers(orders []*dbent.PaymentOrder) TopUsersByCurrency {
|
||||
userMap := make(map[string]map[int64]*TopUserStat)
|
||||
for _, o := range orders {
|
||||
us, ok := userMap[o.UserID]
|
||||
currency := PaymentOrderCurrency(o)
|
||||
users, ok := userMap[currency]
|
||||
if !ok {
|
||||
users = make(map[int64]*TopUserStat)
|
||||
userMap[currency] = users
|
||||
}
|
||||
us, ok := users[o.UserID]
|
||||
if !ok {
|
||||
us = &TopUserStat{UserID: o.UserID, Email: o.UserEmail}
|
||||
userMap[o.UserID] = us
|
||||
users[o.UserID] = us
|
||||
}
|
||||
us.Amount += o.PayAmount
|
||||
}
|
||||
userList := make([]*TopUserStat, 0, len(userMap))
|
||||
for _, us := range userMap {
|
||||
us.Amount = math.Round(us.Amount*100) / 100
|
||||
userList = append(userList, us)
|
||||
}
|
||||
sort.Slice(userList, func(i, j int) bool {
|
||||
return userList[i].Amount > userList[j].Amount
|
||||
})
|
||||
limit := topUsersLimit
|
||||
if len(userList) < limit {
|
||||
limit = len(userList)
|
||||
}
|
||||
result := make([]TopUserStat, 0, limit)
|
||||
for i := 0; i < limit; i++ {
|
||||
result = append(result, *userList[i])
|
||||
result := make(TopUsersByCurrency, len(userMap))
|
||||
for currency, users := range userMap {
|
||||
userList := make([]*TopUserStat, 0, len(users))
|
||||
for _, us := range users {
|
||||
us.Amount = roundAmount(us.Amount)
|
||||
userList = append(userList, us)
|
||||
}
|
||||
sort.Slice(userList, func(i, j int) bool {
|
||||
return userList[i].Amount > userList[j].Amount
|
||||
})
|
||||
limit := topUsersLimit
|
||||
if len(userList) < limit {
|
||||
limit = len(userList)
|
||||
}
|
||||
result[currency] = make([]TopUserStat, 0, limit)
|
||||
for i := 0; i < limit; i++ {
|
||||
result[currency] = append(result[currency], *userList[i])
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func roundCurrencyAmounts(amounts CurrencyAmounts) {
|
||||
for currency, amount := range amounts {
|
||||
amounts[currency] = roundAmount(amount)
|
||||
}
|
||||
}
|
||||
|
||||
func roundAmount(amount float64) float64 {
|
||||
return math.Round(amount*100) / 100
|
||||
}
|
||||
|
||||
// --- Audit Logs ---
|
||||
|
||||
func (s *PaymentService) writeAuditLog(ctx context.Context, oid int64, action, op string, detail map[string]any) {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestComputeBasicStatsGroupsAmountsByCurrency(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
todayStart := time.Date(2026, time.July, 25, 0, 0, 0, 0, time.UTC)
|
||||
yesterday := todayStart.Add(-time.Hour)
|
||||
today := todayStart.Add(time.Hour)
|
||||
orders := []*dbent.PaymentOrder{
|
||||
paymentStatsTestOrder(1, "alice@example.com", "CNY", 10, &today),
|
||||
paymentStatsTestOrder(2, "bob@example.com", "USD", 10, &today),
|
||||
paymentStatsTestOrder(1, "alice@example.com", "CNY", 5, &yesterday),
|
||||
}
|
||||
|
||||
stats := &DashboardStats{}
|
||||
computeBasicStats(stats, orders, todayStart)
|
||||
|
||||
require.Equal(t, CurrencyAmounts{"CNY": 15, "USD": 10}, stats.TotalAmount)
|
||||
require.Equal(t, CurrencyAmounts{"CNY": 10, "USD": 10}, stats.TodayAmount)
|
||||
require.Equal(t, CurrencyAmounts{"CNY": 7.5, "USD": 10}, stats.AvgAmount)
|
||||
require.Equal(t, 3, stats.TotalCount)
|
||||
require.Equal(t, 2, stats.TodayCount)
|
||||
}
|
||||
|
||||
func TestPaymentDashboardBreakdownsGroupAmountsAndRankingsByCurrency(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
firstDay := time.Date(2026, time.July, 24, 12, 0, 0, 0, time.UTC)
|
||||
secondDay := firstDay.AddDate(0, 0, 1)
|
||||
orders := []*dbent.PaymentOrder{
|
||||
paymentStatsTestOrder(1, "alice@example.com", "CNY", 5.555, &firstDay),
|
||||
paymentStatsTestOrder(2, "bob@example.com", "CNY", 10, &firstDay),
|
||||
paymentStatsTestOrder(1, "alice@example.com", "USD", 20, &secondDay),
|
||||
paymentStatsTestOrder(2, "bob@example.com", "USD", 10, &secondDay),
|
||||
}
|
||||
orders[0].PaymentType = "stripe"
|
||||
orders[1].PaymentType = "stripe"
|
||||
orders[2].PaymentType = "stripe"
|
||||
orders[3].PaymentType = "alipay"
|
||||
|
||||
daily := buildDailySeries(orders, firstDay.AddDate(0, 0, -1), 2)
|
||||
require.Equal(t, []DailyStats{
|
||||
{Date: "2026-07-24", Amount: CurrencyAmounts{"CNY": 15.56}, Count: 2},
|
||||
{Date: "2026-07-25", Amount: CurrencyAmounts{"USD": 30}, Count: 2},
|
||||
}, daily)
|
||||
|
||||
methods := buildMethodDistribution(orders)
|
||||
require.Equal(t, []PaymentMethodStat{
|
||||
{Type: "alipay", Amount: CurrencyAmounts{"USD": 10}, Count: 1},
|
||||
{Type: "stripe", Amount: CurrencyAmounts{"CNY": 15.56, "USD": 20}, Count: 3},
|
||||
}, methods)
|
||||
|
||||
users := buildTopUsers(orders)
|
||||
require.Equal(t, TopUsersByCurrency{
|
||||
"CNY": {
|
||||
{UserID: 2, Email: "bob@example.com", Amount: 10},
|
||||
{UserID: 1, Email: "alice@example.com", Amount: 5.56},
|
||||
},
|
||||
"USD": {
|
||||
{UserID: 1, Email: "alice@example.com", Amount: 20},
|
||||
{UserID: 2, Email: "bob@example.com", Amount: 10},
|
||||
},
|
||||
}, users)
|
||||
}
|
||||
|
||||
func paymentStatsTestOrder(userID int64, email, currency string, amount float64, paidAt *time.Time) *dbent.PaymentOrder {
|
||||
return &dbent.PaymentOrder{
|
||||
UserID: userID,
|
||||
UserEmail: email,
|
||||
PayAmount: amount,
|
||||
PaidAt: paidAt,
|
||||
ProviderSnapshot: map[string]any{"currency": currency},
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user