All files / src/components/admin UserRolesSection.tsx

95% Statements 38/40
88.88% Branches 24/27
100% Functions 16/16
100% Lines 36/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257                                                            130x 130x         130x 130x     130x   130x 8x 8x   8x 8x 8x         5x 5x       8x       130x 6x 6x 6x       6x       130x 187x 59x   128x 187x     130x                         18x                             187x                                                     6x                                               1x             1x 1x                                                         6x                                         2x           22x                         10x               273x                      
import { PLATFORM_ROLES, PRO_ROLES } from "@interioring/utils/constants/roles";
import { Plus, Shield, X } from "lucide-react";
import { useMemo, useState } from "react";
import type { Pro, UserTenantRole } from "../../lib/api";
import { Button } from "../ui/button";
import { AdminBand } from "./AdminPageHead";
import { Card } from "../ui/card";
import { DrawerDialog } from "../ui/drawer-dialog";
import { Field, Label } from "../ui/field";
import { Select } from "../ui/select";
import { STATUS_CODE_TYPE } from "../ui/status-ink";
import { cn } from "../../lib/utils";
 
interface UserRolesSectionProps {
	roles: UserTenantRole[];
	pros: Pro[];
	onAddRole: (role: {
		tenantType: "platform" | "pro";
		tenantId?: string;
		role: string;
	}) => Promise<void>;
	onRemoveRole: (roleId: number) => Promise<void>;
}
 
