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 <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-06-20 03:59:24 -07:00
parent 15ec068f2f
commit 53cdb5060a
17 changed files with 1868 additions and 961 deletions

View File

@ -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<GetActivityLogsResponse>("/activity-logs", {
params: filters,
});
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value)
}
export const getActivityLogById = (id: number) =>
http.get<GetActivityLogResponse>(`/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<string, string | number> {
const params: Record<string, string | number> = {
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<ActivityLogListData> {
const res = await http.get<GetActivityLogsResponse>("/activity-logs", {
params: buildQueryParams(filters),
})
return parseActivityLogList(res.data)
}
export async function getActivityLogById(id: number): Promise<ActivityLog> {
const res = await http.get<GetActivityLogResponse>(`/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)
}

View File

@ -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)
) {

View File

@ -1,12 +1,19 @@
import * as React from "react"
import { cn } from "../../lib/utils"
export const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
type TableProps = React.HTMLAttributes<HTMLTableElement> & {
/** Render only the `<table>` element (for use inside an external scroll container). */
noWrapper?: boolean
}
export const Table = React.forwardRef<HTMLTableElement, TableProps>(
({ className, noWrapper = false, ...props }, ref) => {
const table = (
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
</div>
),
)
if (noWrapper) return table
return <div className="relative w-full overflow-auto">{table}</div>
},
)
Table.displayName = "Table"

View File

