Fix scheduled notification actions and speed up payments loading.
Add row actions with view details on scheduled jobs and replace client-side payment fetch-all with server-side pagination and parallel stats queries. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
7b22d6d54c
commit
1799488127
|
|
@ -5,7 +5,9 @@ import {
|
|||
CalendarClock,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Eye,
|
||||
Megaphone,
|
||||
MoreHorizontal,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
XCircle,
|
||||
|
|
@ -13,12 +15,24 @@ import {
|
|||
import { toast } from "sonner"
|
||||
import {
|
||||
cancelScheduledNotification,
|
||||
getScheduledNotificationById,
|
||||
getScheduledNotifications,
|
||||
} from "../../api/notifications.api"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent } from "../../components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
} from "../../components/ui/dialog"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "../../components/ui/dropdown-menu"
|
||||
import { Select } from "../../components/ui/select"
|
||||
import { SpinnerIcon } from "../../components/ui/spinner-icon"
|
||||
import {
|
||||
|
|
@ -71,6 +85,8 @@ export function ScheduledNotificationsPage() {
|
|||
const [statusFilter, setStatusFilter] = useState<"" | ScheduledNotificationStatus>("")
|
||||
const [channelFilter, setChannelFilter] = useState<"" | NotificationChannel>("")
|
||||
const [cancellingId, setCancellingId] = useState<number | null>(null)
|
||||
const [selectedJob, setSelectedJob] = useState<ScheduledNotification | null>(null)
|
||||
const [detailLoading, setDetailLoading] = useState(false)
|
||||
|
||||
const totalPages = useMemo(
|
||||
() => Math.max(1, Math.ceil(totalCount / limit)),
|
||||
|
|
@ -89,11 +105,11 @@ export function ScheduledNotificationsPage() {
|
|||
})
|
||||
setRows(res.data.scheduled_notifications)
|
||||
setTotalCount(res.data.total_count)
|
||||
} catch {
|
||||
} catch (error) {
|
||||
setError(true)
|
||||
setRows([])
|
||||
setTotalCount(0)
|
||||
notifyApiError(err, "Failed to load scheduled notifications")
|
||||
notifyApiError(error, "Failed to load scheduled notifications")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
|
|
@ -116,13 +132,28 @@ export function ScheduledNotificationsPage() {
|
|||
description: `Job #${job.id} was cancelled.`,
|
||||
})
|
||||
await load()
|
||||
} catch {
|
||||
notifyApiError(err, "Failed to cancel scheduled notification")
|
||||
} catch (error) {
|
||||
notifyApiError(error, "Failed to cancel scheduled notification")
|
||||
} finally {
|
||||
setCancellingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleViewDetails = async (job: ScheduledNotification) => {
|
||||
setSelectedJob(job)
|
||||
setDetailLoading(true)
|
||||
try {
|
||||
const res = await getScheduledNotificationById(job.id)
|
||||
if (res.data) {
|
||||
setSelectedJob(res.data)
|
||||
}
|
||||
} catch (error) {
|
||||
notifyApiError(error, "Failed to load scheduled notification details")
|
||||
} finally {
|
||||
setDetailLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const targetingSummary = (job: ScheduledNotification) => {
|
||||
if (job.target_role) return `Role: ${job.target_role}`
|
||||
if (job.target_user_ids?.length) {
|
||||
|
|
@ -288,21 +319,39 @@ export function ScheduledNotificationsPage() {
|
|||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{(job.status === "pending" || job.status === "processing") && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={cancellingId === job.id}
|
||||
onClick={() => void handleCancel(job)}
|
||||
>
|
||||
{cancellingId === job.id ? (
|
||||
<SpinnerIcon className="mr-1 h-3.5 w-3.5" alt="" />
|
||||
) : (
|
||||
<XCircle className="mr-1 h-3.5 w-3.5" />
|
||||
)}
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
<div className="flex justify-end">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 rounded-[6px] p-0 text-grayScale-400 hover:text-grayScale-700"
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-44">
|
||||
<DropdownMenuItem onClick={() => void handleViewDetails(job)}>
|
||||
<Eye className="mr-2 h-3.5 w-3.5" />
|
||||
View details
|
||||
</DropdownMenuItem>
|
||||
{(job.status === "pending" || job.status === "processing") && (
|
||||
<DropdownMenuItem
|
||||
disabled={cancellingId === job.id}
|
||||
onClick={() => void handleCancel(job)}
|
||||
>
|
||||
{cancellingId === job.id ? (
|
||||
<SpinnerIcon className="mr-2 h-3.5 w-3.5" alt="" />
|
||||
) : (
|
||||
<XCircle className="mr-2 h-3.5 w-3.5" />
|
||||
)}
|
||||
Cancel job
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
|
|
@ -339,6 +388,66 @@ export function ScheduledNotificationsPage() {
|
|||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog
|
||||
open={selectedJob != null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setSelectedJob(null)
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-lg gap-0 overflow-hidden rounded-2xl border-0 p-0">
|
||||
{selectedJob ? (
|
||||
<>
|
||||
<div className="border-b border-grayScale-100 px-6 py-5 pr-14">
|
||||
<DialogTitle className="text-base font-bold text-grayScale-900">
|
||||
Scheduled job #{selectedJob.id}
|
||||
</DialogTitle>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||
<Badge variant={scheduledStatusBadgeVariant(selectedJob.status)}>
|
||||
{selectedJob.status}
|
||||
</Badge>
|
||||
<span className="text-xs text-grayScale-500">
|
||||
{channelLabel(selectedJob.channel)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-4 px-6 py-5 text-sm">
|
||||
{detailLoading ? (
|
||||
<div className="flex items-center gap-2 text-grayScale-500">
|
||||
<SpinnerIcon className="h-4 w-4" alt="" />
|
||||
Loading details…
|
||||
</div>
|
||||
) : null}
|
||||
<DetailRow label="Title" value={selectedJob.title || "—"} />
|
||||
<DetailRow label="Message" value={selectedJob.message} />
|
||||
<DetailRow label="Audience" value={targetingSummary(selectedJob)} />
|
||||
<DetailRow
|
||||
label="Scheduled"
|
||||
value={formatScheduledAtLabel(selectedJob.scheduled_at)}
|
||||
/>
|
||||
{selectedJob.sent_at ? (
|
||||
<DetailRow label="Sent" value={formatScheduledAtLabel(selectedJob.sent_at)} />
|
||||
) : null}
|
||||
{selectedJob.last_error ? (
|
||||
<DetailRow label="Last error" value={selectedJob.last_error} />
|
||||
) : null}
|
||||
{selectedJob.channel === "email" && selectedJob.email_template_slug ? (
|
||||
<DetailRow label="Template" value={selectedJob.email_template_slug} />
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DetailRow({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<p className="text-[11px] font-bold uppercase tracking-wider text-grayScale-400">{label}</p>
|
||||
<p className="whitespace-pre-wrap break-words text-grayScale-700">{value}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import {
|
|||
} from "lucide-react"
|
||||
import { Link } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
import { getAllPayments } from "../../api/payments.api"
|
||||
import { getPayments } from "../../api/payments.api"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { ExportCsvButton } from "../../components/export/ExportCsvButton"
|
||||
import { ExportTruncationWarning } from "../../components/export/ExportTruncationWarning"
|
||||
|
|
@ -48,13 +48,12 @@ import {
|
|||
formatPaymentStatus,
|
||||
computePaymentAggregateStats,
|
||||
paymentCustomerName,
|
||||
paymentMatchesDateRange,
|
||||
paymentStatusBadgeVariant,
|
||||
type PaymentAggregateStats,
|
||||
} from "../../lib/payments"
|
||||
import { paymentListFiltersToExportQuery } from "../../lib/csvExportFilters"
|
||||
import { SUBSCRIPTION_CURRENCIES, SUBSCRIPTION_PLAN_CATEGORIES } from "../../lib/subscriptionPlans"
|
||||
import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../lib/csv-export"
|
||||
import { paymentListFiltersToExportQuery } from "../../lib/csvExportFilters"
|
||||
import type {
|
||||
Payment,
|
||||
PaymentPlanCategory,
|
||||
|
|
@ -88,35 +87,16 @@ type PaymentListFilters = {
|
|||
dateTo: string
|
||||
}
|
||||
|
||||
function paymentMatchesSearch(payment: Payment, query: string): boolean {
|
||||
const q = query.trim().toLowerCase()
|
||||
if (!q) return true
|
||||
const haystack = [
|
||||
String(payment.id),
|
||||
String(payment.user_id),
|
||||
String(payment.plan_id),
|
||||
String(payment.subscription_id),
|
||||
payment.session_id,
|
||||
payment.transaction_id,
|
||||
payment.nonce,
|
||||
payment.amount,
|
||||
payment.currency,
|
||||
payment.payment_method,
|
||||
payment.status,
|
||||
payment.plan_name,
|
||||
payment.plan_category,
|
||||
formatPaymentPlanCategory(payment.plan_category),
|
||||
payment.user_email,
|
||||
payment.user_first_name,
|
||||
payment.user_last_name,
|
||||
paymentCustomerName(payment),
|
||||
formatPaymentMethod(payment.payment_method),
|
||||
formatPaymentStatus(payment.status),
|
||||
formatPaymentAmount(payment),
|
||||
]
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
return haystack.includes(q)
|
||||
function buildPaymentsQuery(filters: PaymentListFilters, searchQuery: string) {
|
||||
return paymentListFiltersToExportQuery({
|
||||
status: filters.status || undefined,
|
||||
provider: filters.provider || undefined,
|
||||
planCategory: filters.planCategory || undefined,
|
||||
currency: filters.currency || undefined,
|
||||
reference: searchQuery.trim() || undefined,
|
||||
dateFrom: filters.dateFrom || undefined,
|
||||
dateTo: filters.dateTo || undefined,
|
||||
})
|
||||
}
|
||||
|
||||
function copyText(value: string, label: string) {
|
||||
|
|
@ -140,9 +120,12 @@ export function PaymentsPage() {
|
|||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(false)
|
||||
const [payments, setPayments] = useState<Payment[]>([])
|
||||
const [totalCount, setTotalCount] = useState(0)
|
||||
const [paymentStats, setPaymentStats] = useState<PaymentAggregateStats>(EMPTY_PAYMENT_STATS)
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE)
|
||||
const [searchQuery, setSearchQuery] = useState("")
|
||||
const [debouncedSearchQuery, setDebouncedSearchQuery] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState<PaymentStatus | "">("")
|
||||
const [providerFilter, setProviderFilter] = useState<PaymentProvider | "">("")
|
||||
const [planCategoryFilter, setPlanCategoryFilter] = useState<PaymentPlanCategory | "">("")
|
||||
|
|
@ -182,23 +165,95 @@ export function PaymentsPage() {
|
|||
{ value: dateTo },
|
||||
])
|
||||
|
||||
const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim())
|
||||
const hasActiveFilters = activeFilterCount > 0 || Boolean(debouncedSearchQuery.trim())
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
setDebouncedSearchQuery(searchQuery)
|
||||
}, 300)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [searchQuery])
|
||||
|
||||
const fetchPayments = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError(false)
|
||||
try {
|
||||
const all = await getAllPayments({})
|
||||
setPayments(all)
|
||||
const baseQuery = buildPaymentsQuery(listFilters, debouncedSearchQuery)
|
||||
const offset = (page - 1) * pageSize
|
||||
const listPromise = getPayments({
|
||||
...baseQuery,
|
||||
limit: pageSize,
|
||||
offset,
|
||||
})
|
||||
|
||||
const statsPromise = (async () => {
|
||||
if (!statusFilter) {
|
||||
const [successRes, pendingRes, revenueRes] = await Promise.all([
|
||||
getPayments({ ...baseQuery, status: "SUCCESS", limit: 1, offset: 0 }),
|
||||
getPayments({ ...baseQuery, status: "PENDING", limit: 1, offset: 0 }),
|
||||
getPayments({
|
||||
...baseQuery,
|
||||
status: "SUCCESS",
|
||||
limit: 100,
|
||||
offset: 0,
|
||||
}),
|
||||
])
|
||||
setPaymentStats({
|
||||
successfulCount: successRes.data.total_count,
|
||||
pendingCount: pendingRes.data.total_count,
|
||||
totalRevenue: computePaymentAggregateStats(revenueRes.data.payments).totalRevenue,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const filteredRes = await getPayments({
|
||||
...baseQuery,
|
||||
limit: 1,
|
||||
offset: 0,
|
||||
})
|
||||
const filteredTotal = filteredRes.data.total_count
|
||||
let totalRevenue = 0
|
||||
if (statusFilter === "SUCCESS" && filteredTotal > 0) {
|
||||
const revenueRes = await getPayments({
|
||||
...baseQuery,
|
||||
status: "SUCCESS",
|
||||
limit: Math.min(100, filteredTotal),
|
||||
offset: 0,
|
||||
})
|
||||
totalRevenue = computePaymentAggregateStats(revenueRes.data.payments).totalRevenue
|
||||
}
|
||||
setPaymentStats({
|
||||
successfulCount: statusFilter === "SUCCESS" ? filteredTotal : 0,
|
||||
pendingCount: statusFilter === "PENDING" ? filteredTotal : 0,
|
||||
totalRevenue,
|
||||
})
|
||||
})()
|
||||
|
||||
const [listRes] = await Promise.all([listPromise, statsPromise])
|
||||
|
||||
setPayments(listRes.data.payments)
|
||||
setTotalCount(listRes.data.total_count)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
setError(true)
|
||||
setPayments([])
|
||||
setTotalCount(0)
|
||||
setPaymentStats(EMPTY_PAYMENT_STATS)
|
||||
notifyApiError(e, "Failed to load payments")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
}, [
|
||||
debouncedSearchQuery,
|
||||
statusFilter,
|
||||
providerFilter,
|
||||
planCategoryFilter,
|
||||
currencyFilter,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
page,
|
||||
pageSize,
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
void fetchPayments()
|
||||
|
|
@ -207,7 +262,7 @@ export function PaymentsPage() {
|
|||
useEffect(() => {
|
||||
setPage(1)
|
||||
}, [
|
||||
searchQuery,
|
||||
debouncedSearchQuery,
|
||||
statusFilter,
|
||||
providerFilter,
|
||||
planCategoryFilter,
|
||||
|
|
@ -217,51 +272,11 @@ export function PaymentsPage() {
|
|||
pageSize,
|
||||
])
|
||||
|
||||
const filteredPayments = useMemo(() => {
|
||||
return payments.filter((payment) => {
|
||||
if (statusFilter && payment.status !== statusFilter) return false
|
||||
if (
|
||||
providerFilter &&
|
||||
payment.payment_method?.toUpperCase() !== providerFilter.toUpperCase()
|
||||
) {
|
||||
return false
|
||||
}
|
||||
if (planCategoryFilter && payment.plan_category !== planCategoryFilter) return false
|
||||
if (
|
||||
currencyFilter &&
|
||||
payment.currency?.toUpperCase() !== currencyFilter.toUpperCase()
|
||||
) {
|
||||
return false
|
||||
}
|
||||
if (!paymentMatchesDateRange(payment, dateFrom, dateTo)) return false
|
||||
return paymentMatchesSearch(payment, searchQuery)
|
||||
})
|
||||
}, [
|
||||
payments,
|
||||
statusFilter,
|
||||
providerFilter,
|
||||
planCategoryFilter,
|
||||
currencyFilter,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
searchQuery,
|
||||
])
|
||||
|
||||
const paymentStats: PaymentAggregateStats = useMemo(
|
||||
() =>
|
||||
filteredPayments.length
|
||||
? computePaymentAggregateStats(filteredPayments)
|
||||
: EMPTY_PAYMENT_STATS,
|
||||
[filteredPayments],
|
||||
)
|
||||
|
||||
const totalCount = filteredPayments.length
|
||||
const pageCount = Math.max(1, Math.ceil(totalCount / pageSize))
|
||||
const safePage = Math.min(page, pageCount)
|
||||
const paginatedPayments = useMemo(
|
||||
() => filteredPayments.slice((safePage - 1) * pageSize, safePage * pageSize),
|
||||
[filteredPayments, safePage, pageSize],
|
||||
)
|
||||
const paginatedPayments = payments
|
||||
|
||||
const { successfulCount, totalRevenue, pendingCount } = paymentStats
|
||||
|
||||
const toggleStatus = (value: PaymentStatus) => {
|
||||
setStatusFilter((current) => (current === value ? "" : value))
|
||||
|
|
@ -286,8 +301,6 @@ export function PaymentsPage() {
|
|||
setPage(1)
|
||||
}
|
||||
|
||||
const { successfulCount, totalRevenue, pendingCount } = paymentStats
|
||||
|
||||
const pageStart = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1
|
||||
const pageEnd = Math.min(safePage * pageSize, totalCount)
|
||||
const canPrev = safePage > 1
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user