Files
Minikura/apps/web/app/dashboard/users/page.tsx
T

443 lines
14 KiB
TypeScript
Raw Normal View History

2026-02-13 15:52:13 +07:00
"use client";
2026-08-13 01:58:19 +07:00
import { Ban, CheckCircle, Edit, ShieldCheck, Trash2, UserRoundCheck, Users } from "lucide-react";
2026-08-13 03:29:33 +07:00
import { getErrorMessage } from "@minikura/shared/errors";
import { useCallback, useEffect, useRef, useState } from "react";
2026-08-13 01:58:19 +07:00
import { ConfirmDialog } from "@/components/confirm-dialog";
import { DataTable, type DataTableColumn } from "@/components/data-table";
import { PageHeader, PageShell, StatePanel } from "@/components/page-layout";
import { SectionCard, TableActions } from "@/components/section-card";
import { StatStrip } from "@/components/stat-strip";
import { StatusBadge } from "@/components/status-badge";
2026-02-13 15:52:13 +07:00
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
2026-02-17 18:12:02 +07:00
import { api } from "@/lib/api-client";
import { getUserApi } from "@/lib/api-helpers";
2026-02-13 15:52:13 +07:00
import { useSession } from "@/lib/auth-client";
type User = {
id: string;
name: string;
email: string;
role: string;
2026-08-13 03:29:33 +07:00
createdAt: Date | string;
2026-02-13 15:52:13 +07:00
emailVerified: boolean;
isSuspended: boolean;
2026-08-13 03:29:33 +07:00
banned: boolean;
suspendedUntil: Date | string | null;
2026-02-13 15:52:13 +07:00
};
2026-08-13 03:29:33 +07:00
function formatDateTime(value: Date | string): string {
return new Intl.DateTimeFormat(undefined, {
dateStyle: "medium",
timeStyle: "short",
timeZoneName: "short",
}).format(new Date(value));
}
function localDateTimeMinimum(): string {
const now = new Date(Date.now() + 60_000);
const local = new Date(now.getTime() - now.getTimezoneOffset() * 60_000);
return local.toISOString().slice(0, 16);
}
2026-02-13 15:52:13 +07:00
export default function UsersPage() {
const { data: session } = useSession();
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
const [editingUser, setEditingUser] = useState<User | null>(null);
const [suspendingUser, setSuspendingUser] = useState<User | null>(null);
const [deleteUser, setDeleteUser] = useState<User | null>(null);
2026-08-13 03:29:33 +07:00
const [error, setError] = useState<string | null>(null);
const [pendingAction, setPendingAction] = useState<string | null>(null);
const fetchSequence = useRef(0);
2026-02-13 15:52:13 +07:00
const fetchUsers = useCallback(async () => {
2026-08-13 03:29:33 +07:00
const sequence = ++fetchSequence.current;
setLoading(true);
setError(null);
2026-02-13 15:52:13 +07:00
try {
2026-08-13 01:58:19 +07:00
const { data, error } = await api.api.users.get();
2026-08-13 03:29:33 +07:00
if (error) throw error;
if (!data) throw new Error("The user directory returned no data");
if (sequence === fetchSequence.current) setUsers(data);
} catch (requestError) {
if (sequence === fetchSequence.current) setError(getErrorMessage(requestError));
2026-02-13 15:52:13 +07:00
} finally {
2026-08-13 03:29:33 +07:00
if (sequence === fetchSequence.current) setLoading(false);
2026-02-13 15:52:13 +07:00
}
}, []);
useEffect(() => {
fetchUsers();
}, [fetchUsers]);
const handleEdit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!editingUser) return;
const formData = new FormData(e.currentTarget);
const name = formData.get("name") as string;
2026-08-13 03:29:33 +07:00
const role =
editingUser.id === session?.user?.id
? editingUser.role
: String(formData.get("role") || editingUser.role);
2026-02-13 15:52:13 +07:00
2026-08-13 03:29:33 +07:00
if (editingUser.id === session?.user?.id && role !== "admin") {
setError("You cannot remove your own administrator access.");
return;
}
setPendingAction(`edit:${editingUser.id}`);
setError(null);
2026-02-13 15:52:13 +07:00
try {
const { error } = await api.api.users({ id: editingUser.id }).patch({
name,
role: role as "admin" | "user",
});
2026-08-13 03:29:33 +07:00
if (error) throw error;
setEditingUser(null);
await fetchUsers();
} catch (requestError) {
setError(getErrorMessage(requestError));
} finally {
setPendingAction(null);
}
2026-02-13 15:52:13 +07:00
};
const handleSuspend = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!suspendingUser) return;
const formData = new FormData(e.currentTarget);
const suspendedUntil = formData.get("suspendedUntil") as string;
2026-08-13 03:29:33 +07:00
if (suspendingUser.id === session?.user?.id) {
setError("You cannot suspend your own account.");
return;
}
const suspensionDate = suspendedUntil ? new Date(suspendedUntil) : null;
if (
suspensionDate &&
(Number.isNaN(suspensionDate.getTime()) || suspensionDate <= new Date())
) {
setError("Suspension end time must be in the future.");
return;
}
setPendingAction(`suspend:${suspendingUser.id}`);
setError(null);
2026-02-13 15:52:13 +07:00
try {
const { error } = await getUserApi(suspendingUser.id).suspension.patch({
isSuspended: true,
2026-08-13 03:29:33 +07:00
suspendedUntil: suspensionDate?.toISOString() || null,
2026-02-13 15:52:13 +07:00
});
2026-08-13 03:29:33 +07:00
if (error) throw error;
setSuspendingUser(null);
await fetchUsers();
} catch (requestError) {
setError(getErrorMessage(requestError));
} finally {
setPendingAction(null);
}
2026-02-13 15:52:13 +07:00
};
const handleUnsuspend = async (userId: string) => {
2026-08-13 03:29:33 +07:00
setPendingAction(`unsuspend:${userId}`);
setError(null);
2026-02-13 15:52:13 +07:00
try {
const { error } = await getUserApi(userId).suspension.patch({
isSuspended: false,
suspendedUntil: null,
});
2026-08-13 03:29:33 +07:00
if (error) throw error;
await fetchUsers();
} catch (requestError) {
setError(getErrorMessage(requestError));
} finally {
setPendingAction(null);
}
2026-02-13 15:52:13 +07:00
};
const handleDelete = async () => {
if (!deleteUser) return;
2026-08-13 03:29:33 +07:00
if (deleteUser.id === session?.user?.id) {
setError("You cannot delete your own account.");
setDeleteUser(null);
return;
}
2026-02-13 15:52:13 +07:00
2026-08-13 03:29:33 +07:00
setPendingAction(`delete:${deleteUser.id}`);
setError(null);
2026-02-13 15:52:13 +07:00
try {
const { error } = await api.api.users({ id: deleteUser.id }).delete();
2026-08-13 03:29:33 +07:00
if (error) throw error;
setDeleteUser(null);
await fetchUsers();
} catch (requestError) {
setError(getErrorMessage(requestError));
} finally {
setPendingAction(null);
}
2026-02-13 15:52:13 +07:00
};
const isUserSuspended = (user: User): boolean => {
2026-08-13 03:29:33 +07:00
if (user.banned) return true;
2026-02-13 15:52:13 +07:00
if (!user.isSuspended) return false;
if (user.suspendedUntil && new Date(user.suspendedUntil) <= new Date()) {
return false;
}
return true;
};
2026-08-13 01:58:19 +07:00
const columns: readonly DataTableColumn<User>[] = [
{ id: "name", header: "Name", cell: (user) => user.name, className: "font-bold" },
{
id: "email",
header: "Email",
cell: (user) => user.email,
className: "font-mono text-xs text-muted-foreground",
},
{
id: "role",
header: "Role",
cell: (user) => (
<Badge variant={user.role === "admin" ? "default" : "secondary"}>{user.role}</Badge>
),
},
{
id: "status",
header: "Status",
cell: (user) =>
isUserSuspended(user) ? (
<StatusBadge tone="error">
2026-08-13 03:29:33 +07:00
{user.banned ? "Banned" : "Suspended"}
{!user.banned && user.suspendedUntil && ` until ${formatDateTime(user.suspendedUntil)}`}
2026-08-13 01:58:19 +07:00
</StatusBadge>
) : (
<StatusBadge tone={user.emailVerified ? "success" : "warning"}>
{user.emailVerified ? "Active" : "Unverified"}
</StatusBadge>
),
},
{
id: "created",
header: "Created",
cell: (user) => new Date(user.createdAt).toLocaleDateString(),
className: "text-muted-foreground",
},
{
id: "actions",
header: "Actions",
headerClassName: "text-right",
className: "text-right",
cell: (user) => (
<TableActions>
<Button
variant="ghost"
size="icon"
2026-08-13 03:29:33 +07:00
disabled={pendingAction !== null}
2026-08-13 01:58:19 +07:00
onClick={() => setEditingUser(user)}
aria-label={`Edit ${user.name}`}
>
<Edit />
</Button>
2026-08-13 03:29:33 +07:00
{user.banned ? null : isUserSuspended(user) ? (
2026-08-13 01:58:19 +07:00
<Button
variant="ghost"
size="icon"
2026-08-13 03:29:33 +07:00
disabled={pendingAction !== null}
2026-08-13 01:58:19 +07:00
onClick={() => handleUnsuspend(user.id)}
aria-label={`Restore ${user.name}`}
>
<CheckCircle />
</Button>
) : (
<Button
variant="ghost"
size="icon"
2026-08-13 03:29:33 +07:00
disabled={user.id === session?.user?.id || pendingAction !== null}
2026-08-13 01:58:19 +07:00
onClick={() => setSuspendingUser(user)}
aria-label={`Suspend ${user.name}`}
>
<Ban />
</Button>
)}
<Button
variant="ghost"
size="icon"
2026-08-13 03:29:33 +07:00
disabled={user.id === session?.user?.id || pendingAction !== null}
2026-08-13 01:58:19 +07:00
onClick={() => setDeleteUser(user)}
aria-label={`Delete ${user.name}`}
>
<Trash2 />
</Button>
</TableActions>
),
},
];
2026-02-13 15:52:13 +07:00
return (
2026-08-13 01:58:19 +07:00
<PageShell>
<PageHeader
eyebrow="Directory"
title="Users"
description="Control operator access, roles, and account status."
actions={
!loading && (
<StatStrip
items={[
{ label: "Total", value: users.length, icon: Users },
{
label: "Admins",
value: users.filter((user) => user.role === "admin").length,
icon: ShieldCheck,
},
{
label: "Active",
value: users.filter((user) => !isUserSuspended(user)).length,
icon: UserRoundCheck,
tone: "positive",
},
]}
/>
)
}
/>
2026-02-13 15:52:13 +07:00
2026-08-13 03:29:33 +07:00
{error && !loading && (
<div
role="alert"
className="flex flex-col gap-3 border border-destructive/50 bg-destructive/10 p-4 text-sm sm:flex-row sm:items-center sm:justify-between"
>
<span>{error}</span>
<Button variant="outline" size="sm" onClick={() => void fetchUsers()}>
Retry
</Button>
</div>
)}
2026-08-13 01:58:19 +07:00
{loading ? (
<StatePanel loading title="Loading directory..." className="h-64" />
) : (
<SectionCard
title="Access Registry"
description="All identities authorized in this control plane."
>
<DataTable data={users} columns={columns} getRowKey={(user) => user.id} />
</SectionCard>
)}
2026-02-13 15:52:13 +07:00
<Dialog open={!!editingUser} onOpenChange={() => setEditingUser(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit User</DialogTitle>
<DialogDescription>Update user information and role</DialogDescription>
</DialogHeader>
<form onSubmit={handleEdit}>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="name">Name</Label>
<Input id="name" name="name" defaultValue={editingUser?.name} required />
</div>
<div className="space-y-2">
<Label htmlFor="role">Role</Label>
2026-08-13 03:29:33 +07:00
<Select
name="role"
defaultValue={editingUser?.role}
disabled={editingUser?.id === session?.user?.id}
>
2026-02-13 15:52:13 +07:00
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="user">User</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setEditingUser(null)}>
Cancel
</Button>
2026-08-13 03:29:33 +07:00
<Button type="submit" disabled={pendingAction !== null}>
Save Changes
</Button>
2026-02-13 15:52:13 +07:00
</DialogFooter>
</form>
</DialogContent>
</Dialog>
<Dialog open={!!suspendingUser} onOpenChange={() => setSuspendingUser(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Suspend User</DialogTitle>
<DialogDescription>
Suspend {suspendingUser?.name} from accessing the system
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSuspend}>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="suspendedUntil">Suspend Until (Optional)</Label>
<Input
id="suspendedUntil"
name="suspendedUntil"
type="datetime-local"
2026-08-13 03:29:33 +07:00
min={localDateTimeMinimum()}
2026-02-13 15:52:13 +07:00
placeholder="Leave empty for indefinite suspension"
/>
<p className="text-sm text-muted-foreground">
Leave empty for indefinite suspension
</p>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setSuspendingUser(null)}>
Cancel
</Button>
2026-08-13 03:29:33 +07:00
<Button type="submit" variant="destructive" disabled={pendingAction !== null}>
2026-02-13 15:52:13 +07:00
Suspend User
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
2026-08-13 01:58:19 +07:00
<ConfirmDialog
open={!!deleteUser}
title="Delete User"
description={
<>Are you sure you want to delete {deleteUser?.name}? This action cannot be undone.</>
}
confirmLabel="Delete"
onConfirm={handleDelete}
onOpenChange={(open) => !open && setDeleteUser(null)}
/>
</PageShell>
2026-02-13 15:52:13 +07:00
);
}