@ -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<ActorProfile> {
export async function fetchActorProfile(
actorId: number,
actorRole: string | null | undefined,
actorKind?: "user" | "team_member" | null,
): Promise<ActorProfile> {
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<ActorProfile> => {
const key = cacheKey(actorId, target)

View File

@ -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<string, string> = {
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<string, ActionBadgeTone> = {
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()
}

View File

@ -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)
}

6
src/lib/displayValue.ts Normal file
View File

@ -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
}

View File

@ -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 (
<div className="flex items-start gap-3 py-3.5">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-grayScale-50">
<Icon className="h-4 w-4 text-grayScale-500" />
</div>
<div className="min-w-0 flex-1">
<p className="text-xs font-medium uppercase tracking-wide text-grayScale-400">{label}</p>
<p className="mt-0.5 break-words text-sm font-medium text-grayScale-800">{value}</p>
</div>
</div>
)
}
function StatTile({
icon: Icon,
label,
value,
}: {
icon: React.ComponentType<{ className?: string }>
label: string
value: string
}) {
return (
<div className="rounded-xl border border-grayScale-100 bg-white px-4 py-3.5 shadow-soft">
<div className="flex items-center gap-2 text-grayScale-500">
<Icon className="h-3.5 w-3.5" />
<span className="text-xs font-medium">{label}</span>
</div>
<p className="mt-1.5 text-sm font-semibold text-grayScale-800">{value}</p>
</div>
)
}
function LoadingSkeleton() {
return (
<div className="mx-auto w-full max-w-4xl space-y-5">
<div className="space-y-6">
<div className="h-5 w-32 animate-pulse rounded bg-grayScale-100" />
<div className="h-8 w-56 animate-pulse rounded-lg bg-grayScale-100" />
<div className="h-24 animate-pulse rounded-xl bg-grayScale-100" />
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{[1, 2, 3, 4].map((item) => (
<div key={item} className="h-20 animate-pulse rounded-xl bg-grayScale-100" />
))}
<div className="grid gap-6 lg:grid-cols-[340px_1fr]">
<div className="space-y-6">
<div className="h-80 animate-pulse rounded-2xl bg-grayScale-100" />
<div className="h-48 animate-pulse rounded-2xl bg-grayScale-100" />
</div>
<div className="space-y-6">
<div className="h-56 animate-pulse rounded-2xl bg-grayScale-100" />
<div className="h-72 animate-pulse rounded-2xl bg-grayScale-100" />
</div>
</div>
</div>
)
}
function InfoItem({ label, value }: { label: string; value: string }) {
return (
<div>
<p className="mb-1 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
{label}
</p>
<p className="text-sm text-grayScale-700">{value}</p>
</div>
)
}
function InfoRow({ label, value }: { label: string; value: string }) {
return (
<div className="flex items-center justify-between gap-3">
<span className="text-sm text-grayScale-500">{label}</span>
<span className="text-right text-sm font-medium text-grayScale-700">{value}</span>
</div>
)
}
function ContactField({
icon: Icon,
label,
value,
}: {
icon: React.ComponentType<{ className?: string }>
label: string
value: string
}) {
return (
<div className="flex items-center gap-3">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-grayScale-100">
<Icon className="h-4 w-4 text-grayScale-400" />
</div>
<div className="min-w-0">
<p className="text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
{label}
</p>
<p className="truncate text-sm text-grayScale-700">{value}</p>
</div>
<div className="h-72 animate-pulse rounded-xl bg-grayScale-100" />
</div>
)
}
@ -184,7 +209,7 @@ export function TeamMemberDetailPage() {
if (error || !member) {
return (
<div className="mx-auto w-full max-w-4xl space-y-5">
<div className="mx-auto w-full max-w-3xl space-y-4 py-12">
<Link
to="/team"
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
@ -192,7 +217,7 @@ export function TeamMemberDetailPage() {
<ArrowLeft className="h-4 w-4" />
Back to Team
</Link>
<Card>
<Card className="shadow-soft">
<CardContent className="flex flex-col items-center gap-4 p-10">
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-grayScale-100">
<User className="h-8 w-8 text-grayScale-300" />
@ -200,6 +225,9 @@ export function TeamMemberDetailPage() {
<p className="text-lg font-semibold text-grayScale-600">
{error || "Member not found"}
</p>
<Button asChild variant="outline" className="mt-2">
<Link to="/team">Back to Team</Link>
</Button>
</CardContent>
</Card>
</div>
@ -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 (
<div className="mx-auto w-full max-w-4xl space-y-5">
<div className="space-y-6">
<Link
to="/team"
className="inline-flex items-center gap-2 text-sm font-medium text-grayScale-500 transition-colors hover:text-brand-600"
@ -221,101 +249,144 @@ export function TeamMemberDetailPage() {
</Link>
<div>
<p className="text-sm font-semibold text-grayScale-500">Team directory</p>
<p className="text-sm font-semibold text-grayScale-500">Team members</p>
<h1 className="text-2xl font-semibold tracking-tight text-grayScale-800">{fullName}</h1>
<p className="mt-1 text-sm text-grayScale-500">
Member #{member.id} · {displayValue(member.department)}
Member #{member.id}
{member.department?.trim() ? ` · ${member.department.trim()}` : ""}
</p>
</div>
<Card className="border-grayScale-100 shadow-soft">
<CardContent className="flex flex-col gap-4 p-5 sm:flex-row sm:items-center">
<Avatar className="h-14 w-14 shrink-0">
<AvatarFallback className="bg-grayScale-100 text-base font-semibold text-grayScale-600">
{initials || "?"}
</AvatarFallback>
</Avatar>
<div className="grid gap-6 lg:grid-cols-[340px_1fr]">
<div className="space-y-6">
<Card className="overflow-hidden shadow-soft">
<CardContent className="space-y-5 p-5">
<div className="flex items-center gap-4">
<Avatar className="h-16 w-16 shrink-0">
<AvatarFallback className="bg-brand-100 text-lg font-semibold text-brand-600">
{initials || "?"}
</AvatarFallback>
</Avatar>
<div className="min-w-0">
<h2 className="truncate text-lg font-semibold text-grayScale-800">{fullName}</h2>
<p className="truncate text-sm text-grayScale-500">
{displayValue(member.job_title)}
</p>
<div className="mt-2 flex flex-wrap gap-2">
<span
className={cn(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium",
getRoleBadgeClasses(member.team_role),
)}
>
<Shield className="mr-1 h-3 w-3" />
{roleLabel}
</span>
<Badge className={cn(getStatusClasses(member.status))}>
{formatStatusLabel(member.status)}
</Badge>
</div>
</div>
</div>
<div className="min-w-0 flex-1">
<p className="text-lg font-semibold text-grayScale-800">{fullName}</p>
<p className="text-sm text-grayScale-500">{displayValue(member.job_title)}</p>
</div>
<Separator />
<div className="flex flex-wrap items-center gap-2 sm:justify-end">
<span
className={cn(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium",
getRoleBadgeClasses(member.team_role),
)}
>
<Shield className="mr-1 h-3 w-3" />
{formatRoleLabel(member.team_role)}
</span>
<Badge variant={isActive ? "default" : "secondary"}>
{formatStatusLabel(member.status)}
</Badge>
<Badge variant={member.email_verified ? "default" : "outline"}>
{member.email_verified ? "Verified" : "Unverified"}
</Badge>
</div>
</CardContent>
</Card>
<div className="space-y-3">
<ContactField icon={Mail} label="Email" value={displayValue(member.email)} />
<ContactField icon={Phone} label="Phone" value={displayValue(member.phone_number)} />
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<StatTile icon={CalendarDays} label="Joined" value={formatDate(member.created_at)} />
<StatTile icon={Clock3} label="Last login" value={formatDateTime(member.last_login)} />
<StatTile
icon={BadgeCheck}
label="Email status"
value={member.email_verified ? "Verified" : "Not verified"}
/>
<StatTile icon={Clock3} label="Last updated" value={formatDateTime(member.updated_at)} />
<Separator />
<div className="grid gap-3 text-sm">
<InfoRow label="Email verified" value={member.email_verified ? "Yes" : "No"} />
<InfoRow label="Joined" value={formatDate(member.created_at)} />
<InfoRow label="Last login" value={formatDateTime(member.last_login, "Never")} />
<InfoRow label="Last updated" value={formatDateTime(member.updated_at)} />
</div>
</CardContent>
</Card>
<Card className="shadow-soft">
<CardHeader className="pb-3">
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-100/50">
<Clock3 className="h-4 w-4 text-brand-600" />
</div>
<CardTitle className="text-base">Activity summary</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-4">
<InfoRow label="Member ID" value={`#${member.id}`} />
<InfoRow label="Last seen" value={getRelativeTime(member.last_login)} />
<InfoRow
label="Verification"
value={member.email_verified ? "Verified" : "Pending verification"}
/>
<InfoRow label="Account status" value={formatStatusLabel(member.status)} />
</CardContent>
</Card>
</div>
<div className="space-y-6">
<Card className="shadow-soft">
<CardHeader className="pb-3">
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-mint-100/60">
<UsersRound className="h-4 w-4 text-mint-600" />
</div>
<CardTitle className="text-base">Role & organization</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-5">
<div className="grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-3">
<InfoItem label="Team role" value={roleLabel} />
<InfoItem label="Department" value={displayValue(member.department)} />
<InfoItem label="Job title" value={displayValue(member.job_title)} />
<InfoItem label="Member ID" value={String(member.id)} />
<InfoItem label="Joined" value={formatDate(member.created_at)} />
<InfoItem
label="Email status"
value={member.email_verified ? "Verified" : "Not verified"}
/>
</div>
{member.bio?.trim() ? (
<>
<Separator />
<div>
<p className="mb-2 text-[11px] font-medium uppercase tracking-wider text-grayScale-400">
Bio
</p>
<div className="rounded-xl bg-grayScale-100 p-4 text-sm leading-relaxed text-grayScale-700">
{member.bio.trim()}
</div>
</div>
</>
) : null}
</CardContent>
</Card>
<Card className="shadow-soft">
<CardHeader className="pb-3">
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-slate-100/80">
<ClipboardList className="h-4 w-4 text-slate-600" />
</div>
<div>
<CardTitle className="text-base">Account activity</CardTitle>
<p className="mt-0.5 text-xs text-grayScale-500">
Platform audit trail for actions performed by this team member.
</p>
</div>
</div>
</CardHeader>
<CardContent>
<ActivityLogListPanel fixedActorId={member.id} compact showStats={false} />
</CardContent>
</Card>
</div>
</div>
<Card className="border-grayScale-100 shadow-soft">
<CardHeader className="pb-2">
<CardTitle className="text-base">Member record</CardTitle>
</CardHeader>
<CardContent className="pt-0">
{member.bio ? (
<div className="mb-4 rounded-lg border border-grayScale-100 bg-grayScale-50/60 px-4 py-3">
<p className="text-xs font-medium uppercase tracking-wide text-grayScale-400">Bio</p>
<p className="mt-1 text-sm leading-relaxed text-grayScale-700">{member.bio}</p>
</div>
) : null}
<div className="grid gap-0 md:grid-cols-2 md:gap-x-8">
<div>
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-400">
Contact
</p>
<DetailRow icon={Mail} label="Email" value={displayValue(member.email)} />
<Separator />
<DetailRow icon={Phone} label="Phone" value={displayValue(member.phone_number)} />
</div>
<div>
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-grayScale-400">
Role & organization
</p>
<DetailRow icon={Shield} label="Team role" value={formatRoleLabel(member.team_role)} />
<Separator />
<DetailRow icon={Building2} label="Department" value={displayValue(member.department)} />
<Separator />
<DetailRow icon={Briefcase} label="Job title" value={displayValue(member.job_title)} />
<Separator />
<DetailRow icon={Hash} label="Member ID" value={String(member.id)} />
</div>
</div>
<Separator className="my-4" />
<div className="flex items-center gap-2 text-xs text-grayScale-400">
<UserCircle2 className="h-3.5 w-3.5" />
<span>Read-only team directory record</span>
</div>
</CardContent>
</Card>
</div>
)
}

View File

@ -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<ActivityLog[]>([]);
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<ActivityLog | null>(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 (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-grayScale-600">Activity Log</h1>
<p className="text-sm text-grayScale-400">
Track all actions and changes made across the platform.
</p>
</div>
<Button
variant="outline"
className="gap-2"
onClick={() => {
setPage(1);
fetchLogs();
}}
>
{loading ? <SpinnerIcon className="h-4 w-4" /> : <RefreshCw className="h-4 w-4" />}
Refresh
</Button>
</div>
{/* Stats cards */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<div className="flex items-center gap-4 rounded-xl border bg-white p-4">
<div className="grid h-10 w-10 place-items-center rounded-lg bg-brand-100 text-brand-600">
<Activity className="h-5 w-5" />
</div>
<div>
<p className="text-2xl font-bold text-grayScale-600">{totalCount}</p>
<p className="text-xs text-grayScale-400">Total Logs</p>
</div>
</div>
<div className="flex items-center gap-4 rounded-xl border bg-white p-4">
<div className="grid h-10 w-10 place-items-center rounded-lg bg-emerald-100 text-emerald-600">
<Clock className="h-5 w-5" />
</div>
<div>
<p className="text-2xl font-bold text-grayScale-600">
{logs.length > 0 ? getRelativeTime(logs[0].created_at) : "—"}
</p>
<p className="text-xs text-grayScale-400">Latest Activity</p>
</div>
</div>
<div className="flex items-center gap-4 rounded-xl border bg-white p-4">
<div className="grid h-10 w-10 place-items-center rounded-lg bg-amber-100 text-amber-600">
<FileText className="h-5 w-5" />
</div>
<div>
<p className="text-2xl font-bold text-grayScale-600">{filteredLogs.length}</p>
<p className="text-xs text-grayScale-400">Showing Results</p>
</div>
</div>
</div>
<AdminFiltersPanel
activeFilterCount={activeFilterCount}
onClearFilters={clearFilters}
search={
<div className="relative w-full">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
<Input
placeholder="Search by message, action, or role..."
className="pl-9"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
}
>
<div className="flex flex-wrap items-center gap-3">
<div className="relative">
<select
value={actionFilter}
onChange={(e) => {
setActionFilter(e.target.value);
setPage(1);
}}
className="h-9 appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
>
<option value="">Action: All</option>
{ACTION_TYPES.map((action) => (
<option key={action} value={action}>
{formatActionLabel(action)}
</option>
))}
</select>
<ChevronDown className="absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
</div>
<div className="flex items-center gap-2">
<label className="text-xs font-medium text-grayScale-400">From</label>
<input
type="date"
value={dateAfter}
onChange={(e) => {
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"
/>
</div>
<div className="flex items-center gap-2">
<label className="text-xs font-medium text-grayScale-400">To</label>
<input
type="date"
value={dateBefore}
onChange={(e) => {
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"
/>
</div>
</div>
</AdminFiltersPanel>
{/* Table */}
<div className="rounded-xl border bg-white">
<Table>
<TableHeader>
<TableRow>
<TableHead>ACTION</TableHead>
<TableHead>MESSAGE</TableHead>
<TableHead>ACTOR</TableHead>
<TableHead>RESOURCE</TableHead>
<TableHead>TIMESTAMP</TableHead>
<TableHead className="text-right">DETAILS</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={6} className="text-center py-12">
<div className="flex flex-col items-center gap-3">
<img src={spinnerSrc} alt="" className="h-6 w-6 animate-spin" />
<span className="text-sm text-grayScale-400">Loading activity logs...</span>
</div>
</TableCell>
</TableRow>
) : filteredLogs.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="text-center py-12">
<div className="flex flex-col items-center gap-3">
<Activity className="h-8 w-8 text-grayScale-200" />
<div>
<p className="text-sm font-medium text-grayScale-500">No activity logs found</p>
<p className="text-xs text-grayScale-400 mt-1">
{hasActiveFilters
? "Try adjusting your filters"
: "Activity will appear here once actions are performed"}
</p>
</div>
</div>
</TableCell>
</TableRow>
) : (
paginatedLogs.map((log) => {
const ActionIcon = getActionIcon(log.action);
return (
<TableRow key={log.id} className="group">
<TableCell>
<div className="flex items-center gap-2.5">
<div className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-grayScale-50 text-grayScale-400 group-hover:bg-brand-500 group-hover:text-white transition-colors">
<ActionIcon className="h-4 w-4" />
</div>
<span
className={cn(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium whitespace-nowrap",
getActionBadgeClasses(log.action)
)}
>
{formatActionLabel(log.action)}
</span>
</div>
</TableCell>
<TableCell>
<p className="text-sm text-grayScale-600 max-w-[280px] truncate">
{log.message || "—"}
</p>
</TableCell>
<TableCell>
<ActorHoverCard
actorId={log.actor_id}
actorRole={log.actor_role}
>
<div className="flex items-center gap-2 rounded-lg px-1 py-0.5 transition-colors hover:bg-grayScale-50">
<div className="grid h-7 w-7 shrink-0 place-items-center rounded-full bg-grayScale-100 text-grayScale-500">
<User className="h-3.5 w-3.5" />
</div>
<div>
<p className="text-sm font-medium text-grayScale-600">
ID: {log.actor_id ?? "System"}
</p>
{log.actor_role && (
<p className="text-xs text-grayScale-400">
{formatRoleLabel(log.actor_role)}
</p>
)}
</div>
</div>
</ActorHoverCard>
</TableCell>
<TableCell>
<div>
<p className="text-sm text-grayScale-600">{log.resource_type}</p>
{log.resource_id !== null && (
<p className="text-xs text-grayScale-400">#{log.resource_id}</p>
)}
</div>
</TableCell>
<TableCell>
<div>
<p className="text-sm text-grayScale-600">{formatDate(log.created_at)}</p>
<p className="text-xs text-grayScale-400">
{getRelativeTime(log.created_at)}
</p>
</div>
</TableCell>
<TableCell className="text-right">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 opacity-0 group-hover:opacity-100 transition-opacity"
onClick={() => handleViewDetail(log.id)}
>
<Eye className="h-4 w-4 text-grayScale-400" />
</Button>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
{/* Pagination */}
<div className="flex flex-wrap items-center justify-between gap-3 border-t px-4 py-3 text-sm text-grayScale-500">
<div className="flex items-center gap-2">
<span>Showing</span>
<span className="font-medium text-grayScale-600">
{startEntry}–{endEntry}
</span>
<span>of</span>
<span className="font-medium text-grayScale-600">{totalCount}</span>
<span className="mr-4">entries</span>
<span className="border-l pl-4">Rows per page</span>
<div className="relative">
<select
value={pageSize}
onChange={(e) => {
setPageSize(Number(e.target.value));
setPage(1);
}}
className="h-8 appearance-none rounded-md border bg-white pl-2 pr-7 text-sm font-medium text-grayScale-600 focus:outline-none"
>
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
<option key={size} value={size}>
{size}
</option>
))}
</select>
<ChevronDown className="absolute right-2 top-1/2 h-3 w-3 -translate-y-1/2 text-grayScale-400 pointer-events-none" />
</div>
</div>
<div className="flex items-center gap-1">
<button
onClick={handlePrev}
disabled={safePage === 1}
className={cn(
"h-8 w-8 flex items-center justify-center rounded-md border bg-white text-grayScale-500",
safePage === 1 && "opacity-50 cursor-not-allowed"
)}
>
<ChevronLeft className="h-4 w-4" />
</button>
{getPageNumbers().map((n, idx) =>
typeof n === "string" ? (
<span key={`ellipsis-${idx}`} className="px-2 text-grayScale-400">
...
</span>
) : (
<button
key={n}
type="button"
onClick={() => setPage(n)}
className={cn(
"h-8 w-8 rounded-md border text-sm font-medium",
n === safePage
? "border-brand-500 bg-brand-500 text-white"
: "bg-white text-grayScale-600 hover:bg-grayScale-50"
)}
>
{n}
</button>
)
)}
<button
onClick={handleNext}
disabled={safePage === pageCount}
className={cn(
"h-8 w-8 flex items-center justify-center rounded-md border bg-white text-grayScale-500",
safePage === pageCount && "opacity-50 cursor-not-allowed"
)}
>
<ChevronRight className="h-4 w-4" />
</button>
</div>
</div>
</div>
{/* Detail Dialog */}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Info className="h-5 w-5 text-brand-500" />
Activity Log Detail
</DialogTitle>
<DialogDescription>
Full details for this activity log entry.
</DialogDescription>
</DialogHeader>
{detailLoading ? (
<div className="flex items-center justify-center py-8">
<SpinnerIcon className="h-6 w-6" />
</div>
) : selectedLog ? (
<div className="space-y-4">
{/* Action badge */}
<div className="flex items-center gap-2">
<span
className={cn(
"inline-flex items-center rounded-full border px-3 py-1 text-xs font-semibold",
getActionBadgeClasses(selectedLog.action)
)}
>
{formatActionLabel(selectedLog.action)}
</span>
<Badge variant="secondary" className="text-xs">
ID #{selectedLog.id}
</Badge>
</div>
{/* Message */}
{selectedLog.message && (
<div className="rounded-lg bg-grayScale-50 p-3">
<p className="text-sm text-grayScale-600">{selectedLog.message}</p>
</div>
)}
{/* Detail grid */}
<div className="grid grid-cols-2 gap-3 text-sm">
<DetailItem
icon={<User className="h-4 w-4" />}
label="Actor"
value={`ID: ${selectedLog.actor_id ?? "System"}`}
/>
<DetailItem
icon={<Shield className="h-4 w-4" />}
label="Role"
value={selectedLog.actor_role ? formatRoleLabel(selectedLog.actor_role) : "—"}
/>
<DetailItem
icon={<FileText className="h-4 w-4" />}
label="Resource"
value={`${selectedLog.resource_type}${selectedLog.resource_id !== null ? ` #${selectedLog.resource_id}` : ""}`}
/>
<DetailItem
icon={<Clock className="h-4 w-4" />}
label="Time"
value={`${formatDate(selectedLog.created_at)} ${formatTime(selectedLog.created_at)}`}
/>
<DetailItem
icon={<Globe className="h-4 w-4" />}
label="IP Address"
value={selectedLog.ip_address || "—"}
/>
<DetailItem
icon={<Monitor className="h-4 w-4" />}
label="User Agent"
value={selectedLog.user_agent ? truncateUA(selectedLog.user_agent) : "—"}
/>
</div>
{/* Metadata */}
{selectedLog.metadata && Object.keys(selectedLog.metadata).length > 0 && (
<div>
<p className="text-xs font-semibold uppercase tracking-wider text-grayScale-400 mb-2">
Metadata
</p>
<div className="rounded-lg border bg-grayScale-50 p-3">
<pre className="text-xs text-grayScale-600 whitespace-pre-wrap break-words font-mono">
{JSON.stringify(selectedLog.metadata, null, 2)}
</pre>
</div>
</div>
)}
</div>
) : null}
</DialogContent>
</Dialog>
</div>
);
}
// ── Sub-components ─────────────────────────────────────────────────
function DetailItem({
icon,
label,
value,
}: {
icon: React.ReactNode;
label: string;
value: string;
}) {
return (
<div className="flex items-start gap-2.5 rounded-lg border bg-white p-2.5">
<div className="mt-0.5 text-grayScale-400">{icon}</div>
<div className="min-w-0">
<p className="text-xs text-grayScale-400">{label}</p>
<p className="text-sm font-medium text-grayScale-600 truncate" title={value}>
{value}
<div>
<h1 className="text-2xl font-bold text-grayScale-600">Activity log</h1>
<p className="text-sm text-grayScale-400">
Platform audit trail of who did what, to which resource, and when. This is separate from
learner progress timelines on user profiles.
</p>
</div>
</div>
);
}
function truncateUA(ua: string): string {
if (ua.length <= 40) return ua;
return ua.substring(0, 37) + "...";
<ActivityLogListPanel />
</div>
)
}

View File

@ -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<ActivityLog[]>([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(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<ActivityLog | null>(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 (
<div className={cn("space-y-4", scrollable && "min-w-0")}>
{!compact ? (
<div className="flex items-center justify-end">
<Button variant="outline" className="gap-2" disabled={loading} onClick={() => void fetchLogs()}>
{loading ? <SpinnerIcon className="h-4 w-4" /> : <RefreshCw className="h-4 w-4" />}
Refresh
</Button>
</div>
) : null}
{error ? (
<div className="rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2 text-sm text-destructive">
{error}
</div>
) : null}
{showStats ? (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<div className="flex items-center gap-4 rounded-xl border bg-white p-4">
<div className="grid h-10 w-10 place-items-center rounded-lg bg-brand-100 text-brand-600">
<Activity className="h-5 w-5" />
</div>
<div>
<p className="text-2xl font-bold text-grayScale-600">{totalCount.toLocaleString()}</p>
<p className="text-xs text-grayScale-400">Matching entries</p>
</div>
</div>
<div className="flex items-center gap-4 rounded-xl border bg-white p-4">
<div className="grid h-10 w-10 place-items-center rounded-lg bg-emerald-100 text-emerald-600">
<Clock className="h-5 w-5" />
</div>
<div>
<p className="text-2xl font-bold text-grayScale-600">
{logs[0]?.created_at ? getRelativeActivityTime(logs[0].created_at) : "—"}
</p>
<p className="text-xs text-grayScale-400">Latest on this page</p>
</div>
</div>
<div className="flex items-center gap-4 rounded-xl border bg-white p-4">
<div className="grid h-10 w-10 place-items-center rounded-lg bg-amber-100 text-amber-600">
<FileText className="h-5 w-5" />
</div>
<div>
<p className="text-2xl font-bold text-grayScale-600">{filteredLogs.length}</p>
<p className="text-xs text-grayScale-400">Rows after search (this page)</p>
</div>
</div>
</div>
) : null}
<AdminFiltersPanel activeFilterCount={activeFilterCount} onClearFilters={clearFilters}>
{!compact ? (
<div className="relative w-full">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
<Input
placeholder="Search message, action, or metadata on this page…"
className="pl-9"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
) : null}
<div className="flex flex-wrap items-center gap-3">
<div className="relative">
<select
value={actionFilter}
onChange={(e) => setActionFilter(e.target.value)}
className="h-9 max-w-[220px] appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
>
<option value="">Action: All</option>
{ACTION_FILTER_GROUPS.map((group) => (
<optgroup key={group.label} label={group.label}>
{group.actions.map((action) => (
<option key={action} value={action}>
{actionLabel(action)}
</option>
))}
</optgroup>
))}
</select>
<ChevronDown className="pointer-events-none absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
</div>
<div className="relative">
<select
value={resourceTypeFilter}
onChange={(e) => setResourceTypeFilter(e.target.value)}
className="h-9 max-w-[200px] appearance-none rounded-md border bg-white pl-3 pr-8 text-sm text-grayScale-600 focus:outline-none focus:ring-1 focus:ring-brand-500"
>
<option value="">Resource: All</option>
{RESOURCE_TYPE_OPTIONS.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
<ChevronDown className="pointer-events-none absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 text-grayScale-400" />
</div>
{!fixedActorId ? (
<Input
type="number"
min={1}
placeholder="Resource ID"
value={resourceIdFilter}
onChange={(e) => setResourceIdFilter(e.target.value)}
className="h-9 w-28"
/>
) : null}
<div className="flex items-center gap-2">
<label className="text-xs font-medium text-grayScale-400">From</label>
<input
type="date"
value={dateAfter}
onChange={(e) => 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"
/>
</div>
<div className="flex items-center gap-2">
<label className="text-xs font-medium text-grayScale-400">To</label>
<input
type="date"
value={dateBefore}
onChange={(e) => 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"
/>
</div>
</div>
</AdminFiltersPanel>
<div className="rounded-xl border bg-white">
<div
className={cn(
scrollable && "min-w-0 w-full max-w-full overflow-x-auto",
)}
>
<Table
noWrapper={scrollable}
className={cn(scrollable && "min-w-[920px]")}
>
<TableHeader>
<TableRow>
<TableHead className={cn(scrollable && "whitespace-nowrap")}>Action</TableHead>
<TableHead className={cn(scrollable && "whitespace-nowrap")}>Message</TableHead>
{showActorColumn ? (
<TableHead className={cn(scrollable && "whitespace-nowrap")}>Actor</TableHead>
) : null}
<TableHead className={cn(scrollable && "whitespace-nowrap")}>Resource</TableHead>
<TableHead className={cn(scrollable && "whitespace-nowrap")}>Time</TableHead>
<TableHead className={cn("text-right", scrollable && "whitespace-nowrap")}>Details</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={columnCount} className="py-12 text-center">
<div className="flex flex-col items-center gap-3">
<SpinnerIcon className="h-6 w-6 text-brand-500" />
<span className="text-sm text-grayScale-400">Loading activity logs…</span>
</div>
</TableCell>
</TableRow>
) : filteredLogs.length === 0 ? (
<TableRow>
<TableCell colSpan={columnCount} className="py-12 text-center">
<div className="flex flex-col items-center gap-3">
<Activity className="h-8 w-8 text-grayScale-200" />
<div>
<p className="text-sm font-medium text-grayScale-500">No activity logs found</p>
<p className="mt-1 text-xs text-grayScale-400">
{hasActiveFilters
? "Try adjusting your filters"
: "Activity will appear here once actions are performed"}
</p>
</div>
</div>
</TableCell>
</TableRow>
) : (
filteredLogs.map((log) => (
<TableRow key={log.id} className="group">
<TableCell>
<span
className={cn(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium whitespace-nowrap",
actionBadgeClasses(log.action),
)}
>
{actionLabel(log.action)}
</span>
</TableCell>
<TableCell className={cn(scrollable && "whitespace-nowrap")}>
<p
className={cn(
"text-sm text-grayScale-600",
scrollable ? "whitespace-nowrap" : "max-w-[280px] truncate",
)}
>
{log.message || "—"}
</p>
</TableCell>
{showActorColumn ? (
<TableCell className={cn(scrollable && "whitespace-nowrap")}>
<ActorHoverCard log={log}>
<ActorCell log={log} />
</ActorHoverCard>
</TableCell>
) : null}
<TableCell className={cn(scrollable && "whitespace-nowrap")}>
<ResourceCell log={log} />
</TableCell>
<TableCell className={cn(scrollable && "whitespace-nowrap")}>
<div>
<p className="text-sm text-grayScale-600">{formatActivityDate(log.created_at)}</p>
<p className="text-xs text-grayScale-400" title={formatActivityTime(log.created_at)}>
{getRelativeActivityTime(log.created_at)}
</p>
</div>
</TableCell>
<TableCell className={cn("text-right", scrollable && "whitespace-nowrap")}>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 opacity-0 transition-opacity group-hover:opacity-100"
onClick={() => void handleViewDetail(log.id)}
>
<Eye className="h-4 w-4 text-grayScale-400" />
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
<div className="flex flex-wrap items-center justify-between gap-3 border-t px-4 py-3 text-sm text-grayScale-500">
<div className="flex items-center gap-2">
<span>
Showing {startEntry}–{endEntry} of {totalCount}
</span>
<span className="hidden h-4 w-px bg-grayScale-200 sm:inline" />
<span className="hidden sm:inline">Rows per page</span>
<div className="relative">
<select
value={pageSize}
onChange={(e) => setPageSize(Number(e.target.value))}
className="h-8 appearance-none rounded-md border bg-white pl-2 pr-7 text-sm font-medium text-grayScale-600 focus:outline-none"
>
{TABLE_PAGE_SIZE_OPTIONS.map((size) => (
<option key={size} value={size}>
{size}
</option>
))}
</select>
<ChevronDown className="pointer-events-none absolute right-2 top-1/2 h-3 w-3 -translate-y-1/2 text-grayScale-400" />
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={safePage <= 1 || loading}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
<ChevronLeft className="mr-1 h-4 w-4" />
Previous
</Button>
<span className="text-xs text-grayScale-500">
Page {safePage} of {pageCount}
</span>
<Button
variant="outline"
size="sm"
disabled={safePage >= pageCount || loading}
onClick={() => setPage((p) => p + 1)}
>
Next
<ChevronRight className="ml-1 h-4 w-4" />
</Button>
</div>
</div>
</div>
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Info className="h-5 w-5 text-brand-500" />
Activity log detail
</DialogTitle>
<DialogDescription>Full audit entry including request context and metadata.</DialogDescription>
</DialogHeader>
{detailLoading ? (
<div className="flex items-center justify-center py-8">
<SpinnerIcon className="h-6 w-6" />
</div>
) : selectedLog ? (
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-2">
<span
className={cn(
"inline-flex items-center rounded-full border px-3 py-1 text-xs font-semibold",
actionBadgeClasses(selectedLog.action),
)}
>
{actionLabel(selectedLog.action)}
</span>
<Badge variant="secondary" className="text-xs">
ID #{selectedLog.id}
</Badge>
</div>
{selectedLog.message ? (
<div className="rounded-lg bg-grayScale-50 p-3">
<p className="text-sm text-grayScale-600">{selectedLog.message}</p>
</div>
) : null}
<div className="grid grid-cols-2 gap-3 text-sm">
<DetailItem
icon={<User className="h-4 w-4" />}
label="Actor"
value={<ActorLabel log={selectedLog} linkToProfile />}
/>
<DetailItem
icon={<Shield className="h-4 w-4" />}
label="Role"
value={
selectedLog.actor_role ? formatRoleLabel(selectedLog.actor_role) : "—"
}
/>
<DetailItem
icon={<FileText className="h-4 w-4" />}
label="Resource"
value={
<ResourceCell log={selectedLog} linkInDetail />
}
/>
<DetailItem
icon={<Clock className="h-4 w-4" />}
label="Time"
value={`${formatActivityDate(selectedLog.created_at)} ${formatActivityTime(selectedLog.created_at)}`}
/>
<DetailItem
icon={<Globe className="h-4 w-4" />}
label="IP address"
value={selectedLog.ip_address || "—"}
/>
<DetailItem
icon={<Monitor className="h-4 w-4" />}
label="User agent"
value={
selectedLog.user_agent ? truncateUA(selectedLog.user_agent) : "—"
}
title={selectedLog.user_agent ?? undefined}
/>
</div>
{Object.keys(selectedLog.metadata ?? {}).length > 0 ? (
<div>
<p className="mb-2 text-xs font-semibold uppercase tracking-wider text-grayScale-400">
Technical details
</p>
<div className="rounded-lg border bg-grayScale-50 p-3">
<pre className="whitespace-pre-wrap break-words font-mono text-xs text-grayScale-600">
{JSON.stringify(selectedLog.metadata, null, 2)}
</pre>
</div>
</div>
) : null}
</div>
) : null}
</DialogContent>
</Dialog>
</div>
)
}
function ResourceCell({
log,
linkInDetail = false,
}: {
log: Pick<ActivityLog, "resource_type" | "resource_id">
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 (
<Link
to={path}
className={cn(
"text-sm font-medium text-brand-600 hover:text-brand-700",
linkInDetail ? "inline" : "block",
)}
>
{label}
</Link>
)
}
return (
<div>
<p className="text-sm text-grayScale-600">{resourceTypeLabel(log.resource_type)}</p>
{log.resource_id != null ? (
<p className="text-xs text-grayScale-400">#{log.resource_id}</p>
) : null}
</div>
)
}
function DetailItem({
icon,
label,
value,
title,
}: {
icon: React.ReactNode
label: string
value: React.ReactNode
title?: string
}) {
return (
<div className="flex items-start gap-2.5 rounded-lg border bg-white p-2.5">
<div className="mt-0.5 text-grayScale-400">{icon}</div>
<div className="min-w-0">
<p className="text-xs text-grayScale-400">{label}</p>
<p className="truncate text-sm font-medium text-grayScale-600" title={title}>
{value}
</p>
</div>
</div>
)
}

View File

@ -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<HTMLDivElement>(null)
const showTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@ -32,6 +45,9 @@ export function ActorHoverCard({ actorId, actorRole, children }: ActorHoverCardP
const [profile, setProfile] = useState<ActorProfile | null>(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 ? (
<p className="py-4 text-center text-sm text-grayScale-500">{error}</p>
) : profile ? (
<ActorProfileContent profile={profile} />
) : null}
<ActorProfileContent profile={profile} profilePath={profilePath} />
) : (
<EnrichedActorContent log={log} display={display} profilePath={profilePath} />
)}
</div>,
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<typeof formatActorDisplay>
profilePath: string | null
}) {
const isTeam = log.actor_kind === "team_member"
return (
<div className="space-y-3">
<div className="flex items-start gap-3">
<div
className={cn(
"grid h-10 w-10 shrink-0 place-items-center rounded-lg",
isTeam ? "bg-brand-50 text-brand-600" : "bg-mint-50 text-mint-700",
)}
>
{isTeam ? <Shield className="h-5 w-5" /> : <User className="h-5 w-5" />}
</div>
<div className="min-w-0 flex-1">
{profilePath ? (
<Link
to={profilePath}
className="truncate text-sm font-semibold text-brand-600 hover:text-brand-700"
>
{display.name}
</Link>
) : (
<p className="truncate text-sm font-semibold text-grayScale-900">{display.name}</p>
)}
<p className="text-[11px] font-medium uppercase tracking-wide text-grayScale-400">
{isTeam ? "Team member" : log.actor_kind === "user" ? "User" : "Actor"}
{log.actor_id != null ? ` · #${log.actor_id}` : ""}
</p>
</div>
</div>
<dl className="space-y-2 text-sm">
{display.email ? (
<DetailRow icon={<Mail className="h-3.5 w-3.5" />} label="Email" value={display.email} />
) : null}
{display.role ? <DetailRow label="Role" value={display.role.replace(/_/g, " ")} capitalize /> : null}
</dl>
</div>
)
}
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 ? <Shield className="h-5 w-5" /> : <User className="h-5 w-5" />}
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold text-grayScale-900">{profile.name}</p>
{profilePath ? (
<Link
to={profilePath}
className="truncate text-sm font-semibold text-brand-600 hover:text-brand-700"
>
{profile.name}
</Link>
) : (
<p className="truncate text-sm font-semibold text-grayScale-900">{profile.name}</p>
)}
<p className="text-[11px] font-medium uppercase tracking-wide text-grayScale-400">
{isTeam ? "Team member" : "Learner"} · #{profile.id}
</p>
@ -192,18 +275,13 @@ function ActorProfileContent({ profile }: { profile: ActorProfile }) {
<DetailRow icon={<Mail className="h-3.5 w-3.5" />} label="Email" value={profile.email} />
<DetailRow label="Role" value={profile.roleLabel} />
<DetailRow label="Status" value={profile.status} capitalize />
<DetailRow
label="Email verified"
value={profile.emailVerified ? "Yes" : "No"}
/>
<DetailRow label="Email verified" value={profile.emailVerified ? "Yes" : "No"} />
{profile.kind === "user" ? (
<>
<DetailRow label="Location" value={`${profile.region}, ${profile.country}`} />
<DetailRow
label="Last login"
value={
profile.lastLogin ? formatActorDate(profile.lastLogin) : "Never"
}
value={profile.lastLogin ? formatActorDate(profile.lastLogin) : "Never"}
/>
<DetailRow label="Subscription" value={profile.subscriptionStatus} />
</>
@ -233,14 +311,9 @@ function DetailRow({
<span className="w-3.5 shrink-0" />
)}
<div className="min-w-0 flex-1">
<dt className="text-[10px] font-bold uppercase tracking-wider text-grayScale-400">
{label}
</dt>
<dt className="text-[10px] font-bold uppercase tracking-wider text-grayScale-400">{label}</dt>
<dd
className={cn(
"truncate font-medium text-grayScale-700",
capitalize && "capitalize",
)}
className={cn("truncate font-medium text-grayScale-700", capitalize && "capitalize")}
title={value}
>
{value}

View File

@ -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<string | null>(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 (
<Link to={profilePath} className={className} title={formatActorFallback(log)}>
{label}
</Link>
)
}
return (
<span className={className} title={formatActorFallback(log)}>
{label}
</span>
)
}
export function ActorCell({
log,
}: {
log: ActivityLogActorFields
}) {
const display = formatActorDisplay(log)
return (
<div className="flex items-center gap-2">
<div className="grid h-7 w-7 shrink-0 place-items-center rounded-full bg-grayScale-100 text-grayScale-500">
<User className="h-3.5 w-3.5" />
</div>
<div className="min-w-0">
<p className="truncate text-sm font-medium text-grayScale-600">
<ActorLabel log={log} />
</p>
{display.role ? (
<p className="truncate text-xs text-grayScale-400">{formatRoleLabel(display.role)}</p>
) : null}
</div>
</div>
)
}

View File

@ -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() {
<div className="grid gap-3 text-sm">
<InfoRow label="Joined" value={formatDate(user.created_at)} />
<InfoRow label="Last login" value={formatDateTime(user.last_login)} />
<InfoRow label="Last login" value={formatDateTime(user.last_login, "Never")} />
<InfoRow label="Gender" value={displayValue(user.gender)} />
<InfoRow label="Birthday" value={formatDate(user.birth_day)} />
<InfoRow label="Occupation" value={displayValue(user.occupation)} />
@ -414,7 +411,7 @@ export function UserDetailPage() {
/>
</div>
<div className="space-y-6">
<div className="min-w-0 space-y-6">
<Card className="shadow-soft">
<CardHeader className="pb-3">
<div className="flex items-center gap-2">
@ -456,6 +453,8 @@ export function UserDetailPage() {
error={learningActivityError}
/>
<UserAccountActivitySection userId={user.id} />
<Card className="shadow-soft">
<CardHeader className="pb-3">
<div className="flex items-center gap-2">

View File

@ -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 (
<Card className="min-w-0 shadow-soft">
<CardHeader className="pb-3">
<button
type="button"
className="flex w-full items-start justify-between gap-3 text-left"
onClick={() => setOpen((prev) => !prev)}
aria-expanded={open}
>
<div className="flex items-start gap-2">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-slate-100/80">
<ClipboardList className="h-4 w-4 text-slate-600" />
</div>
<div>
<CardTitle className="text-base">Account activity</CardTitle>
<p className="mt-0.5 text-xs text-grayScale-500">
Platform audit trail for actions performed by this user (not learning milestones).
</p>
</div>
</div>
{open ? (
<ChevronDown className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
) : (
<ChevronRight className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
)}
</button>
</CardHeader>
{open ? (
<CardContent className="min-w-0 overflow-hidden p-6 pt-0">
<ActivityLogListPanel
fixedActorId={userId}
compact
showStats={false}
scrollable
/>
</CardContent>
) : null}
</Card>
)
}

View File

@ -213,6 +213,7 @@ export function UserLearningActivitySection({
loading: boolean;
error: string | null;
}) {
const [open, setOpen] = useState(false);
const [track, setTrack] = useState<Track>("lms");
const programs = activity?.lms.progress.programs ?? [];
const catalogCourses = activity?.exam_prep.progress.catalog_courses ?? [];
@ -258,40 +259,58 @@ export function UserLearningActivitySection({
return (
<Card className="shadow-soft">
<CardHeader className="pb-3">
<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-sky-100/70">
<button
type="button"
className="flex w-full items-start justify-between gap-3 text-left"
onClick={() => setOpen((prev) => !prev)}
aria-expanded={open}
>
<div className="flex items-start gap-2">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-sky-100/70">
<BarChart3 className="h-4 w-4 text-sky-600" />
</div>
<CardTitle className="text-base">Learning activity</CardTitle>
<div>
<CardTitle className="text-base">Learning activity</CardTitle>
<p className="mt-0.5 text-xs text-grayScale-500">
LMS and exam prep progress trees for this learner.
</p>
</div>
</div>
<div className="flex rounded-lg border border-grayScale-200 p-1">
<button
type="button"
className={cn(
"rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
track === "lms" ? "bg-brand-500 text-white" : "text-grayScale-500 hover:text-grayScale-700",
)}
onClick={() => setTrack("lms")}
>
Learn English
</button>
<button
type="button"
className={cn(
"rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
track === "exam_prep"
? "bg-brand-500 text-white"
: "text-grayScale-500 hover:text-grayScale-700",
)}
onClick={() => setTrack("exam_prep")}
>
Exam prep
</button>
</div>
</div>
{open ? (
<ChevronDown className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
) : (
<ChevronRight className="mt-1 h-4 w-4 shrink-0 text-grayScale-400" />
)}
</button>
</CardHeader>
<CardContent className="space-y-4">
{open ? (
<CardContent className="space-y-4">
<div className="flex justify-end">
<div className="flex rounded-lg border border-grayScale-200 p-1">
<button
type="button"
className={cn(
"rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
track === "lms" ? "bg-brand-500 text-white" : "text-grayScale-500 hover:text-grayScale-700",
)}
onClick={() => setTrack("lms")}
>
Learn English
</button>
<button
type="button"
className={cn(
"rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
track === "exam_prep"
? "bg-brand-500 text-white"
: "text-grayScale-500 hover:text-grayScale-700",
)}
onClick={() => setTrack("exam_prep")}
>
Exam prep
</button>
</div>
</div>
{loading ? (
<div className="flex items-center gap-2 rounded-lg border border-grayScale-200 bg-grayScale-100 px-3 py-2 text-xs text-grayScale-500">
<SpinnerIcon className="h-3.5 w-3.5" />
@ -395,7 +414,8 @@ export function UserLearningActivitySection({
{!loading && !error && !activity ? (
<p className="py-6 text-center text-sm text-grayScale-400">No learning activity available.</p>
) : null}
</CardContent>
</CardContent>
) : null}
</Card>
);
}

View File

@ -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 (
<Card className="shadow-soft">
<CardHeader className="pb-3">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-100/50">
<button
type="button"
className="flex w-full items-start justify-between gap-3 text-left"
onClick={() => setOpen((prev) => !prev)}
aria-expanded={open}
>
<div className="flex items-start gap-2">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-brand-100/50">
<CreditCard className="h-4 w-4 text-brand-600" />
</div>
<CardTitle className="text-base">Subscriptions</CardTitle>
<div>
<CardTitle className="text-base">Subscriptions</CardTitle>
<p className="mt-0.5 text-xs text-grayScale-500">
Active plans, billing history, and payment records for this user.
</p>
</div>
</div>
{subscriptions ? (
<Badge className={cn(getSubscriptionStatusClasses(subscriptions.display_status))}>
{formatStatusLabel(subscriptions.display_status)}
</Badge>
) : null}
</div>
<div className="flex shrink-0 items-center gap-2">
{!open && subscriptions ? (
<Badge className={cn(getSubscriptionStatusClasses(subscriptions.display_status))}>
{formatStatusLabel(subscriptions.display_status)}
</Badge>
) : null}
{open ? (
<ChevronDown className="mt-1 h-4 w-4 text-grayScale-400" />
) : (
<ChevronRight className="mt-1 h-4 w-4 text-grayScale-400" />
)}
</div>
</button>
</CardHeader>
<CardContent className="space-y-4">
{open ? (
<CardContent className="space-y-4">
{loading ? (
<div className="flex items-center gap-2 text-sm text-grayScale-400">
<SpinnerIcon className="h-4 w-4" />
@ -108,6 +129,13 @@ export function UserSubscriptionsSection({
{!loading && !error && subscriptions ? (
<>
<div className="flex items-center justify-between gap-3">
<span className="text-sm text-grayScale-500">Overall status</span>
<Badge className={cn(getSubscriptionStatusClasses(subscriptions.display_status))}>
{formatStatusLabel(subscriptions.display_status)}
</Badge>
</div>
<div className="flex items-center justify-between gap-3 text-sm">
<span className="text-grayScale-500">Active subscription</span>
<span className="font-medium text-grayScale-700">
@ -182,7 +210,7 @@ export function UserSubscriptionsSection({
</p>
<p>
<span className="text-grayScale-400">Payment: </span>
{subscription.payment_method || "—"}
{displayValue(subscription.payment_method)}
</p>
<p className="inline-flex items-center gap-1">
<RefreshCw className="h-3 w-3 text-grayScale-400" />
@ -217,7 +245,7 @@ export function UserSubscriptionsSection({
{recentPayments.map((payment) => (
<TableRow key={payment.id}>
<TableCell className="text-sm text-grayScale-700">
{payment.plan_name || "—"}
{displayValue(payment.plan_name)}
</TableCell>
<TableCell className="text-sm text-grayScale-700">
{formatMoney(payment.amount, payment.currency)}
@ -228,7 +256,7 @@ export function UserSubscriptionsSection({
</Badge>
</TableCell>
<TableCell className="text-xs text-grayScale-500">
{payment.payment_method || "—"}
{displayValue(payment.payment_method)}
</TableCell>
<TableCell className="text-xs text-grayScale-500">
{formatDateTime(payment.paid_at || payment.created_at)}
@ -247,7 +275,8 @@ export function UserSubscriptionsSection({
{!loading && !error && !subscriptions ? (
<p className="text-sm text-grayScale-400">No subscription data available.</p>
) : null}
</CardContent>
</CardContent>
) : null}
</Card>
);
}

View File

@ -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<string, unknown> | null
ip_address: string | null
user_agent: string | null
resource_id?: number | null
message?: string | null
metadata: Record<string, unknown>
ip_address?: string | null
user_agent?: string | null
created_at: string
}