Add streaming CSV export for payments, users, subscriptions, activity logs, and team members with list-filter parity, RBAC permissions, and admin panel documentation. Co-authored-by: Cursor <cursoragent@cursor.com>
846 lines
26 KiB
Markdown
846 lines
26 KiB
Markdown
# CSV Export — Admin Panel Integration Guide
|
||
|
||
This guide documents how to integrate **server-side CSV export** into the Yimaru admin panel. Exports mirror each resource’s **list filters** (same query parameters as the JSON list APIs) and return a downloadable file instead of paginated JSON.
|
||
|
||
> **Scope:** Tier 1 admin exports — payments, users, subscriptions, activity logs, and team members.
|
||
> **Related:** List API guides for each resource (e.g. [activity-logs-admin-panel-integration.md](./activity-logs-admin-panel-integration.md)).
|
||
|
||
---
|
||
|
||
## Table of contents
|
||
|
||
1. [Feature overview](#feature-overview)
|
||
2. [Architecture](#architecture)
|
||
3. [Authentication & permissions](#authentication--permissions)
|
||
4. [General integration rules](#general-integration-rules)
|
||
5. [Shared client helper](#shared-client-helper)
|
||
6. [Payments export](#payments-export)
|
||
7. [Users export](#users-export)
|
||
8. [Subscriptions export](#subscriptions-export)
|
||
9. [Activity logs export](#activity-logs-export)
|
||
10. [Team members export](#team-members-export)
|
||
11. [Recommended admin UI](#recommended-admin-ui)
|
||
12. [TypeScript types](#typescript-types)
|
||
13. [React patterns](#react-patterns)
|
||
14. [Error handling](#error-handling)
|
||
15. [Security & compliance](#security--compliance)
|
||
16. [Integration checklist](#integration-checklist)
|
||
17. [Quick reference](#quick-reference)
|
||
|
||
---
|
||
|
||
## Feature overview
|
||
|
||
| Resource | Export endpoint | List endpoint (filters source) | Export permission |
|
||
|----------|-----------------|--------------------------------|-------------------|
|
||
| Payments | `GET /api/v1/admin/payments/export` | `GET /api/v1/admin/payments` | `payments.export` |
|
||
| Users | `GET /api/v1/users/export` | `GET /api/v1/users` | `users.export` |
|
||
| Subscriptions | `GET /api/v1/admin/subscriptions/export` | *(export-only global list)* | `subscriptions.export` |
|
||
| Activity logs | `GET /api/v1/activity-logs/export` | `GET /api/v1/activity-logs` | `activity_logs.export` |
|
||
| Team members | `GET /api/v1/team/members/export` | `GET /api/v1/team/members` | `team.members.export` |
|
||
|
||
### What the API returns
|
||
|
||
| Aspect | Behavior |
|
||
|--------|----------|
|
||
| HTTP method | `GET` only |
|
||
| Success `Content-Type` | `text/csv; charset=utf-8` |
|
||
| Success body | Raw CSV (not JSON) |
|
||
| Filename | `Content-Disposition: attachment; filename="<resource>-YYYY-MM-DD.csv"` |
|
||
| Encoding | UTF-8 with BOM (`EF BB BF`) for Excel compatibility |
|
||
| Row limit | **50,000** rows max per download |
|
||
| Server batching | Internal batches of **500** rows (transparent to the client) |
|
||
| Pagination query params | **Ignored** on export (`limit`, `offset`, `page`, `page_size`) — export walks all matching rows up to the cap |
|
||
|
||
### What the admin panel should do
|
||
|
||
1. Reuse the **same filter state** as the list/table on the page.
|
||
2. Call the **export** URL with those filters as query parameters.
|
||
3. Download the response as a **Blob** and trigger a browser save (do not parse as JSON).
|
||
4. Show **loading** and **error** states; large exports may take several seconds.
|
||
|
||
---
|
||
|
||
## Architecture
|
||
|
||
```mermaid
|
||
flowchart LR
|
||
subgraph AdminPanel["Admin panel"]
|
||
Filters["List page filters"]
|
||
ExportBtn["Export CSV button"]
|
||
BlobDL["Blob download"]
|
||
end
|
||
|
||
subgraph API["Yimaru API"]
|
||
ExportRoute["GET .../export"]
|
||
StreamCSV["StreamCSV helper"]
|
||
ListSvc["List service + DB"]
|
||
end
|
||
|
||
Filters --> ExportBtn
|
||
ExportBtn -->|"same query params"| ExportRoute
|
||
ExportRoute --> StreamCSV
|
||
StreamCSV -->|"batches of 500"| ListSvc
|
||
StreamCSV --> BlobDL
|
||
```
|
||
|
||
- **Handler layer:** `internal/web_server/handlers/admin_export.go`
|
||
- **Filter parsers:** `internal/web_server/handlers/export_filters.go` (shared with list handlers where applicable)
|
||
- **Streaming:** `internal/web_server/response/csv.go` — `StreamCSV`, `ExportBatchSize = 500`, `ExportMaxRows = 50000`
|
||
- **RBAC seeds:** `internal/services/rbac/seeds.go` — `*.export` permissions granted to `ADMIN` by default
|
||
|
||
---
|
||
|
||
## Authentication & permissions
|
||
|
||
All export routes require a Bearer token (same as list APIs):
|
||
|
||
```http
|
||
Authorization: Bearer <access_token>
|
||
```
|
||
|
||
Do **not** send `Accept: application/json` as the only accept type if your HTTP client auto-parses JSON — use `fetch` + `blob()` or set `responseType: 'blob'`.
|
||
|
||
### Login flows
|
||
|
||
| Admin area | Recommended login | Token source |
|
||
|------------|-------------------|--------------|
|
||
| Payments, users, subscriptions, activity logs | Platform admin or team member with permissions | `POST /api/v1/team/login` or `POST /api/v1/auth/admin-login` |
|
||
| Team members export | Team member with `team.members.export` | `POST /api/v1/team/login` |
|
||
|
||
### Export permissions (RBAC)
|
||
|
||
| Permission key | Group | Typical admin role |
|
||
|----------------|-------|-------------------|
|
||
| `payments.export` | Payments | ADMIN, FINANCE |
|
||
| `users.export` | Users | ADMIN, HR |
|
||
| `subscriptions.export` | Subscriptions | ADMIN, FINANCE |
|
||
| `activity_logs.export` | Logs | ADMIN |
|
||
| `team.members.export` | Team | ADMIN, HR |
|
||
|
||
`users.list` does **not** imply `users.export`. Gate the Export button separately:
|
||
|
||
```typescript
|
||
const canExportUsers = permissions.includes("users.export");
|
||
```
|
||
|
||
### RBAC rollout on existing environments
|
||
|
||
New permissions are upserted on API startup. If an environment was deployed before export shipped:
|
||
|
||
1. Restart the API (seeds run on boot), **or**
|
||
2. Call `POST /api/v1/rbac/permissions/sync` (admin), then re-assign permissions to custom roles if needed.
|
||
|
||
---
|
||
|
||
## General integration rules
|
||
|
||
### 1. Mirror list filters exactly
|
||
|
||
Build the export URL from the **current list filter state**, not a separate form (unless you intentionally want different export filters).
|
||
|
||
```typescript
|
||
// Pseudocode: reuse list filter object
|
||
const params = buildPaymentListQueryParams(currentFilters);
|
||
await downloadCsvExport("/api/v1/admin/payments/export", params, token);
|
||
```
|
||
|
||
Omit `limit`, `offset`, `page`, and `page_size` from export URLs — they have no effect.
|
||
|
||
### 2. Do not use the JSON list client
|
||
|
||
Export responses are **not** `{ success, data }` envelopes. A shared `api.get()` that always calls `response.json()` will fail.
|
||
|
||
Use a dedicated **blob download** helper (see [Shared client helper](#shared-client-helper)).
|
||
|
||
### 3. Filename from `Content-Disposition`
|
||
|
||
The server sets:
|
||
|
||
```http
|
||
Content-Disposition: attachment; filename="payments-2026-06-29.csv"
|
||
```
|
||
|
||
Prefer parsing this header for the saved filename; fall back to a local name if missing.
|
||
|
||
### 4. Date query formats
|
||
|
||
| Parameter family | Format |
|
||
|------------------|--------|
|
||
| Payments / subscriptions (`created_from`, `paid_to`, `expires_from`, …) | `RFC3339` **or** `YYYY-MM-DD` |
|
||
| Users (`created_before`, `created_after`) | `RFC3339` only |
|
||
| Activity logs (`after`, `before`) | `RFC3339` only |
|
||
|
||
For date-only inputs in the UI, convert to UTC start/end of day before serializing.
|
||
|
||
### 5. Empty exports
|
||
|
||
If no rows match, the API still returns **200** with a valid CSV containing **only the header row**.
|
||
|
||
### 6. Truncation at 50k rows
|
||
|
||
There is no response header indicating truncation today. If `total_count` on the list API exceeds **50,000**, show a warning:
|
||
|
||
> “Export is limited to 50,000 rows. Narrow your filters for a complete extract.”
|
||
|
||
---
|
||
|
||
## Shared client helper
|
||
|
||
```typescript
|
||
const API_BASE = import.meta.env.VITE_API_URL;
|
||
|
||
export type QueryParams = Record<
|
||
string,
|
||
string | number | boolean | null | undefined
|
||
>;
|
||
|
||
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}` : "";
|
||
}
|
||
|
||
function filenameFromContentDisposition(header: string | null): string | null {
|
||
if (!header) return null;
|
||
const match = /filename="([^"]+)"/i.exec(header);
|
||
return match?.[1] ?? null;
|
||
}
|
||
|
||
/**
|
||
* Downloads a CSV export. Pass the same filter params as the list API (excluding pagination).
|
||
*/
|
||
export async function downloadCsvExport(
|
||
path: string,
|
||
params: QueryParams,
|
||
token: string
|
||
): Promise<string> {
|
||
const url = `${API_BASE}${path}${buildQuery(params)}`;
|
||
const res = await fetch(url, {
|
||
method: "GET",
|
||
headers: {
|
||
Authorization: `Bearer ${token}`,
|
||
// Do not set Accept: application/json
|
||
},
|
||
});
|
||
|
||
if (!res.ok) {
|
||
// Error responses are usually JSON
|
||
let message = `Export failed (${res.status})`;
|
||
try {
|
||
const body = await res.json();
|
||
message = body.message || body.error || message;
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
throw new Error(message);
|
||
}
|
||
|
||
const blob = await res.blob();
|
||
const filename =
|
||
filenameFromContentDisposition(res.headers.get("Content-Disposition")) ??
|
||
"export.csv";
|
||
|
||
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;
|
||
}
|
||
```
|
||
|
||
### Axios variant
|
||
|
||
```typescript
|
||
import axios from "axios";
|
||
|
||
export async function downloadCsvExportAxios(
|
||
path: string,
|
||
params: QueryParams,
|
||
token: string
|
||
): Promise<string> {
|
||
const res = await axios.get(`${API_BASE}${path}`, {
|
||
params,
|
||
headers: { Authorization: `Bearer ${token}` },
|
||
responseType: "blob",
|
||
});
|
||
|
||
const disposition = res.headers["content-disposition"] as string | undefined;
|
||
const filename =
|
||
(disposition && /filename="([^"]+)"/i.exec(disposition)?.[1]) ?? "export.csv";
|
||
|
||
const url = URL.createObjectURL(res.data);
|
||
const a = document.createElement("a");
|
||
a.href = url;
|
||
a.download = filename;
|
||
a.click();
|
||
URL.revokeObjectURL(url);
|
||
return filename;
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## Payments export
|
||
|
||
### Endpoint
|
||
|
||
```http
|
||
GET /api/v1/admin/payments/export
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
**Permission:** `payments.export`
|
||
**Suggested UI:** Payments admin table → “Export CSV” (top right, next to filters)
|
||
|
||
### Query parameters
|
||
|
||
Same as `GET /api/v1/admin/payments` (excluding `limit` / `offset`):
|
||
|
||
| Parameter | Type | Description |
|
||
|-----------|------|-------------|
|
||
| `user_id` | int | Learner user ID |
|
||
| `plan_id` | int | Subscription plan ID |
|
||
| `subscription_id` | int | User subscription ID |
|
||
| `status` | string | `PENDING`, `PROCESSING`, `SUCCESS`, `FAILED`, `CANCELLED`, `EXPIRED` |
|
||
| `provider` or `payment_method` | string | `CHAPA`, `ARIFPAY` |
|
||
| `currency` | string | e.g. `ETB` |
|
||
| `plan_category` | string | `LEARN_ENGLISH`, `IELTS`, `DUOLINGO` |
|
||
| `reference` | string | Partial match on `session_id`, `nonce`, `transaction_id` |
|
||
| `created_from`, `created_to` | datetime | Payment row `created_at` range (`created_to` is exclusive) |
|
||
| `paid_from`, `paid_to` | datetime | `paid_at` range (`paid_to` exclusive) |
|
||
| `min_amount`, `max_amount` | number | Amount filter |
|
||
|
||
### CSV columns (header row order)
|
||
|
||
| Column | Description |
|
||
|--------|-------------|
|
||
| `id` | Payment ID |
|
||
| `user_id` | Learner ID |
|
||
| `user_email`, `user_first_name`, `user_last_name` | Joined from `users` |
|
||
| `plan_id`, `plan_name`, `plan_category` | Plan metadata |
|
||
| `subscription_id` | Linked subscription when set |
|
||
| `session_id`, `transaction_id`, `nonce` | Gateway references |
|
||
| `amount`, `currency` | Charged amount |
|
||
| `payment_method` | Provider (`CHAPA`, `ARIFPAY`, …) |
|
||
| `status` | Payment status |
|
||
| `paid_at`, `expires_at` | RFC3339 or empty |
|
||
| `created_at`, `updated_at` | RFC3339 |
|
||
|
||
### Example
|
||
|
||
```bash
|
||
curl -o payments.csv \
|
||
-H "Authorization: Bearer $TOKEN" \
|
||
"$API/api/v1/admin/payments/export?status=SUCCESS&plan_category=LEARN_ENGLISH&created_from=2026-01-01"
|
||
```
|
||
|
||
---
|
||
|
||
## Users export
|
||
|
||
### Endpoint
|
||
|
||
```http
|
||
GET /api/v1/users/export
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
**Permission:** `users.export`
|
||
**Suggested UI:** Users / Learners list → “Export CSV”
|
||
|
||
### Query parameters
|
||
|
||
Same as `GET /api/v1/users` (excluding `page` / `page_size`):
|
||
|
||
| Parameter | Type | Description |
|
||
|-----------|------|-------------|
|
||
| `role` | string | e.g. `STUDENT`, `ADMIN` |
|
||
| `status` | string | User status filter |
|
||
| `country`, `region` | string | Profile location |
|
||
| `subscription_status` | string | `ACTIVE`, `PENDING`, or `Unsubscribed` (case-insensitive input; `UNSUBSCRIBED` accepted) |
|
||
| `query` | string | Search text |
|
||
| `created_before`, `created_after` | RFC3339 | Registration date range |
|
||
|
||
### CSV columns
|
||
|
||
| Column | Description |
|
||
|--------|-------------|
|
||
| `id` | User ID |
|
||
| `first_name`, `last_name`, `email`, `phone_number` | Identity |
|
||
| `role`, `status` | Account |
|
||
| `country`, `region` | Location |
|
||
| `subscription_status` | Display status: `ACTIVE`, `PENDING`, or `Unsubscribed` |
|
||
| `email_verified`, `phone_verified`, `profile_completed` | `true` / `false` |
|
||
| `created_at`, `updated_at`, `last_login` | RFC3339 UTC or empty |
|
||
|
||
### Notes
|
||
|
||
- Export includes **subscription display status** (batch-loaded per page), matching the list API enrichment.
|
||
- Sensitive fields (password hashes, internal tokens) are **not** exported.
|
||
|
||
---
|
||
|
||
## Subscriptions export
|
||
|
||
### Endpoint
|
||
|
||
```http
|
||
GET /api/v1/admin/subscriptions/export
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
**Permission:** `subscriptions.export`
|
||
**Suggested UI:** Subscriptions / Billing admin page → “Export CSV”
|
||
|
||
There is **no** separate JSON list endpoint for global subscriptions yet; this export is the primary bulk extract. Per-user subscription detail remains at `GET /api/v1/admin/users/:user_id/subscriptions`.
|
||
|
||
### Query parameters
|
||
|
||
| Parameter | Type | Description |
|
||
|-----------|------|-------------|
|
||
| `user_id` | int | Filter to one learner |
|
||
| `plan_id` | int | Filter to one plan |
|
||
| `status` | string | Subscription row status (e.g. `ACTIVE`, `PENDING`, `CANCELLED`, `EXPIRED`) |
|
||
| `plan_category` | string | `LEARN_ENGLISH`, `IELTS`, `DUOLINGO` |
|
||
| `created_from`, `created_to` | datetime | Subscription `created_at` range (`created_to` exclusive) |
|
||
| `expires_from`, `expires_to` | datetime | `expires_at` range (`expires_to` exclusive) |
|
||
|
||
Date params accept `RFC3339` or `YYYY-MM-DD` (same as payments).
|
||
|
||
### CSV columns
|
||
|
||
| Column | Description |
|
||
|--------|-------------|
|
||
| `id` | `user_subscriptions.id` |
|
||
| `user_id`, `user_email`, `user_first_name`, `user_last_name` | Learner |
|
||
| `plan_id`, `plan_name`, `plan_category` | Plan |
|
||
| `status` | Row status |
|
||
| `starts_at`, `expires_at` | RFC3339 UTC |
|
||
| `auto_renew` | `true` / `false` |
|
||
| `payment_reference`, `payment_method` | Checkout metadata |
|
||
| `price`, `currency`, `duration_value`, `duration_unit` | Plan pricing snapshot |
|
||
| `cancelled_at` | RFC3339 or empty |
|
||
| `created_at`, `updated_at` | RFC3339 UTC |
|
||
|
||
### Example
|
||
|
||
```bash
|
||
curl -o subscriptions.csv \
|
||
-H "Authorization: Bearer $TOKEN" \
|
||
"$API/api/v1/admin/subscriptions/export?status=ACTIVE&plan_category=IELTS"
|
||
```
|
||
|
||
---
|
||
|
||
## Activity logs export
|
||
|
||
### Endpoint
|
||
|
||
```http
|
||
GET /api/v1/activity-logs/export
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
**Permission:** `activity_logs.export`
|
||
**Suggested UI:** Global audit log page → “Export CSV” (respect current filters)
|
||
|
||
### Query parameters
|
||
|
||
Same as `GET /api/v1/activity-logs` (excluding `limit` / `offset`):
|
||
|
||
| Parameter | Type | Description |
|
||
|-----------|------|-------------|
|
||
| `actor_id` | int | Who performed the action |
|
||
| `action` | string | e.g. `PRACTICE_CREATED` |
|
||
| `resource_type` | string | e.g. `FAQ`, `EXAM_PREP_PRACTICE` |
|
||
| `resource_id` | int | Target entity ID |
|
||
| `after`, `before` | RFC3339 | `created_at` range |
|
||
|
||
### CSV columns
|
||
|
||
| Column | Description |
|
||
|--------|-------------|
|
||
| `id` | Log entry ID |
|
||
| `actor_id`, `actor_role`, `actor_name`, `actor_email`, `actor_kind` | Resolved actor (same as list API) |
|
||
| `action`, `resource_type`, `resource_id` | What happened |
|
||
| `message` | Human-readable summary |
|
||
| `metadata` | JSON string (may contain commas — properly quoted in CSV) |
|
||
| `ip_address`, `user_agent` | Request context |
|
||
| `created_at` | RFC3339 UTC |
|
||
|
||
See [activity-logs-admin-panel-integration.md](./activity-logs-admin-panel-integration.md) for action/resource catalogs.
|
||
|
||
---
|
||
|
||
## Team members export
|
||
|
||
### Endpoint
|
||
|
||
```http
|
||
GET /api/v1/team/members/export
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
**Permission:** `team.members.export`
|
||
**Suggested UI:** Team / Staff directory → “Export CSV”
|
||
|
||
### Query parameters
|
||
|
||
Same as `GET /api/v1/team/members` (excluding `page` / `page_size`):
|
||
|
||
| Parameter | Type | Description |
|
||
|-----------|------|-------------|
|
||
| `team_role` | string | e.g. `ADMIN`, `CONTENT_MANAGER`, `FINANCE` |
|
||
| `department` | string | Department filter |
|
||
| `status` | string | `active`, `inactive`, `suspended`, `terminated` |
|
||
| `search` | string | Name/email search (exports **all** matches in one file, not paginated) |
|
||
|
||
### CSV columns
|
||
|
||
| Column | Description |
|
||
|--------|-------------|
|
||
| `id` | Team member ID |
|
||
| `first_name`, `last_name`, `email`, `phone_number` | Identity |
|
||
| `team_role`, `department`, `job_title`, `employment_type` | Role metadata |
|
||
| `hire_date` | `YYYY-MM-DD` or empty |
|
||
| `status` | Member status |
|
||
| `email_verified` | `true` / `false` |
|
||
| `last_login`, `created_at`, `updated_at` | RFC3339 or empty |
|
||
|
||
### Notes
|
||
|
||
- **Passwords and permission arrays are not exported.**
|
||
- When `search` is set, the export returns all search hits (subject to the global 50k cap).
|
||
|
||
---
|
||
|
||
## Recommended admin UI
|
||
|
||
### Export button placement
|
||
|
||
```mermaid
|
||
flowchart TD
|
||
A[List page with filters] --> B{User has *.export permission?}
|
||
B -->|No| C[Hide Export button]
|
||
B -->|Yes| D[Show Export CSV button]
|
||
D --> E[User clicks Export]
|
||
E --> F[Build query from current filters]
|
||
F --> G[downloadCsvExport]
|
||
G --> H{Success?}
|
||
H -->|Yes| I[Toast: Downloaded filename]
|
||
H -->|No| J[Toast: error message]
|
||
```
|
||
|
||
| Page | Route (example) | Export permission |
|
||
|------|-----------------|-------------------|
|
||
| Payments | `/admin/payments` | `payments.export` |
|
||
| Users / Learners | `/admin/users` | `users.export` |
|
||
| Subscriptions | `/admin/subscriptions` | `subscriptions.export` |
|
||
| Activity log | `/admin/logs/activity` | `activity_logs.export` |
|
||
| Team directory | `/admin/team` | `team.members.export` |
|
||
|
||
### UX guidelines
|
||
|
||
1. **Disable** the button while a download is in progress; show a spinner on the button or a page-level overlay.
|
||
2. **Reuse filters** — exporting should feel like “download what I’m looking at.”
|
||
3. **Warn on large sets** when list `total_count` > 50,000.
|
||
4. **PII banner** on users, payments, subscriptions, activity logs, and team exports — restrict to authorized staff.
|
||
5. Do **not** open CSV in a new tab via `window.open(url)` — authenticated downloads need the `Authorization` header; use `fetch` + blob.
|
||
6. Optional: after export, offer **“Export activity log”** audit entry on the client (server does not auto-log exports today).
|
||
|
||
### Filter → query mapping example (payments)
|
||
|
||
```typescript
|
||
interface PaymentListFilters {
|
||
userId?: number;
|
||
status?: string;
|
||
planCategory?: string;
|
||
createdFrom?: Date;
|
||
createdTo?: Date;
|
||
}
|
||
|
||
function paymentFiltersToQuery(f: PaymentListFilters): QueryParams {
|
||
return {
|
||
user_id: f.userId,
|
||
status: f.status,
|
||
plan_category: f.planCategory,
|
||
created_from: f.createdFrom?.toISOString(),
|
||
created_to: f.createdTo?.toISOString(),
|
||
};
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## TypeScript types
|
||
|
||
```typescript
|
||
export type ExportResource =
|
||
| "payments"
|
||
| "users"
|
||
| "subscriptions"
|
||
| "activity-logs"
|
||
| "team-members";
|
||
|
||
export const EXPORT_ROUTES: Record<ExportResource, string> = {
|
||
payments: "/api/v1/admin/payments/export",
|
||
users: "/api/v1/users/export",
|
||
subscriptions: "/api/v1/admin/subscriptions/export",
|
||
"activity-logs": "/api/v1/activity-logs/export",
|
||
"team-members": "/api/v1/team/members/export",
|
||
};
|
||
|
||
export const EXPORT_PERMISSIONS: Record<ExportResource, string> = {
|
||
payments: "payments.export",
|
||
users: "users.export",
|
||
subscriptions: "subscriptions.export",
|
||
"activity-logs": "activity_logs.export",
|
||
"team-members": "team.members.export",
|
||
};
|
||
|
||
export interface PaymentExportFilters {
|
||
user_id?: number;
|
||
plan_id?: number;
|
||
subscription_id?: number;
|
||
status?: string;
|
||
provider?: string;
|
||
currency?: string;
|
||
plan_category?: string;
|
||
reference?: string;
|
||
created_from?: string;
|
||
created_to?: string;
|
||
paid_from?: string;
|
||
paid_to?: string;
|
||
min_amount?: number;
|
||
max_amount?: number;
|
||
}
|
||
|
||
export interface UserExportFilters {
|
||
role?: string;
|
||
status?: string;
|
||
country?: string;
|
||
region?: string;
|
||
subscription_status?: "ACTIVE" | "PENDING" | "Unsubscribed";
|
||
query?: string;
|
||
created_before?: string;
|
||
created_after?: string;
|
||
}
|
||
|
||
export interface SubscriptionExportFilters {
|
||
user_id?: number;
|
||
plan_id?: number;
|
||
status?: string;
|
||
plan_category?: string;
|
||
created_from?: string;
|
||
created_to?: string;
|
||
expires_from?: string;
|
||
expires_to?: string;
|
||
}
|
||
|
||
export interface ActivityLogExportFilters {
|
||
actor_id?: number;
|
||
action?: string;
|
||
resource_type?: string;
|
||
resource_id?: number;
|
||
after?: string;
|
||
before?: string;
|
||
}
|
||
|
||
export interface TeamMemberExportFilters {
|
||
team_role?: string;
|
||
department?: string;
|
||
status?: string;
|
||
search?: string;
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## React patterns
|
||
|
||
### Permission-gated export button
|
||
|
||
```tsx
|
||
import { downloadCsvExport } from "@/lib/csv-export";
|
||
import { usePermissions } from "@/hooks/usePermissions";
|
||
|
||
type Props = {
|
||
token: string;
|
||
filters: Record<string, string | number | undefined>;
|
||
};
|
||
|
||
export function ExportPaymentsButton({ token, filters }: Props) {
|
||
const { hasPermission } = usePermissions();
|
||
const [loading, setLoading] = useState(false);
|
||
|
||
if (!hasPermission("payments.export")) return null;
|
||
|
||
async function onExport() {
|
||
setLoading(true);
|
||
try {
|
||
const filename = await downloadCsvExport(
|
||
"/api/v1/admin/payments/export",
|
||
filters,
|
||
token
|
||
);
|
||
toast.success(`Downloaded ${filename}`);
|
||
} catch (e) {
|
||
toast.error(e instanceof Error ? e.message : "Export failed");
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
}
|
||
|
||
return (
|
||
<button type="button" onClick={onExport} disabled={loading}>
|
||
{loading ? "Exporting…" : "Export CSV"}
|
||
</button>
|
||
);
|
||
}
|
||
```
|
||
|
||
### List page integration
|
||
|
||
```tsx
|
||
// PaymentsPage.tsx — sketch
|
||
const [filters, setFilters] = useState<PaymentListFilters>({ status: "SUCCESS" });
|
||
|
||
return (
|
||
<Page>
|
||
<PaymentFilters value={filters} onChange={setFilters} />
|
||
<Toolbar>
|
||
<PaymentTable filters={filters} />
|
||
<ExportPaymentsButton
|
||
token={session.accessToken}
|
||
filters={paymentFiltersToQuery(filters)}
|
||
/>
|
||
</Toolbar>
|
||
</Page>
|
||
);
|
||
```
|
||
|
||
### Truncation warning
|
||
|
||
```tsx
|
||
{totalCount > 50_000 && (
|
||
<Alert variant="warning">
|
||
More than 50,000 rows match. CSV export includes at most 50,000 rows.
|
||
Narrow your filters for a complete extract.
|
||
</Alert>
|
||
)}
|
||
```
|
||
|
||
---
|
||
|
||
## Error handling
|
||
|
||
| HTTP | Typical cause | UI message |
|
||
|------|---------------|------------|
|
||
| `400` | Invalid query param (bad date, enum, number) | Show API `message` or `error` |
|
||
| `401` | Missing/expired token | Redirect to login |
|
||
| `403` | Missing `*.export` permission | “You don’t have permission to export” |
|
||
| `500` | Server error | Generic retry message |
|
||
|
||
Error bodies are usually JSON even though success is CSV:
|
||
|
||
```json
|
||
{
|
||
"message": "Invalid query parameters",
|
||
"error": "invalid plan_category"
|
||
}
|
||
```
|
||
|
||
**Users export** may return plain text for some `400` responses (`fiber.NewError`) — still parse `response.json()` when `Content-Type` is `application/json`, otherwise use `response.text()`.
|
||
|
||
---
|
||
|
||
## Security & compliance
|
||
|
||
1. **Separate permissions** — `*.list` ≠ `*.export`; finance may list payments but not export, if roles are configured that way.
|
||
2. **PII** — exports contain emails, names, IPs (activity logs), and payment amounts. Apply the same access controls as the list pages.
|
||
3. **No caching** — do not proxy CSV through a public CDN; download directly from the API with auth.
|
||
4. **Client storage** — avoid persisting CSV blobs in `localStorage` / IndexedDB.
|
||
5. **Audit** — consider logging export actions in the admin UI until server-side export auditing exists.
|
||
|
||
---
|
||
|
||
## Integration checklist
|
||
|
||
### Backend / access
|
||
|
||
- [ ] API deployed with export routes and RBAC seeds
|
||
- [ ] `POST /api/v1/rbac/permissions/sync` run (or server restarted) on staging/production
|
||
- [ ] Test role has each required `*.export` permission
|
||
- [ ] Verify each `GET .../export` returns `200` + `text/csv` with a Bearer token
|
||
|
||
### Shared client
|
||
|
||
- [ ] `downloadCsvExport` helper uses `blob()` (not JSON parser)
|
||
- [ ] Filename parsed from `Content-Disposition`
|
||
- [ ] Errors from non-OK responses surfaced to the user
|
||
|
||
### Per page
|
||
|
||
- [ ] **Payments** — Export button; filters mapped to query params
|
||
- [ ] **Users** — Export button; `subscription_status` values match list API
|
||
- [ ] **Subscriptions** — Export button; date filters wired
|
||
- [ ] **Activity logs** — Export button; `after`/`before` in RFC3339
|
||
- [ ] **Team** — Export button; `search` mode tested
|
||
|
||
### UX / QA
|
||
|
||
- [ ] Loading state while export runs
|
||
- [ ] Empty filter set downloads header-only CSV
|
||
- [ ] Filtered export matches list row count (up to 50k)
|
||
- [ ] Excel opens file correctly (UTF-8 BOM)
|
||
- [ ] 403 hides or disables Export for unauthorized roles
|
||
- [ ] Warning shown when `total_count` > 50,000
|
||
|
||
---
|
||
|
||
## Quick reference
|
||
|
||
```bash
|
||
# Payments
|
||
curl -o payments.csv -H "Authorization: Bearer $TOKEN" \
|
||
"$API/api/v1/admin/payments/export?status=SUCCESS"
|
||
|
||
# Users
|
||
curl -o users.csv -H "Authorization: Bearer $TOKEN" \
|
||
"$API/api/v1/users/export?role=STUDENT&subscription_status=ACTIVE"
|
||
|
||
# Subscriptions
|
||
curl -o subscriptions.csv -H "Authorization: Bearer $TOKEN" \
|
||
"$API/api/v1/admin/subscriptions/export?plan_category=LEARN_ENGLISH"
|
||
|
||
# Activity logs
|
||
curl -o activity-logs.csv -H "Authorization: Bearer $TOKEN" \
|
||
"$API/api/v1/activity-logs/export?action=FAQ_UPDATED&after=2026-06-01T00:00:00Z"
|
||
|
||
# Team members
|
||
curl -o team-members.csv -H "Authorization: Bearer $TOKEN" \
|
||
"$API/api/v1/team/members/export?status=active"
|
||
```
|
||
|
||
| Resource | Method | Path | Permission |
|
||
|----------|--------|------|------------|
|
||
| Payments | `GET` | `/api/v1/admin/payments/export` | `payments.export` |
|
||
| Users | `GET` | `/api/v1/users/export` | `users.export` |
|
||
| Subscriptions | `GET` | `/api/v1/admin/subscriptions/export` | `subscriptions.export` |
|
||
| Activity logs | `GET` | `/api/v1/activity-logs/export` | `activity_logs.export` |
|
||
| Team members | `GET` | `/api/v1/team/members/export` | `team.members.export` |
|