export function UserRolesSection({
	roles,
	pros,
	onAddRole,
	onRemoveRole,
}: UserRolesSectionProps) {
	const [showAddRole, setShowAddRole] = useState(false);
	const [newRole, setNewRole] = useState({
		tenantType: "platform" as "platform" | "pro",
		tenantId: "",
		role: "",
	});
	const [isAddingRole, setIsAddingRole] = useState(false);
	const [removingRoleId, setRemovingRoleId] = useState<number | null>(null);
 
	// O(1) pro lookup by ID
	const proMap = useMemo(() => new Map(pros.map((p) => [p.id, p])), [pros]);
 
	const handleAddRole = async () => {
		Iif (!newRole.role) return;
		Iif (newRole.tenantType === "pro" && !newRole.tenantId) return;
 
		setIsAddingRole(true);
		try {
			await onAddRole({
				tenantType: newRole.tenantType,
				tenantId: newRole.tenantType === "pro" ? newRole.tenantId : undefined,
				role: newRole.role,
			});
			setShowAddRole(false);
			setNewRole({ tenantType: "platform", tenantId: "", role: "" });
		} catch {
			// Error is handled by parent component, keep modal open so user can retry
		} finally {
			setIsAddingRole(false);
		}
	};
 
	const handleRemoveRole = async (roleId: number) => {
		setRemovingRoleId(roleId);
		try {
			await onRemoveRole(roleId);
		} catch {
			// Error is handled by parent component
		} finally {
			setRemovingRoleId(null);
		}
	};
 
	const getRoleDisplay = (role: UserTenantRole) => {
		if (role.tenantType === "platform") {
			return `Platform: ${role.role.replace("_", " ")}`;
		}
		const pro = proMap.get(role.tenantId ?? "");
		return `Pro (${pro?.businessName || role.tenantId}): ${role.role}`;
	};
 
	return (
		<>
			<section className="space-y-2">
				<div className="flex items-center gap-2">
					<Shield
						aria-hidden="true"
						className="size-4 shrink-0 text-foreground-muted"
					/>
					<AdminBand
						title="Roles"
						count={roles.length}
						className="grow"
						actions={
							<Button size="sm" onClick={() => setShowAddRole(true)}>
								<Plus aria-hidden="true" />
								Add Role
							</Button>
						}
					/>
				</div>
				{roles.length === 0 ? (
					<p className="py-8 text-center text-sm text-foreground-muted">
						No roles assigned. Click "Add Role" to assign one.
					</p>
				) : (
					// Ruled rows that tint on hover, not a stack of tinted boxes.
					<Card className="overflow-hidden">
						{roles.map((role) => (
							<div
								key={role.id}
								className="flex items-center justify-between gap-3 px-3.5 py-2.5 transition-colors hover:bg-foreground-default/7 [&+div]:border-t [&+div]:border-border-default"
							>
								<div>
									{/*
									 * A tenant type is a printed LABEL, not a status: 2px radius and
									 * `.label` caps on the field tint, never a pill. Status ink is
									 * reserved for state, and a tenant type is not one.
									 */}
									<span
										className={cn(
											"mr-2 inline-flex items-center rounded-sm px-1.5 py-0.5",
											STATUS_CODE_TYPE,
											role.tenantType === "platform"
												? "bg-background-muted font-bold text-foreground-default"
												: "bg-primary-100 text-primary-900",
										)}
									>
										{role.tenantType}
									</span>
									<span className="text-foreground-default">
										{getRoleDisplay(role)}
									</span>
								</div>
								<button
									type="button"
									onClick={() => handleRemoveRole(role.id)}
									disabled={removingRoleId === role.id}
									className="p-1 text-error hover:bg-error-light rounded disabled:opacity-50"
									title="Remove role"
								>
									{removingRoleId === role.id ? (
										<span className="block h-4 w-4 border-2 border-error border-t-transparent rounded-full animate-spin" />
									) : (
										<X className="h-4 w-4" />
									)}
								</button>
							</div>
						))}
					</Card>
				)}
			</section>
 
			{/*
			 * Add Role — on the DrawerDialog primitive, which carries the focus
			 * trap, the Escape handler and the dialog role the hand-rolled overlay
			 * did not.
			 */}
			<DrawerDialog
				open={showAddRole}
				onClose={() => setShowAddRole(false)}
				title="Add Role"
				footer={
					<div className="flex justify-end gap-2">
						<Button
							variant="outline"
							onClick={() => {
								setShowAddRole(false);
								setNewRole({
									tenantType: "platform",
									tenantId: "",
									role: "",
								});
							}}
						>
							Cancel
						</Button>
						<Button
							onClick={handleAddRole}
							isLoading={isAddingRole}
							disabled={
								!newRole.role ||
								(newRole.tenantType === "pro" && !newRole.tenantId)
							}
						>
							Add Role
						</Button>
					</div>
				}
			>
				<div className="space-y-4">
					<Field controlId="role-type">
						<Label>Role Type</Label>
						<Select
							id="role-type"
							value={newRole.tenantType}
							onChange={(e) =>
								setNewRole({
									...newRole,
									tenantType: e.target.value as "platform" | "pro",
									role: "",
									tenantId: "",
								})
							}
							className="w-full"
						>
							<option value="platform">Platform (Admin)</option>
							<option value="pro">Pro (Team Member)</option>
						</Select>
					</Field>
 
					{newRole.tenantType === "pro" && (
						<Field controlId="pro-select">
							<Label>Pro</Label>
							<Select
								id="pro-select"
								value={newRole.tenantId}
								onChange={(e) =>
									setNewRole({ ...newRole, tenantId: e.target.value })
								}
								className="w-full"
							>
								<option value="">Select pro</option>
								{pros.map((pro) => (
									<option key={pro.id} value={pro.id}>
										{pro.businessName}
									</option>
								))}
							</Select>
						</Field>
					)}
 
					<Field controlId="role-select">
						<Label>Role</Label>
						<Select
							id="role-select"
							value={newRole.role}
							onChange={(e) => setNewRole({ ...newRole, role: e.target.value })}
							className="w-full"
						>
							<option value="">Select role</option>
							{(newRole.tenantType === "platform"
								? PLATFORM_ROLES
								: PRO_ROLES
							).map((role) => (
								<option key={role} value={role}>
									{role.replace("_", " ")}
								</option>
							))}
						</Select>
					</Field>
				</div>
			</DrawerDialog>
		</>
	);
}