Fix payments page summary cards to aggregate across all filtered results.
Fetch the full payment dataset for analytics so successful count and revenue reflect every matching transaction, not just the current table page. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
f833275b75
commit
5e7765d6e3
|
|
@ -1,4 +1,5 @@
|
||||||
import http from "./http"
|
import http from "./http"
|
||||||
|
import { fetchAllOffsetPages } from "../lib/fetchAllOffsetPages"
|
||||||
import type { GetPaymentsParams, Payment, PaymentsListData, PaymentsListResponse } from "../types/payment.types"
|
import type { GetPaymentsParams, Payment, PaymentsListData, PaymentsListResponse } from "../types/payment.types"
|
||||||
|
|
||||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
|
@ -93,6 +94,33 @@ function buildQueryParams(params: GetPaymentsParams): Record<string, string | nu
|
||||||
return query
|
return query
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function paymentsFilterParams(
|
||||||
|
params: Omit<GetPaymentsParams, "limit" | "offset">,
|
||||||
|
): Omit<GetPaymentsParams, "limit" | "offset"> {
|
||||||
|
const next: Omit<GetPaymentsParams, "limit" | "offset"> = {}
|
||||||
|
if (params.status?.trim()) next.status = params.status.trim()
|
||||||
|
if (params.provider?.trim()) {
|
||||||
|
next.provider = params.provider.trim()
|
||||||
|
} else if (params.payment_method?.trim()) {
|
||||||
|
next.payment_method = params.payment_method.trim()
|
||||||
|
}
|
||||||
|
if (params.plan_category?.trim()) next.plan_category = params.plan_category.trim()
|
||||||
|
if (params.currency?.trim()) next.currency = params.currency.trim()
|
||||||
|
if (params.reference?.trim()) next.reference = params.reference.trim()
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fetches every payment matching filters (paginates through the API). */
|
||||||
|
export async function getAllPayments(
|
||||||
|
params: Omit<GetPaymentsParams, "limit" | "offset"> = {},
|
||||||
|
): Promise<Payment[]> {
|
||||||
|
const filters = paymentsFilterParams(params)
|
||||||
|
return fetchAllOffsetPages(async (offset, limit) => {
|
||||||
|
const res = await getPayments({ ...filters, limit, offset })
|
||||||
|
return { items: res.data.payments, total_count: res.data.total_count }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export const getPayments = (params: GetPaymentsParams = {}) =>
|
export const getPayments = (params: GetPaymentsParams = {}) =>
|
||||||
http.get<PaymentsListResponse>("/admin/payments", { params: buildQueryParams(params) }).then((res) => {
|
http.get<PaymentsListResponse>("/admin/payments", { params: buildQueryParams(params) }).then((res) => {
|
||||||
const parsed = parsePaymentsList(res.data)
|
const parsed = parsePaymentsList(res.data)
|
||||||
|
|
|
||||||
|
|
@ -49,3 +49,27 @@ export function paymentStatusBadgeVariant(
|
||||||
if (s === "FAILED" || s === "CANCELLED" || s === "EXPIRED") return "destructive"
|
if (s === "FAILED" || s === "CANCELLED" || s === "EXPIRED") return "destructive"
|
||||||
return "secondary"
|
return "secondary"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PaymentAggregateStats {
|
||||||
|
successfulCount: number
|
||||||
|
totalRevenue: number
|
||||||
|
pendingCount: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function computePaymentAggregateStats(payments: Payment[]): PaymentAggregateStats {
|
||||||
|
let successfulCount = 0
|
||||||
|
let totalRevenue = 0
|
||||||
|
let pendingCount = 0
|
||||||
|
|
||||||
|
for (const payment of payments) {
|
||||||
|
const status = payment.status.toUpperCase()
|
||||||
|
if (status === "SUCCESS") {
|
||||||
|
successfulCount += 1
|
||||||
|
totalRevenue += Number(payment.amount) || 0
|
||||||
|
} else if (status === "PENDING" || status === "PROCESSING") {
|
||||||
|
pendingCount += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { successfulCount, totalRevenue, pendingCount }
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ import {
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import { Link } from "react-router-dom"
|
import { Link } from "react-router-dom"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { getPayments } from "../../api/payments.api"
|
import { getAllPayments, getPayments, paymentsFilterParams } from "../../api/payments.api"
|
||||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||||
import { Badge } from "../../components/ui/badge"
|
import { Badge } from "../../components/ui/badge"
|
||||||
import { Button } from "../../components/ui/button"
|
import { Button } from "../../components/ui/button"
|
||||||
|
|
@ -37,8 +37,10 @@ import {
|
||||||
formatPaymentMethod,
|
formatPaymentMethod,
|
||||||
formatPaymentPlanCategory,
|
formatPaymentPlanCategory,
|
||||||
formatPaymentStatus,
|
formatPaymentStatus,
|
||||||
|
computePaymentAggregateStats,
|
||||||
paymentCustomerName,
|
paymentCustomerName,
|
||||||
paymentStatusBadgeVariant,
|
paymentStatusBadgeVariant,
|
||||||
|
type PaymentAggregateStats,
|
||||||
} from "../../lib/payments"
|
} from "../../lib/payments"
|
||||||
import { SUBSCRIPTION_CURRENCIES, SUBSCRIPTION_PLAN_CATEGORIES } from "../../lib/subscriptionPlans"
|
import { SUBSCRIPTION_CURRENCIES, SUBSCRIPTION_PLAN_CATEGORIES } from "../../lib/subscriptionPlans"
|
||||||
import type {
|
import type {
|
||||||
|
|
@ -82,11 +84,19 @@ function copyText(value: string, label: string) {
|
||||||
toast.success(`${label} copied`)
|
toast.success(`${label} copied`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const EMPTY_PAYMENT_STATS: PaymentAggregateStats = {
|
||||||
|
successfulCount: 0,
|
||||||
|
totalRevenue: 0,
|
||||||
|
pendingCount: 0,
|
||||||
|
}
|
||||||
|
|
||||||
export function PaymentsPage() {
|
export function PaymentsPage() {
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [statsLoading, setStatsLoading] = useState(true)
|
||||||
const [error, setError] = useState(false)
|
const [error, setError] = useState(false)
|
||||||
const [payments, setPayments] = useState<Payment[]>([])
|
const [payments, setPayments] = useState<Payment[]>([])
|
||||||
const [totalCount, setTotalCount] = useState(0)
|
const [totalCount, setTotalCount] = useState(0)
|
||||||
|
const [paymentStats, setPaymentStats] = useState<PaymentAggregateStats>(EMPTY_PAYMENT_STATS)
|
||||||
const [offset, setOffset] = useState(0)
|
const [offset, setOffset] = useState(0)
|
||||||
const [pageSize, setPageSize] = useState(20)
|
const [pageSize, setPageSize] = useState(20)
|
||||||
const [statusFilter, setStatusFilter] = useState<PaymentStatus | "">("")
|
const [statusFilter, setStatusFilter] = useState<PaymentStatus | "">("")
|
||||||
|
|
@ -134,11 +144,13 @@ export function PaymentsPage() {
|
||||||
const res = await getPayments({
|
const res = await getPayments({
|
||||||
limit,
|
limit,
|
||||||
offset: nextOffset,
|
offset: nextOffset,
|
||||||
|
...paymentsFilterParams({
|
||||||
...(filters.status ? { status: filters.status } : {}),
|
...(filters.status ? { status: filters.status } : {}),
|
||||||
...(filters.provider ? { provider: filters.provider } : {}),
|
...(filters.provider ? { provider: filters.provider } : {}),
|
||||||
...(filters.planCategory ? { plan_category: filters.planCategory } : {}),
|
...(filters.planCategory ? { plan_category: filters.planCategory } : {}),
|
||||||
...(filters.currency ? { currency: filters.currency } : {}),
|
...(filters.currency ? { currency: filters.currency } : {}),
|
||||||
...(filters.reference ? { reference: filters.reference } : {}),
|
...(filters.reference ? { reference: filters.reference } : {}),
|
||||||
|
}),
|
||||||
})
|
})
|
||||||
setPayments(res.data.payments)
|
setPayments(res.data.payments)
|
||||||
setTotalCount(res.data.total_count)
|
setTotalCount(res.data.total_count)
|
||||||
|
|
@ -155,6 +167,26 @@ export function PaymentsPage() {
|
||||||
[],
|
[],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const fetchPaymentStats = useCallback(async (filters: PaymentListFilters) => {
|
||||||
|
setStatsLoading(true)
|
||||||
|
try {
|
||||||
|
const all = await getAllPayments({
|
||||||
|
...(filters.status ? { status: filters.status } : {}),
|
||||||
|
...(filters.provider ? { provider: filters.provider } : {}),
|
||||||
|
...(filters.planCategory ? { plan_category: filters.planCategory } : {}),
|
||||||
|
...(filters.currency ? { currency: filters.currency } : {}),
|
||||||
|
...(filters.reference ? { reference: filters.reference } : {}),
|
||||||
|
})
|
||||||
|
setPaymentStats(computePaymentAggregateStats(all))
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
setPaymentStats(EMPTY_PAYMENT_STATS)
|
||||||
|
toast.error("Failed to load payment summary")
|
||||||
|
} finally {
|
||||||
|
setStatsLoading(false)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void fetchPayments(offset, pageSize, listFilters)
|
void fetchPayments(offset, pageSize, listFilters)
|
||||||
}, [
|
}, [
|
||||||
|
|
@ -168,6 +200,17 @@ export function PaymentsPage() {
|
||||||
fetchPayments,
|
fetchPayments,
|
||||||
])
|
])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void fetchPaymentStats(listFilters)
|
||||||
|
}, [
|
||||||
|
statusFilter,
|
||||||
|
providerFilter,
|
||||||
|
planCategoryFilter,
|
||||||
|
currencyFilter,
|
||||||
|
referenceFilter,
|
||||||
|
fetchPaymentStats,
|
||||||
|
])
|
||||||
|
|
||||||
const toggleStatus = (value: PaymentStatus) => {
|
const toggleStatus = (value: PaymentStatus) => {
|
||||||
setStatusFilter((current) => (current === value ? "" : value))
|
setStatusFilter((current) => (current === value ? "" : value))
|
||||||
setOffset(0)
|
setOffset(0)
|
||||||
|
|
@ -193,12 +236,12 @@ export function PaymentsPage() {
|
||||||
setOffset(0)
|
setOffset(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
const successfulOnPage = payments.filter((p) => p.status.toUpperCase() === "SUCCESS")
|
const refreshAll = () => {
|
||||||
const pageRevenue = successfulOnPage.reduce((sum, p) => sum + (Number(p.amount) || 0), 0)
|
void fetchPayments(offset, pageSize, listFilters)
|
||||||
const pendingOnPage = payments.filter((p) => {
|
void fetchPaymentStats(listFilters)
|
||||||
const s = p.status.toUpperCase()
|
}
|
||||||
return s === "PENDING" || s === "PROCESSING"
|
|
||||||
}).length
|
const { successfulCount, totalRevenue, pendingCount } = paymentStats
|
||||||
|
|
||||||
const pageStart = totalCount === 0 ? 0 : offset + 1
|
const pageStart = totalCount === 0 ? 0 : offset + 1
|
||||||
const pageEnd = Math.min(offset + payments.length, totalCount)
|
const pageEnd = Math.min(offset + payments.length, totalCount)
|
||||||
|
|
@ -220,8 +263,8 @@ export function PaymentsPage() {
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="shrink-0 rounded-[6px]"
|
className="shrink-0 rounded-[6px]"
|
||||||
disabled={loading}
|
disabled={loading || statsLoading}
|
||||||
onClick={() => void fetchPayments(offset, pageSize, listFilters)}
|
onClick={refreshAll}
|
||||||
>
|
>
|
||||||
<RefreshCw className={cn("mr-2 h-4 w-4", loading && "animate-spin")} />
|
<RefreshCw className={cn("mr-2 h-4 w-4", loading && "animate-spin")} />
|
||||||
Refresh
|
Refresh
|
||||||
|
|
@ -248,8 +291,10 @@ export function PaymentsPage() {
|
||||||
<TrendingUp className="h-5 w-5" />
|
<TrendingUp className="h-5 w-5" />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="text-xs font-medium text-grayScale-500">Successful (this page)</p>
|
<p className="text-xs font-medium text-grayScale-500">Successful payments</p>
|
||||||
<p className="text-2xl font-bold text-grayScale-900">{successfulOnPage.length}</p>
|
<p className="text-2xl font-bold text-grayScale-900">
|
||||||
|
{statsLoading ? "…" : successfulCount.toLocaleString()}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
@ -260,11 +305,13 @@ export function PaymentsPage() {
|
||||||
<Wallet className="h-5 w-5" />
|
<Wallet className="h-5 w-5" />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="text-xs font-medium text-grayScale-500">Revenue (this page)</p>
|
<p className="text-xs font-medium text-grayScale-500">Revenue</p>
|
||||||
<p className="text-2xl font-bold text-grayScale-900">
|
<p className="text-2xl font-bold text-grayScale-900">
|
||||||
{pageRevenue.toLocaleString()} ETB
|
{statsLoading ? "…" : `${totalRevenue.toLocaleString()} ETB`}
|
||||||
|
</p>
|
||||||
|
<p className="text-[11px] text-grayScale-400">
|
||||||
|
{statsLoading ? "Loading summary…" : `${pendingCount.toLocaleString()} pending`}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-[11px] text-grayScale-400">{pendingOnPage} pending on page</p>
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
@ -395,7 +442,7 @@ export function PaymentsPage() {
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
className="rounded-[6px]"
|
className="rounded-[6px]"
|
||||||
onClick={() => void fetchPayments(offset, pageSize, listFilters)}
|
onClick={refreshAll}
|
||||||
>
|
>
|
||||||
Try again
|
Try again
|
||||||
</Button>
|
</Button>
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user