feat: add Tier 1 admin CSV export APIs and integration guide
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>
This commit is contained in:
parent
75fb913704
commit
713bd95f97
|
|
@ -252,3 +252,41 @@ SET
|
|||
expires_at = $1,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $2;
|
||||
|
||||
-- name: ListUserSubscriptionsAdmin :many
|
||||
SELECT
|
||||
COUNT(*) OVER () AS total_count,
|
||||
us.id,
|
||||
us.user_id,
|
||||
us.plan_id,
|
||||
us.starts_at,
|
||||
us.expires_at,
|
||||
us.status,
|
||||
us.payment_reference,
|
||||
us.payment_method,
|
||||
us.auto_renew,
|
||||
us.cancelled_at,
|
||||
us.created_at,
|
||||
us.updated_at,
|
||||
sp.name AS plan_name,
|
||||
sp.category AS plan_category,
|
||||
sp.duration_value,
|
||||
sp.duration_unit,
|
||||
sp.price,
|
||||
sp.currency,
|
||||
u.email AS user_email,
|
||||
u.first_name AS user_first_name,
|
||||
u.last_name AS user_last_name
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
JOIN users u ON u.id = us.user_id
|
||||
WHERE (sqlc.narg('user_id')::bigint IS NULL OR us.user_id = sqlc.narg('user_id')::bigint)
|
||||
AND (sqlc.narg('plan_id')::bigint IS NULL OR us.plan_id = sqlc.narg('plan_id')::bigint)
|
||||
AND (sqlc.narg('status')::varchar IS NULL OR us.status = sqlc.narg('status')::varchar)
|
||||
AND (sqlc.narg('plan_category')::varchar IS NULL OR sp.category = sqlc.narg('plan_category')::varchar)
|
||||
AND (sqlc.narg('created_from')::timestamptz IS NULL OR us.created_at >= sqlc.narg('created_from')::timestamptz)
|
||||
AND (sqlc.narg('created_to')::timestamptz IS NULL OR us.created_at < sqlc.narg('created_to')::timestamptz)
|
||||
AND (sqlc.narg('expires_from')::timestamptz IS NULL OR us.expires_at >= sqlc.narg('expires_from')::timestamptz)
|
||||
AND (sqlc.narg('expires_to')::timestamptz IS NULL OR us.expires_at < sqlc.narg('expires_to')::timestamptz)
|
||||
ORDER BY us.created_at DESC
|
||||
LIMIT sqlc.arg('limit') OFFSET sqlc.arg('offset');
|
||||
|
|
|
|||
845
docs/csv-export-admin-panel-integration.md
Normal file
845
docs/csv-export-admin-panel-integration.md
Normal file
|
|
@ -0,0 +1,845 @@
|
|||
# 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` |
|
||||
|
|
@ -921,6 +921,137 @@ func (q *Queries) ListSubscriptionPlans(ctx context.Context, dollar_1 bool) ([]S
|
|||
return items, nil
|
||||
}
|
||||
|
||||
const ListUserSubscriptionsAdmin = `-- name: ListUserSubscriptionsAdmin :many
|
||||
SELECT
|
||||
COUNT(*) OVER () AS total_count,
|
||||
us.id,
|
||||
us.user_id,
|
||||
us.plan_id,
|
||||
us.starts_at,
|
||||
us.expires_at,
|
||||
us.status,
|
||||
us.payment_reference,
|
||||
us.payment_method,
|
||||
us.auto_renew,
|
||||
us.cancelled_at,
|
||||
us.created_at,
|
||||
us.updated_at,
|
||||
sp.name AS plan_name,
|
||||
sp.category AS plan_category,
|
||||
sp.duration_value,
|
||||
sp.duration_unit,
|
||||
sp.price,
|
||||
sp.currency,
|
||||
u.email AS user_email,
|
||||
u.first_name AS user_first_name,
|
||||
u.last_name AS user_last_name
|
||||
FROM user_subscriptions us
|
||||
JOIN subscription_plans sp ON sp.id = us.plan_id
|
||||
JOIN users u ON u.id = us.user_id
|
||||
WHERE ($1::bigint IS NULL OR us.user_id = $1::bigint)
|
||||
AND ($2::bigint IS NULL OR us.plan_id = $2::bigint)
|
||||
AND ($3::varchar IS NULL OR us.status = $3::varchar)
|
||||
AND ($4::varchar IS NULL OR sp.category = $4::varchar)
|
||||
AND ($5::timestamptz IS NULL OR us.created_at >= $5::timestamptz)
|
||||
AND ($6::timestamptz IS NULL OR us.created_at < $6::timestamptz)
|
||||
AND ($7::timestamptz IS NULL OR us.expires_at >= $7::timestamptz)
|
||||
AND ($8::timestamptz IS NULL OR us.expires_at < $8::timestamptz)
|
||||
ORDER BY us.created_at DESC
|
||||
LIMIT $10 OFFSET $9
|
||||
`
|
||||
|
||||
type ListUserSubscriptionsAdminParams struct {
|
||||
UserID pgtype.Int8 `json:"user_id"`
|
||||
PlanID pgtype.Int8 `json:"plan_id"`
|
||||
Status pgtype.Text `json:"status"`
|
||||
PlanCategory pgtype.Text `json:"plan_category"`
|
||||
CreatedFrom pgtype.Timestamptz `json:"created_from"`
|
||||
CreatedTo pgtype.Timestamptz `json:"created_to"`
|
||||
ExpiresFrom pgtype.Timestamptz `json:"expires_from"`
|
||||
ExpiresTo pgtype.Timestamptz `json:"expires_to"`
|
||||
Offset int32 `json:"offset"`
|
||||
Limit int32 `json:"limit"`
|
||||
}
|
||||
|
||||
type ListUserSubscriptionsAdminRow struct {
|
||||
TotalCount int64 `json:"total_count"`
|
||||
ID int64 `json:"id"`
|
||||
UserID int64 `json:"user_id"`
|
||||
PlanID int64 `json:"plan_id"`
|
||||
StartsAt pgtype.Timestamptz `json:"starts_at"`
|
||||
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
|
||||
Status string `json:"status"`
|
||||
PaymentReference pgtype.Text `json:"payment_reference"`
|
||||
PaymentMethod pgtype.Text `json:"payment_method"`
|
||||
AutoRenew bool `json:"auto_renew"`
|
||||
CancelledAt pgtype.Timestamptz `json:"cancelled_at"`
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
|
||||
PlanName string `json:"plan_name"`
|
||||
PlanCategory string `json:"plan_category"`
|
||||
DurationValue int32 `json:"duration_value"`
|
||||
DurationUnit string `json:"duration_unit"`
|
||||
Price pgtype.Numeric `json:"price"`
|
||||
Currency string `json:"currency"`
|
||||
UserEmail pgtype.Text `json:"user_email"`
|
||||
UserFirstName pgtype.Text `json:"user_first_name"`
|
||||
UserLastName pgtype.Text `json:"user_last_name"`
|
||||
}
|
||||
|
||||
func (q *Queries) ListUserSubscriptionsAdmin(ctx context.Context, arg ListUserSubscriptionsAdminParams) ([]ListUserSubscriptionsAdminRow, error) {
|
||||
rows, err := q.db.Query(ctx, ListUserSubscriptionsAdmin,
|
||||
arg.UserID,
|
||||
arg.PlanID,
|
||||
arg.Status,
|
||||
arg.PlanCategory,
|
||||
arg.CreatedFrom,
|
||||
arg.CreatedTo,
|
||||
arg.ExpiresFrom,
|
||||
arg.ExpiresTo,
|
||||
arg.Offset,
|
||||
arg.Limit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListUserSubscriptionsAdminRow
|
||||
for rows.Next() {
|
||||
var i ListUserSubscriptionsAdminRow
|
||||
if err := rows.Scan(
|
||||
&i.TotalCount,
|
||||
&i.ID,
|
||||
&i.UserID,
|
||||
&i.PlanID,
|
||||
&i.StartsAt,
|
||||
&i.ExpiresAt,
|
||||
&i.Status,
|
||||
&i.PaymentReference,
|
||||
&i.PaymentMethod,
|
||||
&i.AutoRenew,
|
||||
&i.CancelledAt,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.PlanName,
|
||||
&i.PlanCategory,
|
||||
&i.DurationValue,
|
||||
&i.DurationUnit,
|
||||
&i.Price,
|
||||
&i.Currency,
|
||||
&i.UserEmail,
|
||||
&i.UserFirstName,
|
||||
&i.UserLastName,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const UpdateAutoRenew = `-- name: UpdateAutoRenew :exec
|
||||
UPDATE user_subscriptions
|
||||
SET
|
||||
|
|
|
|||
|
|
@ -186,3 +186,32 @@ func CalculateExpiryDate(startTime time.Time, durationValue int32, durationUnit
|
|||
return startTime.AddDate(0, int(durationValue), 0) // Default to months
|
||||
}
|
||||
}
|
||||
|
||||
// UserSubscriptionAdminRow includes learner identity for admin list/export.
|
||||
type UserSubscriptionAdminRow struct {
|
||||
UserSubscription
|
||||
UserEmail string
|
||||
UserFirstName string
|
||||
UserLastName string
|
||||
}
|
||||
|
||||
// UserSubscriptionAdminFilter filters the global admin subscription list.
|
||||
type UserSubscriptionAdminFilter struct {
|
||||
UserID *int64
|
||||
PlanID *int64
|
||||
Status *string
|
||||
PlanCategory *string
|
||||
CreatedFrom *time.Time
|
||||
CreatedTo *time.Time
|
||||
ExpiresFrom *time.Time
|
||||
ExpiresTo *time.Time
|
||||
Limit int32
|
||||
Offset int32
|
||||
}
|
||||
|
||||
// UserSubscriptionAdminPage is a paginated admin subscription list.
|
||||
type UserSubscriptionAdminPage struct {
|
||||
Items []UserSubscriptionAdminRow
|
||||
Total int64
|
||||
Limit, Offset int32
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,5 +29,6 @@ type SubscriptionStore interface {
|
|||
UpdateSubscriptionStatus(ctx context.Context, id int64, status string) error
|
||||
UpdateAutoRenew(ctx context.Context, id int64, autoRenew bool) error
|
||||
ExtendSubscription(ctx context.Context, id int64, newExpiresAt time.Time) error
|
||||
ListUserSubscriptionsAdmin(ctx context.Context, filter domain.UserSubscriptionAdminFilter) (domain.UserSubscriptionAdminPage, error)
|
||||
ListLearnEnglishSubscriptionsExpiringInSevenDays(ctx context.Context) ([]domain.SubscriptionExpiryReminder, error)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -270,6 +270,55 @@ func (s *Store) ExtendSubscription(ctx context.Context, id int64, newExpiresAt t
|
|||
})
|
||||
}
|
||||
|
||||
func (s *Store) ListUserSubscriptionsAdmin(ctx context.Context, filter domain.UserSubscriptionAdminFilter) (domain.UserSubscriptionAdminPage, error) {
|
||||
rows, err := s.queries.ListUserSubscriptionsAdmin(ctx, dbgen.ListUserSubscriptionsAdminParams{
|
||||
UserID: int64PtrToPgInt8(filter.UserID),
|
||||
PlanID: int64PtrToPgInt8(filter.PlanID),
|
||||
Status: toPgText(filter.Status),
|
||||
PlanCategory: toPgText(filter.PlanCategory),
|
||||
CreatedFrom: toPgTimestamptzPtr(filter.CreatedFrom),
|
||||
CreatedTo: toPgTimestamptzPtr(filter.CreatedTo),
|
||||
ExpiresFrom: toPgTimestamptzPtr(filter.ExpiresFrom),
|
||||
ExpiresTo: toPgTimestamptzPtr(filter.ExpiresTo),
|
||||
Limit: filter.Limit,
|
||||
Offset: filter.Offset,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.UserSubscriptionAdminPage{}, err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return domain.UserSubscriptionAdminPage{
|
||||
Items: []domain.UserSubscriptionAdminRow{},
|
||||
Total: 0,
|
||||
Limit: filter.Limit,
|
||||
Offset: filter.Offset,
|
||||
}, nil
|
||||
}
|
||||
|
||||
items := make([]domain.UserSubscriptionAdminRow, len(rows))
|
||||
for i, row := range rows {
|
||||
sub := mapUserSubscriptionPlanJoinRow(
|
||||
row.ID, row.UserID, row.PlanID, row.StartsAt, row.ExpiresAt, row.Status,
|
||||
row.PaymentReference, row.PaymentMethod, row.AutoRenew, row.CancelledAt,
|
||||
row.CreatedAt, row.UpdatedAt, row.PlanName, row.PlanCategory,
|
||||
row.DurationValue, row.DurationUnit, row.Price, row.Currency,
|
||||
)
|
||||
items[i] = domain.UserSubscriptionAdminRow{
|
||||
UserSubscription: sub,
|
||||
UserEmail: derefString(fromPgText(row.UserEmail)),
|
||||
UserFirstName: derefString(fromPgText(row.UserFirstName)),
|
||||
UserLastName: derefString(fromPgText(row.UserLastName)),
|
||||
}
|
||||
}
|
||||
|
||||
return domain.UserSubscriptionAdminPage{
|
||||
Items: items,
|
||||
Total: rows[0].TotalCount,
|
||||
Limit: filter.Limit,
|
||||
Offset: filter.Offset,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Helper conversion functions
|
||||
|
||||
func subscriptionPlanToDomain(p dbgen.SubscriptionPlan) *domain.SubscriptionPlan {
|
||||
|
|
|
|||
|
|
@ -164,6 +164,7 @@ var AllPermissions = []domain.PermissionSeed{
|
|||
{Key: "subscriptions.checkout", Name: "Checkout Subscription", Description: "Initiate subscription payment", GroupName: "Subscriptions"},
|
||||
{Key: "subscriptions.get_mine", Name: "Get My Subscription", Description: "Get own subscription", GroupName: "Subscriptions"},
|
||||
{Key: "subscriptions.get_by_user", Name: "Get User Subscriptions (Admin)", Description: "Get full subscription details for a user", GroupName: "Subscriptions"},
|
||||
{Key: "subscriptions.export", Name: "Export Subscriptions", Description: "Export user subscriptions as CSV (admin)", GroupName: "Subscriptions"},
|
||||
{Key: "subscriptions.history", Name: "Subscription History", Description: "Get subscription history", GroupName: "Subscriptions"},
|
||||
{Key: "subscriptions.status", Name: "Check Subscription Status", Description: "Check subscription status", GroupName: "Subscriptions"},
|
||||
{Key: "subscriptions.cancel", Name: "Cancel Subscription", Description: "Cancel a subscription", GroupName: "Subscriptions"},
|
||||
|
|
@ -178,9 +179,11 @@ var AllPermissions = []domain.PermissionSeed{
|
|||
{Key: "payments.direct_initiate", Name: "Initiate Direct Payment", Description: "Initiate direct payment", GroupName: "Payments"},
|
||||
{Key: "payments.direct_verify_otp", Name: "Verify Direct Payment OTP", Description: "Verify OTP for direct payment", GroupName: "Payments"},
|
||||
{Key: "payments.list_all", Name: "List All Payments", Description: "List and filter all gateway payments (admin)", GroupName: "Payments"},
|
||||
{Key: "payments.export", Name: "Export Payments", Description: "Export payments as CSV (admin)", GroupName: "Payments"},
|
||||
|
||||
// Users
|
||||
{Key: "users.list", Name: "List Users", Description: "List all users", GroupName: "Users"},
|
||||
{Key: "users.export", Name: "Export Users", Description: "Export users as CSV (admin)", GroupName: "Users"},
|
||||
{Key: "users.get", Name: "Get User", Description: "Get user by ID", GroupName: "Users"},
|
||||
{Key: "users.update_self", Name: "Update Own Profile", Description: "Update own user profile", GroupName: "Users"},
|
||||
{Key: "users.update_status", Name: "Update User Status", Description: "Activate/deactivate users", GroupName: "Users"},
|
||||
|
|
@ -204,6 +207,7 @@ var AllPermissions = []domain.PermissionSeed{
|
|||
// Logs
|
||||
{Key: "logs.list", Name: "List Logs", Description: "List system logs", GroupName: "Logs"},
|
||||
{Key: "activity_logs.list", Name: "List Activity Logs", Description: "List activity logs", GroupName: "Logs"},
|
||||
{Key: "activity_logs.export", Name: "Export Activity Logs", Description: "Export activity logs as CSV", GroupName: "Logs"},
|
||||
{Key: "activity_logs.get", Name: "Get Activity Log", Description: "Get activity log by ID", GroupName: "Logs"},
|
||||
|
||||
// Notifications
|
||||
|
|
@ -293,6 +297,7 @@ var AllPermissions = []domain.PermissionSeed{
|
|||
{Key: "team.profile.update_mine", Name: "Update My Team Profile", Description: "Update own team profile", GroupName: "Team"},
|
||||
{Key: "team.stats", Name: "Get Team Stats", Description: "Get team member statistics", GroupName: "Team"},
|
||||
{Key: "team.members.list", Name: "List Team Members", Description: "List all team members", GroupName: "Team"},
|
||||
{Key: "team.members.export", Name: "Export Team Members", Description: "Export team members as CSV", GroupName: "Team"},
|
||||
{Key: "team.members.create", Name: "Create Team Member", Description: "Create a team member", GroupName: "Team"},
|
||||
{Key: "team.members.get", Name: "Get Team Member", Description: "Get team member by ID", GroupName: "Team"},
|
||||
{Key: "team.members.update", Name: "Update Team Member", Description: "Update a team member", GroupName: "Team"},
|
||||
|
|
@ -449,20 +454,20 @@ var DefaultRolePermissions = map[string][]string{
|
|||
|
||||
// Subscriptions & Payments (full access)
|
||||
"subscription_plans.create", "subscription_plans.update", "subscription_plans.delete",
|
||||
"subscriptions.create", "subscriptions.checkout", "subscriptions.get_mine", "subscriptions.get_by_user", "subscriptions.history",
|
||||
"subscriptions.create", "subscriptions.checkout", "subscriptions.get_mine", "subscriptions.get_by_user", "subscriptions.export", "subscriptions.history",
|
||||
"subscriptions.status", "subscriptions.cancel", "subscriptions.set_auto_renew",
|
||||
"payments.initiate", "payments.verify", "payments.list_mine", "payments.get", "payments.cancel",
|
||||
"payments.direct_initiate", "payments.direct_verify_otp", "payments.list_all",
|
||||
"payments.direct_initiate", "payments.direct_verify_otp", "payments.list_all", "payments.export",
|
||||
|
||||
// Users (full access)
|
||||
"users.list", "users.get", "users.update_self", "users.update_status", "users.delete", "users.delete_self", "users.cancel_delete_self", "users.purge_due_deletions", "users.deletion_requests.list", "users.search",
|
||||
"users.list", "users.export", "users.get", "users.update_self", "users.update_status", "users.delete", "users.delete_self", "users.cancel_delete_self", "users.purge_due_deletions", "users.deletion_requests.list", "users.search",
|
||||
"users.profile_completed", "users.upload_profile_picture", "users.admin_profile", "users.user_profile",
|
||||
|
||||
// Admin management
|
||||
"admins.list", "admins.get", "admins.create", "admins.update",
|
||||
|
||||
// Logs (previously OnlyAdminAndAbove)
|
||||
"logs.list", "activity_logs.list", "activity_logs.get",
|
||||
"logs.list", "activity_logs.list", "activity_logs.export", "activity_logs.get",
|
||||
|
||||
// Notifications (full access including bulk)
|
||||
"notifications.ws_connect", "notifications.list_mine", "notifications.list_all",
|
||||
|
|
@ -500,7 +505,7 @@ var DefaultRolePermissions = map[string][]string{
|
|||
"vimeo.uploads.pull", "vimeo.uploads.tus",
|
||||
|
||||
// Team (full access)
|
||||
"team.profile.get_mine", "team.profile.update_mine", "team.stats", "team.members.list", "team.members.create", "team.members.invite",
|
||||
"team.profile.get_mine", "team.profile.update_mine", "team.stats", "team.members.list", "team.members.export", "team.members.create", "team.members.invite",
|
||||
"team.members.get", "team.members.update", "team.members.update_status", "team.members.delete", "team.members.change_password",
|
||||
"team.invitations.list", "team.invitations.resend", "team.invitations.revoke",
|
||||
|
||||
|
|
|
|||
|
|
@ -121,6 +121,10 @@ func (s *Service) GetSubscriptionHistory(ctx context.Context, userID int64, limi
|
|||
return s.store.GetUserSubscriptionHistory(ctx, userID, limit, offset)
|
||||
}
|
||||
|
||||
func (s *Service) ListUserSubscriptionsAdmin(ctx context.Context, filter domain.UserSubscriptionAdminFilter) (domain.UserSubscriptionAdminPage, error) {
|
||||
return s.store.ListUserSubscriptionsAdmin(ctx, filter)
|
||||
}
|
||||
|
||||
func (s *Service) HasActiveSubscription(ctx context.Context, userID int64) (bool, error) {
|
||||
return s.store.HasActiveSubscription(ctx, userID)
|
||||
}
|
||||
|
|
|
|||
394
internal/web_server/handlers/admin_export.go
Normal file
394
internal/web_server/handlers/admin_export.go
Normal file
|
|
@ -0,0 +1,394 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Yimaru-Backend/internal/web_server/response"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func csvOptionalString(p *string) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
return *p
|
||||
}
|
||||
|
||||
func csvOptionalInt64(p *int64) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
return strconv.FormatInt(*p, 64)
|
||||
}
|
||||
|
||||
func csvTimeRFC3339(t time.Time) string {
|
||||
if t.IsZero() {
|
||||
return ""
|
||||
}
|
||||
return t.UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
func csvTimePtr(p *time.Time) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
return csvTimeRFC3339(*p)
|
||||
}
|
||||
|
||||
func csvFloatPtr(p *float64) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
return strconv.FormatFloat(*p, 'f', 2, 64)
|
||||
}
|
||||
|
||||
func csvBool(b bool) string {
|
||||
if b {
|
||||
return "true"
|
||||
}
|
||||
return "false"
|
||||
}
|
||||
|
||||
func csvJSON(raw json.RawMessage) string {
|
||||
if len(raw) == 0 {
|
||||
return ""
|
||||
}
|
||||
return string(raw)
|
||||
}
|
||||
|
||||
// ExportAdminPaymentsCSV godoc
|
||||
// @Summary Export payments as CSV (admin)
|
||||
// @Tags payments
|
||||
// @Produce text/csv
|
||||
// @Router /api/v1/admin/payments/export [get]
|
||||
func (h *Handler) ExportAdminPaymentsCSV(c *fiber.Ctx) error {
|
||||
filter, err := paymentListFilterFields(c)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Invalid query parameters",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
headers := []string{
|
||||
"id", "user_id", "user_email", "user_first_name", "user_last_name",
|
||||
"plan_id", "plan_name", "plan_category", "subscription_id",
|
||||
"session_id", "transaction_id", "nonce", "amount", "currency",
|
||||
"payment_method", "status", "paid_at", "expires_at", "created_at", "updated_at",
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
return response.StreamCSV(c, exportFilename("payments"), headers, func(offset, limit int32) ([][]string, error) {
|
||||
filter.Limit = limit
|
||||
filter.Offset = offset
|
||||
page, err := h.chapaSvc.ListPaymentsAdmin(ctx, filter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows := make([][]string, len(page.Items))
|
||||
for i := range page.Items {
|
||||
res := adminPaymentListToRes(&page.Items[i])
|
||||
rows[i] = []string{
|
||||
strconv.FormatInt(res.ID, 10),
|
||||
strconv.FormatInt(res.UserID, 10),
|
||||
csvOptionalString(res.UserEmail),
|
||||
csvOptionalString(res.UserFirstName),
|
||||
csvOptionalString(res.UserLastName),
|
||||
csvOptionalInt64(res.PlanID),
|
||||
csvOptionalString(res.PlanName),
|
||||
csvOptionalString(res.PlanCategory),
|
||||
csvOptionalInt64(res.SubscriptionID),
|
||||
csvOptionalString(res.SessionID),
|
||||
csvOptionalString(res.TransactionID),
|
||||
res.Nonce,
|
||||
strconv.FormatFloat(res.Amount, 'f', 2, 64),
|
||||
res.Currency,
|
||||
csvOptionalString(res.PaymentMethod),
|
||||
res.Status,
|
||||
csvOptionalString(res.PaidAt),
|
||||
csvOptionalString(res.ExpiresAt),
|
||||
res.CreatedAt,
|
||||
csvOptionalString(res.UpdatedAt),
|
||||
}
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
}
|
||||
|
||||
// ExportUsersCSV godoc
|
||||
// @Summary Export users as CSV (admin)
|
||||
// @Tags user
|
||||
// @Produce text/csv
|
||||
// @Router /api/v1/users/export [get]
|
||||
func (h *Handler) ExportUsersCSV(c *fiber.Ctx) error {
|
||||
filter, err := parseUserListFilter(c)
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
if valErrs, ok := h.validator.Validate(c, filter); !ok {
|
||||
var errMsg string
|
||||
for f, msg := range valErrs {
|
||||
errMsg += fmt.Sprintf("%s: %s; ", f, msg)
|
||||
}
|
||||
return fiber.NewError(fiber.StatusBadRequest, errMsg)
|
||||
}
|
||||
|
||||
headers := []string{
|
||||
"id", "first_name", "last_name", "email", "phone_number", "role", "status",
|
||||
"country", "region", "subscription_status", "email_verified", "phone_verified",
|
||||
"profile_completed", "created_at", "updated_at", "last_login",
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
batchSize := int32(response.ExportBatchSize)
|
||||
return response.StreamCSV(c, exportFilename("users"), headers, func(offset, limit int32) ([][]string, error) {
|
||||
filter.Page = int64(offset / batchSize)
|
||||
filter.PageSize = int64(batchSize)
|
||||
users, _, err := h.userSvc.GetAllUsers(ctx, filter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(users) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
userIDs := make([]int64, len(users))
|
||||
for i, u := range users {
|
||||
userIDs[i] = u.ID
|
||||
}
|
||||
subStatuses, err := h.subscriptionsSvc.ListSubscriptionDisplayStatusesForUserIDs(ctx, userIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rows := make([][]string, len(users))
|
||||
for i, u := range users {
|
||||
subStatus := "Unsubscribed"
|
||||
if s, ok := subStatuses[u.ID]; ok {
|
||||
subStatus = s
|
||||
}
|
||||
rows[i] = []string{
|
||||
strconv.FormatInt(u.ID, 10),
|
||||
u.FirstName,
|
||||
u.LastName,
|
||||
u.Email,
|
||||
u.PhoneNumber,
|
||||
string(u.Role),
|
||||
string(u.Status),
|
||||
u.Country,
|
||||
u.Region,
|
||||
subStatus,
|
||||
csvBool(u.EmailVerified),
|
||||
csvBool(u.PhoneVerified),
|
||||
csvBool(u.ProfileCompleted),
|
||||
csvTimeRFC3339(u.CreatedAt),
|
||||
csvTimePtr(u.UpdatedAt),
|
||||
csvTimePtr(u.LastLogin),
|
||||
}
|
||||
}
|
||||
if int32(len(rows)) > limit {
|
||||
rows = rows[:limit]
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
}
|
||||
|
||||
// ExportActivityLogsCSV godoc
|
||||
// @Summary Export activity logs as CSV (admin)
|
||||
// @Tags activity-logs
|
||||
// @Produce text/csv
|
||||
// @Router /api/v1/activity-logs/export [get]
|
||||
func (h *Handler) ExportActivityLogsCSV(c *fiber.Ctx) error {
|
||||
filter, err := parseActivityLogFilterFields(c)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: err.Error(),
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
headers := []string{
|
||||
"id", "actor_id", "actor_role", "actor_name", "actor_email", "actor_kind",
|
||||
"action", "resource_type", "resource_id", "message", "metadata",
|
||||
"ip_address", "user_agent", "created_at",
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
return response.StreamCSV(c, exportFilename("activity-logs"), headers, func(offset, limit int32) ([][]string, error) {
|
||||
filter.Limit = limit
|
||||
filter.Offset = offset
|
||||
logs, _, err := h.activityLogSvc.List(ctx, filter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows := make([][]string, len(logs))
|
||||
for i, l := range logs {
|
||||
res := h.toActivityLogRes(ctx, l)
|
||||
rows[i] = []string{
|
||||
strconv.FormatInt(res.ID, 10),
|
||||
csvOptionalInt64(res.ActorID),
|
||||
csvOptionalString(res.ActorRole),
|
||||
csvOptionalString(res.ActorName),
|
||||
csvOptionalString(res.ActorEmail),
|
||||
csvOptionalString(res.ActorKind),
|
||||
res.Action,
|
||||
res.ResourceType,
|
||||
csvOptionalInt64(res.ResourceID),
|
||||
csvOptionalString(res.Message),
|
||||
csvJSON(res.Metadata),
|
||||
csvOptionalString(res.IPAddress),
|
||||
csvOptionalString(res.UserAgent),
|
||||
csvTimeRFC3339(res.CreatedAt),
|
||||
}
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
}
|
||||
|
||||
// ExportUserSubscriptionsCSV godoc
|
||||
// @Summary Export user subscriptions as CSV (admin)
|
||||
// @Tags subscriptions
|
||||
// @Produce text/csv
|
||||
// @Router /api/v1/admin/subscriptions/export [get]
|
||||
func (h *Handler) ExportUserSubscriptionsCSV(c *fiber.Ctx) error {
|
||||
filter, err := parseUserSubscriptionAdminFilterFields(c)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||
Message: "Invalid query parameters",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
headers := []string{
|
||||
"id", "user_id", "user_email", "user_first_name", "user_last_name",
|
||||
"plan_id", "plan_name", "plan_category", "status",
|
||||
"starts_at", "expires_at", "auto_renew", "payment_reference", "payment_method",
|
||||
"price", "currency", "duration_value", "duration_unit",
|
||||
"cancelled_at", "created_at", "updated_at",
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
return response.StreamCSV(c, exportFilename("subscriptions"), headers, func(offset, limit int32) ([][]string, error) {
|
||||
filter.Limit = limit
|
||||
filter.Offset = offset
|
||||
page, err := h.subscriptionsSvc.ListUserSubscriptionsAdmin(ctx, filter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows := make([][]string, len(page.Items))
|
||||
for i, row := range page.Items {
|
||||
sub := row.UserSubscription
|
||||
rows[i] = []string{
|
||||
strconv.FormatInt(sub.ID, 10),
|
||||
strconv.FormatInt(sub.UserID, 10),
|
||||
row.UserEmail,
|
||||
row.UserFirstName,
|
||||
row.UserLastName,
|
||||
strconv.FormatInt(sub.PlanID, 10),
|
||||
csvOptionalString(sub.PlanName),
|
||||
csvOptionalString(sub.PlanCategory),
|
||||
sub.Status,
|
||||
csvTimeRFC3339(sub.StartsAt),
|
||||
csvTimeRFC3339(sub.ExpiresAt),
|
||||
csvBool(sub.AutoRenew),
|
||||
csvOptionalString(sub.PaymentReference),
|
||||
csvOptionalString(sub.PaymentMethod),
|
||||
csvFloatPtr(sub.Price),
|
||||
csvOptionalString(sub.Currency),
|
||||
int32CSV(sub.DurationValue),
|
||||
csvOptionalString(sub.DurationUnit),
|
||||
csvTimePtr(sub.CancelledAt),
|
||||
csvTimeRFC3339(sub.CreatedAt),
|
||||
csvTimePtr(sub.UpdatedAt),
|
||||
}
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
}
|
||||
|
||||
// ExportTeamMembersCSV godoc
|
||||
// @Summary Export team members as CSV (admin)
|
||||
// @Tags team
|
||||
// @Produce text/csv
|
||||
// @Router /api/v1/team/members/export [get]
|
||||
func (h *Handler) ExportTeamMembersCSV(c *fiber.Ctx) error {
|
||||
filter := parseTeamMemberListFilter(c)
|
||||
ctx := c.Context()
|
||||
|
||||
headers := []string{
|
||||
"id", "first_name", "last_name", "email", "phone_number",
|
||||
"team_role", "department", "job_title", "employment_type", "hire_date",
|
||||
"status", "email_verified", "last_login", "created_at", "updated_at",
|
||||
}
|
||||
|
||||
if filter.Search != "" {
|
||||
members, err := h.teamSvc.SearchTeamMembers(ctx, filter.Search, filter.TeamRole, filter.Status)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||
Message: "Failed to export team members",
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
rows := teamMembersToCSVRows(members)
|
||||
return response.StreamCSV(c, exportFilename("team-members"), headers, func(offset, limit int32) ([][]string, error) {
|
||||
if offset > 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if int(limit) < len(rows) {
|
||||
return rows[:limit], nil
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
}
|
||||
|
||||
batchSize := int32(response.ExportBatchSize)
|
||||
return response.StreamCSV(c, exportFilename("team-members"), headers, func(offset, limit int32) ([][]string, error) {
|
||||
filter.Page = int64(offset/batchSize) + 1
|
||||
filter.PageSize = int64(batchSize)
|
||||
members, _, err := h.teamSvc.GetAllTeamMembers(ctx, filter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows := teamMembersToCSVRows(members)
|
||||
if int32(len(rows)) > limit {
|
||||
rows = rows[:limit]
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
}
|
||||
|
||||
func int32CSV(p *int32) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
return strconv.FormatInt(int64(*p), 10)
|
||||
}
|
||||
|
||||
func teamMembersToCSVRows(members []domain.TeamMember) [][]string {
|
||||
rows := make([][]string, len(members))
|
||||
for i := range members {
|
||||
res := toTeamMemberResponse(&members[i])
|
||||
rows[i] = []string{
|
||||
strconv.FormatInt(res.ID, 10),
|
||||
res.FirstName,
|
||||
res.LastName,
|
||||
res.Email,
|
||||
res.PhoneNumber,
|
||||
string(res.TeamRole),
|
||||
res.Department,
|
||||
res.JobTitle,
|
||||
string(res.EmploymentType),
|
||||
res.HireDate,
|
||||
string(res.Status),
|
||||
csvBool(res.EmailVerified),
|
||||
csvTimePtr(res.LastLogin),
|
||||
csvTimeRFC3339(res.CreatedAt),
|
||||
csvTimePtr(res.UpdatedAt),
|
||||
}
|
||||
}
|
||||
return rows
|
||||
}
|
||||
264
internal/web_server/handlers/export_filters.go
Normal file
264
internal/web_server/handlers/export_filters.go
Normal file
|
|
@ -0,0 +1,264 @@
|
|||
package handlers
|
||||
|
||||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func paymentListFilterFields(c *fiber.Ctx) (domain.PaymentListFilter, error) {
|
||||
filter := domain.PaymentListFilter{}
|
||||
|
||||
if v := strings.TrimSpace(c.Query("user_id")); v != "" {
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid user_id")
|
||||
}
|
||||
filter.UserID = &id
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("plan_id")); v != "" {
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid plan_id")
|
||||
}
|
||||
filter.PlanID = &id
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("subscription_id")); v != "" {
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid subscription_id")
|
||||
}
|
||||
filter.SubscriptionID = &id
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("status")); v != "" {
|
||||
status := strings.ToUpper(v)
|
||||
if !isValidPaymentStatus(status) {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid status")
|
||||
}
|
||||
filter.Status = &status
|
||||
}
|
||||
provider := firstNonEmpty(strings.TrimSpace(c.Query("provider")), strings.TrimSpace(c.Query("payment_method")))
|
||||
if provider != "" {
|
||||
p, err := domain.ParsePaymentProvider(provider)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, err
|
||||
}
|
||||
method := string(p)
|
||||
filter.PaymentMethod = &method
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("currency")); v != "" {
|
||||
cur := strings.ToUpper(v)
|
||||
filter.Currency = &cur
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("plan_category")); v != "" {
|
||||
cat := strings.ToUpper(v)
|
||||
if cat != string(domain.SubscriptionCategoryLearnEnglish) &&
|
||||
cat != string(domain.SubscriptionCategoryIELTS) &&
|
||||
cat != string(domain.SubscriptionCategoryDuolingo) {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid plan_category")
|
||||
}
|
||||
filter.PlanCategory = &cat
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("reference")); v != "" {
|
||||
filter.Reference = &v
|
||||
}
|
||||
|
||||
for _, pair := range []struct {
|
||||
q string
|
||||
dest **time.Time
|
||||
}{
|
||||
{"created_from", &filter.CreatedFrom},
|
||||
{"created_to", &filter.CreatedTo},
|
||||
{"paid_from", &filter.PaidFrom},
|
||||
{"paid_to", &filter.PaidTo},
|
||||
} {
|
||||
if v := strings.TrimSpace(c.Query(pair.q)); v != "" {
|
||||
t, err := parseQueryTime(v)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid %s", pair.q)
|
||||
}
|
||||
*pair.dest = &t
|
||||
}
|
||||
}
|
||||
|
||||
if v := strings.TrimSpace(c.Query("min_amount")); v != "" {
|
||||
amount, err := strconv.ParseFloat(v, 64)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid min_amount")
|
||||
}
|
||||
filter.MinAmount = &amount
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("max_amount")); v != "" {
|
||||
amount, err := strconv.ParseFloat(v, 64)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid max_amount")
|
||||
}
|
||||
filter.MaxAmount = &amount
|
||||
}
|
||||
|
||||
return filter, nil
|
||||
}
|
||||
|
||||
func parseUserListFilter(c *fiber.Ctx) (domain.UserFilter, error) {
|
||||
createdBeforeQuery := c.Query("created_before")
|
||||
var createdBefore domain.ValidTime
|
||||
if createdBeforeQuery != "" {
|
||||
parsed, err := time.Parse(time.RFC3339, createdBeforeQuery)
|
||||
if err != nil {
|
||||
return domain.UserFilter{}, fmt.Errorf("invalid created_before format")
|
||||
}
|
||||
createdBefore = domain.ValidTime{Value: parsed, Valid: true}
|
||||
}
|
||||
|
||||
createdAfterQuery := c.Query("created_after")
|
||||
var createdAfter domain.ValidTime
|
||||
if createdAfterQuery != "" {
|
||||
parsed, err := time.Parse(time.RFC3339, createdAfterQuery)
|
||||
if err != nil {
|
||||
return domain.UserFilter{}, fmt.Errorf("invalid created_after format")
|
||||
}
|
||||
createdAfter = domain.ValidTime{Value: parsed, Valid: true}
|
||||
}
|
||||
|
||||
subscriptionStatusQuery := strings.TrimSpace(c.Query("subscription_status"))
|
||||
var subscriptionStatusFilter string
|
||||
if subscriptionStatusQuery != "" {
|
||||
switch strings.ToUpper(subscriptionStatusQuery) {
|
||||
case "ACTIVE":
|
||||
subscriptionStatusFilter = "ACTIVE"
|
||||
case "PENDING":
|
||||
subscriptionStatusFilter = "PENDING"
|
||||
case "UNSUBSCRIBED":
|
||||
subscriptionStatusFilter = "Unsubscribed"
|
||||
default:
|
||||
return domain.UserFilter{}, fmt.Errorf("invalid subscription_status; use ACTIVE, PENDING, or Unsubscribed")
|
||||
}
|
||||
}
|
||||
|
||||
return domain.UserFilter{
|
||||
Role: c.Query("role"),
|
||||
Status: c.Query("status"),
|
||||
Country: strings.TrimSpace(c.Query("country")),
|
||||
Region: strings.TrimSpace(c.Query("region")),
|
||||
SubscriptionStatus: subscriptionStatusFilter,
|
||||
Query: c.Query("query"),
|
||||
CreatedBefore: createdBefore,
|
||||
CreatedAfter: createdAfter,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseActivityLogFilterFields(c *fiber.Ctx) (domain.ActivityLogFilter, error) {
|
||||
var filter domain.ActivityLogFilter
|
||||
|
||||
if v := c.Query("actor_id"); v != "" {
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return domain.ActivityLogFilter{}, fmt.Errorf("invalid actor_id parameter")
|
||||
}
|
||||
filter.ActorID = &id
|
||||
}
|
||||
if v := c.Query("action"); v != "" {
|
||||
filter.Action = &v
|
||||
}
|
||||
if v := c.Query("resource_type"); v != "" {
|
||||
filter.ResourceType = &v
|
||||
}
|
||||
if v := c.Query("resource_id"); v != "" {
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return domain.ActivityLogFilter{}, fmt.Errorf("invalid resource_id parameter")
|
||||
}
|
||||
filter.ResourceID = &id
|
||||
}
|
||||
if v := c.Query("after"); v != "" {
|
||||
t, err := time.Parse(time.RFC3339, v)
|
||||
if err != nil {
|
||||
return domain.ActivityLogFilter{}, fmt.Errorf("invalid after parameter, expected RFC3339 format")
|
||||
}
|
||||
filter.After = &t
|
||||
}
|
||||
if v := c.Query("before"); v != "" {
|
||||
t, err := time.Parse(time.RFC3339, v)
|
||||
if err != nil {
|
||||
return domain.ActivityLogFilter{}, fmt.Errorf("invalid before parameter, expected RFC3339 format")
|
||||
}
|
||||
filter.Before = &t
|
||||
}
|
||||
|
||||
return filter, nil
|
||||
}
|
||||
|
||||
func parseTeamMemberListFilter(c *fiber.Ctx) domain.TeamMemberFilter {
|
||||
filter := domain.TeamMemberFilter{}
|
||||
if teamRole := c.Query("team_role"); teamRole != "" {
|
||||
filter.TeamRole = &teamRole
|
||||
}
|
||||
if department := c.Query("department"); department != "" {
|
||||
filter.Department = &department
|
||||
}
|
||||
if status := c.Query("status"); status != "" {
|
||||
filter.Status = &status
|
||||
}
|
||||
filter.Search = c.Query("search")
|
||||
return filter
|
||||
}
|
||||
|
||||
func parseUserSubscriptionAdminFilterFields(c *fiber.Ctx) (domain.UserSubscriptionAdminFilter, error) {
|
||||
filter := domain.UserSubscriptionAdminFilter{}
|
||||
|
||||
if v := strings.TrimSpace(c.Query("user_id")); v != "" {
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return domain.UserSubscriptionAdminFilter{}, fmt.Errorf("invalid user_id")
|
||||
}
|
||||
filter.UserID = &id
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("plan_id")); v != "" {
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return domain.UserSubscriptionAdminFilter{}, fmt.Errorf("invalid plan_id")
|
||||
}
|
||||
filter.PlanID = &id
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("status")); v != "" {
|
||||
status := strings.ToUpper(v)
|
||||
filter.Status = &status
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("plan_category")); v != "" {
|
||||
cat := strings.ToUpper(v)
|
||||
if cat != string(domain.SubscriptionCategoryLearnEnglish) &&
|
||||
cat != string(domain.SubscriptionCategoryIELTS) &&
|
||||
cat != string(domain.SubscriptionCategoryDuolingo) {
|
||||
return domain.UserSubscriptionAdminFilter{}, fmt.Errorf("invalid plan_category")
|
||||
}
|
||||
filter.PlanCategory = &cat
|
||||
}
|
||||
|
||||
for _, pair := range []struct {
|
||||
q string
|
||||
dest **time.Time
|
||||
}{
|
||||
{"created_from", &filter.CreatedFrom},
|
||||
{"created_to", &filter.CreatedTo},
|
||||
{"expires_from", &filter.ExpiresFrom},
|
||||
{"expires_to", &filter.ExpiresTo},
|
||||
} {
|
||||
if v := strings.TrimSpace(c.Query(pair.q)); v != "" {
|
||||
t, err := parseQueryTime(v)
|
||||
if err != nil {
|
||||
return domain.UserSubscriptionAdminFilter{}, fmt.Errorf("invalid %s", pair.q)
|
||||
}
|
||||
*pair.dest = &t
|
||||
}
|
||||
}
|
||||
|
||||
return filter, nil
|
||||
}
|
||||
|
||||
func exportFilename(base string) string {
|
||||
return fmt.Sprintf("%s-%s.csv", base, time.Now().UTC().Format("2006-01-02"))
|
||||
}
|
||||
|
|
@ -4,7 +4,6 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"Yimaru-Backend/internal/domain"
|
||||
|
|
@ -174,98 +173,12 @@ func parsePaymentListFilter(c *fiber.Ctx) (domain.PaymentListFilter, error) {
|
|||
return domain.PaymentListFilter{}, fmt.Errorf("invalid offset")
|
||||
}
|
||||
|
||||
filter := domain.PaymentListFilter{
|
||||
Limit: int32(limit),
|
||||
Offset: int32(offset),
|
||||
filter, err := paymentListFilterFields(c)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, err
|
||||
}
|
||||
|
||||
if v := strings.TrimSpace(c.Query("user_id")); v != "" {
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid user_id")
|
||||
}
|
||||
filter.UserID = &id
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("plan_id")); v != "" {
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid plan_id")
|
||||
}
|
||||
filter.PlanID = &id
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("subscription_id")); v != "" {
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid subscription_id")
|
||||
}
|
||||
filter.SubscriptionID = &id
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("status")); v != "" {
|
||||
status := strings.ToUpper(v)
|
||||
if !isValidPaymentStatus(status) {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid status")
|
||||
}
|
||||
filter.Status = &status
|
||||
}
|
||||
provider := firstNonEmpty(strings.TrimSpace(c.Query("provider")), strings.TrimSpace(c.Query("payment_method")))
|
||||
if provider != "" {
|
||||
p, err := domain.ParsePaymentProvider(provider)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, err
|
||||
}
|
||||
method := string(p)
|
||||
filter.PaymentMethod = &method
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("currency")); v != "" {
|
||||
cur := strings.ToUpper(v)
|
||||
filter.Currency = &cur
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("plan_category")); v != "" {
|
||||
cat := strings.ToUpper(v)
|
||||
if cat != string(domain.SubscriptionCategoryLearnEnglish) &&
|
||||
cat != string(domain.SubscriptionCategoryIELTS) &&
|
||||
cat != string(domain.SubscriptionCategoryDuolingo) {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid plan_category")
|
||||
}
|
||||
filter.PlanCategory = &cat
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("reference")); v != "" {
|
||||
filter.Reference = &v
|
||||
}
|
||||
|
||||
for _, pair := range []struct {
|
||||
q string
|
||||
dest **time.Time
|
||||
}{
|
||||
{"created_from", &filter.CreatedFrom},
|
||||
{"created_to", &filter.CreatedTo},
|
||||
{"paid_from", &filter.PaidFrom},
|
||||
{"paid_to", &filter.PaidTo},
|
||||
} {
|
||||
if v := strings.TrimSpace(c.Query(pair.q)); v != "" {
|
||||
t, err := parseQueryTime(v)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid %s", pair.q)
|
||||
}
|
||||
*pair.dest = &t
|
||||
}
|
||||
}
|
||||
|
||||
if v := strings.TrimSpace(c.Query("min_amount")); v != "" {
|
||||
amount, err := strconv.ParseFloat(v, 64)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid min_amount")
|
||||
}
|
||||
filter.MinAmount = &amount
|
||||
}
|
||||
if v := strings.TrimSpace(c.Query("max_amount")); v != "" {
|
||||
amount, err := strconv.ParseFloat(v, 64)
|
||||
if err != nil {
|
||||
return domain.PaymentListFilter{}, fmt.Errorf("invalid max_amount")
|
||||
}
|
||||
filter.MaxAmount = &amount
|
||||
}
|
||||
|
||||
filter.Limit = int32(limit)
|
||||
filter.Offset = int32(offset)
|
||||
return filter, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
71
internal/web_server/response/csv.go
Normal file
71
internal/web_server/response/csv.go
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
package response
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
const (
|
||||
ExportBatchSize = 500
|
||||
ExportMaxRows = 50000
|
||||
)
|
||||
|
||||
// StreamCSV writes a UTF-8 CSV attachment, fetching rows in batches until a batch is empty
|
||||
// or ExportMaxRows is reached.
|
||||
func StreamCSV(
|
||||
c *fiber.Ctx,
|
||||
filename string,
|
||||
headers []string,
|
||||
fetchBatch func(offset, limit int32) ([][]string, error),
|
||||
) error {
|
||||
c.Set("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
|
||||
|
||||
c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
|
||||
if _, err := w.Write([]byte{0xEF, 0xBB, 0xBF}); err != nil {
|
||||
return
|
||||
}
|
||||
writer := csv.NewWriter(w)
|
||||
if err := writer.Write(headers); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var offset int32
|
||||
var written int
|
||||
for written < ExportMaxRows {
|
||||
limit := int32(ExportBatchSize)
|
||||
if remaining := ExportMaxRows - written; remaining < ExportBatchSize {
|
||||
limit = int32(remaining)
|
||||
}
|
||||
rows, err := fetchBatch(offset, limit)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
break
|
||||
}
|
||||
for _, row := range rows {
|
||||
if err := writer.Write(row); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
writer.Flush()
|
||||
if err := writer.Error(); err != nil {
|
||||
return
|
||||
}
|
||||
if err := w.Flush(); err != nil {
|
||||
return
|
||||
}
|
||||
written += len(rows)
|
||||
if len(rows) < int(limit) {
|
||||
break
|
||||
}
|
||||
offset += int32(len(rows))
|
||||
}
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
@ -255,6 +255,7 @@ func (a *App) initAppRoutes() {
|
|||
|
||||
// Admin payments (register before /admin/:id<int> so "payments" is not captured as an admin id)
|
||||
groupV1.Get("/admin/payments", a.authMiddleware, a.RequirePermission("payments.list_all"), h.ListAdminPayments)
|
||||
groupV1.Get("/admin/payments/export", a.authMiddleware, a.RequirePermission("payments.export"), h.ExportAdminPaymentsCSV)
|
||||
groupV1.Get("/admin/payments/:id", a.authMiddleware, a.RequirePermission("payments.list_all"), h.GetAdminPayment)
|
||||
|
||||
// Question Sets
|
||||
|
|
@ -352,7 +353,9 @@ func (a *App) initAppRoutes() {
|
|||
// User Routes
|
||||
groupV1.Get("/user/:user_id/is-profile-completed", a.authMiddleware, a.RequirePermission("users.profile_completed"), h.CheckProfileCompleted)
|
||||
groupV1.Get("/users", a.authMiddleware, a.RequirePermission("users.list"), h.GetAllUsers)
|
||||
groupV1.Get("/users/export", a.authMiddleware, a.RequirePermission("users.export"), h.ExportUsersCSV)
|
||||
groupV1.Get("/admin/users/deletion-requests", a.authMiddleware, a.RequirePermission("users.deletion_requests.list"), h.ListAccountDeletionRequests)
|
||||
groupV1.Get("/admin/subscriptions/export", a.authMiddleware, a.RequirePermission("subscriptions.export"), h.ExportUserSubscriptionsCSV)
|
||||
groupV1.Get("/admin/users/:user_id/lms-learning-activity", a.authMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserLMSLearningActivity)
|
||||
groupV1.Get("/admin/users/:user_id/recent-activity", a.authMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserRecentActivity)
|
||||
groupV1.Get("/admin/users/:user_id/learning-activity", a.authMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserLearningActivityDetails)
|
||||
|
|
@ -389,6 +392,7 @@ func (a *App) initAppRoutes() {
|
|||
// Logs
|
||||
groupV1.Get("/logs", a.authMiddleware, a.RequirePermission("logs.list"), handlers.GetLogsHandler(context.Background()))
|
||||
groupV1.Get("/activity-logs", a.authMiddleware, a.RequirePermission("activity_logs.list"), h.GetActivityLogs)
|
||||
groupV1.Get("/activity-logs/export", a.authMiddleware, a.RequirePermission("activity_logs.export"), h.ExportActivityLogsCSV)
|
||||
groupV1.Get("/activity-logs/:id", a.authMiddleware, a.RequirePermission("activity_logs.get"), h.GetActivityLogByID)
|
||||
|
||||
// Notifications
|
||||
|
|
@ -463,6 +467,7 @@ func (a *App) initAppRoutes() {
|
|||
teamGroup.Put("/me", a.authMiddleware, a.RequirePermission("team.profile.update_mine"), h.UpdateMyTeamProfile)
|
||||
teamGroup.Get("/stats", a.authMiddleware, a.RequirePermission("team.stats"), h.GetTeamMemberStats)
|
||||
teamGroup.Get("/members", a.authMiddleware, a.RequirePermission("team.members.list"), h.GetAllTeamMembers)
|
||||
teamGroup.Get("/members/export", a.authMiddleware, a.RequirePermission("team.members.export"), h.ExportTeamMembersCSV)
|
||||
teamGroup.Post("/members/invite", a.authMiddleware, a.RequirePermission("team.members.invite"), h.InviteTeamMember)
|
||||
teamGroup.Post("/members", a.authMiddleware, a.RequirePermission("team.members.create"), h.CreateTeamMember)
|
||||
teamGroup.Post("/members/:id/resend-invite", a.authMiddleware, a.RequirePermission("team.invitations.resend"), h.ResendTeamInvitation)
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user