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) }} +

@@ -63,7 +69,7 @@ diff --git a/frontend/src/components/admin/payment/PaymentMethodChart.vue b/frontend/src/components/admin/payment/PaymentMethodChart.vue index dd6909e95b..00b3178f24 100644 --- a/frontend/src/components/admin/payment/PaymentMethodChart.vue +++ b/frontend/src/components/admin/payment/PaymentMethodChart.vue @@ -18,20 +18,23 @@ {{ t('payment.methods.' + method.type, method.type) }} -
- - ${{ method.amount.toFixed(2) }} +
+ + {{ formatMoney(currency, amount) }} ({{ method.count }})
-
-
+
+ {{ currency }} +
+
+
@@ -41,11 +44,12 @@ diff --git a/frontend/src/components/admin/payment/TopUsersLeaderboard.vue b/frontend/src/components/admin/payment/TopUsersLeaderboard.vue index 1c85fcf161..ca635735d2 100644 --- a/frontend/src/components/admin/payment/TopUsersLeaderboard.vue +++ b/frontend/src/components/admin/payment/TopUsersLeaderboard.vue @@ -4,31 +4,34 @@ {{ t('payment.admin.topUsers') }}
{{ t('payment.admin.noData') }}
-
-
- - {{ idx + 1 }} +
+

{{ currency }}

+
+
+ + {{ idx + 1 }} + + {{ user.email }} +
+ + {{ formatMoney(currency, user.amount) }} - {{ user.email }}
- - ${{ user.amount.toFixed(2) }} -
@@ -36,11 +39,12 @@ diff --git a/frontend/src/types/payment.ts b/frontend/src/types/payment.ts index 726e101edd..b94dbf42e4 100644 --- a/frontend/src/types/payment.ts +++ b/frontend/src/types/payment.ts @@ -222,13 +222,33 @@ export interface CreateOrderResult { jsapi_payload?: WechatJSAPIPayload } +export type CurrencyAmounts = Record + +export interface DailyPaymentStats { + date: string + amount: CurrencyAmounts + count: number +} + +export interface PaymentMethodStats { + type: string + amount: CurrencyAmounts + count: number +} + +export interface TopUserPaymentStats { + user_id: number + email: string + amount: number +} + export interface DashboardStats { - today_amount: number - total_amount: number + today_amount: CurrencyAmounts + total_amount: CurrencyAmounts today_count: number total_count: number - avg_amount: number - daily_series: { date: string; amount: number; count: number }[] - payment_methods: { type: string; amount: number; count: number }[] - top_users: { user_id: number; email: string; amount: number }[] + avg_amount: CurrencyAmounts + daily_series: DailyPaymentStats[] + payment_methods: PaymentMethodStats[] + top_users: Record } diff --git a/frontend/src/views/admin/orders/AdminPaymentDashboardView.vue b/frontend/src/views/admin/orders/AdminPaymentDashboardView.vue index 5a80db44f0..70fe95962a 100644 --- a/frontend/src/views/admin/orders/AdminPaymentDashboardView.vue +++ b/frontend/src/views/admin/orders/AdminPaymentDashboardView.vue @@ -41,8 +41,8 @@ {{ t('payment.methods.' + method.type, method.type) }}
-
- ¥{{ method.amount.toFixed(2) }} +
+ {{ formatMoney(currency, amount) }} ({{ method.count }})
@@ -50,14 +50,17 @@

{{ t('payment.admin.topUsers') }}

-
{{ t('payment.admin.noData') }}
+
{{ t('payment.admin.noData') }}
-
-
- {{ idx + 1 }} - {{ user.email }} +
+

{{ currency }}

+
+
+ {{ idx + 1 }} + {{ user.email }} +
+ {{ formatMoney(currency, user.amount) }}
- ¥{{ user.amount.toFixed(2) }}
@@ -73,7 +76,7 @@ import { useI18n } from 'vue-i18n' import { useAppStore } from '@/stores/app' import { adminPaymentAPI } from '@/api/admin/payment' import { extractI18nErrorMessage } from '@/utils/apiError' -import type { DashboardStats } from '@/types/payment' +import type { CurrencyAmounts, DashboardStats, TopUserPaymentStats } from '@/types/payment' import AppLayout from '@/components/layout/AppLayout.vue' import LoadingSpinner from '@/components/common/LoadingSpinner.vue' import Icon from '@/components/icons/Icon.vue' @@ -104,6 +107,22 @@ function rankClass(idx: number): string { return 'bg-gray-100 text-gray-500 dark:bg-dark-700 dark:text-gray-400' } +function sortedAmounts(amounts: CurrencyAmounts): [string, number][] { + return Object.entries(amounts).sort(([left], [right]) => left.localeCompare(right)) +} + +function sortedTopUsers(usersByCurrency: Record): [string, TopUserPaymentStats[]][] { + return Object.entries(usersByCurrency).sort(([left], [right]) => left.localeCompare(right)) +} + +function hasTopUsers(usersByCurrency: Record): boolean { + return Object.values(usersByCurrency).some(users => users.length > 0) +} + +function formatMoney(currency: string, amount: number): string { + return new Intl.NumberFormat(undefined, { style: 'currency', currency }).format(amount) +} + async function loadDashboard() { loading.value = true try {