feat(web): add admin users settings page (MS21-UI-001) #573

Merged
jason.woltje merged 1 commits from feat/ms21-ui-users into main 2026-02-28 20:50:12 +00:00
6 changed files with 573 additions and 4 deletions

View File

@@ -75,6 +75,16 @@
"milestone_at_end": "", "milestone_at_end": "",
"tasks_completed": [], "tasks_completed": [],
"last_task_id": "" "last_task_id": ""
},
{
"session_id": "sess-002",
"runtime": "unknown",
"started_at": "2026-02-28T20:30:13Z",
"ended_at": "",
"ended_reason": "",
"milestone_at_end": "",
"tasks_completed": [],
"last_task_id": ""
} }
] ]
} }

View File

@@ -1,8 +1,8 @@
{ {
"session_id": "sess-001", "session_id": "sess-002",
"runtime": "unknown", "runtime": "unknown",
"pid": 2396592, "pid": 3178395,
"started_at": "2026-02-28T17:48:51Z", "started_at": "2026-02-28T20:30:13Z",
"project_path": "/tmp/ms21-api-003", "project_path": "/tmp/ms21-ui-001",
"milestone_id": "" "milestone_id": ""
} }

View File

@@ -196,6 +196,31 @@ const categories: CategoryConfig[] = [
</svg> </svg>
), ),
}, },
{
title: "Users",
description: "Invite, manage roles, and deactivate users across your workspaces.",
href: "/settings/users",
accent: "var(--ms-green-400)",
iconBg: "rgba(34, 197, 94, 0.12)",
icon: (
<svg
width="20"
height="20"
viewBox="0 0 20 20"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<circle cx="8" cy="7" r="2.5" />
<circle cx="13.5" cy="8.5" r="2" />
<path d="M3.5 16c0-2.5 2-4.5 4.5-4.5s4.5 2 4.5 4.5" />
<path d="M12 13.8c.5-.8 1.4-1.3 2.5-1.3 1.7 0 3 1.3 3 3" />
</svg>
),
},
{ {
title: "Workspaces", title: "Workspaces",
description: description:

View File

@@ -0,0 +1,435 @@
"use client";
import {
useCallback,
useEffect,
useState,
type ChangeEvent,
type ReactElement,
type SyntheticEvent,
} from "react";
import Link from "next/link";
import { UserPlus, UserX } from "lucide-react";
import { WorkspaceMemberRole } from "@mosaic/shared";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} 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";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
deactivateUser,
fetchAdminUsers,
inviteUser,
type AdminUser,
type AdminUsersResponse,
type InviteUserDto,
} from "@/lib/api/admin";
const ROLE_PRIORITY: Record<WorkspaceMemberRole, number> = {
[WorkspaceMemberRole.OWNER]: 4,
[WorkspaceMemberRole.ADMIN]: 3,
[WorkspaceMemberRole.MEMBER]: 2,
[WorkspaceMemberRole.GUEST]: 1,
};
const INITIAL_INVITE_FORM = {
email: "",
name: "",
workspaceId: "",
role: WorkspaceMemberRole.MEMBER,
};
function toRoleLabel(role: WorkspaceMemberRole): string {
return `${role.charAt(0)}${role.slice(1).toLowerCase()}`;
}
function getPrimaryRole(user: AdminUser): WorkspaceMemberRole | null {
const [firstMembership, ...restMemberships] = user.workspaceMemberships;
if (!firstMembership) {
return null;
}
return restMemberships.reduce((highest, membership) => {
if (ROLE_PRIORITY[membership.role] > ROLE_PRIORITY[highest]) {
return membership.role;
}
return highest;
}, firstMembership.role);
}
export default function UsersSettingsPage(): ReactElement {
const [users, setUsers] = useState<AdminUser[]>([]);
const [meta, setMeta] = useState<AdminUsersResponse["meta"] | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [isRefreshing, setIsRefreshing] = useState<boolean>(false);
const [error, setError] = useState<string | null>(null);
const [isInviteOpen, setIsInviteOpen] = useState<boolean>(false);
const [inviteForm, setInviteForm] = useState(INITIAL_INVITE_FORM);
const [inviteError, setInviteError] = useState<string | null>(null);
const [isInviting, setIsInviting] = useState<boolean>(false);
const [deactivateTarget, setDeactivateTarget] = useState<AdminUser | null>(null);
const [isDeactivating, setIsDeactivating] = useState<boolean>(false);
const loadUsers = useCallback(async (showLoadingState: boolean): Promise<void> => {
try {
if (showLoadingState) {
setIsLoading(true);
} else {
setIsRefreshing(true);
}
const response = await fetchAdminUsers(1, 50);
setUsers(response.data);
setMeta(response.meta);
setError(null);
} catch (err: unknown) {
setError(err instanceof Error ? err.message : "Failed to load admin users");
} finally {
setIsLoading(false);
setIsRefreshing(false);
}
}, []);
useEffect(() => {
void loadUsers(true);
}, [loadUsers]);
function resetInviteForm(): void {
setInviteForm(INITIAL_INVITE_FORM);
setInviteError(null);
}
function handleInviteOpenChange(open: boolean): void {
if (!open && !isInviting) {
resetInviteForm();
}
setIsInviteOpen(open);
}
async function handleInviteSubmit(e: SyntheticEvent): Promise<void> {
e.preventDefault();
setInviteError(null);
const email = inviteForm.email.trim();
if (!email) {
setInviteError("Email is required.");
return;
}
const dto: InviteUserDto = { email };
const name = inviteForm.name.trim();
if (name) {
dto.name = name;
}
const workspaceId = inviteForm.workspaceId.trim();
if (workspaceId) {
dto.workspaceId = workspaceId;
dto.role = inviteForm.role;
}
try {
setIsInviting(true);
await inviteUser(dto);
setIsInviteOpen(false);
resetInviteForm();
await loadUsers(false);
} catch (err: unknown) {
setInviteError(err instanceof Error ? err.message : "Failed to invite user");
} finally {
setIsInviting(false);
}
}
async function confirmDeactivate(): Promise<void> {
if (!deactivateTarget) {
return;
}
try {
setIsDeactivating(true);
await deactivateUser(deactivateTarget.id);
setDeactivateTarget(null);
await loadUsers(false);
setError(null);
} catch (err: unknown) {
setError(err instanceof Error ? err.message : "Failed to deactivate user");
} finally {
setIsDeactivating(false);
}
}
return (
<div className="max-w-6xl mx-auto p-6 space-y-6">
<div className="flex items-start justify-between gap-4">
<div>
<div className="flex items-center gap-3">
<h1 className="text-3xl font-bold">Users</h1>
{meta ? <Badge variant="outline">{meta.total} total</Badge> : null}
</div>
<p className="text-muted-foreground mt-1">Invite and manage workspace users</p>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
onClick={() => {
void loadUsers(false);
}}
disabled={isLoading || isRefreshing}
>
{isRefreshing ? "Refreshing..." : "Refresh"}
</Button>
<Dialog open={isInviteOpen} onOpenChange={handleInviteOpenChange}>
<DialogTrigger asChild>
<Button>
<UserPlus className="h-4 w-4 mr-2" />
Invite User
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Invite User</DialogTitle>
<DialogDescription>
Create an invited account and optionally assign workspace access.
</DialogDescription>
</DialogHeader>
<form
onSubmit={(e) => {
void handleInviteSubmit(e);
}}
className="space-y-4"
>
<div className="space-y-2">
<Label htmlFor="invite-email">Email</Label>
<Input
id="invite-email"
type="email"
value={inviteForm.email}
onChange={(e: ChangeEvent<HTMLInputElement>) => {
setInviteForm((prev) => ({ ...prev, email: e.target.value }));
}}
placeholder="user@example.com"
maxLength={255}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="invite-name">Name (optional)</Label>
<Input
id="invite-name"
type="text"
value={inviteForm.name}
onChange={(e: ChangeEvent<HTMLInputElement>) => {
setInviteForm((prev) => ({ ...prev, name: e.target.value }));
}}
placeholder="Jane Doe"
maxLength={255}
/>
</div>
<div className="space-y-2">
<Label htmlFor="invite-workspace-id">Workspace ID (optional)</Label>
<Input
id="invite-workspace-id"
type="text"
value={inviteForm.workspaceId}
onChange={(e: ChangeEvent<HTMLInputElement>) => {
setInviteForm((prev) => ({ ...prev, workspaceId: e.target.value }));
}}
placeholder="UUID workspace id"
/>
</div>
<div className="space-y-2">
<Label htmlFor="invite-role">Role</Label>
<Select
value={inviteForm.role}
onValueChange={(value) => {
setInviteForm((prev) => ({ ...prev, role: value as WorkspaceMemberRole }));
}}
>
<SelectTrigger id="invite-role">
<SelectValue placeholder="Select role" />
</SelectTrigger>
<SelectContent>
{Object.values(WorkspaceMemberRole).map((role) => (
<SelectItem key={role} value={role}>
{toRoleLabel(role)}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Role is only applied when workspace ID is provided.
</p>
</div>
{inviteError ? (
<p className="text-sm text-destructive" role="alert">
{inviteError}
</p>
) : null}
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => {
handleInviteOpenChange(false);
}}
disabled={isInviting}
>
Cancel
</Button>
<Button type="submit" disabled={isInviting}>
{isInviting ? "Inviting..." : "Send Invite"}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</div>
</div>
<div>
<Link href="/settings" className="text-sm text-blue-600 hover:text-blue-700">
Back to Settings
</Link>
</div>
{error ? (
<Card>
<CardContent className="py-4">
<p className="text-sm text-destructive" role="alert">
{error}
</p>
</CardContent>
</Card>
) : null}
{isLoading ? (
<Card>
<CardContent className="py-12 text-center text-muted-foreground">
Loading users...
</CardContent>
</Card>
) : users.length === 0 ? (
<Card>
<CardHeader>
<CardTitle>No Users Yet</CardTitle>
<CardDescription>Invite the first user to get started.</CardDescription>
</CardHeader>
</Card>
) : (
<Card>
<CardHeader>
<CardTitle>User Directory</CardTitle>
<CardDescription>Name, email, role, and account status.</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
{users.map((user) => {
const primaryRole = getPrimaryRole(user);
const isActive = user.deactivatedAt === null;
return (
<div
key={user.id}
className="rounded-md border p-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between"
>
<div className="space-y-1 min-w-0">
<p className="font-semibold truncate">{user.name || "Unnamed User"}</p>
<p className="text-sm text-muted-foreground truncate">{user.email}</p>
</div>
<div className="flex items-center gap-2 flex-wrap md:justify-end">
<Badge variant="outline">
{primaryRole ? toRoleLabel(primaryRole) : "No role"}
</Badge>
<Badge variant={isActive ? "secondary" : "destructive"}>
{isActive ? "Active" : "Inactive"}
</Badge>
{isActive ? (
<Button
variant="destructive"
size="sm"
onClick={() => {
setDeactivateTarget(user);
}}
>
<UserX className="h-4 w-4 mr-2" />
Deactivate
</Button>
) : null}
</div>
</div>
);
})}
</CardContent>
</Card>
)}
<AlertDialog
open={deactivateTarget !== null}
onOpenChange={(open) => {
if (!open && !isDeactivating) {
setDeactivateTarget(null);
}
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Deactivate User</AlertDialogTitle>
<AlertDialogDescription>
Deactivate {deactivateTarget?.email}? They will no longer be able to access the
system.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeactivating}>Cancel</AlertDialogCancel>
<AlertDialogAction
disabled={isDeactivating}
onClick={() => {
void confirmDeactivate();
}}
>
{isDeactivating ? "Deactivating..." : "Deactivate"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}

View File

@@ -0,0 +1,98 @@
/**
* Admin API Client
* Handles admin user management requests
*/
import type { WorkspaceMemberRole } from "@mosaic/shared";
import { apiGet, apiPatch, apiPost, apiDelete } from "./client";
export interface AdminWorkspaceMembership {
workspaceId: string;
workspaceName: string;
role: WorkspaceMemberRole;
joinedAt: string;
}
export interface AdminUser {
id: string;
name: string;
email: string;
emailVerified: boolean;
image: string | null;
createdAt: string;
deactivatedAt: string | null;
isLocalAuth: boolean;
invitedAt: string | null;
invitedBy: string | null;
workspaceMemberships: AdminWorkspaceMembership[];
}
export interface AdminUsersResponse {
data: AdminUser[];
meta: {
total: number;
page: number;
limit: number;
totalPages: number;
};
}
export interface InviteUserDto {
email: string;
name?: string;
workspaceId?: string;
role?: WorkspaceMemberRole;
}
export interface InvitationResponse {
userId: string;
invitationToken: string;
email: string;
invitedAt: string;
}
export interface UpdateUserDto {
name?: string;
deactivatedAt?: string | null;
emailVerified?: boolean;
preferences?: Record<string, unknown>;
}
/**
* Fetch paginated admin users
*/
export async function fetchAdminUsers(page?: number, limit?: number): Promise<AdminUsersResponse> {
const params = new URLSearchParams();
if (page !== undefined) {
params.append("page", String(page));
}
if (limit !== undefined) {
params.append("limit", String(limit));
}
const endpoint = `/api/admin/users${params.toString() ? `?${params.toString()}` : ""}`;
return apiGet<AdminUsersResponse>(endpoint);
}
/**
* Invite a user by email
*/
export async function inviteUser(dto: InviteUserDto): Promise<InvitationResponse> {
return apiPost<InvitationResponse>("/api/admin/users/invite", dto);
}
/**
* Update admin user fields
*/
export async function updateUser(id: string, dto: UpdateUserDto): Promise<AdminUser> {
return apiPatch<AdminUser>(`/api/admin/users/${id}`, dto);
}
/**
* Deactivate a user account
*/
export async function deactivateUser(id: string): Promise<AdminUser> {
return apiDelete<AdminUser>(`/api/admin/users/${id}`);
}

View File

@@ -16,3 +16,4 @@ export * from "./telemetry";
export * from "./dashboard"; export * from "./dashboard";
export * from "./projects"; export * from "./projects";
export * from "./workspaces"; export * from "./workspaces";
export * from "./admin";