RezinaLMS-BackEnd/docs/activity-logs-admin-panel-integration.md
Yared Yemane eb0c87059f fix: enrich activity log actors and add admin integration guide
Record explicit actor on login/register flows and return actor_name, actor_email, and actor_kind from activity log APIs so admin audit rows no longer show System for authenticated events.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-20 03:29:20 -07:00

1106 lines
38 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Activity Logs — Admin Panel Integration Guide
This guide documents how to integrate the **platform activity log (audit trail)** into the Yimaru admin panel. It covers authentication, RBAC permissions, read-only APIs, filtering, pagination, action/resource catalogs, actor resolution, recommended UI patterns, TypeScript types, and how activity logs relate to other “activity” endpoints on user profiles.
---
## Table of contents
1. [Feature overview](#feature-overview)
2. [Three different “activity” concepts](#three-different-activity-concepts)
3. [Architecture](#architecture)
4. [Authentication & permissions](#authentication--permissions)
5. [RBAC setup & troubleshooting 403](#rbac-setup--troubleshooting-403)
6. [Data model](#data-model)
7. [Response envelopes](#response-envelopes)
8. [API reference](#api-reference)
9. [Filtering, pagination & date ranges](#filtering-pagination--date-ranges)
10. [Action catalog](#action-catalog)
11. [Resource type catalog](#resource-type-catalog)
12. [Metadata conventions](#metadata-conventions)
13. [Actor resolution](#actor-resolution)
14. [Deep linking to related admin screens](#deep-linking-to-related-admin-screens)
15. [Related admin endpoints (user profile)](#related-admin-endpoints-user-profile)
16. [Recommended admin UI screens](#recommended-admin-ui-screens)
17. [TypeScript types & API client](#typescript-types--api-client)
18. [Display helpers (labels, icons, colors)](#display-helpers-labels-icons-colors)
19. [Error handling](#error-handling)
20. [Performance & UX notes](#performance--ux-notes)
21. [Integration checklist](#integration-checklist)
22. [Limitations & future work](#limitations--future-work)
23. [Quick reference](#quick-reference)
---
## Feature overview
The activity log is an **append-only audit trail** stored in PostgreSQL. Each row captures **who did what, to which resource, when**, plus optional context (`message`, `metadata`, `ip_address`, `user_agent`).
| Capability | Admin panel | Mobile / learner app |
|------------|-------------|----------------------|
| List activity logs | Yes (`GET /activity-logs`) | No |
| View log detail | Yes (`GET /activity-logs/:id`) | No |
| Filter by actor / action / resource / date | Yes | No |
| Create / edit / delete logs | **No** (server-written only) | No |
**Important:** Logging is **manual per handler** on the backend. Most **read-only GET** endpoints do **not** produce log entries. Mutations, auth events, payments, notifications, and learner completions that call `recordActivity` / `RecordAction` are logged.
---
## Three different “activity” concepts
Do not conflate these when building the admin UI:
| Concept | Endpoint(s) | Purpose | Audience |
|---------|-------------|---------|----------|
| **Platform activity log** (this guide) | `GET /api/v1/activity-logs` | Audit trail of actions across the whole system | Admins / compliance |
| **User learning milestones** | `GET /api/v1/admin/users/:user_id/recent-activity` | Learner progress timeline (joined, completed lesson/module/course/program) | User profile in admin |
| **System / Mongo logs** | `GET /api/v1/logs` | Technical request/error logs (different permission: `logs.list`) | DevOps / debugging |
Use **activity logs** for “who changed this FAQ?” or “who logged in yesterday?”. Use **recent-activity** for “what has this student completed?”.
---
## Architecture
```mermaid
flowchart LR
subgraph AdminPanel["Admin panel"]
GlobalLog["Global audit log page"]
ResourceTab["Resource-scoped history tab"]
UserAudit["User audit filter (actor_id)"]
end
subgraph API["Yimaru API"]
ListRoute["GET /activity-logs"]
GetRoute["GET /activity-logs/:id"]
end
subgraph Handlers["HTTP handlers"]
Mutations["CRUD / auth / payments / …"]
RecordHelper["recordActivity()"]
end
subgraph DB["PostgreSQL"]
ActivityTable["activity_logs"]
end
GlobalLog --> ListRoute
ResourceTab --> ListRoute
UserAudit --> ListRoute
ListRoute --> ActivityTable
GetRoute --> ActivityTable
Mutations --> RecordHelper
RecordHelper -->|"async goroutine"| ActivityTable
```
- **Migration:** `000014_activity_logs` — `activity_logs` table + indexes
- **RBAC seeds:** `activity_logs.list`, `activity_logs.get` (group: **Logs**)
- **Recording:** `internal/web_server/handlers/activity_log_helper.go` — `recordActivity(c, …)` fires `RecordAction` in a background goroutine so API latency is not blocked by inserts
- **Source of truth for enums:** `internal/domain/activity_log.go` (`ActivityAction`, `ResourceType`)
---
## Authentication & permissions
All activity log endpoints require:
```http
Authorization: Bearer <access_token>
Content-Type: application/json
```
### How to obtain a token
| Login flow | Endpoint | Typical use |
|------------|----------|-------------|
| **Team member (recommended for admin panel)** | `POST /api/v1/team/login` | Staff in `team_members` |
| **Platform admin user** | `POST /api/v1/auth/admin-login` | `users.role` = `ADMIN` |
| **Super admin** | `POST /api/v1/auth/super-admin-login` | `users.role` = `SUPER_ADMIN` |
Use the **`access_token`** from the login response. Learner tokens (`STUDENT`, `OPEN_LEARNER`) do **not** have activity log permissions by default.
### RBAC permission keys
| Action | Permission | HTTP |
|--------|------------|------|
| List activity logs | `activity_logs.list` | `GET /api/v1/activity-logs` |
| Get one log entry | `activity_logs.get` | `GET /api/v1/activity-logs/:id` |
### Default roles with access
| JWT `Role` | Activity log access | Notes |
|------------|---------------------|-------|
| `SUPER_ADMIN` | Full | RBAC bypass — all permissions |
| `ADMIN` | Full | RBAC bypass — all permissions |
| `INSTRUCTOR` | **Denied** by default | Unless custom role grants `activity_logs.*` |
| `SUPPORT` | **Denied** by default | Unless custom role grants `activity_logs.*` |
| `STUDENT` / `OPEN_LEARNER` | **Denied** | Learner roles |
Seeded permissions for the **`ADMIN`** RBAC role include:
- `activity_logs.list`
- `activity_logs.get`
Custom roles created in the RBAC UI must be assigned these keys explicitly.
### UI gating
- Show **Logs → Activity** (or **Audit trail**) menu only when the session has `activity_logs.list` (or role is `ADMIN` / `SUPER_ADMIN`).
- Detail drawer / page requires `activity_logs.get` (usually same users as list).
---
## RBAC setup & troubleshooting 403
If `GET /api/v1/activity-logs` returns **403 Forbidden**:
### 1. Confirm the JWT role
Decode the Bearer token and inspect **`Role`**:
```json
{ "UserId": 42, "Role": "ADMIN", ... }
```
### 2. Check permission assignment
`403` with message `"You don't have permission to access this resource"` means `HasPermission(role, "activity_logs.list")` returned false.
- **`ADMIN` / `SUPER_ADMIN`:** Should always pass (hard bypass in `rbac.Service.HasPermission`).
- **`INSTRUCTOR` / `SUPPORT` / custom roles:** Need explicit `activity_logs.list` and `activity_logs.get` via RBAC role editor or DB seed update.
### 3. Re-sync RBAC after deploy
If permissions were added in a migration, restart the API (seeds run on startup) or call:
```http
POST /api/v1/rbac/permissions/sync
```
(requires `rbac.permissions.sync`)
### 4. Do not confuse with system logs
`GET /api/v1/logs` uses permission **`logs.list`**, not `activity_logs.list`. These are separate menu items.
---
## Data model
### Database (`activity_logs`)
| Column | Type | Description |
|--------|------|-------------|
| `id` | `BIGSERIAL` | Primary key |
| `actor_id` | `BIGINT NULL` | User or team member ID from JWT `user_id` at write time |
| `actor_role` | `TEXT NULL` | JWT role string (e.g. `ADMIN`, `INSTRUCTOR`, `STUDENT`) |
| `action` | `TEXT NOT NULL` | Machine-readable action code (see [Action catalog](#action-catalog)) |
| `resource_type` | `TEXT NOT NULL` | Resource category (see [Resource type catalog](#resource-type-catalog)) |
| `resource_id` | `BIGINT NULL` | Primary entity ID when applicable |
| `message` | `TEXT NULL` | Human-readable summary (shown in UI as primary line) |
| `metadata` | `JSONB NOT NULL` | Structured extras; default `{}` |
| `ip_address` | `TEXT NULL` | Client IP from request |
| `user_agent` | `TEXT NULL` | `User-Agent` header |
| `created_at` | `TIMESTAMPTZ NOT NULL` | Event time (UTC) |
**Indexes:** `created_at DESC`, `(actor_id, created_at)`, `(resource_type, resource_id, created_at)`, `(action, created_at)`.
### API JSON shape (`activityLogRes`)
| Field | Type | JSON key | Notes |
|-------|------|----------|-------|
| ID | `int64` | `id` | |
| Actor ID | `*int64` | `actor_id` | Omitted when null |
| Actor role | `*string` | `actor_role` | Omitted when null |
| Actor name | `*string` | `actor_name` | Resolved server-side from `users` or `team_members` when `actor_id` is set |
| Actor email | `*string` | `actor_email` | Resolved server-side when available |
| Actor kind | `*string` | `actor_kind` | `"user"` or `"team_member"` when resolved |
| Action | `string` | `action` | Uppercase snake case |
| Resource type | `string` | `resource_type` | Uppercase snake case |
| Resource ID | `*int64` | `resource_id` | Omitted when null |
| Message | `*string` | `message` | Omitted when null |
| Metadata | `object` | `metadata` | Always present; `{}` when empty |
| IP address | `*string` | `ip_address` | |
| User agent | `*string` | `user_agent` | |
| Created at | `string` (RFC3339) | `created_at` | |
There is **no** embedded actor name in the stored row, but list/detail API responses **enrich** each entry with `actor_name`, `actor_email`, and `actor_kind` when `actor_id` can be resolved from `users` or `team_members`.
**Admin panel display priority:**
1. Use `actor_name` + `actor_role` from the API when `actor_name` is present.
2. Fall back to `actor_email` if name is empty.
3. Fall back to `#${actor_id} (${actor_role})` when ID exists but enrichment failed.
4. Show **System** only when `actor_id` is null (webhooks, some background jobs).
**Note:** Login/register events previously showed **System** because auth routes run before JWT is in request context; the backend now records explicit `actor_id` and `actor_role` on those events. Existing historical rows may still have null actors.
---
## Response envelopes
All successful responses use the standard wrapper:
```json
{
"message": "Activity logs retrieved successfully",
"data": { ... },
"success": true,
"status_code": 200,
"metadata": null
}
```
Errors use `domain.ErrorResponse`:
```json
{
"message": "Invalid actor_id parameter",
"error": "strconv.ParseInt: parsing \"abc\": invalid syntax"
}
```
---
## API reference
Base path: **`/api/v1`**
### List activity logs
```http
GET /api/v1/activity-logs
Authorization: Bearer <token>
```
**Permission:** `activity_logs.list`
#### Query parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `actor_id` | int64 | No | Filter by actor (JWT `user_id` at event time) |
| `action` | string | No | Exact match on action code (e.g. `FAQ_CREATED`) |
| `resource_type` | string | No | Exact match (e.g. `FAQ`) |
| `resource_id` | int64 | No | Exact match on resource primary key |
| `after` | RFC3339 datetime | No | `created_at >= after` |
| `before` | RFC3339 datetime | No | `created_at <= before` |
| `limit` | int | No | Page size; default **20**, max **100** |
| `offset` | int | No | Offset; default **0** |
**Sort order:** `created_at DESC` (newest first).
#### Example request
```http
GET /api/v1/activity-logs?resource_type=FAQ&resource_id=12&limit=50&offset=0
Authorization: Bearer eyJhbG...
```
#### Example response
```json
{
"message": "Activity logs retrieved successfully",
"data": {
"logs": [
{
"id": 1042,
"actor_id": 7,
"actor_role": "ADMIN",
"actor_name": "Jane Admin",
"actor_email": "jane@yimaru.com",
"actor_kind": "team_member",
"action": "FAQ_UPDATED",
"resource_type": "FAQ",
"resource_id": 12,
"message": "Updated FAQ: How do I reset my password?",
"metadata": {},
"ip_address": "203.0.113.10",
"user_agent": "Mozilla/5.0 ...",
"created_at": "2026-06-18T14:22:01.123456Z"
}
],
"total_count": 1,
"limit": 50,
"offset": 0
},
"success": true,
"status_code": 200,
"metadata": null
}
```
#### List response fields
| Field | Type | Description |
|-------|------|-------------|
| `logs` | array | Current page of entries |
| `total_count` | int64 | Total rows matching filters (for pagination UI) |
| `limit` | int32 | Applied page size |
| `offset` | int32 | Applied offset |
---
### Get activity log by ID
```http
GET /api/v1/activity-logs/:id
Authorization: Bearer <token>
```
**Permission:** `activity_logs.get`
#### Example response
```json
{
"message": "Activity log retrieved successfully",
"data": {
"id": 1042,
"actor_id": 7,
"actor_role": "ADMIN",
"actor_name": "Jane Admin",
"actor_email": "jane@yimaru.com",
"actor_kind": "team_member",
"action": "NOTIFICATION_BULK_SENT",
"resource_type": "NOTIFICATION",
"message": "Bulk notification sent to 1523 recipients",
"metadata": {
"recipient_count": 1523,
"type": "PUSH",
"channel": "FCM"
},
"ip_address": "203.0.113.10",
"user_agent": "Mozilla/5.0 ...",
"created_at": "2026-06-18T14:22:01.123456Z"
},
"success": true,
"status_code": 200,
"metadata": null
}
```
#### Errors
| Status | When |
|--------|------|
| `400` | Invalid `id` path param |
| `403` | Missing permission |
| `404` | Log ID not found |
| `500` | Server error |
---
## Filtering, pagination & date ranges
### Pagination pattern
Use **offset/limit** with `total_count`:
```typescript
const pageSize = 25;
const page = 2; // 0-based
const offset = page * pageSize;
const res = await listActivityLogs({ limit: pageSize, offset });
const totalPages = Math.ceil(res.total_count / pageSize);
```
### Combining filters
All filters are **AND**ed. Examples:
| Use case | Query |
|----------|-------|
| All actions by staff user 7 | `?actor_id=7` |
| History for FAQ #12 | `?resource_type=FAQ&resource_id=12` |
| All logins in June 2026 | `?action=AUTH_LOGIN&after=2026-06-01T00:00:00Z&before=2026-06-30T23:59:59Z` |
| Exam prep course edits | `?resource_type=EXAM_PREP_CATALOG_COURSE&action=EXAM_PREP_CATALOG_COURSE_UPDATED` |
### Date range UI
Send **`after`** / **`before`** as **RFC3339** strings in UTC:
```typescript
const after = new Date("2026-06-01").toISOString(); // 2026-06-01T00:00:00.000Z
const before = new Date("2026-06-30T23:59:59.999Z").toISOString();
```
Invalid datetime → `400` with `"Invalid after parameter, expected RFC3339 format"`.
### Client-side search (recommended)
There is **no** server-side full-text search on `message`. For a search box:
1. Load a reasonable page (or multiple pages) with narrow server filters (date, action, resource).
2. Filter client-side on `message`, `action`, `metadata` JSON stringified.
For large deployments, prefer server filters (date + action + resource) before client search.
---
## Action catalog
Actions are uppercase snake-case strings. Grouped below for admin UI filter dropdowns.
### Authentication & session
| Action | Typical resource | When logged |
|--------|------------------|-------------|
| `AUTH_LOGIN` | `AUTH` | User / admin / OAuth / team login |
| `AUTH_LOGOUT` | `AUTH` | Logout |
| `AUTH_REGISTER` | `AUTH` | New user registration |
| `AUTH_TOKEN_REFRESHED` | `AUTH` | Token refresh |
### Users & admins
| Action | Resource | When logged |
|--------|----------|-------------|
| `USER_CREATED` | `USER` | Registration / admin create |
| `USER_UPDATED` | `USER` | Profile, status, knowledge level, self-delete request/cancel |
| `USER_DELETED` | `USER` | Admin delete |
| `USER_PASSWORD_RESET` | `USER` | Password reset completed |
| `USER_PROFILE_PICTURE_UPDATED` | `USER` | Avatar upload |
| `USERS_PURGED` | `USER` | Scheduled deletion purge job |
| `ADMIN_CREATED` | `ADMIN` | New admin account |
| `ADMIN_UPDATED` | `ADMIN` | Admin profile update |
### Team
| Action | Resource | When logged |
|--------|----------|-------------|
| `TEAM_MEMBER_CREATED` | `TEAM_MEMBER` | Create team member |
| `TEAM_MEMBER_INVITED` | `TEAM_MEMBER` | Invite sent |
| `TEAM_MEMBER_UPDATED` | `TEAM_MEMBER` | Update / invitation accepted |
| `TEAM_MEMBER_DELETED` | `TEAM_MEMBER` | Remove member |
| `TEAM_MEMBER_PASSWORD_CHANGED` | `TEAM_MEMBER` | Password change |
| `TEAM_INVITATION_RESENT` | `TEAM_MEMBER` | Resend invite |
| `TEAM_INVITATION_REVOKED` | `TEAM_MEMBER` | Revoke invite |
### LMS content
| Action | Resource |
|--------|----------|
| `PROGRAM_CREATED` / `_UPDATED` / `_DELETED` | `PROGRAM` |
| `COURSE_CREATED` / `_UPDATED` / `_DELETED` | `COURSE` |
| `SUB_COURSE_CREATED` / `_UPDATED` / `_DELETED` / `SUB_COURSE_DEACTIVATED` | `SUB_COURSE` |
| `MODULE_CREATED` / `_UPDATED` / `_DELETED` | `MODULE` |
| `LESSON_CREATED` / `_UPDATED` / `_DELETED` | `LESSON` |
| `PRACTICE_CREATED` / `_UPDATED` / `_DELETED` | `PRACTICE` |
| `VIDEO_CREATED` / `VIDEO_UPLOADED` / `VIDEO_PUBLISHED` / `VIDEO_UPDATED` / `VIDEO_ARCHIVED` / `VIDEO_DELETED` | `VIDEO` |
| `CATEGORY_CREATED` / `_UPDATED` / `_DELETED` | `CATEGORY` |
### Questions & assessments
| Action | Resource |
|--------|----------|
| `QUESTION_CREATED` / `_UPDATED` / `_DELETED` | `QUESTION` |
| `QUESTION_SET_CREATED` / `_UPDATED` / `_DELETED` | `QUESTION_SET` |
| `QUESTION_TYPE_DEFINITION_CREATED` / `_UPDATED` / `_DELETED` | `QUESTION_TYPE_DEFINITION` |
| `QUESTION_TYPE_DEFINITION_GROUP_CREATED` / `_UPDATED` / `_DELETED` | `QUESTION_TYPE_DEFINITION_GROUP` |
| `ASSESSMENT_QUESTION_CREATED` | `ASSESSMENT_QUESTION` |
| `QUESTION_AUDIO_ANSWER_SUBMITTED` | `QUESTION` |
### Exam prep
| Action | Resource |
|--------|----------|
| `EXAM_PREP_CATALOG_COURSE_CREATED` / `_UPDATED` / `_DELETED` / `_REORDERED` | `EXAM_PREP_CATALOG_COURSE` |
| `EXAM_PREP_UNIT_CREATED` / `_UPDATED` / `_DELETED` / `_REORDERED` | `EXAM_PREP_UNIT` |
| `EXAM_PREP_MODULE_CREATED` / `_UPDATED` / `_DELETED` / `_REORDERED` | `EXAM_PREP_MODULE` |
| `EXAM_PREP_LESSON_CREATED` / `_UPDATED` / `_DELETED` / `_REORDERED` | `EXAM_PREP_LESSON` |
| `EXAM_PREP_PRACTICE_CREATED` / `_UPDATED` / `_DELETED` | `EXAM_PREP_PRACTICE` |
### Personas, FAQs, CMS
| Action | Resource |
|--------|----------|
| `PERSONA_CREATED` / `_UPDATED` / `_DELETED` | `PERSONA` |
| `FAQ_CREATED` / `_UPDATED` / `_DELETED` | `FAQ` |
| `APP_VERSION_CREATED` / `_UPDATED` / `_DELETED` | `APP_VERSION` |
| `EMAIL_TEMPLATE_CREATED` / `_UPDATED` / `_DELETED` | `EMAIL_TEMPLATE` |
| `FIELD_OPTION_CREATED` / `_UPDATED` / `_DELETED` | `FIELD_OPTION` |
| `SETTINGS_UPDATED` | `SETTINGS` |
### Subscriptions & payments
| Action | Resource |
|--------|----------|
| `SUBSCRIPTION_PLAN_CREATED` / `_UPDATED` / `_DELETED` | `SUBSCRIPTION_PLAN` |
| `SUBSCRIPTION_CREATED` | `SUBSCRIPTION` |
| `SUBSCRIPTION_CANCELLED` | `SUBSCRIPTION` |
| `SUBSCRIPTION_AUTO_RENEW_UPDATED` | `SUBSCRIPTION` |
| `PAYMENT_INITIATED` / `PAYMENT_VERIFIED` / `PAYMENT_CANCELLED` | `PAYMENT` |
| `PAYMENT_WEBHOOK_RECEIVED` | `PAYMENT` |
### Notifications & devices
| Action | Resource |
|--------|----------|
| `NOTIFICATION_CREATED` / `_UPDATED` / `_DELETED` | `NOTIFICATION` |
| `NOTIFICATION_BULK_SENT` | `NOTIFICATION` |
| `SCHEDULED_NOTIFICATION_CANCELLED` | `NOTIFICATION` |
| `SMS_SENT` | `NOTIFICATION` |
| `DEVICE_REGISTERED` / `DEVICE_UNREGISTERED` | `DEVICE` |
### Learner progress & engagement
| Action | Resource |
|--------|----------|
| `LESSON_COMPLETED` | `LESSON` |
| `PRACTICE_COMPLETED` | `PRACTICE` |
| `VIDEO_ENGAGEMENT_RECORDED` | `VIDEO` |
| `RATING_SUBMITTED` / `RATING_DELETED` | `RATING` |
### Issues, files, referrals
| Action | Resource |
|--------|----------|
| `ISSUE_CREATED` / `ISSUE_STATUS_UPDATED` / `ISSUE_DELETED` | `ISSUE` |
| `FILE_UPLOADED` / `FILE_PRESIGN_CREATED` | `FILE` |
| `REFERRAL_CODE_CREATED` | `REFERRAL` |
**Note:** New actions may be added as handlers adopt `recordActivity`. Treat unknown `action` values gracefully in the UI (display raw string).
---
## Resource type catalog
Use for filter dropdowns and deep-link routing.
| Resource type | Example admin context |
|---------------|----------------------|
| `AUTH` | Login sessions (no single entity page) |
| `USER` | User detail `/admin/users/:id` |
| `ADMIN` | Admin management |
| `TEAM_MEMBER` | Team member detail |
| `PROGRAM` | LMS program editor |
| `COURSE` | Course editor |
| `SUB_COURSE` | Sub-course editor |
| `MODULE` | Module editor |
| `LESSON` | Lesson editor |
| `PRACTICE` | Practice editor |
| `VIDEO` | Video library |
| `CATEGORY` | Course categories |
| `QUESTION` | Question bank |
| `QUESTION_SET` | Question set editor |
| `QUESTION_TYPE_DEFINITION` | Question type builder |
| `QUESTION_TYPE_DEFINITION_GROUP` | Question type groups |
| `EXAM_PREP_CATALOG_COURSE` | Exam prep catalog course |
| `EXAM_PREP_UNIT` | Exam prep unit |
| `EXAM_PREP_MODULE` | Exam prep module |
| `EXAM_PREP_LESSON` | Exam prep lesson |
| `EXAM_PREP_PRACTICE` | Exam prep practice |
| `PERSONA` | Personas |
| `FAQ` | FAQ management |
| `APP_VERSION` | Mobile app versions |
| `EMAIL_TEMPLATE` | Email templates |
| `FIELD_OPTION` | Field options |
| `SETTINGS` | Platform settings |
| `SUBSCRIPTION_PLAN` | Subscription plans |
| `SUBSCRIPTION` | User subscription |
| `PAYMENT` | Payment detail |
| `NOTIFICATION` | Notifications |
| `DEVICE` | (usually no admin page) |
| `RATING` | Ratings moderation |
| `ISSUE` | Issue tracker |
| `FILE` | Media library |
| `REFERRAL` | Referrals |
| `ASSESSMENT_QUESTION` | Initial assessment |
---
## Metadata conventions
`metadata` is **handler-defined** JSON. It is optional at write time; reads always return an object (empty `{}` is common).
### Patterns observed in the codebase
| Scenario | Example metadata |
|----------|------------------|
| Notification sent | `{ "notification_id": 99, "recipient_id": 42, "type": "PUSH", "channel": "FCM" }` |
| Bulk notification | `{ "recipient_count": 1523, "type": "...", "channel": "..." }` |
| Payment webhook | `{ "tx_ref": "...", "event": "...", "status": "..." }` |
| Question mutations | Question type, set IDs, field deltas (varies) |
| User status change | `{ "status": "ACTIVE" }` or similar |
| Team invitation | `{ "invitation_id": 5, "email": "..." }` |
### UI recommendations
- Detail view: pretty-print JSON in a collapsible **“Technical details”** panel.
- List view: do **not** show raw JSON; use `message` as the headline.
- When `metadata` contains IDs useful for navigation (e.g. `recipient_id`), offer links if the admin has permission for that screen.
---
## Actor resolution
Each log stores **`actor_id`** and **`actor_role`** at write time. List and detail API responses also include server-resolved display fields:
| Response field | Description |
|----------------|-------------|
| `actor_name` | Full name from `users` or `team_members` when resolvable |
| `actor_email` | Email from the matched record |
| `actor_kind` | `"user"` or `"team_member"` — which table matched |
### How the backend resolves actors
| Signal | Lookup order |
|--------|--------------|
| `actor_role` = `INSTRUCTOR` or `SUPPORT` | `team_members` first, then `users` |
| `resource_type` = `TEAM_MEMBER` | `team_members` first, then `users` |
| `actor_role` = `STUDENT` or `OPEN_LEARNER` | `users` first, then `team_members` |
| Other roles (e.g. `ADMIN`) | `users` first, then `team_members` |
### Login / register actor recording
Auth routes run **before** a JWT exists in request context. The backend uses explicit actor recording on:
- User login (customer, admin, super-admin, Google, Apple)
- Team member login and token refresh
- User registration and team invitation accept
**New events** from these flows include `actor_id` and `actor_role`. **Older rows** created before this fix may still have null `actor_id` and show as **System** in the UI.
### Admin panel display (recommended)
Use API enrichment first — no extra user/team fetch required for most rows:
```typescript
type ActorKind = "user" | "team_member";
export interface ActivityLog {
actor_id?: number | null;
actor_role?: string | null;
actor_name?: string | null;
actor_email?: string | null;
actor_kind?: ActorKind | null;
// ...
}
function formatActor(log: ActivityLog): { name: string; role?: string; kind?: ActorKind } {
if (log.actor_name) {
return { name: log.actor_name, role: log.actor_role ?? undefined, kind: log.actor_kind ?? undefined };
}
if (log.actor_email) {
return { name: log.actor_email, role: log.actor_role ?? undefined, kind: log.actor_kind ?? undefined };
}
if (log.actor_id) {
return { name: `#${log.actor_id}`, role: log.actor_role ?? undefined };
}
return { name: "System" };
}
```
**Actor column layout:** show `actor_name` on the first line and `actor_role` in smaller muted text below (same pattern as learner rows).
### Optional client-side fallback
If `actor_id` is set but `actor_name` is empty (rare enrichment miss), you may still fetch:
| `actor_kind` | Endpoint |
|--------------|----------|
| `user` | `GET /api/v1/users/:id` |
| `team_member` | `GET /api/v1/team/members/:id` |
| unknown | try user, then team member |
Webhooks and unauthenticated background jobs may legitimately have null `actor_id` — keep **System** for those.
---
## Deep linking to related admin screens
When `resource_id` is present, link rows to existing admin routes (adjust paths to match your router):
| `resource_type` | Suggested admin route |
|-----------------|----------------------|
| `FAQ` | `/admin/help/faqs/:resource_id/edit` |
| `PERSONA` | `/admin/personas/:resource_id` |
| `EXAM_PREP_CATALOG_COURSE` | `/admin/exam-prep/catalog-courses/:resource_id` |
| `EXAM_PREP_UNIT` | `/admin/exam-prep/units/:resource_id` |
| `EXAM_PREP_MODULE` | `/admin/exam-prep/modules/:resource_id` |
| `EXAM_PREP_LESSON` | `/admin/exam-prep/lessons/:resource_id` |
| `EXAM_PREP_PRACTICE` | `/admin/exam-prep/practices/:resource_id` |
| `QUESTION_TYPE_DEFINITION` | `/admin/question-types/:resource_id` |
| `USER` | `/admin/users/:resource_id` |
| `SUBSCRIPTION` | `/admin/users/:userId/subscriptions` (may need metadata) |
| `PAYMENT` | Payments list filtered by ID |
If `resource_id` is null (bulk operations, webhooks), show message only — no link.
---
## Related admin endpoints (user profile)
These complement but **do not replace** activity logs on user detail pages:
| Endpoint | Permission | Purpose |
|----------|------------|---------|
| `GET /admin/users/:user_id/recent-activity` | `progress.get_any_user` | Learner milestone timeline |
| `GET /admin/users/:user_id/learning-activity` | `progress.get_any_user` | Full LMS + exam prep trees + recent feed |
| `GET /admin/users/:user_id/lms-learning-activity` | `progress.get_any_user` | LMS completion tree only |
| `GET /admin/users/:user_id/subscriptions` | `subscriptions.get_by_user` | Billing history |
**Recommended user profile tabs:**
| Tab | Data source |
|-----|-------------|
| **Learning progress** | `learning-activity` |
| **Audit / account actions** | `GET /activity-logs?actor_id=:user_id` |
| **Billing** | `subscriptions` |
Learner **completions** appear in both activity logs (`PRACTICE_COMPLETED`, `LESSON_COMPLETED`) and recent-activity feeds — choose one primary UX per tab to avoid duplication, or dedupe by timestamp + kind.
---
## Recommended admin UI screens
### 1. Global activity log page
**Route example:** `/admin/logs/activity`
| UI element | Behavior |
|------------|----------|
| Data table | Columns: Time, Actor, Action (label), Message, Resource, IP |
| Date range picker | Maps to `after` / `before` |
| Action filter | Multi-select or dropdown from [Action catalog](#action-catalog) groups |
| Resource type filter | Dropdown |
| Actor filter | User/team picker → `actor_id` |
| Resource ID filter | Optional numeric input (when drilling down) |
| Pagination | `limit` + `offset` from `total_count` |
| Row click | Open detail drawer → `GET /activity-logs/:id` |
| Refresh | Re-fetch list; consider 30–60s auto-refresh for ops dashboards |
**Columns detail:**
- **Time:** Format `created_at` in admin timezone; show relative time (“2 hours ago”) in tooltip.
- **Action:** Human label via [Display helpers](#display-helpers-labels-icons-colors); badge color by category.
- **Resource:** `resource_type` label + `#resource_id` link when present.
- **Actor:** `actor_name` + `actor_role` from API; fallback to `#id (ROLE)` or **System**
### 2. Resource-scoped history tab
On FAQ edit, exam prep entity edit, persona edit, etc.:
```http
GET /api/v1/activity-logs?resource_type=FAQ&resource_id={id}&limit=20
```
Show a **“History”** or **“Audit log”** tab below the form — read-only timeline, no mutations.
### 3. Detail drawer / page
**Route example:** `/admin/logs/activity/:id`
| Section | Content |
|---------|---------|
| Summary | `message`, `action`, `created_at` |
| Actor | Resolved name, `actor_role`, link to user/team profile |
| Resource | Type + ID + deep link |
| Request context | `ip_address`, truncated `user_agent` (expandable) |
| Metadata | JSON viewer |
### 4. Dashboard widget (optional)
Recent critical events on admin home:
```http
GET /api/v1/activity-logs?limit=10&offset=0
```
Filter client-side to high-signal actions: `AUTH_LOGIN`, `USER_DELETED`, `PAYMENT_WEBHOOK_RECEIVED`, `NOTIFICATION_BULK_SENT`, `SETTINGS_UPDATED`.
---
## TypeScript types & API client
### Types
```typescript
export interface ActivityLog {
id: number;
actor_id?: number | null;
actor_role?: string | null;
actor_name?: string | null;
actor_email?: string | null;
actor_kind?: "user" | "team_member" | null;
action: string;
resource_type: string;
resource_id?: number | null;
message?: string | null;
metadata: Record<string, unknown>;
ip_address?: string | null;
user_agent?: string | null;
created_at: string; // ISO 8601
}
export interface ActivityLogListData {
logs: ActivityLog[];
total_count: number;
limit: number;
offset: number;
}
export interface ApiResponse<T> {
message: string;
data: T;
success: boolean;
status_code: number;
metadata?: unknown;
}
export interface ActivityLogFilterParams {
actor_id?: number;
action?: string;
resource_type?: string;
resource_id?: number;
after?: string; // RFC3339
before?: string; // RFC3339
limit?: number;
offset?: number;
}
```
### API client example
```typescript
const API_BASE = import.meta.env.VITE_API_BASE_URL ?? "/api/v1";
function authHeaders(token: string): HeadersInit {
return {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
}
export async function listActivityLogs(
token: string,
params: ActivityLogFilterParams = {}
): Promise<ActivityLogListData> {
const qs = new URLSearchParams();
if (params.actor_id != null) qs.set("actor_id", String(params.actor_id));
if (params.action) qs.set("action", params.action);
if (params.resource_type) qs.set("resource_type", params.resource_type);
if (params.resource_id != null) qs.set("resource_id", String(params.resource_id));
if (params.after) qs.set("after", params.after);
if (params.before) qs.set("before", params.before);
qs.set("limit", String(params.limit ?? 20));
qs.set("offset", String(params.offset ?? 0));
const res = await fetch(`${API_BASE}/activity-logs?${qs}`, {
headers: authHeaders(token),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.message ?? `HTTP ${res.status}`);
}
const body: ApiResponse<ActivityLogListData> = await res.json();
return body.data;
}
export async function getActivityLogById(
token: string,
id: number
): Promise<ActivityLog> {
const res = await fetch(`${API_BASE}/activity-logs/${id}`, {
headers: authHeaders(token),
});
if (res.status === 404) {
throw new Error("Activity log not found");
}
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.message ?? `HTTP ${res.status}`);
}
const body: ApiResponse<ActivityLog> = await res.json();
return body.data;
}
```
### React Query hook sketch
```typescript
import { useQuery } from "@tanstack/react-query";
export function useActivityLogs(token: string, filters: ActivityLogFilterParams) {
return useQuery({
queryKey: ["activity-logs", filters],
queryFn: () => listActivityLogs(token, filters),
staleTime: 30_000,
});
}
```
---
## Display helpers (labels, icons, colors)
Map machine codes to friendly UI strings:
```typescript
const ACTION_LABELS: Record<string, string> = {
AUTH_LOGIN: "Signed in",
AUTH_LOGOUT: "Signed out",
FAQ_CREATED: "FAQ created",
FAQ_UPDATED: "FAQ updated",
FAQ_DELETED: "FAQ deleted",
EXAM_PREP_CATALOG_COURSE_UPDATED: "Exam prep course updated",
PRACTICE_COMPLETED: "Practice completed",
PAYMENT_WEBHOOK_RECEIVED: "Payment webhook received",
NOTIFICATION_BULK_SENT: "Bulk notification sent",
// … extend as needed
};
export function actionLabel(action: string): string {
return ACTION_LABELS[action] ?? action.replace(/_/g, " ").toLowerCase();
}
const ACTION_CATEGORY: Record<string, string> = {
AUTH_LOGIN: "auth",
AUTH_LOGOUT: "auth",
FAQ_CREATED: "content",
USER_DELETED: "user",
PAYMENT_INITIATED: "billing",
// …
};
export function actionBadgeColor(action: string): string {
const cat = ACTION_CATEGORY[action] ?? "default";
switch (cat) {
case "auth": return "blue";
case "content": return "green";
case "user": return "orange";
case "billing": return "purple";
default: return "gray";
}
}
```
Prefer showing **`message`** when present — it is written for human operators (e.g. `"Updated FAQ: How do I reset my password?"`).
---
## Error handling
| HTTP | `message` (typical) | Admin UI behavior |
|------|---------------------|-------------------|
| `400` | Invalid query param | Highlight field; show `error` detail |
| `401` | Unauthorized | Redirect to login |
| `403` | Permission denied | Hide page or show “No access” |
| `404` | Activity log not found | Toast + return to list |
| `500` | Failed to retrieve activity logs | Retry button |
Example 403 body:
```json
{
"message": "You don't have permission to access this resource",
"error": "You don't have permission to access this resource"
}
```
---
## Performance & UX notes
1. **Async writes:** Logs are inserted in a goroutine after the HTTP response. A mutation succeeded in UI may appear in the log **~100–500ms** later — refresh list after save if showing inline history.
2. **Max page size:** `limit` capped at **100** server-side.
3. **No export API:** CSV export must be client-side from fetched pages or a future backend feature.
4. **Volume:** Use date + action filters for busy environments; avoid loading unbounded history.
5. **PII:** Logs may contain IPs, user agents, and messages with emails/titles — restrict page to trusted staff roles.
---
## Integration checklist
### Backend / access
- [ ] Confirm admin login token has `Role` = `ADMIN` or `SUPER_ADMIN`, or custom role with `activity_logs.list` + `activity_logs.get`
- [ ] Verify `GET /api/v1/activity-logs` returns `200` in staging
- [ ] Do not use `GET /api/v1/logs` for this feature (different system)
### Global audit page
- [ ] Route `/admin/logs/activity` (or equivalent)
- [ ] Table with pagination using `total_count`
- [ ] Filters: date range, action, resource type, actor
- [ ] Detail drawer with metadata JSON viewer
- [ ] Permission-gated menu item
### Resource-scoped history
- [ ] FAQ edit → History tab (`resource_type=FAQ`)
- [ ] Exam prep entities → History tab with matching resource type
- [ ] Personas, question types, email templates (same pattern)
### User profile
- [ ] Tab “Account activity” → `?actor_id={userId}`
- [ ] Keep “Learning progress” on `recent-activity` / `learning-activity` endpoints
### Polish
- [ ] Action label map + badge colors
- [ ] Actor column uses `actor_name` + `actor_role` from API (not client user lookup)
- [ ] Deep links from `resource_type` + `resource_id`
- [ ] Empty state copy when no logs match filters
### QA scenarios
- [ ] Create FAQ → row appears with `FAQ_CREATED`
- [ ] Update FAQ → `FAQ_UPDATED` with `resource_id` matching FAQ
- [ ] Filter `actor_id` shows only that user’s actions
- [ ] Invalid `after` date → 400 with clear error
- [ ] User without permission → 403, menu hidden
- [ ] Team member login → actor shows name + role (not **System**)
- [ ] User OAuth login → actor shows learner name + `STUDENT`
---
## Limitations & future work
| Topic | Current behavior |
|-------|------------------|
| Write API | None — logs are server-generated only |
| Delete / retention | No admin API to purge old logs |
| Full-text search | No server-side search on `message` |
| Actor display name | Enriched on read via `actor_name` / `actor_email` / `actor_kind`; not stored in DB row |
| Historical login rows | Rows before actor-recording fix may still have null `actor_id` |
| Resource title | Not embedded; use `message` or fetch entity |
| Read GET requests | Generally not logged |
| Guaranteed coverage | Not every handler logs yet — coverage grows with `recordActivity` adoption |
| Real-time updates | No WebSocket; poll or refresh manually |
| CSV / PDF export | Not implemented |
Possible backend enhancements (not available today): full-text search, export, retention policy, enriched resource titles in list rows, webhook on critical actions.
---
## Quick reference
| Method | Path | Permission | Purpose |
|--------|------|------------|---------|
| `GET` | `/api/v1/activity-logs` | `activity_logs.list` | Filtered paginated list |
| `GET` | `/api/v1/activity-logs/:id` | `activity_logs.get` | Single entry detail |
**Related (not activity logs):**
| Method | Path | Permission | Purpose |
|--------|------|------------|---------|
| `GET` | `/api/v1/logs` | `logs.list` | System / Mongo technical logs |
| `GET` | `/api/v1/admin/users/:user_id/recent-activity` | `progress.get_any_user` | Learner milestone feed |
**Source files:**
- Domain enums: `internal/domain/activity_log.go`
- Handlers: `internal/web_server/handlers/activity_logs.go`
- Recording helper: `internal/web_server/handlers/activity_log_helper.go`
- Routes: `internal/web_server/routes.go` (lines ~384–385)
- RBAC: `internal/services/rbac/seeds.go` (`activity_logs.list`, `activity_logs.get`)