mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-10-07 15:38:22 +08: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},
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-xs font-medium text-gray-500 dark:text-gray-400">{{ t('payment.admin.todayRevenue') }}</p>
|
||||
<p class="text-xl font-bold text-gray-900 dark:text-white">${{ formatMoney(stats.today_amount) }}</p>
|
||||
<p v-for="[currency, amount] in sortedAmounts(stats.today_amount)" :key="currency" class="text-xl font-bold text-gray-900 dark:text-white">
|
||||
{{ formatMoney(currency, amount) }}
|
||||
</p>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400">
|
||||
{{ stats.today_count }} {{ t('payment.admin.orders') }}
|
||||
</p>
|
||||
@@ -24,7 +26,9 @@
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-xs font-medium text-gray-500 dark:text-gray-400">{{ t('payment.admin.totalRevenue') }}</p>
|
||||
<p class="text-xl font-bold text-gray-900 dark:text-white">${{ formatMoney(stats.total_amount) }}</p>
|
||||
<p v-for="[currency, amount] in sortedAmounts(stats.total_amount)" :key="currency" class="text-xl font-bold text-gray-900 dark:text-white">
|
||||
{{ formatMoney(currency, amount) }}
|
||||
</p>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400">
|
||||
{{ stats.total_count }} {{ t('payment.admin.orders') }}
|
||||
</p>
|
||||
@@ -53,7 +57,9 @@
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-xs font-medium text-gray-500 dark:text-gray-400">{{ t('payment.admin.avgAmount') }}</p>
|
||||
<p class="text-xl font-bold text-gray-900 dark:text-white">${{ formatMoney(stats.avg_amount) }}</p>
|
||||
<p v-for="[currency, amount] in sortedAmounts(stats.avg_amount)" :key="currency" class="text-xl font-bold text-gray-900 dark:text-white">
|
||||
{{ formatMoney(currency, amount) }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -63,7 +69,7 @@
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import type { DashboardStats } from '@/types/payment'
|
||||
import type { CurrencyAmounts, DashboardStats } from '@/types/payment'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -71,7 +77,11 @@ defineProps<{
|
||||
stats: DashboardStats
|
||||
}>()
|
||||
|
||||
function formatMoney(value: number): string {
|
||||
return value.toFixed(2)
|
||||
function sortedAmounts(amounts: CurrencyAmounts): [string, number][] {
|
||||
return Object.entries(amounts).sort(([left], [right]) => left.localeCompare(right))
|
||||
}
|
||||
|
||||
function formatMoney(currency: string, amount: number): string {
|
||||
return new Intl.NumberFormat(undefined, { style: 'currency', currency }).format(amount)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -18,20 +18,23 @@
|
||||
{{ t('payment.methods.' + method.type, method.type) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="text-right">
|
||||
<span class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
${{ method.amount.toFixed(2) }}
|
||||
<div class="space-y-1 text-right">
|
||||
<span v-for="[currency, amount] in sortedAmounts(method.amount)" :key="currency" class="block text-sm font-medium text-gray-900 dark:text-white">
|
||||
{{ formatMoney(currency, amount) }}
|
||||
</span>
|
||||
<span class="ml-2 text-xs text-gray-500 dark:text-gray-400">
|
||||
({{ method.count }})
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="h-2 w-full overflow-hidden rounded-full bg-gray-100 dark:bg-dark-700">
|
||||
<div
|
||||
:class="['h-full rounded-full transition-all', barColorMap[method.type] || 'bg-gray-400']"
|
||||
:style="{ width: barWidth(method.amount) + '%' }"
|
||||
></div>
|
||||
<div v-for="[currency, amount] in sortedAmounts(method.amount)" :key="currency" class="flex items-center gap-2">
|
||||
<span class="w-10 text-xs text-gray-500 dark:text-gray-400">{{ currency }}</span>
|
||||
<div class="h-2 flex-1 overflow-hidden rounded-full bg-gray-100 dark:bg-dark-700">
|
||||
<div
|
||||
:class="['h-full rounded-full transition-all', barColorMap[method.type] || 'bg-gray-400']"
|
||||
:style="{ width: barWidth(currency, amount) + '%' }"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -41,11 +44,12 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import type { CurrencyAmounts, PaymentMethodStats } from '@/types/payment'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const props = defineProps<{
|
||||
methods: { type: string; amount: number; count: number }[]
|
||||
methods: PaymentMethodStats[]
|
||||
}>()
|
||||
|
||||
const colorMap: Record<string, string> = {
|
||||
@@ -64,12 +68,24 @@ const barColorMap: Record<string, string> = {
|
||||
stripe: 'bg-purple-500',
|
||||
}
|
||||
|
||||
const maxAmount = computed(() => {
|
||||
if (!props.methods?.length) return 1
|
||||
return Math.max(...props.methods.map(m => m.amount), 1)
|
||||
const maxAmounts = computed<CurrencyAmounts>(() => {
|
||||
return props.methods.reduce<CurrencyAmounts>((maximums, method) => {
|
||||
for (const [currency, amount] of Object.entries(method.amount)) {
|
||||
maximums[currency] = Math.max(maximums[currency] || 0, amount)
|
||||
}
|
||||
return maximums
|
||||
}, {})
|
||||
})
|
||||
|
||||
function barWidth(amount: number): number {
|
||||
return Math.min((amount / maxAmount.value) * 100, 100)
|
||||
function sortedAmounts(amounts: CurrencyAmounts): [string, number][] {
|
||||
return Object.entries(amounts).sort(([left], [right]) => left.localeCompare(right))
|
||||
}
|
||||
|
||||
function barWidth(currency: string, amount: number): number {
|
||||
return Math.min((amount / (maxAmounts.value[currency] || 1)) * 100, 100)
|
||||
}
|
||||
|
||||
function formatMoney(currency: string, amount: number): string {
|
||||
return new Intl.NumberFormat(undefined, { style: 'currency', currency }).format(amount)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -4,31 +4,34 @@
|
||||
{{ t('payment.admin.topUsers') }}
|
||||
</h3>
|
||||
<div
|
||||
v-if="!users?.length"
|
||||
v-if="!hasUsers(props.users)"
|
||||
class="flex h-32 items-center justify-center text-sm text-gray-500 dark:text-gray-400"
|
||||
>
|
||||
{{ t('payment.admin.noData') }}
|
||||
</div>
|
||||
<div v-else class="space-y-2">
|
||||
<div
|
||||
v-for="(user, idx) in users"
|
||||
:key="user.user_id"
|
||||
class="flex items-center justify-between rounded-lg px-3 py-2 hover:bg-gray-50 dark:hover:bg-dark-700"
|
||||
>
|
||||
<div class="flex items-center gap-3">
|
||||
<span
|
||||
:class="[
|
||||
'flex h-6 w-6 items-center justify-center rounded-full text-xs font-bold',
|
||||
rankClass(idx),
|
||||
]"
|
||||
>
|
||||
{{ idx + 1 }}
|
||||
<div v-for="[currency, currencyUsers] in sortedUsers(props.users)" :key="currency" class="space-y-2">
|
||||
<p class="text-xs font-semibold text-gray-500 dark:text-gray-400">{{ currency }}</p>
|
||||
<div
|
||||
v-for="(user, idx) in currencyUsers"
|
||||
:key="user.user_id"
|
||||
class="flex items-center justify-between rounded-lg px-3 py-2 hover:bg-gray-50 dark:hover:bg-dark-700"
|
||||
>
|
||||
<div class="flex items-center gap-3">
|
||||
<span
|
||||
:class="[
|
||||
'flex h-6 w-6 items-center justify-center rounded-full text-xs font-bold',
|
||||
rankClass(idx),
|
||||
]"
|
||||
>
|
||||
{{ idx + 1 }}
|
||||
</span>
|
||||
<span class="text-sm text-gray-700 dark:text-gray-300">{{ user.email }}</span>
|
||||
</div>
|
||||
<span class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{{ formatMoney(currency, user.amount) }}
|
||||
</span>
|
||||
<span class="text-sm text-gray-700 dark:text-gray-300">{{ user.email }}</span>
|
||||
</div>
|
||||
<span class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
${{ user.amount.toFixed(2) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -36,11 +39,12 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import type { TopUserPaymentStats } from '@/types/payment'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
defineProps<{
|
||||
users: { user_id: number; email: string; amount: number }[]
|
||||
const props = defineProps<{
|
||||
users: Record<string, TopUserPaymentStats[]>
|
||||
}>()
|
||||
|
||||
function rankClass(idx: number): string {
|
||||
@@ -49,4 +53,16 @@ function rankClass(idx: number): string {
|
||||
if (idx === 2) return 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400'
|
||||
return 'bg-gray-100 text-gray-500 dark:bg-dark-700 dark:text-gray-400'
|
||||
}
|
||||
|
||||
function hasUsers(usersByCurrency: Record<string, TopUserPaymentStats[]>): boolean {
|
||||
return Object.values(usersByCurrency).some(users => users.length > 0)
|
||||
}
|
||||
|
||||
function sortedUsers(usersByCurrency: Record<string, TopUserPaymentStats[]>): [string, TopUserPaymentStats[]][] {
|
||||
return Object.entries(usersByCurrency).sort(([left], [right]) => left.localeCompare(right))
|
||||
}
|
||||
|
||||
function formatMoney(currency: string, amount: number): string {
|
||||
return new Intl.NumberFormat(undefined, { style: 'currency', currency }).format(amount)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -222,13 +222,33 @@ export interface CreateOrderResult {
|
||||
jsapi_payload?: WechatJSAPIPayload
|
||||
}
|
||||
|
||||
export type CurrencyAmounts = Record<string, number>
|
||||
|
||||
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<string, TopUserPaymentStats[]>
|
||||
}
|
||||
|
||||
@@ -41,8 +41,8 @@
|
||||
<span :class="['inline-block h-3 w-3 rounded-full', methodColor(method.type)]"></span>
|
||||
<span class="text-sm text-gray-700 dark:text-gray-300">{{ t('payment.methods.' + method.type, method.type) }}</span>
|
||||
</div>
|
||||
<div class="text-right">
|
||||
<span class="text-sm font-medium text-gray-900 dark:text-white">¥{{ method.amount.toFixed(2) }}</span>
|
||||
<div class="space-y-1 text-right">
|
||||
<span v-for="[currency, amount] in sortedAmounts(method.amount)" :key="currency" class="block text-sm font-medium text-gray-900 dark:text-white">{{ formatMoney(currency, amount) }}</span>
|
||||
<span class="ml-2 text-xs text-gray-500 dark:text-gray-400">({{ method.count }})</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -50,14 +50,17 @@
|
||||
</div>
|
||||
<div class="card p-4">
|
||||
<h3 class="mb-4 text-sm font-semibold text-gray-900 dark:text-white">{{ t('payment.admin.topUsers') }}</h3>
|
||||
<div v-if="!stats.top_users?.length" class="flex h-32 items-center justify-center text-sm text-gray-500 dark:text-gray-400">{{ t('payment.admin.noData') }}</div>
|
||||
<div v-if="!hasTopUsers(stats.top_users)" class="flex h-32 items-center justify-center text-sm text-gray-500 dark:text-gray-400">{{ t('payment.admin.noData') }}</div>
|
||||
<div v-else class="space-y-2">
|
||||
<div v-for="(user, idx) in stats.top_users" :key="user.user_id" class="flex items-center justify-between rounded-lg px-3 py-2 hover:bg-gray-50 dark:hover:bg-dark-700">
|
||||
<div class="flex items-center gap-3">
|
||||
<span :class="['flex h-6 w-6 items-center justify-center rounded-full text-xs font-bold', rankClass(idx)]">{{ idx + 1 }}</span>
|
||||
<span class="text-sm text-gray-700 dark:text-gray-300">{{ user.email }}</span>
|
||||
<div v-for="[currency, users] in sortedTopUsers(stats.top_users)" :key="currency" class="space-y-2">
|
||||
<p class="text-xs font-semibold text-gray-500 dark:text-gray-400">{{ currency }}</p>
|
||||
<div v-for="(user, idx) in users" :key="user.user_id" class="flex items-center justify-between rounded-lg px-3 py-2 hover:bg-gray-50 dark:hover:bg-dark-700">
|
||||
<div class="flex items-center gap-3">
|
||||
<span :class="['flex h-6 w-6 items-center justify-center rounded-full text-xs font-bold', rankClass(idx)]">{{ idx + 1 }}</span>
|
||||
<span class="text-sm text-gray-700 dark:text-gray-300">{{ user.email }}</span>
|
||||
</div>
|
||||
<span class="text-sm font-medium text-gray-900 dark:text-white">{{ formatMoney(currency, user.amount) }}</span>
|
||||
</div>
|
||||
<span class="text-sm font-medium text-gray-900 dark:text-white">¥{{ user.amount.toFixed(2) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -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[]>): [string, TopUserPaymentStats[]][] {
|
||||
return Object.entries(usersByCurrency).sort(([left], [right]) => left.localeCompare(right))
|
||||
}
|
||||
|
||||
function hasTopUsers(usersByCurrency: Record<string, TopUserPaymentStats[]>): 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 {
|
||||
|
||||
Reference in New Issue
Block a user