From 53cdb5060a1a56571b7dba20b269ec8439c16711 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Sat, 20 Jun 2026 03:59:24 -0700 Subject: [PATCH] Integrate activity logs and polish user profile audit UX. Add global and profile-scoped activity log views with server-side actor enrichment, admin sidebar access for ADMIN/Super Admin roles, collapsible user detail sections, and horizontally scrollable account activity tables. Co-authored-by: Cursor --- src/api/activity-logs.api.ts | 144 +++- src/components/sidebar/Sidebar.tsx | 11 +- src/components/ui/table.tsx | 17 +- src/lib/activityLogActor.ts | 17 +- src/lib/activityLogDisplay.ts | 389 ++++++++++ src/lib/activityLogPermissions.ts | 18 + src/lib/displayValue.ts | 6 + src/pages/team/TeamMemberDetailPage.tsx | 391 ++++++---- src/pages/user-log/UserLogPage.tsx | 690 +----------------- .../components/ActivityLogListPanel.tsx | 666 +++++++++++++++++ .../user-log/components/ActorHoverCard.tsx | 129 +++- src/pages/user-log/components/ActorLabel.tsx | 104 +++ src/pages/user-management/UserDetailPage.tsx | 27 +- .../components/UserAccountActivitySection.tsx | 48 ++ .../UserLearningActivitySection.tsx | 82 ++- .../components/UserSubscriptionsSection.tsx | 71 +- src/types/activity-log.types.ts | 19 +- 17 files changed, 1868 insertions(+), 961 deletions(-) create mode 100644 src/lib/activityLogDisplay.ts create mode 100644 src/lib/activityLogPermissions.ts create mode 100644 src/lib/displayValue.ts create mode 100644 src/pages/user-log/components/ActivityLogListPanel.tsx create mode 100644 src/pages/user-log/components/ActorLabel.tsx create mode 100644 src/pages/user-management/components/UserAccountActivitySection.tsx diff --git a/src/api/activity-logs.api.ts b/src/api/activity-logs.api.ts index ab1632c..e27b07e 100644 --- a/src/api/activity-logs.api.ts +++ b/src/api/activity-logs.api.ts @@ -1,14 +1,138 @@ -import http from "./http"; +import http from "./http" import type { - GetActivityLogsResponse, - GetActivityLogResponse, + ActivityLog, ActivityLogFilters, -} from "../types/activity-log.types"; + ActivityLogListData, + GetActivityLogResponse, + GetActivityLogsResponse, +} from "../types/activity-log.types" -export const getActivityLogs = (filters?: ActivityLogFilters) => - http.get("/activity-logs", { - params: filters, - }); +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value) +} -export const getActivityLogById = (id: number) => - http.get(`/activity-logs/${id}`); +export function normalizeActivityLog(raw: unknown): ActivityLog | null { + if (!isRecord(raw)) return null + const id = Number(raw.id ?? raw.ID) + if (!Number.isFinite(id) || id <= 0) return null + + const actorIdRaw = raw.actor_id ?? raw.ActorId ?? raw.actorId + const actorNameRaw = raw.actor_name ?? raw.ActorName ?? raw.actorName + const actorEmailRaw = raw.actor_email ?? raw.ActorEmail ?? raw.actorEmail + const actorKindRaw = raw.actor_kind ?? raw.ActorKind ?? raw.actorKind + const resourceIdRaw = raw.resource_id ?? raw.ResourceId ?? raw.resourceId + const metadataRaw = raw.metadata ?? raw.Metadata + + const actorKind = + actorKindRaw === "user" || actorKindRaw === "team_member" + ? actorKindRaw + : actorKindRaw === "team" + ? "team_member" + : null + + return { + id, + actor_id: + actorIdRaw == null || actorIdRaw === "" + ? null + : Number.isFinite(Number(actorIdRaw)) + ? Number(actorIdRaw) + : null, + actor_role: + raw.actor_role != null || raw.ActorRole != null + ? String(raw.actor_role ?? raw.ActorRole) + : null, + actor_name: + actorNameRaw != null && String(actorNameRaw).trim() + ? String(actorNameRaw).trim() + : null, + actor_email: + actorEmailRaw != null && String(actorEmailRaw).trim() + ? String(actorEmailRaw).trim() + : null, + actor_kind: actorKind, + action: String(raw.action ?? raw.Action ?? ""), + resource_type: String(raw.resource_type ?? raw.ResourceType ?? ""), + resource_id: + resourceIdRaw == null || resourceIdRaw === "" + ? null + : Number.isFinite(Number(resourceIdRaw)) + ? Number(resourceIdRaw) + : null, + message: + raw.message != null || raw.Message != null + ? String(raw.message ?? raw.Message) + : null, + metadata: isRecord(metadataRaw) ? metadataRaw : {}, + ip_address: + raw.ip_address != null || raw.IpAddress != null + ? String(raw.ip_address ?? raw.IpAddress) + : null, + user_agent: + raw.user_agent != null || raw.UserAgent != null + ? String(raw.user_agent ?? raw.UserAgent) + : null, + created_at: String(raw.created_at ?? raw.CreatedAt ?? ""), + } +} + +function unwrapPayload(body: unknown): unknown { + if (!isRecord(body)) return body + return body.data ?? body.Data ?? body +} + +export function parseActivityLogList(body: unknown): ActivityLogListData { + const empty: ActivityLogListData = { logs: [], total_count: 0, limit: 20, offset: 0 } + const payload = unwrapPayload(body) + if (!isRecord(payload)) return empty + + const inner = payload.logs ?? payload.Logs + const logs = Array.isArray(inner) + ? inner.map(normalizeActivityLog).filter((row): row is ActivityLog => row != null) + : [] + + const total_count = Number(payload.total_count ?? payload.TotalCount ?? logs.length) + const limit = Number(payload.limit ?? payload.Limit ?? 20) + const offset = Number(payload.offset ?? payload.Offset ?? 0) + + return { + logs, + total_count: Number.isFinite(total_count) ? total_count : logs.length, + limit: Number.isFinite(limit) ? limit : 20, + offset: Number.isFinite(offset) ? offset : 0, + } +} + +function buildQueryParams(filters?: ActivityLogFilters): Record { + const params: Record = { + limit: Math.min(100, Math.max(1, filters?.limit ?? 20)), + offset: Math.max(0, filters?.offset ?? 0), + } + if (filters?.actor_id != null) params.actor_id = filters.actor_id + if (filters?.action?.trim()) params.action = filters.action.trim() + if (filters?.resource_type?.trim()) params.resource_type = filters.resource_type.trim() + if (filters?.resource_id != null) params.resource_id = filters.resource_id + if (filters?.after?.trim()) params.after = filters.after.trim() + if (filters?.before?.trim()) params.before = filters.before.trim() + return params +} + +export async function getActivityLogs(filters?: ActivityLogFilters): Promise { + const res = await http.get("/activity-logs", { + params: buildQueryParams(filters), + }) + return parseActivityLogList(res.data) +} + +export async function getActivityLogById(id: number): Promise { + const res = await http.get(`/activity-logs/${id}`) + const payload = unwrapPayload(res.data) + const log = normalizeActivityLog(payload) + if (!log) throw new Error("Activity log not found") + return log +} + +export function activityLogApiErrorMessage(error: unknown, fallback: string): string { + const err = error as { response?: { data?: { message?: string; error?: string } } } + return String(err.response?.data?.message || err.response?.data?.error || fallback) +} diff --git a/src/components/sidebar/Sidebar.tsx b/src/components/sidebar/Sidebar.tsx index 1f356ef..989e5f5 100644 --- a/src/components/sidebar/Sidebar.tsx +++ b/src/components/sidebar/Sidebar.tsx @@ -26,6 +26,7 @@ import { useTeamPermissions } from "../../hooks/useTeamPermissions"; import { hasFaqPermission } from "../../lib/faqPermissions"; import { hasRatingsPermission } from "../../lib/ratingsPermissions"; import { hasPersonaPermission } from "../../lib/personasPermissions"; +import { hasActivityLogPermission } from "../../lib/activityLogPermissions"; import { SidebarNavGroup } from "./SidebarNavGroup"; type NavLinkItem = { @@ -108,7 +109,7 @@ const navEntries: NavEntry[] = [ { kind: "section", label: "Operations" }, { kind: "link", label: "Payments", to: "/payments", icon: CreditCard }, - { kind: "link", label: "User activity log", to: "/user-log", icon: ClipboardList }, + { kind: "link", label: "Activity log", to: "/user-log", icon: ClipboardList, permission: "activity_logs.list" }, { kind: "link", label: "Issue reports", to: "/issues", icon: CircleAlert }, { kind: "link", @@ -277,11 +278,19 @@ export function Sidebar({ ) { return null; } + if ( + entry.permission === "activity_logs.list" && + !permissionsLoading && + !hasActivityLogPermission("activity_logs.list", permissions) + ) { + return null; + } if ( entry.permission && entry.permission !== "faqs.list" && entry.permission !== "ratings.list_by_target" && entry.permission !== "personas.list" && + entry.permission !== "activity_logs.list" && !permissionsLoading && !hasPermission(entry.permission) ) { diff --git a/src/components/ui/table.tsx b/src/components/ui/table.tsx index 2ff88bf..9563cb9 100644 --- a/src/components/ui/table.tsx +++ b/src/components/ui/table.tsx @@ -1,12 +1,19 @@ import * as React from "react" import { cn } from "../../lib/utils" -export const Table = React.forwardRef>( - ({ className, ...props }, ref) => ( -
+type TableProps = React.HTMLAttributes & { + /** Render only the `` element (for use inside an external scroll container). */ + noWrapper?: boolean +} + +export const Table = React.forwardRef( + ({ className, noWrapper = false, ...props }, ref) => { + const table = (
- - ), + ) + if (noWrapper) return table + return
{table}
+ }, ) Table.displayName = "Table" diff --git a/src/lib/activityLogActor.ts b/src/lib/activityLogActor.ts index fabf1b9..f0f4e95 100644 --- a/src/lib/activityLogActor.ts +++ b/src/lib/activityLogActor.ts @@ -8,7 +8,15 @@ const TEAM_ROLE_VALUES = new Set( TEAM_ROLE_OPTIONS.map((o) => o.value.toUpperCase()), ) -const APP_USER_ROLES = new Set(["STUDENT", "LEARNER", "USER", "SUBSCRIBER"]) +const APP_USER_ROLES = new Set([ + "STUDENT", + "OPEN_LEARNER", + "ADMIN", + "SUPER_ADMIN", + "USER", + "SUBSCRIBER", + "LEARNER", +]) export type ActorProfileKind = "team" | "user" @@ -46,8 +54,8 @@ function normalizeRole(role: string): string { export function resolveActorKind(actorRole: string | null | undefined): ActorProfileKind | null { if (!actorRole?.trim()) return null const upper = normalizeRole(actorRole) - if (TEAM_ROLE_VALUES.has(upper)) return "team" if (APP_USER_ROLES.has(upper)) return "user" + if (TEAM_ROLE_VALUES.has(upper)) return "team" return null } @@ -107,8 +115,11 @@ async function fetchUserProfile(actorId: number): Promise { export async function fetchActorProfile( actorId: number, actorRole: string | null | undefined, + actorKind?: "user" | "team_member" | null, ): Promise { - const kind = resolveActorKind(actorRole) + const kindFromApi = + actorKind === "team_member" ? "team" : actorKind === "user" ? "user" : null + const kind = kindFromApi ?? resolveActorKind(actorRole) const load = async (target: ActorProfileKind): Promise => { const key = cacheKey(actorId, target) diff --git a/src/lib/activityLogDisplay.ts b/src/lib/activityLogDisplay.ts new file mode 100644 index 0000000..957183b --- /dev/null +++ b/src/lib/activityLogDisplay.ts @@ -0,0 +1,389 @@ +import type { ActivityLog, ActivityLogActorKind } from "../types/activity-log.types" + +export type ActorDisplay = { + name: string + role?: string + kind?: ActivityLogActorKind + email?: string +} + +export type ActivityLogActorFields = Pick< + ActivityLog, + "actor_id" | "actor_role" | "actor_name" | "actor_email" | "actor_kind" +> + +export type ActionBadgeTone = "auth" | "content" | "user" | "billing" | "team" | "default" + +const ACTION_LABELS: Record = { + AUTH_LOGIN: "Signed in", + AUTH_LOGOUT: "Signed out", + AUTH_REGISTER: "Registered", + AUTH_TOKEN_REFRESHED: "Token refreshed", + USER_CREATED: "User created", + USER_UPDATED: "User updated", + USER_DELETED: "User deleted", + USER_PASSWORD_RESET: "Password reset", + USER_PROFILE_PICTURE_UPDATED: "Profile picture updated", + USERS_PURGED: "Users purged", + ADMIN_CREATED: "Admin created", + ADMIN_UPDATED: "Admin updated", + TEAM_MEMBER_CREATED: "Team member created", + TEAM_MEMBER_INVITED: "Team member invited", + TEAM_MEMBER_UPDATED: "Team member updated", + TEAM_MEMBER_DELETED: "Team member deleted", + TEAM_MEMBER_PASSWORD_CHANGED: "Team password changed", + TEAM_INVITATION_RESENT: "Invitation resent", + TEAM_INVITATION_REVOKED: "Invitation revoked", + FAQ_CREATED: "FAQ created", + FAQ_UPDATED: "FAQ updated", + FAQ_DELETED: "FAQ deleted", + PERSONA_CREATED: "Persona created", + PERSONA_UPDATED: "Persona updated", + PERSONA_DELETED: "Persona deleted", + QUESTION_TYPE_DEFINITION_CREATED: "Question type created", + QUESTION_TYPE_DEFINITION_UPDATED: "Question type updated", + QUESTION_TYPE_DEFINITION_DELETED: "Question type deleted", + QUESTION_TYPE_DEFINITION_GROUP_CREATED: "Question type group created", + QUESTION_TYPE_DEFINITION_GROUP_UPDATED: "Question type group updated", + QUESTION_TYPE_DEFINITION_GROUP_DELETED: "Question type group deleted", + PAYMENT_INITIATED: "Payment initiated", + PAYMENT_VERIFIED: "Payment verified", + PAYMENT_CANCELLED: "Payment cancelled", + PAYMENT_WEBHOOK_RECEIVED: "Payment webhook received", + NOTIFICATION_BULK_SENT: "Bulk notification sent", + NOTIFICATION_CREATED: "Notification created", + NOTIFICATION_UPDATED: "Notification updated", + NOTIFICATION_DELETED: "Notification deleted", + PRACTICE_COMPLETED: "Practice completed", + LESSON_COMPLETED: "Lesson completed", + SETTINGS_UPDATED: "Settings updated", +} + +const ACTION_CATEGORY: Record = { + AUTH_LOGIN: "auth", + AUTH_LOGOUT: "auth", + AUTH_REGISTER: "auth", + AUTH_TOKEN_REFRESHED: "auth", + USER_CREATED: "user", + USER_UPDATED: "user", + USER_DELETED: "user", + USER_PASSWORD_RESET: "user", + USERS_PURGED: "user", + ADMIN_CREATED: "user", + ADMIN_UPDATED: "user", + TEAM_MEMBER_CREATED: "team", + TEAM_MEMBER_UPDATED: "team", + TEAM_MEMBER_DELETED: "team", + TEAM_MEMBER_INVITED: "team", + PAYMENT_INITIATED: "billing", + PAYMENT_VERIFIED: "billing", + PAYMENT_CANCELLED: "billing", + PAYMENT_WEBHOOK_RECEIVED: "billing", + SUBSCRIPTION_CREATED: "billing", + SUBSCRIPTION_CANCELLED: "billing", +} + +export const ACTION_FILTER_GROUPS: { label: string; actions: string[] }[] = [ + { + label: "Authentication", + actions: ["AUTH_LOGIN", "AUTH_LOGOUT", "AUTH_REGISTER", "AUTH_TOKEN_REFRESHED"], + }, + { + label: "Users & admins", + actions: [ + "USER_CREATED", + "USER_UPDATED", + "USER_DELETED", + "USER_PASSWORD_RESET", + "ADMIN_CREATED", + "ADMIN_UPDATED", + ], + }, + { + label: "Team", + actions: [ + "TEAM_MEMBER_CREATED", + "TEAM_MEMBER_INVITED", + "TEAM_MEMBER_UPDATED", + "TEAM_MEMBER_DELETED", + "TEAM_MEMBER_PASSWORD_CHANGED", + "TEAM_INVITATION_RESENT", + "TEAM_INVITATION_REVOKED", + ], + }, + { + label: "LMS content", + actions: [ + "PROGRAM_CREATED", + "PROGRAM_UPDATED", + "PROGRAM_DELETED", + "COURSE_CREATED", + "COURSE_UPDATED", + "COURSE_DELETED", + "MODULE_CREATED", + "MODULE_UPDATED", + "MODULE_DELETED", + "LESSON_CREATED", + "LESSON_UPDATED", + "LESSON_DELETED", + "PRACTICE_CREATED", + "PRACTICE_UPDATED", + "PRACTICE_DELETED", + ], + }, + { + label: "Questions", + actions: [ + "QUESTION_CREATED", + "QUESTION_UPDATED", + "QUESTION_DELETED", + "QUESTION_TYPE_DEFINITION_CREATED", + "QUESTION_TYPE_DEFINITION_UPDATED", + "QUESTION_TYPE_DEFINITION_DELETED", + "QUESTION_TYPE_DEFINITION_GROUP_CREATED", + "QUESTION_TYPE_DEFINITION_GROUP_UPDATED", + "QUESTION_TYPE_DEFINITION_GROUP_DELETED", + ], + }, + { + label: "CMS & personas", + actions: [ + "FAQ_CREATED", + "FAQ_UPDATED", + "FAQ_DELETED", + "PERSONA_CREATED", + "PERSONA_UPDATED", + "PERSONA_DELETED", + "EMAIL_TEMPLATE_CREATED", + "EMAIL_TEMPLATE_UPDATED", + "EMAIL_TEMPLATE_DELETED", + "SETTINGS_UPDATED", + ], + }, + { + label: "Billing", + actions: [ + "SUBSCRIPTION_PLAN_CREATED", + "SUBSCRIPTION_PLAN_UPDATED", + "SUBSCRIPTION_CREATED", + "SUBSCRIPTION_CANCELLED", + "PAYMENT_INITIATED", + "PAYMENT_VERIFIED", + "PAYMENT_CANCELLED", + "PAYMENT_WEBHOOK_RECEIVED", + ], + }, + { + label: "Notifications", + actions: [ + "NOTIFICATION_CREATED", + "NOTIFICATION_UPDATED", + "NOTIFICATION_DELETED", + "NOTIFICATION_BULK_SENT", + "SCHEDULED_NOTIFICATION_CANCELLED", + ], + }, + { + label: "Learner progress", + actions: ["LESSON_COMPLETED", "PRACTICE_COMPLETED", "RATING_SUBMITTED", "RATING_DELETED"], + }, +] + +export const RESOURCE_TYPE_OPTIONS: { value: string; label: string }[] = [ + { value: "AUTH", label: "Authentication" }, + { value: "USER", label: "User" }, + { value: "ADMIN", label: "Admin" }, + { value: "TEAM_MEMBER", label: "Team member" }, + { value: "PROGRAM", label: "Program" }, + { value: "COURSE", label: "Course" }, + { value: "MODULE", label: "Module" }, + { value: "LESSON", label: "Lesson" }, + { value: "PRACTICE", label: "Practice" }, + { value: "QUESTION", label: "Question" }, + { value: "QUESTION_TYPE_DEFINITION", label: "Question type" }, + { value: "QUESTION_TYPE_DEFINITION_GROUP", label: "Question type group" }, + { value: "FAQ", label: "FAQ" }, + { value: "PERSONA", label: "Persona" }, + { value: "PAYMENT", label: "Payment" }, + { value: "SUBSCRIPTION", label: "Subscription" }, + { value: "SUBSCRIPTION_PLAN", label: "Subscription plan" }, + { value: "NOTIFICATION", label: "Notification" }, + { value: "EMAIL_TEMPLATE", label: "Email template" }, + { value: "SETTINGS", label: "Settings" }, + { value: "VIDEO", label: "Video" }, + { value: "CATEGORY", label: "Category" }, + { value: "SUB_COURSE", label: "Sub-course" }, + { value: "QUESTION_SET", label: "Question set" }, + { value: "EXAM_PREP_CATALOG_COURSE", label: "Exam prep course" }, + { value: "EXAM_PREP_UNIT", label: "Exam prep unit" }, + { value: "EXAM_PREP_MODULE", label: "Exam prep module" }, + { value: "EXAM_PREP_LESSON", label: "Exam prep lesson" }, + { value: "EXAM_PREP_PRACTICE", label: "Exam prep practice" }, + { value: "APP_VERSION", label: "App version" }, + { value: "FIELD_OPTION", label: "Field option" }, + { value: "DEVICE", label: "Device" }, + { value: "FILE", label: "File" }, + { value: "REFERRAL", label: "Referral" }, + { value: "ASSESSMENT_QUESTION", label: "Assessment question" }, + { value: "ISSUE", label: "Issue" }, + { value: "RATING", label: "Rating" }, +] + +export function actionLabel(action: string): string { + return ACTION_LABELS[action] ?? action.replace(/_/g, " ").toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase()) +} + +export function actionBadgeTone(action: string): ActionBadgeTone { + if (ACTION_CATEGORY[action]) return ACTION_CATEGORY[action] + if (action.startsWith("TEAM_")) return "team" + if (action.startsWith("AUTH_")) return "auth" + if (action.includes("PAYMENT") || action.includes("SUBSCRIPTION")) return "billing" + if (action.startsWith("USER_") || action.startsWith("ADMIN_")) return "user" + if ( + action.includes("CREATED") || + action.includes("UPDATED") || + action.includes("DELETED") || + action.includes("COMPLETED") + ) { + return "content" + } + return "default" +} + +export function actionBadgeClasses(action: string): string { + const tone = actionBadgeTone(action) + switch (tone) { + case "auth": + return "bg-amber-50 text-amber-700 border-amber-200" + case "content": + return "bg-emerald-50 text-emerald-700 border-emerald-200" + case "user": + return "bg-orange-50 text-orange-700 border-orange-200" + case "billing": + return "bg-violet-50 text-violet-700 border-violet-200" + case "team": + return "bg-blue-50 text-blue-700 border-blue-200" + default: + return "bg-grayScale-100 text-grayScale-600 border-grayScale-200" + } +} + +export function resourceTypeLabel(resourceType: string): string { + const match = RESOURCE_TYPE_OPTIONS.find((o) => o.value === resourceType) + return match?.label ?? resourceType.replace(/_/g, " ").toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase()) +} + +export function formatActorDisplay(log: ActivityLogActorFields): ActorDisplay { + if (log.actor_name?.trim()) { + return { + name: log.actor_name.trim(), + role: log.actor_role ?? undefined, + kind: log.actor_kind ?? undefined, + email: log.actor_email ?? undefined, + } + } + if (log.actor_email?.trim()) { + return { + name: log.actor_email.trim(), + role: log.actor_role ?? undefined, + kind: log.actor_kind ?? undefined, + email: log.actor_email.trim(), + } + } + if (log.actor_id != null) { + return { name: `#${log.actor_id}`, role: log.actor_role ?? undefined } + } + return { name: "System" } +} + +export function formatActorFallback(log: ActivityLogActorFields): string { + const { name, role } = formatActorDisplay(log) + if (name === "System") return name + if (name.startsWith("#") && role) return `${name} (${role})` + return name +} + +export function activityLogActorPath(log: ActivityLogActorFields): string | null { + if (log.actor_id == null) return null + if (log.actor_kind === "team_member") return `/team/${log.actor_id}` + if (log.actor_kind === "user") return `/users/${log.actor_id}` + const role = log.actor_role?.trim().toUpperCase() + if (role === "INSTRUCTOR" || role === "SUPPORT" || role === "CONTENT_MANAGER") { + return `/team/${log.actor_id}` + } + return `/users/${log.actor_id}` +} + +/** Admin routes for deep linking from activity log rows. */ +export function activityLogResourcePath( + resourceType: string, + resourceId: number | null | undefined, +): string | null { + if (resourceId == null || resourceId <= 0) return null + switch (resourceType) { + case "USER": + case "ADMIN": + return `/users/${resourceId}` + case "TEAM_MEMBER": + return `/team/${resourceId}` + case "FAQ": + return `/help/faqs/${resourceId}/edit` + case "PERSONA": + return `/personas` + case "QUESTION_TYPE_DEFINITION": + return `/new-content/question-types/${resourceId}/edit` + case "QUESTION_TYPE_DEFINITION_GROUP": + return `/new-content/question-types/groups/${resourceId}` + case "PAYMENT": + return `/payments` + case "NOTIFICATION": + return `/notifications` + case "EMAIL_TEMPLATE": + return `/notifications/email-templates` + case "SUBSCRIPTION_PLAN": + return `/settings` + case "ISSUE": + return `/issues` + default: + return null + } +} + +export function formatActivityDate(dateStr: string): string { + return new Date(dateStr).toLocaleDateString(undefined, { + year: "numeric", + month: "short", + day: "numeric", + }) +} + +export function formatActivityTime(dateStr: string): string { + return new Date(dateStr).toLocaleTimeString(undefined, { + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }) +} + +export function getRelativeActivityTime(dateStr: string): string { + const now = new Date() + const date = new Date(dateStr) + const diffMs = now.getTime() - date.getTime() + const diffMins = Math.floor(diffMs / 60000) + const diffHours = Math.floor(diffMs / 3600000) + const diffDays = Math.floor(diffMs / 86400000) + + if (diffMins < 1) return "Just now" + if (diffMins < 60) return `${diffMins}m ago` + if (diffHours < 24) return `${diffHours}h ago` + if (diffDays < 7) return `${diffDays}d ago` + return formatActivityDate(dateStr) +} + +export function toRfc3339StartOfDay(dateValue: string): string { + return new Date(`${dateValue}T00:00:00`).toISOString() +} + +export function toRfc3339EndOfDay(dateValue: string): string { + return new Date(`${dateValue}T23:59:59.999`).toISOString() +} diff --git a/src/lib/activityLogPermissions.ts b/src/lib/activityLogPermissions.ts new file mode 100644 index 0000000..35ba8d4 --- /dev/null +++ b/src/lib/activityLogPermissions.ts @@ -0,0 +1,18 @@ +const ACTIVITY_LOG_BYPASS_TEAM_ROLES = new Set(["SUPER_ADMIN", "ADMIN"]) + +export function getSessionTeamRole(): string { + return localStorage.getItem("role")?.trim() ?? "" +} + +export function hasActivityLogRoleBypass(): boolean { + const role = getSessionTeamRole().toUpperCase() + return ACTIVITY_LOG_BYPASS_TEAM_ROLES.has(role) +} + +export function hasActivityLogPermission( + permission: string, + permissions: string[], +): boolean { + if (hasActivityLogRoleBypass()) return true + return permissions.includes(permission) +} diff --git a/src/lib/displayValue.ts b/src/lib/displayValue.ts new file mode 100644 index 0000000..7bfac1d --- /dev/null +++ b/src/lib/displayValue.ts @@ -0,0 +1,6 @@ +export const NOT_ASSIGNED_LABEL = "Not assigned" + +export function displayValue(value: string | null | undefined): string { + const trimmed = value?.trim() + return trimmed ? trimmed : NOT_ASSIGNED_LABEL +} diff --git a/src/pages/team/TeamMemberDetailPage.tsx b/src/pages/team/TeamMemberDetailPage.tsx index 767736f..0859606 100644 --- a/src/pages/team/TeamMemberDetailPage.tsx +++ b/src/pages/team/TeamMemberDetailPage.tsx @@ -2,43 +2,37 @@ import { useEffect, useState } from "react" import { Link, useParams } from "react-router-dom" import { ArrowLeft, - BadgeCheck, - Briefcase, - Building2, - CalendarDays, Clock3, - Hash, + ClipboardList, Mail, Phone, Shield, User, - UserCircle2, + UsersRound, } from "lucide-react" import { Badge } from "../../components/ui/badge" +import { Button } from "../../components/ui/button" import { Card, CardContent, CardHeader, CardTitle } from "../../components/ui/card" import { Avatar, AvatarFallback } from "../../components/ui/avatar" import { Separator } from "../../components/ui/separator" import { cn } from "../../lib/utils" +import { formatTeamRoleLabel } from "../../lib/teamRoles" +import { displayValue, NOT_ASSIGNED_LABEL } from "../../lib/displayValue" import { getTeamMemberById } from "../../api/team.api" import type { TeamMemberDetail } from "../../types/team.types" +import { ActivityLogListPanel } from "../user-log/components/ActivityLogListPanel" -function formatRoleLabel(role: string): string { - const value = role.trim() - if (!value) return "—" +function formatStatusLabel(status: string): string { + const value = status.trim() + if (!value) return NOT_ASSIGNED_LABEL return value .split("_") .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()) .join(" ") } -function formatStatusLabel(status: string): string { - const value = status.trim() - if (!value) return "—" - return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase() -} - function formatDate(dateStr: string | null | undefined): string { - if (!dateStr?.trim()) return "—" + if (!dateStr?.trim()) return NOT_ASSIGNED_LABEL const date = new Date(dateStr) if (Number.isNaN(date.getTime())) return dateStr return date.toLocaleDateString(undefined, { @@ -48,8 +42,11 @@ function formatDate(dateStr: string | null | undefined): string { }) } -function formatDateTime(dateStr: string | null | undefined): string { - if (!dateStr?.trim()) return "—" +function formatDateTime( + dateStr: string | null | undefined, + emptyLabel: string = NOT_ASSIGNED_LABEL, +): string { + if (!dateStr?.trim()) return emptyLabel const date = new Date(dateStr) if (Number.isNaN(date.getTime())) return dateStr return date.toLocaleString(undefined, { @@ -61,9 +58,32 @@ function formatDateTime(dateStr: string | null | undefined): string { }) } -function displayValue(value: string | null | undefined): string { - const trimmed = value?.trim() - return trimmed ? trimmed : "—" +function getRelativeTime(dateStr: string | null | undefined): string { + if (!dateStr?.trim()) return "Never" + const now = new Date() + const date = new Date(dateStr) + if (Number.isNaN(date.getTime())) return NOT_ASSIGNED_LABEL + const diffMs = now.getTime() - date.getTime() + const diffMins = Math.floor(diffMs / 60000) + const diffHours = Math.floor(diffMs / 3600000) + const diffDays = Math.floor(diffMs / 86400000) + + if (diffMins < 1) return "Just now" + if (diffMins < 60) return `${diffMins}m ago` + if (diffHours < 24) return `${diffHours}h ago` + if (diffDays < 7) return `${diffDays}d ago` + return formatDate(dateStr) +} + +function getStatusClasses(status: string): string { + const normalized = status.trim().toLowerCase() + if (normalized === "active") { + return "bg-mint-500/15 text-mint-500 border border-mint-500/25" + } + if (normalized === "invited" || normalized === "pending") { + return "bg-gold-100 text-gold-600 border border-gold-300/40" + } + return "bg-destructive/15 text-destructive border border-destructive/25" } function getRoleBadgeClasses(role: string): string { @@ -90,60 +110,65 @@ function getRoleBadgeClasses(role: string): string { } } -function DetailRow({ - icon: Icon, - label, - value, -}: { - icon: React.ComponentType<{ className?: string }> - label: string - value: string -}) { - return ( -
-
- -
-
-

{label}

-

{value}

-
-
- ) -} - -function StatTile({ - icon: Icon, - label, - value, -}: { - icon: React.ComponentType<{ className?: string }> - label: string - value: string -}) { - return ( -
-
- - {label} -
-

{value}

-
- ) -} - function LoadingSkeleton() { return ( -
+
-
-
- {[1, 2, 3, 4].map((item) => ( -
- ))} +
+
+
+
+
+
+
+
+
+
+
+ ) +} + +function InfoItem({ label, value }: { label: string; value: string }) { + return ( +
+

+ {label} +

+

{value}

+
+ ) +} + +function InfoRow({ label, value }: { label: string; value: string }) { + return ( +
+ {label} + {value} +
+ ) +} + +function ContactField({ + icon: Icon, + label, + value, +}: { + icon: React.ComponentType<{ className?: string }> + label: string + value: string +}) { + return ( +
+
+ +
+
+

+ {label} +

+

{value}

-
) } @@ -184,7 +209,7 @@ export function TeamMemberDetailPage() { if (error || !member) { return ( -
+
Back to Team - +
@@ -200,6 +225,9 @@ export function TeamMemberDetailPage() {

{error || "Member not found"}

+
@@ -208,10 +236,10 @@ export function TeamMemberDetailPage() { const fullName = `${member.first_name} ${member.last_name}`.trim() const initials = `${member.first_name?.[0] ?? ""}${member.last_name?.[0] ?? ""}`.toUpperCase() - const isActive = member.status.trim().toLowerCase() === "active" + const roleLabel = formatTeamRoleLabel(member.team_role) return ( -
+
-

Team directory

+

Team members

{fullName}

- Member #{member.id} · {displayValue(member.department)} + Member #{member.id} + {member.department?.trim() ? ` · ${member.department.trim()}` : ""}

- - - - - {initials || "?"} - - +
+
+ + +
+ + + {initials || "?"} + + +
+

{fullName}

+

+ {displayValue(member.job_title)} +

+
+ + + {roleLabel} + + + {formatStatusLabel(member.status)} + +
+
+
-
-

{fullName}

-

{displayValue(member.job_title)}

-
+ -
- - - {formatRoleLabel(member.team_role)} - - - {formatStatusLabel(member.status)} - - - {member.email_verified ? "Verified" : "Unverified"} - -
-
-
+
+ + +
-
- - - - + + +
+ + + + +
+ + + + + +
+
+ +
+ Activity summary +
+
+ + + + + + +
+
+ +
+ + +
+
+ +
+ Role & organization +
+
+ +
+ + + + + + +
+ + {member.bio?.trim() ? ( + <> + +
+

+ Bio +

+
+ {member.bio.trim()} +
+
+ + ) : null} +
+
+ + + +
+
+ +
+
+ Account activity +

+ Platform audit trail for actions performed by this team member. +

+
+
+
+ + + +
+
- - - - Member record - - - {member.bio ? ( -
-

Bio

-

{member.bio}

-
- ) : null} - -
-
-

- Contact -

- - - -
- -
-

- Role & organization -

- - - - - - - -
-
- - - -
- - Read-only team directory record -
-
-
) } diff --git a/src/pages/user-log/UserLogPage.tsx b/src/pages/user-log/UserLogPage.tsx index c899013..e89a592 100644 --- a/src/pages/user-log/UserLogPage.tsx +++ b/src/pages/user-log/UserLogPage.tsx @@ -1,689 +1,17 @@ -import { useCallback, useEffect, useState } from "react"; -import spinnerSrc from "../../assets/Circular-indeterminate progress indicator.svg"; -import { - Search, - ChevronDown, - ChevronLeft, - ChevronRight, - Activity, - Eye, - RefreshCw, - Clock, - User, - Globe, - Monitor, - FileText, - Info, - Shield, -} from "lucide-react"; -import { AdminFiltersPanel } from "../../components/filters/AdminFiltersPanel"; -import { Button } from "../../components/ui/button"; -import { Input } from "../../components/ui/input"; -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from "../../components/ui/table"; -import { Badge } from "../../components/ui/badge"; -import { - Dialog, - DialogContent, - DialogHeader, - DialogTitle, - DialogDescription, -} from "../../components/ui/dialog"; -import { countActiveFilters } from "../../lib/adminFilterUtils"; -import { fetchAllOffsetPages } from "../../lib/fetchAllOffsetPages"; -import { cn } from "../../lib/utils"; -import { TABLE_PAGE_SIZE_OPTIONS } from "../../lib/tablePagination"; -import { getActivityLogs, getActivityLogById } from "../../api/activity-logs.api"; -import type { ActivityLog, ActivityLogFilters } from "../../types/activity-log.types"; -import { SpinnerIcon } from "../../components/ui/spinner-icon"; -import { ActorHoverCard } from "./components/ActorHoverCard"; +import { ActivityLogListPanel } from "./components/ActivityLogListPanel" -// ── Action type configuration ────────────────────────────────────── -const ACTION_TYPES = [ - "TEAM_MEMBER_CREATED", - "TEAM_MEMBER_UPDATED", - "TEAM_MEMBER_DELETED", - "TEAM_MEMBER_DEACTIVATED", - "TEAM_MEMBER_REACTIVATED", - "VIDEO_UPLOADED", - "VIDEO_DELETED", - "COURSE_CREATED", - "COURSE_UPDATED", - "COURSE_DELETED", - "USER_REGISTERED", - "USER_UPDATED", - "USER_DELETED", - "ROLE_CREATED", - "ROLE_UPDATED", - "ROLE_DELETED", - "LOGIN", - "LOGOUT", -] as const; - -function getActionBadgeClasses(action: string): string { - if (action.includes("CREATED") || action.includes("REGISTERED") || action.includes("UPLOADED")) - return "bg-emerald-50 text-emerald-700 border-emerald-200"; - if (action.includes("UPDATED") || action.includes("REACTIVATED")) - return "bg-blue-50 text-blue-700 border-blue-200"; - if (action.includes("DELETED") || action.includes("DEACTIVATED")) - return "bg-red-50 text-red-700 border-red-200"; - if (action.includes("LOGIN") || action.includes("LOGOUT")) - return "bg-amber-50 text-amber-700 border-amber-200"; - return "bg-grayScale-100 text-grayScale-600 border-grayScale-200"; -} - -function getActionIcon(action: string) { - if (action.includes("TEAM_MEMBER")) return User; - if (action.includes("VIDEO")) return FileText; - if (action.includes("COURSE")) return FileText; - if (action.includes("ROLE")) return Shield; - return Activity; -} - -function formatActionLabel(action: string): string { - return action - .split("_") - .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()) - .join(" "); -} - -function formatDate(dateStr: string): string { - return new Date(dateStr).toLocaleDateString("en-US", { - year: "numeric", - month: "short", - day: "numeric", - }); -} - -function formatTime(dateStr: string): string { - return new Date(dateStr).toLocaleTimeString("en-US", { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - }); -} - -function getRelativeTime(dateStr: string): string { - const now = new Date(); - const date = new Date(dateStr); - const diffMs = now.getTime() - date.getTime(); - const diffMins = Math.floor(diffMs / 60000); - const diffHours = Math.floor(diffMs / 3600000); - const diffDays = Math.floor(diffMs / 86400000); - - if (diffMins < 1) return "Just now"; - if (diffMins < 60) return `${diffMins}m ago`; - if (diffHours < 24) return `${diffHours}h ago`; - if (diffDays < 7) return `${diffDays}d ago`; - return formatDate(dateStr); -} - -function formatRoleLabel(role: string): string { - return role - .split("_") - .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()) - .join(" "); -} - -// ── Main Component ───────────────────────────────────────────────── export function UserLogPage() { - const [logs, setLogs] = useState([]); - const [loading, setLoading] = useState(false); - const [page, setPage] = useState(1); - const [pageSize, setPageSize] = useState(10); - const [actionFilter, setActionFilter] = useState(""); - const [searchQuery, setSearchQuery] = useState(""); - const [dateAfter, setDateAfter] = useState(""); - const [dateBefore, setDateBefore] = useState(""); - - // Detail dialog - const [selectedLog, setSelectedLog] = useState(null); - const [detailLoading, setDetailLoading] = useState(false); - const [dialogOpen, setDialogOpen] = useState(false); - - const fetchLogs = useCallback(async () => { - setLoading(true); - try { - const allLogs = await fetchAllOffsetPages(async (offset, limit) => { - const filters: ActivityLogFilters = { limit, offset }; - if (actionFilter) filters.action = actionFilter; - if (dateAfter) filters.after = new Date(dateAfter).toISOString(); - if (dateBefore) filters.before = new Date(dateBefore).toISOString(); - - const res = await getActivityLogs(filters); - return { - items: res.data.data.logs, - total_count: res.data.data.total_count, - }; - }); - setLogs(allLogs); - } catch (error) { - console.error("Failed to fetch activity logs:", error); - setLogs([]); - } finally { - setLoading(false); - } - }, [actionFilter, dateAfter, dateBefore]); - - useEffect(() => { - fetchLogs(); - }, [fetchLogs]); - - useEffect(() => { - setPage(1); - }, [searchQuery, pageSize]); - - const handleViewDetail = async (logId: number) => { - setDialogOpen(true); - setDetailLoading(true); - try { - const res = await getActivityLogById(logId); - setSelectedLog(res.data.data); - } catch (error) { - console.error("Failed to fetch log detail:", error); - } finally { - setDetailLoading(false); - } - }; - - const handleCloseDialog = () => { - setDialogOpen(false); - setSelectedLog(null); - }; - - const clearFilters = () => { - setActionFilter(""); - setDateAfter(""); - setDateBefore(""); - setPage(1); - }; - - const activeFilterCount = countActiveFilters([ - { value: actionFilter }, - { value: dateAfter }, - { value: dateBefore }, - ]); - - const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim()); - - // Filter logs by search (client-side on the message field) - const filteredLogs = searchQuery - ? logs.filter( - (log) => - log.message?.toLowerCase().includes(searchQuery.toLowerCase()) || - log.action.toLowerCase().includes(searchQuery.toLowerCase()) || - log.actor_role?.toLowerCase().includes(searchQuery.toLowerCase()) - ) - : logs; - - const totalCount = filteredLogs.length; - - // Pagination - const pageCount = Math.max(1, Math.ceil(totalCount / pageSize)); - const safePage = Math.min(page, pageCount); - const paginatedLogs = filteredLogs.slice((safePage - 1) * pageSize, safePage * pageSize); - const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1; - const endEntry = Math.min(safePage * pageSize, totalCount); - - const handlePrev = () => safePage > 1 && setPage(safePage - 1); - const handleNext = () => safePage < pageCount && setPage(safePage + 1); - - const getPageNumbers = () => { - const pages: (number | string)[] = []; - if (pageCount <= 7) { - for (let i = 1; i <= pageCount; i++) pages.push(i); - } else { - pages.push(1, 2, 3); - if (safePage > 4) pages.push("..."); - if (safePage > 3 && safePage < pageCount - 2) pages.push(safePage); - if (safePage < pageCount - 3) pages.push("..."); - pages.push(pageCount); - } - return pages; - }; - return (
- {/* Header */} -
-
-

Activity Log

-

- Track all actions and changes made across the platform. -

-
- -
- - {/* Stats cards */} -
-
-
- -
-
-

{totalCount}

-

Total Logs

-
-
-
-
- -
-
-

- {logs.length > 0 ? getRelativeTime(logs[0].created_at) : "—"} -

-

Latest Activity

-
-
-
-
- -
-
-

{filteredLogs.length}

-

Showing Results

-
-
-
- - - - setSearchQuery(e.target.value)} - /> -
- } - > -
-
- - -
-
- - { - setDateAfter(e.target.value); - setPage(1); - }} - className="h-9 rounded-md border bg-white px-3 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500" - /> -
-
- - { - setDateBefore(e.target.value); - setPage(1); - }} - className="h-9 rounded-md border bg-white px-3 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500" - /> -
-
- - - {/* Table */} -
-
- - - ACTION - MESSAGE - ACTOR - RESOURCE - TIMESTAMP - DETAILS - - - - - {loading ? ( - - -
- - Loading activity logs... -
-
-
- ) : filteredLogs.length === 0 ? ( - - -
- -
-

No activity logs found

-

- {hasActiveFilters - ? "Try adjusting your filters" - : "Activity will appear here once actions are performed"} -

-
-
-
-
- ) : ( - paginatedLogs.map((log) => { - const ActionIcon = getActionIcon(log.action); - return ( - - -
-
- -
- - {formatActionLabel(log.action)} - -
-
- -

- {log.message || "—"} -

-
- - -
-
- -
-
-

- ID: {log.actor_id ?? "System"} -

- {log.actor_role && ( -

- {formatRoleLabel(log.actor_role)} -

- )} -
-
-
-
- -
-

{log.resource_type}

- {log.resource_id !== null && ( -

#{log.resource_id}

- )} -
-
- -
-

{formatDate(log.created_at)}

-

- {getRelativeTime(log.created_at)} -

-
-
- - - -
- ); - }) - )} -
-
- - {/* Pagination */} -
-
- Showing - - {startEntry}–{endEntry} - - of - {totalCount} - entries - Rows per page -
- - -
-
- -
- - - {getPageNumbers().map((n, idx) => - typeof n === "string" ? ( - - ... - - ) : ( - - ) - )} - - -
-
-
- - {/* Detail Dialog */} - - - - - - Activity Log Detail - - - Full details for this activity log entry. - - - - {detailLoading ? ( -
- -
- ) : selectedLog ? ( -
- {/* Action badge */} -
- - {formatActionLabel(selectedLog.action)} - - - ID #{selectedLog.id} - -
- - {/* Message */} - {selectedLog.message && ( -
-

{selectedLog.message}

-
- )} - - {/* Detail grid */} -
- } - label="Actor" - value={`ID: ${selectedLog.actor_id ?? "System"}`} - /> - } - label="Role" - value={selectedLog.actor_role ? formatRoleLabel(selectedLog.actor_role) : "—"} - /> - } - label="Resource" - value={`${selectedLog.resource_type}${selectedLog.resource_id !== null ? ` #${selectedLog.resource_id}` : ""}`} - /> - } - label="Time" - value={`${formatDate(selectedLog.created_at)} ${formatTime(selectedLog.created_at)}`} - /> - } - label="IP Address" - value={selectedLog.ip_address || "—"} - /> - } - label="User Agent" - value={selectedLog.user_agent ? truncateUA(selectedLog.user_agent) : "—"} - /> -
- - {/* Metadata */} - {selectedLog.metadata && Object.keys(selectedLog.metadata).length > 0 && ( -
-

- Metadata -

-
-
-                      {JSON.stringify(selectedLog.metadata, null, 2)}
-                    
-
-
- )} -
- ) : null} -
-
- - ); -} - -// ── Sub-components ───────────────────────────────────────────────── - -function DetailItem({ - icon, - label, - value, -}: { - icon: React.ReactNode; - label: string; - value: string; -}) { - return ( -
-
{icon}
-
-

{label}

-

- {value} +

+

Activity log

+

+ Platform audit trail of who did what, to which resource, and when. This is separate from + learner progress timelines on user profiles.

-
- ); -} -function truncateUA(ua: string): string { - if (ua.length <= 40) return ua; - return ua.substring(0, 37) + "..."; + +
+ ) } diff --git a/src/pages/user-log/components/ActivityLogListPanel.tsx b/src/pages/user-log/components/ActivityLogListPanel.tsx new file mode 100644 index 0000000..0a264fa --- /dev/null +++ b/src/pages/user-log/components/ActivityLogListPanel.tsx @@ -0,0 +1,666 @@ +import { useCallback, useEffect, useMemo, useState } from "react" +import { Link } from "react-router-dom" +import { + Activity, + ChevronDown, + ChevronLeft, + ChevronRight, + Clock, + Eye, + FileText, + Globe, + Info, + Monitor, + RefreshCw, + Search, + Shield, + User, +} from "lucide-react" +import { toast } from "sonner" +import { + activityLogApiErrorMessage, + getActivityLogById, + getActivityLogs, +} from "../../../api/activity-logs.api" +import { AdminFiltersPanel } from "../../../components/filters/AdminFiltersPanel" +import { Badge } from "../../../components/ui/badge" +import { Button } from "../../../components/ui/button" +import { Input } from "../../../components/ui/input" +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "../../../components/ui/dialog" +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "../../../components/ui/table" +import { SpinnerIcon } from "../../../components/ui/spinner-icon" +import { countActiveFilters } from "../../../lib/adminFilterUtils" +import { + ACTION_FILTER_GROUPS, + RESOURCE_TYPE_OPTIONS, + actionBadgeClasses, + actionLabel, + activityLogResourcePath, + formatActivityDate, + formatActivityTime, + getRelativeActivityTime, + resourceTypeLabel, + toRfc3339EndOfDay, + toRfc3339StartOfDay, +} from "../../../lib/activityLogDisplay" +import { cn } from "../../../lib/utils" +import { TABLE_PAGE_SIZE_OPTIONS } from "../../../lib/tablePagination" +import type { ActivityLog, ActivityLogFilters } from "../../../types/activity-log.types" +import { ActorCell, ActorLabel } from "./ActorLabel" +import { ActorHoverCard } from "./ActorHoverCard" + +export interface ActivityLogListPanelProps { + /** When set, locks the list to actions by this actor (user profile audit tab). */ + fixedActorId?: number + compact?: boolean + showStats?: boolean + /** Enable horizontal scroll for embedded/narrow layouts (e.g. user profile). */ + scrollable?: boolean +} + +function formatRoleLabel(role: string): string { + return role + .split("_") + .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()) + .join(" ") +} + +function truncateUA(ua: string): string { + if (ua.length <= 48) return ua + return `${ua.substring(0, 45)}…` +} + +export function ActivityLogListPanel({ + fixedActorId, + compact = false, + showStats = !compact, + scrollable = false, +}: ActivityLogListPanelProps) { + const [logs, setLogs] = useState([]) + const [loading, setLoading] = useState(false) + const [error, setError] = useState(null) + const [totalCount, setTotalCount] = useState(0) + const [page, setPage] = useState(1) + const [pageSize, setPageSize] = useState(compact ? 10 : 20) + + const [actionFilter, setActionFilter] = useState("") + const [resourceTypeFilter, setResourceTypeFilter] = useState("") + const [resourceIdFilter, setResourceIdFilter] = useState("") + const [searchQuery, setSearchQuery] = useState("") + const [dateAfter, setDateAfter] = useState("") + const [dateBefore, setDateBefore] = useState("") + + const [selectedLog, setSelectedLog] = useState(null) + const [detailLoading, setDetailLoading] = useState(false) + const [dialogOpen, setDialogOpen] = useState(false) + + const serverFilters = useMemo((): ActivityLogFilters => { + const offset = (page - 1) * pageSize + const filters: ActivityLogFilters = { limit: pageSize, offset } + if (fixedActorId != null) filters.actor_id = fixedActorId + if (actionFilter) filters.action = actionFilter + if (resourceTypeFilter) filters.resource_type = resourceTypeFilter + const resourceId = Number(resourceIdFilter) + if (resourceIdFilter.trim() && Number.isFinite(resourceId) && resourceId > 0) { + filters.resource_id = resourceId + } + if (dateAfter) filters.after = toRfc3339StartOfDay(dateAfter) + if (dateBefore) filters.before = toRfc3339EndOfDay(dateBefore) + return filters + }, [ + page, + pageSize, + fixedActorId, + actionFilter, + resourceTypeFilter, + resourceIdFilter, + dateAfter, + dateBefore, + ]) + + const fetchLogs = useCallback(async () => { + setLoading(true) + setError(null) + try { + const data = await getActivityLogs(serverFilters) + setLogs(data.logs) + setTotalCount(data.total_count) + } catch (e) { + console.error("Failed to fetch activity logs:", e) + setLogs([]) + setTotalCount(0) + setError(activityLogApiErrorMessage(e, "Failed to load activity logs")) + toast.error(activityLogApiErrorMessage(e, "Failed to load activity logs")) + } finally { + setLoading(false) + } + }, [serverFilters]) + + useEffect(() => { + void fetchLogs() + }, [fetchLogs]) + + useEffect(() => { + setPage(1) + }, [actionFilter, resourceTypeFilter, resourceIdFilter, dateAfter, dateBefore, fixedActorId, pageSize]) + + const handleViewDetail = async (logId: number) => { + setDialogOpen(true) + setDetailLoading(true) + setSelectedLog(null) + try { + const log = await getActivityLogById(logId) + setSelectedLog(log) + } catch (e) { + console.error("Failed to fetch log detail:", e) + toast.error(activityLogApiErrorMessage(e, "Failed to load log detail")) + setDialogOpen(false) + } finally { + setDetailLoading(false) + } + } + + const clearFilters = () => { + setActionFilter("") + setResourceTypeFilter("") + setResourceIdFilter("") + setDateAfter("") + setDateBefore("") + setSearchQuery("") + setPage(1) + } + + const activeFilterCount = countActiveFilters([ + { value: actionFilter }, + { value: resourceTypeFilter }, + { value: resourceIdFilter }, + { value: dateAfter }, + { value: dateBefore }, + ]) + + const hasActiveFilters = activeFilterCount > 0 || Boolean(searchQuery.trim()) + + const filteredLogs = useMemo(() => { + const q = searchQuery.trim().toLowerCase() + if (!q) return logs + return logs.filter((log) => { + const haystack = [ + log.message, + log.action, + log.actor_name, + log.actor_email, + log.actor_role, + log.resource_type, + log.resource_id != null ? String(log.resource_id) : "", + JSON.stringify(log.metadata ?? {}), + ] + .filter(Boolean) + .join(" ") + .toLowerCase() + return haystack.includes(q) + }) + }, [logs, searchQuery]) + + const pageCount = Math.max(1, Math.ceil(totalCount / pageSize)) + const safePage = Math.min(page, pageCount) + const startEntry = totalCount === 0 ? 0 : (safePage - 1) * pageSize + 1 + const endEntry = Math.min(safePage * pageSize, totalCount) + const showActorColumn = fixedActorId == null + const columnCount = showActorColumn ? 6 : 5 + + return ( +
+ {!compact ? ( +
+ +
+ ) : null} + + {error ? ( +
+ {error} +
+ ) : null} + + {showStats ? ( +
+
+
+ +
+
+

{totalCount.toLocaleString()}

+

Matching entries

+
+
+
+
+ +
+
+

+ {logs[0]?.created_at ? getRelativeActivityTime(logs[0].created_at) : "—"} +

+

Latest on this page

+
+
+
+
+ +
+
+

{filteredLogs.length}

+

Rows after search (this page)

+
+
+
+ ) : null} + + + {!compact ? ( +
+ + setSearchQuery(e.target.value)} + /> +
+ ) : null} + +
+
+ + +
+ +
+ + +
+ + {!fixedActorId ? ( + setResourceIdFilter(e.target.value)} + className="h-9 w-28" + /> + ) : null} + +
+ + setDateAfter(e.target.value)} + className="h-9 rounded-md border bg-white px-3 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500" + /> +
+
+ + setDateBefore(e.target.value)} + className="h-9 rounded-md border bg-white px-3 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500" + /> +
+
+
+ +
+
+ + + + Action + Message + {showActorColumn ? ( + Actor + ) : null} + Resource + Time + Details + + + + {loading ? ( + + +
+ + Loading activity logs… +
+
+
+ ) : filteredLogs.length === 0 ? ( + + +
+ +
+

No activity logs found

+

+ {hasActiveFilters + ? "Try adjusting your filters" + : "Activity will appear here once actions are performed"} +

+
+
+
+
+ ) : ( + filteredLogs.map((log) => ( + + + + {actionLabel(log.action)} + + + +

+ {log.message || "—"} +

+
+ {showActorColumn ? ( + + + + + + ) : null} + + + + +
+

{formatActivityDate(log.created_at)}

+

+ {getRelativeActivityTime(log.created_at)} +

+
+
+ + + +
+ )) + )} +
+
+
+ +
+
+ + Showing {startEntry}–{endEntry} of {totalCount} + + + Rows per page +
+ + +
+
+ +
+ + + Page {safePage} of {pageCount} + + +
+
+
+ + + + + + + Activity log detail + + Full audit entry including request context and metadata. + + + {detailLoading ? ( +
+ +
+ ) : selectedLog ? ( +
+
+ + {actionLabel(selectedLog.action)} + + + ID #{selectedLog.id} + +
+ + {selectedLog.message ? ( +
+

{selectedLog.message}

+
+ ) : null} + +
+ } + label="Actor" + value={} + /> + } + label="Role" + value={ + selectedLog.actor_role ? formatRoleLabel(selectedLog.actor_role) : "—" + } + /> + } + label="Resource" + value={ + + } + /> + } + label="Time" + value={`${formatActivityDate(selectedLog.created_at)} ${formatActivityTime(selectedLog.created_at)}`} + /> + } + label="IP address" + value={selectedLog.ip_address || "—"} + /> + } + label="User agent" + value={ + selectedLog.user_agent ? truncateUA(selectedLog.user_agent) : "—" + } + title={selectedLog.user_agent ?? undefined} + /> +
+ + {Object.keys(selectedLog.metadata ?? {}).length > 0 ? ( +
+

+ Technical details +

+
+
+                      {JSON.stringify(selectedLog.metadata, null, 2)}
+                    
+
+
+ ) : null} +
+ ) : null} +
+
+
+ ) +} + +function ResourceCell({ + log, + linkInDetail = false, +}: { + log: Pick + linkInDetail?: boolean +}) { + const path = activityLogResourcePath(log.resource_type, log.resource_id) + const label = `${resourceTypeLabel(log.resource_type)}${ + log.resource_id != null ? ` #${log.resource_id}` : "" + }` + + if (path && log.resource_id != null) { + return ( + + {label} + + ) + } + + return ( +
+

{resourceTypeLabel(log.resource_type)}

+ {log.resource_id != null ? ( +

#{log.resource_id}

+ ) : null} +
+ ) +} + +function DetailItem({ + icon, + label, + value, + title, +}: { + icon: React.ReactNode + label: string + value: React.ReactNode + title?: string +}) { + return ( +
+
{icon}
+
+

{label}

+

+ {value} +

+
+
+ ) +} diff --git a/src/pages/user-log/components/ActorHoverCard.tsx b/src/pages/user-log/components/ActorHoverCard.tsx index 0c025dc..c6f599c 100644 --- a/src/pages/user-log/components/ActorHoverCard.tsx +++ b/src/pages/user-log/components/ActorHoverCard.tsx @@ -1,5 +1,6 @@ import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react" import { createPortal } from "react-dom" +import { Link } from "react-router-dom" import { Mail, Shield, User } from "lucide-react" import { cn } from "../../../lib/utils" import { @@ -7,18 +8,30 @@ import { formatActorDate, type ActorProfile, } from "../../../lib/activityLogActor" +import { + activityLogActorPath, + formatActorDisplay, + type ActivityLogActorFields, +} from "../../../lib/activityLogDisplay" import { SpinnerIcon } from "../../../components/ui/spinner-icon" const HOVER_DELAY_MS = 280 const HIDE_DELAY_MS = 120 type ActorHoverCardProps = { - actorId: number | null - actorRole: string | null + log: ActivityLogActorFields children: ReactNode } -export function ActorHoverCard({ actorId, actorRole, children }: ActorHoverCardProps) { +function hasApiEnrichment(log: ActivityLogActorFields): boolean { + return Boolean(log.actor_name?.trim() || log.actor_email?.trim()) +} + +function needsProfileFetch(log: ActivityLogActorFields): boolean { + return log.actor_id != null && !hasApiEnrichment(log) +} + +export function ActorHoverCard({ log, children }: ActorHoverCardProps) { const tooltipId = useId() const triggerRef = useRef(null) const showTimerRef = useRef | null>(null) @@ -32,6 +45,9 @@ export function ActorHoverCard({ actorId, actorRole, children }: ActorHoverCardP const [profile, setProfile] = useState(null) const [position, setPosition] = useState({ top: 0, left: 0 }) + const display = formatActorDisplay(log) + const profilePath = activityLogActorPath(log) + const updatePosition = useCallback(() => { const rect = triggerRef.current?.getBoundingClientRect() if (!rect) return @@ -65,12 +81,12 @@ export function ActorHoverCard({ actorId, actorRole, children }: ActorHoverCardP }, [clearTimers]) const loadProfile = useCallback(async () => { - if (actorId == null) return + if (log.actor_id == null || !needsProfileFetch(log)) return const requestId = ++requestRef.current setLoading(true) setError(null) try { - const data = await fetchActorProfile(actorId, actorRole) + const data = await fetchActorProfile(log.actor_id, log.actor_role, log.actor_kind) if (requestId !== requestRef.current) return setProfile(data) } catch { @@ -80,18 +96,18 @@ export function ActorHoverCard({ actorId, actorRole, children }: ActorHoverCardP } finally { if (requestId === requestRef.current) setLoading(false) } - }, [actorId, actorRole]) + }, [log]) const handleEnter = useCallback(() => { - if (actorId == null) return + if (log.actor_id == null) return clearTimers() hideTimerRef.current = setTimeout(() => { updatePosition() setOpen(true) requestAnimationFrame(() => setVisible(true)) - void loadProfile() + if (needsProfileFetch(log)) void loadProfile() }, HOVER_DELAY_MS) - }, [actorId, clearTimers, loadProfile, updatePosition]) + }, [log, clearTimers, loadProfile, updatePosition]) const handleLeave = useCallback(() => { clearTimers() @@ -118,7 +134,7 @@ export function ActorHoverCard({ actorId, actorRole, children }: ActorHoverCardP useEffect(() => () => clearTimers(), [clearTimers]) - if (actorId == null) { + if (log.actor_id == null) { return <>{children} } @@ -157,8 +173,10 @@ export function ActorHoverCard({ actorId, actorRole, children }: ActorHoverCardP ) : error ? (

