From 6d99e668d218c5f269b9a45ec437823a6ef58588 Mon Sep 17 00:00:00 2001 From: haruka <1628615876@qq.com> Date: Sun, 26 Jul 2026 03:18:30 +0800 Subject: [PATCH] fix(payment): group dashboard stats by currency --- backend/internal/service/payment_service.go | 34 ++++--- backend/internal/service/payment_stats.go | 93 ++++++++++++------- .../internal/service/payment_stats_test.go | 84 +++++++++++++++++ .../admin/payment/DailyRevenueChart.vue | 34 ++++--- .../admin/payment/OrderStatsCards.vue | 22 +++-- .../admin/payment/PaymentMethodChart.vue | 44 ++++++--- .../admin/payment/TopUsersLeaderboard.vue | 56 +++++++---- frontend/src/types/payment.ts | 32 +++++-- .../orders/AdminPaymentDashboardView.vue | 37 ++++++-- 9 files changed, 324 insertions(+), 112 deletions(-) create mode 100644 backend/internal/service/payment_stats_test.go diff --git a/backend/internal/service/payment_service.go b/backend/internal/service/payment_service.go index 3518fbe2e9..792a842a23 100644 --- a/backend/internal/service/payment_service.go +++ b/backend/internal/service/payment_service.go @@ -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 { diff --git a/backend/internal/service/payment_stats.go b/backend/internal/service/payment_stats.go index d206b27171..9dc48e0125 100644 --- a/backend/internal/service/payment_stats.go +++ b/backend/internal/service/payment_stats.go @@ -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) { diff --git a/backend/internal/service/payment_stats_test.go b/backend/internal/service/payment_stats_test.go new file mode 100644 index 0000000000..267719288a --- /dev/null +++ b/backend/internal/service/payment_stats_test.go @@ -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}, + } +} diff --git a/frontend/src/components/admin/payment/DailyRevenueChart.vue b/frontend/src/components/admin/payment/DailyRevenueChart.vue index 77583da17b..6e2544f994 100644 --- a/frontend/src/components/admin/payment/DailyRevenueChart.vue +++ b/frontend/src/components/admin/payment/DailyRevenueChart.vue @@ -33,31 +33,43 @@ import { } from 'chart.js' import { Line } from 'vue-chartjs' import LoadingSpinner from '@/components/common/LoadingSpinner.vue' +import type { DailyPaymentStats } from '@/types/payment' ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Tooltip, Legend, Filler) const { t } = useI18n() const props = defineProps<{ - data: { date: string; amount: number; count: number }[] + data: DailyPaymentStats[] loading?: boolean }>() +const colors = [ + ['rgb(59, 130, 246)', 'rgba(59, 130, 246, 0.1)'], + ['rgb(168, 85, 247)', 'rgba(168, 85, 247, 0.1)'], + ['rgb(245, 158, 11)', 'rgba(245, 158, 11, 0.1)'], + ['rgb(239, 68, 68)', 'rgba(239, 68, 68, 0.1)'], +] + const chartData = computed(() => { if (!props.data || props.data.length === 0) return null + const currencies = [...new Set(props.data.flatMap(day => Object.keys(day.amount)))].sort() return { labels: props.data.map(d => d.date), datasets: [ - { - label: t('payment.admin.revenue'), - data: props.data.map(d => d.amount), - borderColor: 'rgb(59, 130, 246)', - backgroundColor: 'rgba(59, 130, 246, 0.1)', - fill: true, - tension: 0.3, - pointRadius: 3, - pointHoverRadius: 5, - }, + ...currencies.map((currency, index) => { + const [borderColor, backgroundColor] = colors[index % colors.length] + return { + label: `${currency} ${t('payment.admin.revenue')}`, + data: props.data.map(day => day.amount[currency] || 0), + borderColor, + backgroundColor, + fill: true, + tension: 0.3, + pointRadius: 3, + pointHoverRadius: 5, + } + }), { label: t('payment.admin.orderCount'), data: props.data.map(d => d.count), diff --git a/frontend/src/components/admin/payment/OrderStatsCards.vue b/frontend/src/components/admin/payment/OrderStatsCards.vue index 0f7ec956d9..1fece5fb56 100644 --- a/frontend/src/components/admin/payment/OrderStatsCards.vue +++ b/frontend/src/components/admin/payment/OrderStatsCards.vue @@ -8,7 +8,9 @@
{{ t('payment.admin.todayRevenue') }}
-${{ formatMoney(stats.today_amount) }}
++ {{ formatMoney(currency, amount) }} +
{{ stats.today_count }} {{ t('payment.admin.orders') }}
@@ -24,7 +26,9 @@{{ t('payment.admin.totalRevenue') }}
-${{ formatMoney(stats.total_amount) }}
++ {{ formatMoney(currency, amount) }} +
{{ stats.total_count }} {{ t('payment.admin.orders') }}
@@ -53,7 +57,9 @@{{ t('payment.admin.avgAmount') }}
-${{ formatMoney(stats.avg_amount) }}
++ {{ formatMoney(currency, amount) }} +
{{ currency }}
+{{ currency }}
+