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 258 259 260 261 262 | 233x 233x 233x 233x 233x 233x 233x 233x 233x 83x 83x 1x 1x 83x 83x 233x 233x 233x 233x 233x 233x 233x 233x 233x 20x 20x 3x 3x 17x 17x 2x 2x 15x 2x 2x 13x 13x 3x 3x 3x 1x 1x 12x 1x 1x 11x 11x 11x 11x 8x 3x 7x 7x 7x 7x 7x 7x 4x 4x 11x 233x 14x 14x 9x 9x 6x 3x 233x 31x 8x 3x 15x 2x 2x | import { useState, useCallback } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Search, UserPlus, Users } from "lucide-react";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "../../components/ui/card";
import { Button } from "../../components/ui/button";
import { EmptyState } from "../../components/ui/empty-state";
import { Input } from "../../components/ui/input";
import { adminApi, ApiError, GENERIC_ERROR_MESSAGE, type AdminUser } from "../../lib/api";
import { queryKeys } from "../../lib/query-keys";
import { UserTable } from "../../components/admin/UserTable";
import { CreateUserModal } from "../../components/admin/CreateUserModal";
import { useAdminUsersList, useAdminProLookup } from "../../hooks/queries/useAdminQueries";
import { useConfirmDialog } from "../../hooks";
export function AdminUsersPage() {
const queryClient = useQueryClient();
const { confirm, dialog: confirmDialog } = useConfirmDialog();
const [search, setSearch] = useState("");
const {
data,
isLoading,
isFetchingNextPage: isLoadingMore,
hasNextPage: hasMore,
fetchNextPage,
} = useAdminUsersList({ search });
const users = data?.pages?.flatMap((p) => p.data || []) ?? [];
const total = data?.pages?.[0]?.meta?.total ?? 0;
// Pro lookup for the create user modal
const { data: proList } = useAdminProLookup();
const pros = proList || [];
const loadMoreRef = useCallback(
(node: HTMLDivElement | null) => {
Iif (!node) return;
const observer = new IntersectionObserver(
(entries) => {
Eif (entries[0].isIntersecting && hasMore && !isLoadingMore) {
fetchNextPage();
}
},
{ threshold: 0.1 },
);
observer.observe(node);
return () => observer.disconnect();
},
[hasMore, isLoadingMore, fetchNextPage],
);
// Create user modal
const [showCreateModal, setShowCreateModal] = useState(false);
const [newUser, setNewUser] = useState({
name: "",
email: "",
password: "",
phoneNumber: "",
});
const [isCreating, setIsCreating] = useState(false);
const [createError, setCreateError] = useState<string | null>(null);
// Pro assignment
const [assignToPro, setAssignToPro] = useState(false);
const [selectedProId, setSelectedProId] = useState("");
const [selectedRole, setSelectedRole] = useState<
"owner" | "manager" | "staff"
>("staff");
const handleSearch = () => {
// Filters are reactive via useAdminUsersList — search state change triggers refetch
};
const handleCreateUser = async () => {
const trimmedName = newUser.name.trim();
if (!trimmedName || !newUser.email.trim() || !newUser.password) {
setCreateError("Name, email, and password are required");
return;
}
const nameLetters = trimmedName.match(/\p{L}/gu);
if (!nameLetters || nameLetters.length < 2 || !/^[\p{L}]+(?:[ '-][\p{L}]+)*$/u.test(trimmedName)) {
setCreateError("Name must contain at least 2 letters and only letters, spaces, hyphens, or apostrophes");
return;
}
if (newUser.password.length < 8) {
setCreateError("Password must be at least 8 characters");
return;
}
const trimmedPhone = newUser.phoneNumber.trim();
if (trimmedPhone) {
let digits = trimmedPhone.replace(/\D/g, "");
if (digits.length === 12 && digits.startsWith("91")) digits = digits.slice(2);
if (digits.length !== 10) {
setCreateError("Phone number must be exactly 10 digits");
return;
}
}
if (assignToPro && !selectedProId) {
setCreateError("Please select a pro");
return;
}
setIsCreating(true);
setCreateError(null);
try {
const result = await adminApi.createUser({
name: newUser.name.trim(),
email: newUser.email.trim(),
password: newUser.password,
phoneNumber: newUser.phoneNumber.trim() || undefined,
});
// If pro assignment is enabled, add the role
if (assignToPro && selectedProId && result.data) {
await adminApi.addProTeamMember(selectedProId, {
userId: result.data.id,
role: selectedRole,
});
}
setShowCreateModal(false);
setNewUser({ name: "", email: "", password: "", phoneNumber: "" });
setAssignToPro(false);
setSelectedProId("");
setSelectedRole("staff");
queryClient.invalidateQueries({ queryKey: queryKeys.admin.users.all });
} catch (err) {
console.error("Failed to create user:", err);
setCreateError(
err instanceof ApiError ? err.message : GENERIC_ERROR_MESSAGE,
);
} finally {
setIsCreating(false);
}
};
const handleToggleBan = async (user: AdminUser) => {
const action = user.banned ? "unban" : "ban";
if (!(await confirm({ title: `${action.charAt(0).toUpperCase() + action.slice(1)} user`, description: `Are you sure you want to ${action} ${user.name}?`, confirmLabel: action.charAt(0).toUpperCase() + action.slice(1), variant: "destructive" }))) return;
try {
await adminApi.banUser(user.id, !user.banned);
queryClient.invalidateQueries({ queryKey: queryKeys.admin.users.all });
} catch (err) {
console.error(`Failed to ${action} user:`, err);
}
};
return (
<>
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 className="text-2xl font-bold text-foreground-default">
Users
</h1>
<p className="text-foreground-muted">
Manage all users on the platform.
</p>
</div>
<Button onClick={() => setShowCreateModal(true)}>
<UserPlus className="h-4 w-4 mr-2" />
Add User
</Button>
</div>
{/* Filters */}
<Card>
<CardContent className="pt-6">
<div className="flex flex-col sm:flex-row gap-4">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle" />
<Input
placeholder="Search users by name or email..."
value={search}
onChange={(e) => setSearch(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSearch()}
className="pl-10"
/>
</div>
<Button onClick={handleSearch}>Search</Button>
</div>
</CardContent>
</Card>
{/* Table */}
<Card>
<CardHeader>
<CardTitle className="text-lg">{total} Users</CardTitle>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="space-y-4">
{[1, 2, 3, 4, 5].map((i) => (
<div
key={i}
className="h-16 bg-background-muted rounded animate-pulse"
/>
))}
</div>
) : users.length === 0 ? (
<EmptyState
icon={Users}
title="No users found"
description="Try adjusting your search or filters."
/>
) : (
<>
<UserTable users={users} onToggleBan={handleToggleBan} />
{/* Infinite scroll trigger */}
<div
ref={loadMoreRef}
className="h-10 flex items-center justify-center"
>
{isLoadingMore && (
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary-600" />
)}
{!hasMore && users.length > 0 && (
<p className="text-sm text-foreground-muted">
No more users
</p>
)}
</div>
</>
)}
</CardContent>
</Card>
</div>
{/* Create User Modal */}
<CreateUserModal
isOpen={showCreateModal}
newUser={newUser}
pros={pros}
assignToPro={assignToPro}
selectedProId={selectedProId}
selectedRole={selectedRole}
isCreating={isCreating}
error={createError}
onClose={() => {
setShowCreateModal(false);
setCreateError(null);
}}
onUserChange={setNewUser}
onAssignToProChange={setAssignToPro}
onSelectedProIdChange={setSelectedProId}
onSelectedRoleChange={setSelectedRole}
onSubmit={handleCreateUser}
/>
{confirmDialog}
</>
);
}
|