{error}

) : profile ? ( - - ) : null} + + ) : ( + + )} , document.body, )} @@ -166,7 +184,63 @@ export function ActorHoverCard({ actorId, actorRole, children }: ActorHoverCardP ) } -function ActorProfileContent({ profile }: { profile: ActorProfile }) { +function EnrichedActorContent({ + log, + display, + profilePath, +}: { + log: ActivityLogActorFields + display: ReturnType + profilePath: string | null +}) { + const isTeam = log.actor_kind === "team_member" + + return ( +
+
+
+ {isTeam ? : } +
+
+ {profilePath ? ( + + {display.name} + + ) : ( +

{display.name}

+ )} +

+ {isTeam ? "Team member" : log.actor_kind === "user" ? "User" : "Actor"} + {log.actor_id != null ? ` · #${log.actor_id}` : ""} +

+
+
+ +
+ {display.email ? ( + } label="Email" value={display.email} /> + ) : null} + {display.role ? : null} +
+
+ ) +} + +function ActorProfileContent({ + profile, + profilePath, +}: { + profile: ActorProfile + profilePath: string | null +}) { const isTeam = profile.kind === "team" return ( @@ -181,7 +255,16 @@ function ActorProfileContent({ profile }: { profile: ActorProfile }) { {isTeam ? : }
-

{profile.name}

+ {profilePath ? ( + + {profile.name} + + ) : ( +

{profile.name}

+ )}

{isTeam ? "Team member" : "Learner"} · #{profile.id}

@@ -192,18 +275,13 @@ function ActorProfileContent({ profile }: { profile: ActorProfile }) { } label="Email" value={profile.email} /> - + {profile.kind === "user" ? ( <> @@ -233,14 +311,9 @@ function DetailRow({ )}
-
- {label} -
+
{label}
{value} diff --git a/src/pages/user-log/components/ActorLabel.tsx b/src/pages/user-log/components/ActorLabel.tsx new file mode 100644 index 0000000..e683893 --- /dev/null +++ b/src/pages/user-log/components/ActorLabel.tsx @@ -0,0 +1,104 @@ +import { useEffect, useState } from "react" +import { Link } from "react-router-dom" +import { User } from "lucide-react" +import { fetchActorProfile } from "../../../lib/activityLogActor" +import { + activityLogActorPath, + formatActorDisplay, + formatActorFallback, + type ActivityLogActorFields, +} from "../../../lib/activityLogDisplay" + +function formatRoleLabel(role: string): string { + return role + .split("_") + .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()) + .join(" ") +} + +function needsActorFetch(log: ActivityLogActorFields): boolean { + return log.actor_id != null && !log.actor_name?.trim() && !log.actor_email?.trim() +} + +export function ActorLabel({ + log, + className, + linkToProfile = false, +}: { + log: ActivityLogActorFields + className?: string + linkToProfile?: boolean +}) { + const [fallbackName, setFallbackName] = useState(null) + const [loading, setLoading] = useState(false) + + useEffect(() => { + if (!needsActorFetch(log)) { + setFallbackName(null) + return + } + + let cancelled = false + setLoading(true) + void fetchActorProfile(log.actor_id!, log.actor_role, log.actor_kind) + .then((profile) => { + if (!cancelled) setFallbackName(profile.name) + }) + .catch(() => { + if (!cancelled) setFallbackName(null) + }) + .finally(() => { + if (!cancelled) setLoading(false) + }) + + return () => { + cancelled = true + } + }, [log.actor_id, log.actor_role, log.actor_kind, log.actor_name, log.actor_email]) + + const display = formatActorDisplay(log) + const name = + display.name !== "System" && !display.name.startsWith("#") + ? display.name + : fallbackName ?? display.name + const label = loading && needsActorFetch(log) ? "Loading…" : name + + const profilePath = linkToProfile ? activityLogActorPath(log) : null + if (profilePath) { + return ( + + {label} + + ) + } + + return ( + + {label} + + ) +} + +export function ActorCell({ + log, +}: { + log: ActivityLogActorFields +}) { + const display = formatActorDisplay(log) + + return ( +
+
+ +
+
+

+ +

+ {display.role ? ( +

{formatRoleLabel(display.role)}

+ ) : null} +
+
+ ) +} diff --git a/src/pages/user-management/UserDetailPage.tsx b/src/pages/user-management/UserDetailPage.tsx index c2ca838..004c315 100644 --- a/src/pages/user-management/UserDetailPage.tsx +++ b/src/pages/user-management/UserDetailPage.tsx @@ -28,7 +28,9 @@ import { SpinnerIcon } from "../../components/ui/spinner-icon"; import type { UserProfileData, UserRecentActivityItem } from "../../types/user.types"; import type { UserLearningActivityData, UserSubscriptionsData } from "../../types/userAdmin.types"; import { UserLearningActivitySection } from "./components/UserLearningActivitySection"; +import { UserAccountActivitySection } from "./components/UserAccountActivitySection"; import { UserSubscriptionsSection } from "./components/UserSubscriptionsSection"; +import { displayValue, NOT_ASSIGNED_LABEL } from "../../lib/displayValue"; const activityIcons = { completed: CheckCircle2, @@ -45,14 +47,9 @@ function visualActivityKind(kind: string): keyof typeof activityIcons { return "default"; } -function displayValue(value: string | null | undefined): string { - const trimmed = value?.trim(); - return trimmed ? trimmed : "—"; -} - function formatRoleLabel(role: string): string { const value = role.trim(); - if (!value) return "—"; + if (!value) return NOT_ASSIGNED_LABEL; return value .split("_") .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()) @@ -61,7 +58,7 @@ function formatRoleLabel(role: string): string { function formatStatusLabel(status: string): string { const value = status.trim(); - if (!value) return "—"; + if (!value) return NOT_ASSIGNED_LABEL; return value .split("_") .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()) @@ -70,12 +67,12 @@ function formatStatusLabel(status: string): string { function formatAgeGroup(ageGroup: string): string { const value = ageGroup.trim(); - if (!value) return "—"; + if (!value) return NOT_ASSIGNED_LABEL; return value.replace(/_/g, "-"); } function formatDate(dateStr: string | null | undefined): string { - if (!dateStr?.trim()) return "—"; + if (!dateStr?.trim()) return NOT_ASSIGNED_LABEL; const date = new Date(dateStr); if (Number.isNaN(date.getTime())) return dateStr; return date.toLocaleDateString(undefined, { @@ -85,10 +82,10 @@ function formatDate(dateStr: string | null | undefined): string { }); } -function formatDateTime(value?: string | null): string { - if (!value?.trim()) return "—"; +function formatDateTime(value?: string | null, emptyLabel = NOT_ASSIGNED_LABEL): string { + if (!value?.trim()) return emptyLabel; const parsed = new Date(value); - if (Number.isNaN(parsed.getTime())) return "—"; + if (Number.isNaN(parsed.getTime())) return NOT_ASSIGNED_LABEL; return parsed.toLocaleString(undefined, { month: "short", day: "numeric", @@ -375,7 +372,7 @@ export function UserDetailPage() {
- + @@ -414,7 +411,7 @@ export function UserDetailPage() { />
-
+
@@ -456,6 +453,8 @@ export function UserDetailPage() { error={learningActivityError} /> + +
diff --git a/src/pages/user-management/components/UserAccountActivitySection.tsx b/src/pages/user-management/components/UserAccountActivitySection.tsx new file mode 100644 index 0000000..902da8e --- /dev/null +++ b/src/pages/user-management/components/UserAccountActivitySection.tsx @@ -0,0 +1,48 @@ +import { useState } from "react" +import { ChevronDown, ChevronRight, ClipboardList } from "lucide-react" +import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card" +import { ActivityLogListPanel } from "../../user-log/components/ActivityLogListPanel" + +export function UserAccountActivitySection({ userId }: { userId: number }) { + const [open, setOpen] = useState(false) + + return ( + + + + + {open ? ( + + + + ) : null} + + ) +} diff --git a/src/pages/user-management/components/UserLearningActivitySection.tsx b/src/pages/user-management/components/UserLearningActivitySection.tsx index cddf7f0..4b18c66 100644 --- a/src/pages/user-management/components/UserLearningActivitySection.tsx +++ b/src/pages/user-management/components/UserLearningActivitySection.tsx @@ -213,6 +213,7 @@ export function UserLearningActivitySection({ loading: boolean; error: string | null; }) { + const [open, setOpen] = useState(false); const [track, setTrack] = useState("lms"); const programs = activity?.lms.progress.programs ?? []; const catalogCourses = activity?.exam_prep.progress.catalog_courses ?? []; @@ -258,40 +259,58 @@ export function UserLearningActivitySection({ return ( -
-
-
+ - -
-
+ {open ? ( + + ) : ( + + )} + - + {open ? ( + +
+
+ + +
+
{loading ? (
@@ -395,7 +414,8 @@ export function UserLearningActivitySection({ {!loading && !error && !activity ? (

No learning activity available.

) : null} - + + ) : null} ); } diff --git a/src/pages/user-management/components/UserSubscriptionsSection.tsx b/src/pages/user-management/components/UserSubscriptionsSection.tsx index 8ade4e3..4fda5e0 100644 --- a/src/pages/user-management/components/UserSubscriptionsSection.tsx +++ b/src/pages/user-management/components/UserSubscriptionsSection.tsx @@ -1,4 +1,5 @@ -import { CreditCard, RefreshCw } from "lucide-react"; +import { useState } from "react"; +import { ChevronDown, ChevronRight, CreditCard, RefreshCw } from "lucide-react"; import { Badge } from "../../../components/ui/badge"; import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card"; import { Separator } from "../../../components/ui/separator"; @@ -13,11 +14,12 @@ import { } from "../../../components/ui/table"; import { cn } from "../../../lib/utils"; import { formatPlanCategory } from "../../../lib/subscriptionPlans"; +import { displayValue, NOT_ASSIGNED_LABEL } from "../../../lib/displayValue"; import type { UserSubscriptionsData } from "../../../types/userAdmin.types"; function formatStatusLabel(status: string): string { const value = status.trim(); - if (!value) return "—"; + if (!value) return NOT_ASSIGNED_LABEL; return value .split("_") .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()) @@ -29,9 +31,9 @@ function formatCategoryLabel(value: string): string { } function formatDateTime(value?: string | null): string { - if (!value?.trim()) return "—"; + if (!value?.trim()) return NOT_ASSIGNED_LABEL; const parsed = new Date(value); - if (Number.isNaN(parsed.getTime())) return "—"; + if (Number.isNaN(parsed.getTime())) return NOT_ASSIGNED_LABEL; return parsed.toLocaleString(undefined, { month: "short", day: "numeric", @@ -56,14 +58,14 @@ function getSubscriptionStatusClasses(status: string): string { } function formatDuration(value: number, unit: string): string { - if (!value) return "—"; + if (!value) return NOT_ASSIGNED_LABEL; const label = unit.trim().toLowerCase(); const plural = value === 1 ? label.replace(/s$/, "") : label.endsWith("s") ? label : `${label}s`; return `${value} ${plural}`; } function formatMoney(amount: number, currency: string): string { - if (!Number.isFinite(amount)) return "—"; + if (!Number.isFinite(amount)) return NOT_ASSIGNED_LABEL; const code = currency.trim() || "ETB"; return `${amount.toLocaleString()} ${code}`; } @@ -77,26 +79,45 @@ export function UserSubscriptionsSection({ loading: boolean; error: string | null; }) { + const [open, setOpen] = useState(false); const recentPayments = subscriptions?.payments.slice(0, 8) ?? []; return ( -
-
-
+
+
+ {!open && subscriptions ? ( + + {formatStatusLabel(subscriptions.display_status)} + + ) : null} + {open ? ( + + ) : ( + + )} +
+ - + {open ? ( + {loading ? (
@@ -108,6 +129,13 @@ export function UserSubscriptionsSection({ {!loading && !error && subscriptions ? ( <> +
+ Overall status + + {formatStatusLabel(subscriptions.display_status)} + +
+
Active subscription @@ -182,7 +210,7 @@ export function UserSubscriptionsSection({

Payment: - {subscription.payment_method || "—"} + {displayValue(subscription.payment_method)}

@@ -217,7 +245,7 @@ export function UserSubscriptionsSection({ {recentPayments.map((payment) => ( - {payment.plan_name || "—"} + {displayValue(payment.plan_name)} {formatMoney(payment.amount, payment.currency)} @@ -228,7 +256,7 @@ export function UserSubscriptionsSection({ - {payment.payment_method || "—"} + {displayValue(payment.payment_method)} {formatDateTime(payment.paid_at || payment.created_at)} @@ -247,7 +275,8 @@ export function UserSubscriptionsSection({ {!loading && !error && !subscriptions ? (

No subscription data available.

) : null} - + + ) : null} ); } diff --git a/src/types/activity-log.types.ts b/src/types/activity-log.types.ts index e3443fe..c32787a 100644 --- a/src/types/activity-log.types.ts +++ b/src/types/activity-log.types.ts @@ -1,14 +1,19 @@ +export type ActivityLogActorKind = "user" | "team_member" + export interface ActivityLog { id: number - actor_id: number | null - actor_role: string | null + actor_id?: number | null + actor_role?: string | null + actor_name?: string | null + actor_email?: string | null + actor_kind?: ActivityLogActorKind | null action: string resource_type: string - resource_id: number | null - message: string | null - metadata: Record | null - ip_address: string | null - user_agent: string | null + resource_id?: number | null + message?: string | null + metadata: Record + ip_address?: string | null + user_agent?: string | null created_at: string }