Integrate server-side CSV export across admin list pages.
Add blob download helpers, permission-gated export buttons that mirror list filters, role-based export access, and client-side filenames using resource name plus timestamp. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
a8243e3ae4
commit
f06d35632f
|
|
@ -90,6 +90,29 @@ export const getTeamMembers = (page?: number, pageSize?: number) =>
|
|||
},
|
||||
})
|
||||
|
||||
/** Permissions for the signed-in team member (from the members list payload). */
|
||||
export async function fetchCurrentTeamMemberPermissions(): Promise<string[]> {
|
||||
const memberId = Number(localStorage.getItem("member_id"))
|
||||
if (!Number.isFinite(memberId)) return []
|
||||
|
||||
const batchSize = 100
|
||||
let page = 1
|
||||
let totalPages = 1
|
||||
|
||||
do {
|
||||
const res = await getTeamMembers(page, batchSize)
|
||||
totalPages = res.data.metadata?.total_pages ?? 1
|
||||
const members = (res.data.data ?? [])
|
||||
.map((entry) => normalizeTeamMember(entry))
|
||||
.filter((entry): entry is TeamMember => entry != null)
|
||||
const self = members.find((member) => member.id === memberId)
|
||||
if (self) return self.permissions ?? []
|
||||
page++
|
||||
} while (page <= totalPages)
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
export const getTeamMemberById = (id: number) =>
|
||||
http.get<GetTeamMemberResponse>(`/team/members/${id}`).then((res) => {
|
||||
const body = res.data
|
||||
|
|
|
|||
|
|
@ -409,7 +409,7 @@ export interface GetUsersParams {
|
|||
subscription_status?: string
|
||||
}
|
||||
|
||||
function buildGetUsersQuery(params: GetUsersParams): Record<string, string | number> {
|
||||
export function buildUsersListQuery(params: GetUsersParams): Record<string, string | number> {
|
||||
const q: Record<string, string | number> = {}
|
||||
const addString = (key: string, value: string | undefined) => {
|
||||
const v = value?.trim()
|
||||
|
|
@ -431,7 +431,7 @@ function buildGetUsersQuery(params: GetUsersParams): Record<string, string | num
|
|||
|
||||
export const getUsers = (params: GetUsersParams = {}) =>
|
||||
http.get<GetUsersResponse>("/users", {
|
||||
params: buildGetUsersQuery(params),
|
||||
params: buildUsersListQuery(params),
|
||||
});
|
||||
|
||||
export type UserStatus = "ACTIVE" | "DEACTIVATED" | "SUSPENDED" | "PENDING";
|
||||
|
|
|
|||
|
|
@ -58,6 +58,7 @@ import { HumanLanguageSubModulePage } from "../pages/content-management/HumanLan
|
|||
import { UserLogPage } from "../pages/user-log/UserLogPage";
|
||||
import { IssuesPage } from "../pages/issues/IssuesPage";
|
||||
import { PaymentsPage } from "../pages/payments/PaymentsPage";
|
||||
import { SubscriptionsExportPage } from "../pages/subscriptions/SubscriptionsExportPage";
|
||||
import { ProfilePage } from "../pages/ProfilePage";
|
||||
import { SettingsPage } from "../pages/SettingsPage";
|
||||
import { TeamManagementPage } from "../pages/team/TeamManagementPage";
|
||||
|
|
@ -333,6 +334,7 @@ export function AppRoutes() {
|
|||
/>
|
||||
<Route path="/notifications/all" element={<AllNotificationsPage />} />
|
||||
<Route path="/payments" element={<PaymentsPage />} />
|
||||
<Route path="/subscriptions/export" element={<SubscriptionsExportPage />} />
|
||||
<Route path="/user-log" element={<UserLogPage />} />
|
||||
<Route path="/issues" element={<IssuesPage />} />
|
||||
<Route path="/help/faqs" element={<FaqsPage />} />
|
||||
|
|
|
|||
65
src/components/export/ExportCsvButton.tsx
Normal file
65
src/components/export/ExportCsvButton.tsx
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import { Download } from "lucide-react"
|
||||
import { useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { useTeamPermissions } from "../../hooks/useTeamPermissions"
|
||||
import { downloadCsvExport, type QueryParams } from "../../lib/csv-export"
|
||||
import { hasExportPermission } from "../../lib/exportPermissions"
|
||||
import { Button } from "../ui/button"
|
||||
import { SpinnerIcon } from "../ui/spinner-icon"
|
||||
import { cn } from "../../lib/utils"
|
||||
|
||||
type ExportCsvButtonProps = {
|
||||
permission: string
|
||||
exportPath: string
|
||||
params: QueryParams
|
||||
/** Defaults from export path when omitted (e.g. payments → payments_2026-06-23_14-30-00.csv). */
|
||||
resourceName?: string
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
variant?: "default" | "outline" | "ghost"
|
||||
size?: "default" | "sm" | "lg" | "icon"
|
||||
}
|
||||
|
||||
export function ExportCsvButton({
|
||||
permission,
|
||||
exportPath,
|
||||
params,
|
||||
resourceName,
|
||||
disabled = false,
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "default",
|
||||
}: ExportCsvButtonProps) {
|
||||
const { permissions, loading: permLoading } = useTeamPermissions()
|
||||
const [exporting, setExporting] = useState(false)
|
||||
|
||||
const canExport = hasExportPermission(permission, permissions)
|
||||
|
||||
if (permLoading || !canExport) return null
|
||||
|
||||
async function handleExport() {
|
||||
setExporting(true)
|
||||
try {
|
||||
const filename = await downloadCsvExport(exportPath, params, { resourceName })
|
||||
toast.success(`Downloaded ${filename}`)
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Export failed")
|
||||
} finally {
|
||||
setExporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn("shrink-0 gap-2", className)}
|
||||
disabled={disabled || exporting}
|
||||
onClick={() => void handleExport()}
|
||||
>
|
||||
{exporting ? <SpinnerIcon className="h-4 w-4" /> : <Download className="h-4 w-4" />}
|
||||
{exporting ? "Exporting…" : "Export CSV"}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
16
src/components/export/ExportTruncationWarning.tsx
Normal file
16
src/components/export/ExportTruncationWarning.tsx
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { EXPORT_MAX_ROWS } from "../../lib/csv-export"
|
||||
|
||||
type ExportTruncationWarningProps = {
|
||||
totalCount?: number
|
||||
}
|
||||
|
||||
export function ExportTruncationWarning({ totalCount }: ExportTruncationWarningProps) {
|
||||
if (totalCount == null || totalCount <= EXPORT_MAX_ROWS) return null
|
||||
|
||||
return (
|
||||
<p className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800">
|
||||
More than {EXPORT_MAX_ROWS.toLocaleString()} rows match. CSV export includes at most{" "}
|
||||
{EXPORT_MAX_ROWS.toLocaleString()} rows. Narrow your filters for a complete extract.
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
|
@ -27,6 +27,7 @@ import { hasFaqPermission } from "../../lib/faqPermissions";
|
|||
import { hasRatingsPermission } from "../../lib/ratingsPermissions";
|
||||
import { hasPersonaPermission } from "../../lib/personasPermissions";
|
||||
import { hasActivityLogPermission } from "../../lib/activityLogPermissions";
|
||||
import { hasExportPermission } from "../../lib/exportPermissions";
|
||||
import { SidebarNavGroup } from "./SidebarNavGroup";
|
||||
|
||||
type NavLinkItem = {
|
||||
|
|
@ -110,6 +111,13 @@ const navEntries: NavEntry[] = [
|
|||
|
||||
{ kind: "section", label: "Operations" },
|
||||
{ kind: "link", label: "Payments", to: "/payments", icon: CreditCard },
|
||||
{
|
||||
kind: "link",
|
||||
label: "Subscriptions export",
|
||||
to: "/subscriptions/export",
|
||||
icon: CreditCard,
|
||||
permission: "subscriptions.export",
|
||||
},
|
||||
{ kind: "link", label: "Activity log", to: "/user-log", icon: ClipboardList, permission: "activity_logs.list" },
|
||||
{ kind: "link", label: "Issue reports", to: "/issues", icon: CircleAlert },
|
||||
{
|
||||
|
|
@ -286,12 +294,20 @@ export function Sidebar({
|
|||
) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
entry.permission === "subscriptions.export" &&
|
||||
!permissionsLoading &&
|
||||
!hasExportPermission("subscriptions.export", permissions)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
entry.permission &&
|
||||
entry.permission !== "faqs.list" &&
|
||||
entry.permission !== "ratings.list_by_target" &&
|
||||
entry.permission !== "personas.list" &&
|
||||
entry.permission !== "activity_logs.list" &&
|
||||
entry.permission !== "subscriptions.export" &&
|
||||
!permissionsLoading &&
|
||||
!hasPermission(entry.permission)
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { useCallback, useEffect, useState } from "react"
|
||||
import { fetchCurrentTeamMemberPermissions } from "../api/team.api"
|
||||
import { getMyProfile } from "../api/users.api"
|
||||
import type { TeamMeProfile } from "../types/team.types"
|
||||
|
||||
|
|
@ -9,6 +10,12 @@ export function useTeamPermissions() {
|
|||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const fromMembersList = await fetchCurrentTeamMemberPermissions()
|
||||
if (fromMembersList.length > 0) {
|
||||
setPermissions(fromMembersList)
|
||||
return
|
||||
}
|
||||
|
||||
const res = await getMyProfile()
|
||||
const profile = res.data?.data as TeamMeProfile & { permissions?: string[] }
|
||||
setPermissions(Array.isArray(profile?.permissions) ? profile.permissions : [])
|
||||
|
|
|
|||
120
src/lib/csv-export.ts
Normal file
120
src/lib/csv-export.ts
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
import { getAccessToken } from "./teamAuthStorage"
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_BASE_URL as string
|
||||
|
||||
export const EXPORT_MAX_ROWS = 50_000
|
||||
|
||||
export type QueryParams = Record<string, string | number | boolean | null | undefined>
|
||||
|
||||
export const EXPORT_ROUTES = {
|
||||
payments: "/admin/payments/export",
|
||||
users: "/users/export",
|
||||
subscriptions: "/admin/subscriptions/export",
|
||||
activityLogs: "/activity-logs/export",
|
||||
teamMembers: "/team/members/export",
|
||||
} as const
|
||||
|
||||
export const EXPORT_PERMISSIONS = {
|
||||
payments: "payments.export",
|
||||
users: "users.export",
|
||||
subscriptions: "subscriptions.export",
|
||||
activityLogs: "activity_logs.export",
|
||||
teamMembers: "team.members.export",
|
||||
} as const
|
||||
|
||||
/** Base name used in downloaded CSV filenames (resource + local date/time). */
|
||||
export const EXPORT_RESOURCE_NAMES = {
|
||||
payments: "payments",
|
||||
users: "users",
|
||||
subscriptions: "subscriptions",
|
||||
activityLogs: "activity-logs",
|
||||
teamMembers: "team-members",
|
||||
} as const
|
||||
|
||||
const EXPORT_PATH_RESOURCE_NAMES: Record<string, string> = {
|
||||
[EXPORT_ROUTES.payments]: EXPORT_RESOURCE_NAMES.payments,
|
||||
[EXPORT_ROUTES.users]: EXPORT_RESOURCE_NAMES.users,
|
||||
[EXPORT_ROUTES.subscriptions]: EXPORT_RESOURCE_NAMES.subscriptions,
|
||||
[EXPORT_ROUTES.activityLogs]: EXPORT_RESOURCE_NAMES.activityLogs,
|
||||
[EXPORT_ROUTES.teamMembers]: EXPORT_RESOURCE_NAMES.teamMembers,
|
||||
}
|
||||
|
||||
export function buildExportFilename(resourceName: string, at: Date = new Date()): string {
|
||||
const pad = (n: number) => String(n).padStart(2, "0")
|
||||
const date = `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}`
|
||||
const time = `${pad(at.getHours())}-${pad(at.getMinutes())}-${pad(at.getSeconds())}`
|
||||
return `${resourceName}_${date}_${time}.csv`
|
||||
}
|
||||
|
||||
function resolveExportResourceName(path: string, override?: string): string {
|
||||
const custom = override?.trim()
|
||||
if (custom) return custom
|
||||
return EXPORT_PATH_RESOURCE_NAMES[path] ?? "export"
|
||||
}
|
||||
|
||||
function buildQuery(params: QueryParams): string {
|
||||
const sp = new URLSearchParams()
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value === null || value === undefined || value === "") continue
|
||||
sp.set(key, String(value))
|
||||
}
|
||||
const qs = sp.toString()
|
||||
return qs ? `?${qs}` : ""
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads a CSV export. Pass the same filter params as the list API (excluding pagination).
|
||||
*/
|
||||
export async function downloadCsvExport(
|
||||
path: string,
|
||||
params: QueryParams,
|
||||
options?: { token?: string | null; resourceName?: string },
|
||||
): Promise<string> {
|
||||
const accessToken = options?.token ?? getAccessToken()
|
||||
if (!accessToken) {
|
||||
throw new Error("Not authenticated")
|
||||
}
|
||||
|
||||
const url = `${API_BASE}${path}${buildQuery(params)}`
|
||||
const res = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
let message = `Export failed (${res.status})`
|
||||
const contentType = res.headers.get("Content-Type") ?? ""
|
||||
try {
|
||||
if (contentType.includes("application/json")) {
|
||||
const body = (await res.json()) as { message?: string; error?: string }
|
||||
message = body.message || body.error || message
|
||||
} else {
|
||||
const text = await res.text()
|
||||
if (text.trim()) message = text.trim()
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
throw new Error(message)
|
||||
}
|
||||
|
||||
const blob = await res.blob()
|
||||
const filename = buildExportFilename(resolveExportResourceName(path, options?.resourceName))
|
||||
|
||||
const objectUrl = URL.createObjectURL(blob)
|
||||
try {
|
||||
const a = document.createElement("a")
|
||||
a.href = objectUrl
|
||||
a.download = filename
|
||||
a.rel = "noopener"
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
} finally {
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
}
|
||||
|
||||
return filename
|
||||
}
|
||||
76
src/lib/csvExportFilters.ts
Normal file
76
src/lib/csvExportFilters.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import type { GetUsersParams } from "../api/users.api"
|
||||
import { buildUsersListQuery } from "../api/users.api"
|
||||
import { paymentsFilterParams } from "../api/payments.api"
|
||||
import type { ActivityLogFilters } from "../types/activity-log.types"
|
||||
import type { QueryParams } from "./csv-export"
|
||||
|
||||
export function paymentListFiltersToExportQuery(filters: {
|
||||
status?: string
|
||||
provider?: string
|
||||
planCategory?: string
|
||||
currency?: string
|
||||
reference?: string
|
||||
}): QueryParams {
|
||||
return paymentsFilterParams({
|
||||
...(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 } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
export function usersExportQuery(params: Omit<GetUsersParams, "page" | "page_size">): QueryParams {
|
||||
return buildUsersListQuery(params)
|
||||
}
|
||||
|
||||
export function activityLogExportQuery(filters: ActivityLogFilters): QueryParams {
|
||||
const { limit: _limit, offset: _offset, ...rest } = filters
|
||||
return rest
|
||||
}
|
||||
|
||||
export function teamMemberExportQuery(filters: {
|
||||
team_role?: string
|
||||
department?: string
|
||||
status?: string
|
||||
search?: string
|
||||
}): QueryParams {
|
||||
const params: QueryParams = {}
|
||||
const role = filters.team_role?.trim()
|
||||
const department = filters.department?.trim()
|
||||
const status = filters.status?.trim()
|
||||
const search = filters.search?.trim()
|
||||
if (role) params.team_role = role
|
||||
if (department) params.department = department
|
||||
if (status) params.status = status
|
||||
if (search) params.search = search
|
||||
return params
|
||||
}
|
||||
|
||||
export function subscriptionExportQuery(filters: {
|
||||
user_id?: number
|
||||
plan_id?: number
|
||||
status?: string
|
||||
plan_category?: string
|
||||
created_from?: string
|
||||
created_to?: string
|
||||
expires_from?: string
|
||||
expires_to?: string
|
||||
}): QueryParams {
|
||||
const params: QueryParams = {}
|
||||
if (filters.user_id != null && Number.isFinite(filters.user_id)) {
|
||||
params.user_id = filters.user_id
|
||||
}
|
||||
if (filters.plan_id != null && Number.isFinite(filters.plan_id)) {
|
||||
params.plan_id = filters.plan_id
|
||||
}
|
||||
const status = filters.status?.trim()
|
||||
const planCategory = filters.plan_category?.trim()
|
||||
if (status) params.status = status
|
||||
if (planCategory) params.plan_category = planCategory
|
||||
if (filters.created_from?.trim()) params.created_from = filters.created_from.trim()
|
||||
if (filters.created_to?.trim()) params.created_to = filters.created_to.trim()
|
||||
if (filters.expires_from?.trim()) params.expires_from = filters.expires_from.trim()
|
||||
if (filters.expires_to?.trim()) params.expires_to = filters.expires_to.trim()
|
||||
return params
|
||||
}
|
||||
23
src/lib/exportPermissions.ts
Normal file
23
src/lib/exportPermissions.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { getSessionTeamRole } from "./teamRole"
|
||||
|
||||
const ALL_EXPORT_PERMISSIONS = [
|
||||
"payments.export",
|
||||
"users.export",
|
||||
"subscriptions.export",
|
||||
"activity_logs.export",
|
||||
"team.members.export",
|
||||
] as const
|
||||
|
||||
/** Default export access by team role (matches API RBAC seeds). */
|
||||
const EXPORT_ROLE_PERMISSIONS: Record<string, readonly string[]> = {
|
||||
SUPER_ADMIN: ALL_EXPORT_PERMISSIONS,
|
||||
ADMIN: ALL_EXPORT_PERMISSIONS,
|
||||
FINANCE: ["payments.export", "subscriptions.export"],
|
||||
HR: ["users.export", "team.members.export"],
|
||||
}
|
||||
|
||||
export function hasExportPermission(permission: string, permissions: string[]): boolean {
|
||||
if (permissions.includes(permission)) return true
|
||||
const rolePerms = EXPORT_ROLE_PERMISSIONS[getSessionTeamRole().toUpperCase()]
|
||||
return rolePerms?.includes(permission) ?? false
|
||||
}
|
||||
3
src/lib/teamRole.ts
Normal file
3
src/lib/teamRole.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export function getSessionTeamRole(): string {
|
||||
return localStorage.getItem("role")?.trim() ?? ""
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { useCallback, useEffect, useState, type ReactNode } from "react"
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
|
|
@ -16,6 +16,8 @@ import { Link } from "react-router-dom"
|
|||
import { toast } from "sonner"
|
||||
import { getAllPayments, getPayments, paymentsFilterParams } from "../../api/payments.api"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { ExportCsvButton } from "../../components/export/ExportCsvButton"
|
||||
import { ExportTruncationWarning } from "../../components/export/ExportTruncationWarning"
|
||||
import { Badge } from "../../components/ui/badge"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card"
|
||||
|
|
@ -43,6 +45,8 @@ import {
|
|||
type PaymentAggregateStats,
|
||||
} from "../../lib/payments"
|
||||
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,
|
||||
|
|
@ -126,6 +130,11 @@ export function PaymentsPage() {
|
|||
reference: referenceFilter,
|
||||
}
|
||||
|
||||
const exportParams = useMemo(
|
||||
() => paymentListFiltersToExportQuery(listFilters),
|
||||
[listFilters],
|
||||
)
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: statusFilter },
|
||||
{ value: providerFilter },
|
||||
|
|
@ -260,15 +269,23 @@ export function PaymentsPage() {
|
|||
Browse and filter checkout transactions from Chapa, Arifpay, and other providers.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="shrink-0 rounded-[6px]"
|
||||
disabled={loading || statsLoading}
|
||||
onClick={refreshAll}
|
||||
>
|
||||
<RefreshCw className={cn("mr-2 h-4 w-4", loading && "animate-spin")} />
|
||||
Refresh
|
||||
</Button>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<ExportCsvButton
|
||||
permission={EXPORT_PERMISSIONS.payments}
|
||||
exportPath={EXPORT_ROUTES.payments}
|
||||
params={exportParams}
|
||||
disabled={loading}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="shrink-0 rounded-[6px]"
|
||||
disabled={loading || statsLoading}
|
||||
onClick={refreshAll}
|
||||
>
|
||||
<RefreshCw className={cn("mr-2 h-4 w-4", loading && "animate-spin")} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
|
|
@ -322,6 +339,7 @@ export function PaymentsPage() {
|
|||
<CardTitle className="text-sm font-bold text-grayScale-900">Transaction history</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="min-w-0 space-y-4 p-4 sm:p-6">
|
||||
<ExportTruncationWarning totalCount={totalCount} />
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
|
|
|
|||
188
src/pages/subscriptions/SubscriptionsExportPage.tsx
Normal file
188
src/pages/subscriptions/SubscriptionsExportPage.tsx
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
import { useMemo, useState } from "react"
|
||||
import { ChevronDown } from "lucide-react"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { ExportCsvButton } from "../../components/export/ExportCsvButton"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { countActiveFilters } from "../../lib/adminFilterUtils"
|
||||
import {
|
||||
toRfc3339EndOfDay,
|
||||
toRfc3339StartOfDay,
|
||||
} from "../../lib/activityLogDisplay"
|
||||
import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../lib/csv-export"
|
||||
import { subscriptionExportQuery } from "../../lib/csvExportFilters"
|
||||
import { SUBSCRIPTION_PLAN_CATEGORIES } from "../../lib/subscriptionPlans"
|
||||
|
||||
const SUBSCRIPTION_STATUS_OPTIONS = [
|
||||
{ value: "", label: "All statuses" },
|
||||
{ value: "ACTIVE", label: "Active" },
|
||||
{ value: "PENDING", label: "Pending" },
|
||||
{ value: "CANCELLED", label: "Cancelled" },
|
||||
{ value: "EXPIRED", label: "Expired" },
|
||||
] as const
|
||||
|
||||
export function SubscriptionsExportPage() {
|
||||
const [userId, setUserId] = useState("")
|
||||
const [planId, setPlanId] = useState("")
|
||||
const [status, setStatus] = useState("")
|
||||
const [planCategory, setPlanCategory] = useState("")
|
||||
const [createdFrom, setCreatedFrom] = useState("")
|
||||
const [createdTo, setCreatedTo] = useState("")
|
||||
const [expiresFrom, setExpiresFrom] = useState("")
|
||||
const [expiresTo, setExpiresTo] = useState("")
|
||||
|
||||
const exportParams = useMemo(
|
||||
() =>
|
||||
subscriptionExportQuery({
|
||||
user_id: userId.trim() ? Number(userId) : undefined,
|
||||
plan_id: planId.trim() ? Number(planId) : undefined,
|
||||
status: status || undefined,
|
||||
plan_category: planCategory || undefined,
|
||||
created_from: createdFrom ? toRfc3339StartOfDay(createdFrom) : undefined,
|
||||
created_to: createdTo ? toRfc3339EndOfDay(createdTo) : undefined,
|
||||
expires_from: expiresFrom ? toRfc3339StartOfDay(expiresFrom) : undefined,
|
||||
expires_to: expiresTo ? toRfc3339EndOfDay(expiresTo) : undefined,
|
||||
}),
|
||||
[userId, planId, status, planCategory, createdFrom, createdTo, expiresFrom, expiresTo],
|
||||
)
|
||||
|
||||
const activeFilterCount = countActiveFilters([
|
||||
{ value: userId },
|
||||
{ value: planId },
|
||||
{ value: status },
|
||||
{ value: planCategory },
|
||||
{ value: createdFrom },
|
||||
{ value: createdTo },
|
||||
{ value: expiresFrom },
|
||||
{ value: expiresTo },
|
||||
])
|
||||
|
||||
const clearFilters = () => {
|
||||
setUserId("")
|
||||
setPlanId("")
|
||||
setStatus("")
|
||||
setPlanCategory("")
|
||||
setCreatedFrom("")
|
||||
setCreatedTo("")
|
||||
setExpiresFrom("")
|
||||
setExpiresTo("")
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto min-w-0 w-full max-w-4xl space-y-6 px-4 py-6 sm:px-6 lg:px-8">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-[11px] font-bold uppercase tracking-wider text-brand-500">Billing</p>
|
||||
<h1 className="text-2xl font-bold tracking-tight text-grayScale-900">Subscriptions export</h1>
|
||||
<p className="mt-1 max-w-2xl text-sm text-grayScale-500">
|
||||
Download learner subscriptions as CSV. Apply filters below to match the records you need.
|
||||
Exports are limited to 50,000 rows per download.
|
||||
</p>
|
||||
</div>
|
||||
<ExportCsvButton
|
||||
permission={EXPORT_PERMISSIONS.subscriptions}
|
||||
exportPath={EXPORT_ROUTES.subscriptions}
|
||||
params={exportParams}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="rounded-[8px] border border-grayScale-100 bg-white p-4 sm:p-6">
|
||||
<AdminFiltersPanel
|
||||
activeFilterCount={activeFilterCount}
|
||||
onClearFilters={clearFilters}
|
||||
footer="Date filters use UTC start/end of day. Per-user subscription detail remains on each user profile."
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder="User ID"
|
||||
className="h-9 w-full sm:w-32"
|
||||
value={userId}
|
||||
onChange={(e) => setUserId(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder="Plan ID"
|
||||
className="h-9 w-full sm:w-32"
|
||||
value={planId}
|
||||
onChange={(e) => setPlanId(e.target.value)}
|
||||
/>
|
||||
<div className="relative w-full sm:w-auto">
|
||||
<select
|
||||
value={status}
|
||||
onChange={(e) => setStatus(e.target.value)}
|
||||
className="h-9 w-full appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500 sm:w-auto"
|
||||
>
|
||||
{SUBSCRIPTION_STATUS_OPTIONS.map((opt) => (
|
||||
<option key={opt.value || "all"} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="pointer-events-none absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
</div>
|
||||
<div className="relative w-full sm:w-auto">
|
||||
<select
|
||||
value={planCategory}
|
||||
onChange={(e) => setPlanCategory(e.target.value)}
|
||||
className="h-9 w-full appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500 sm:w-auto"
|
||||
>
|
||||
<option value="">All plan categories</option>
|
||||
{SUBSCRIPTION_PLAN_CATEGORIES.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronDown className="pointer-events-none absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<label className="flex flex-col gap-1 text-xs text-grayScale-500">
|
||||
Created from
|
||||
<Input
|
||||
type="date"
|
||||
className="h-9 w-full sm:w-auto"
|
||||
value={createdFrom}
|
||||
onChange={(e) => setCreatedFrom(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-xs text-grayScale-500">
|
||||
Created to
|
||||
<Input
|
||||
type="date"
|
||||
className="h-9 w-full sm:w-auto"
|
||||
value={createdTo}
|
||||
onChange={(e) => setCreatedTo(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-xs text-grayScale-500">
|
||||
Expires from
|
||||
<Input
|
||||
type="date"
|
||||
className="h-9 w-full sm:w-auto"
|
||||
value={expiresFrom}
|
||||
onChange={(e) => setExpiresFrom(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 text-xs text-grayScale-500">
|
||||
Expires to
|
||||
<Input
|
||||
type="date"
|
||||
className="h-9 w-full sm:w-auto"
|
||||
value={expiresTo}
|
||||
onChange={(e) => setExpiresTo(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-grayScale-400">
|
||||
Subscription exports may contain learner PII and billing data. Restrict access to authorized
|
||||
staff only.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ import {
|
|||
X,
|
||||
} from "lucide-react";
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel";
|
||||
import { ExportCsvButton } from "../../components/export/ExportCsvButton";
|
||||
import { Button } from "../../components/ui/button";
|
||||
import { Input } from "../../components/ui/input";
|
||||
import {
|
||||
|
|
@ -28,6 +29,8 @@ import { getTeamMembers, updateTeamMemberStatus } from "../../api/team.api";
|
|||
import type { TeamMember } from "../../types/team.types";
|
||||
import { toast } from "sonner";
|
||||
import { InviteTeamMemberDialog } from "../role-management/components/InviteTeamMemberDialog";
|
||||
import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../lib/csv-export";
|
||||
import { teamMemberExportQuery } from "../../lib/csvExportFilters";
|
||||
|
||||
function formatDate(dateStr: string): string {
|
||||
return new Date(dateStr).toLocaleDateString("en-US", {
|
||||
|
|
@ -228,6 +231,16 @@ export function TeamManagementPage() {
|
|||
setStatusFilter("");
|
||||
};
|
||||
|
||||
const exportParams = useMemo(
|
||||
() =>
|
||||
teamMemberExportQuery({
|
||||
team_role: roleFilter || undefined,
|
||||
status: statusFilter || undefined,
|
||||
search: search || undefined,
|
||||
}),
|
||||
[roleFilter, statusFilter, search],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
|
|
@ -237,13 +250,22 @@ export function TeamManagementPage() {
|
|||
Manage user access, roles, and platform permissions.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
className="bg-brand-600 hover:bg-brand-500 text-white w-full sm:w-auto"
|
||||
onClick={() => setInviteOpen(true)}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
Add Team Member
|
||||
</Button>
|
||||
<div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
|
||||
<ExportCsvButton
|
||||
permission={EXPORT_PERMISSIONS.teamMembers}
|
||||
exportPath={EXPORT_ROUTES.teamMembers}
|
||||
params={exportParams}
|
||||
disabled={loading}
|
||||
className="w-full sm:w-auto"
|
||||
/>
|
||||
<Button
|
||||
className="bg-brand-600 hover:bg-brand-500 text-white w-full sm:w-auto"
|
||||
onClick={() => setInviteOpen(true)}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
Add Team Member
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AdminFiltersPanel
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ import {
|
|||
getActivityLogs,
|
||||
} from "../../../api/activity-logs.api"
|
||||
import { AdminFiltersPanel } from "../../../components/filters/AdminFiltersPanel"
|
||||
import { ExportCsvButton } from "../../../components/export/ExportCsvButton"
|
||||
import { ExportTruncationWarning } from "../../../components/export/ExportTruncationWarning"
|
||||
import { Badge } from "../../../components/ui/badge"
|
||||
import { Button } from "../../../components/ui/button"
|
||||
import { Input } from "../../../components/ui/input"
|
||||
|
|
@ -57,6 +59,8 @@ import {
|
|||
toRfc3339StartOfDay,
|
||||
} from "../../../lib/activityLogDisplay"
|
||||
import { cn } from "../../../lib/utils"
|
||||
import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../../lib/csv-export"
|
||||
import { activityLogExportQuery } from "../../../lib/csvExportFilters"
|
||||
import { TABLE_PAGE_SIZE_OPTIONS } from "../../../lib/tablePagination"
|
||||
import type { ActivityLog, ActivityLogFilters } from "../../../types/activity-log.types"
|
||||
import { ActorCell, ActorLabel } from "./ActorLabel"
|
||||
|
|
@ -131,6 +135,11 @@ export function ActivityLogListPanel({
|
|||
dateBefore,
|
||||
])
|
||||
|
||||
const exportParams = useMemo(
|
||||
() => activityLogExportQuery(serverFilters),
|
||||
[serverFilters],
|
||||
)
|
||||
|
||||
const fetchLogs = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
|
@ -224,13 +233,29 @@ export function ActivityLogListPanel({
|
|||
return (
|
||||
<div className={cn("space-y-4", scrollable && "min-w-0")}>
|
||||
{!compact ? (
|
||||
<div className="flex items-center justify-end">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<ExportCsvButton
|
||||
permission={EXPORT_PERMISSIONS.activityLogs}
|
||||
exportPath={EXPORT_ROUTES.activityLogs}
|
||||
params={exportParams}
|
||||
disabled={loading}
|
||||
/>
|
||||
<Button variant="outline" className="gap-2" disabled={loading} onClick={() => void fetchLogs()}>
|
||||
{loading ? <SpinnerIcon className="h-4 w-4" /> : <RefreshCw className="h-4 w-4" />}
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
) : (
|
||||
<div className="flex justify-end">
|
||||
<ExportCsvButton
|
||||
permission={EXPORT_PERMISSIONS.activityLogs}
|
||||
exportPath={EXPORT_ROUTES.activityLogs}
|
||||
params={exportParams}
|
||||
disabled={loading}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error ? (
|
||||
<div className="rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2 text-sm text-destructive">
|
||||
|
|
@ -272,6 +297,8 @@ export function ActivityLogListPanel({
|
|||
</div>
|
||||
) : null}
|
||||
|
||||
<ExportTruncationWarning totalCount={totalCount} />
|
||||
|
||||
<AdminFiltersPanel activeFilterCount={activeFilterCount} onClearFilters={clearFilters}>
|
||||
{!compact ? (
|
||||
<div className="relative w-full">
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import { ChevronDown, ChevronLeft, ChevronRight, Search, TrendingUp, UserCheck, Users, X } from "lucide-react"
|
||||
import { useEffect, useState } from "react"
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import * as DropdownMenu from "@radix-ui/react-dropdown-menu"
|
||||
import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"
|
||||
import { ExportCsvButton } from "../../components/export/ExportCsvButton"
|
||||
import { ExportTruncationWarning } from "../../components/export/ExportTruncationWarning"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../components/ui/table"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "../../components/ui/avatar"
|
||||
|
|
@ -21,6 +23,8 @@ import { useUsersStore } from "../../zustand/userStore"
|
|||
import { toast } from "sonner"
|
||||
import axios from "axios"
|
||||
import { USER_FILTER_COUNTRIES, USER_FILTER_ETHIOPIA_REGIONS } from "../../data/userFilterLocations"
|
||||
import { EXPORT_PERMISSIONS, EXPORT_ROUTES } from "../../lib/csv-export"
|
||||
import { usersExportQuery } from "../../lib/csvExportFilters"
|
||||
|
||||
function formatJoinedAt(iso: string): string {
|
||||
if (!iso?.trim()) return "—"
|
||||
|
|
@ -334,6 +338,30 @@ export function UsersListPage() {
|
|||
setPage(1)
|
||||
}
|
||||
|
||||
const exportParams = useMemo(
|
||||
() =>
|
||||
usersExportQuery({
|
||||
role: roleFilter || undefined,
|
||||
status: statusFilter || undefined,
|
||||
query: search || undefined,
|
||||
created_after: toRfc3339FromDatetimeLocal(createdAfterLocal),
|
||||
created_before: toRfc3339FromDatetimeLocal(createdBeforeLocal),
|
||||
country: countryFilter.trim() || undefined,
|
||||
region: regionFilter.trim() || undefined,
|
||||
subscription_status: subscriptionStatusFilter || undefined,
|
||||
}),
|
||||
[
|
||||
roleFilter,
|
||||
statusFilter,
|
||||
search,
|
||||
createdAfterLocal,
|
||||
createdBeforeLocal,
|
||||
countryFilter,
|
||||
regionFilter,
|
||||
subscriptionStatusFilter,
|
||||
],
|
||||
)
|
||||
|
||||
const renderContactDetails = (phone: string | undefined, email: string | undefined) => {
|
||||
const hasPhone = Boolean(phone?.trim())
|
||||
const hasEmail = Boolean(email?.trim())
|
||||
|
|
@ -351,9 +379,17 @@ export function UsersListPage() {
|
|||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-grayScale-600">Users List</h1>
|
||||
<p className="text-sm text-grayScale-400">View and manage all registered users.</p>
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-grayScale-600">Users List</h1>
|
||||
<p className="text-sm text-grayScale-400">View and manage all registered users.</p>
|
||||
</div>
|
||||
<ExportCsvButton
|
||||
permission={EXPORT_PERMISSIONS.users}
|
||||
exportPath={EXPORT_ROUTES.users}
|
||||
params={exportParams}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Platform-wide user summary (same metrics as former User Management dashboard) */}
|
||||
|
|
@ -420,6 +456,9 @@ export function UsersListPage() {
|
|||
</div>
|
||||
|
||||
<div className="min-w-0 overflow-hidden bg-white rounded-xl border">
|
||||
<div className="px-4 pt-4">
|
||||
<ExportTruncationWarning totalCount={total} />
|
||||
</div>
|
||||
<AdminFiltersPanel
|
||||
className="border-0 border-b rounded-none shadow-none"
|
||||
activeFilterCount={activeFilterCount}
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user