Spaces:
Sleeping
Sleeping
File size: 28,492 Bytes
2d1d3d3 1e5ae4b 0c0f5cc 1e5ae4b 2d1d3d3 1e5ae4b 0c0f5cc 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 49c6642 cc20f66 1e5ae4b 53a811b 1e5ae4b 311effb 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 311effb 1e5ae4b cc20f66 1e5ae4b 311effb cc20f66 1e5ae4b cc20f66 311effb cc20f66 311effb cc20f66 49c6642 311effb cc20f66 311effb cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 49c6642 cc20f66 1e5ae4b 0c0f5cc 1e5ae4b 53a811b 1e5ae4b 311effb 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b 311effb 1e5ae4b 53a811b 1e5ae4b cc20f66 1e5ae4b 311effb 1e5ae4b 53a811b 1e5ae4b cc20f66 1e5ae4b 0c0f5cc 1e5ae4b 311effb 1e5ae4b 311effb 1e5ae4b 311effb 1e5ae4b cc20f66 0c0f5cc cc20f66 1e5ae4b cc20f66 1e5ae4b 0c0f5cc 1e5ae4b 49c6642 cc20f66 49c6642 cc20f66 49c6642 cc20f66 1e5ae4b cc20f66 0c0f5cc 1e5ae4b cc20f66 1e5ae4b cc20f66 0c0f5cc 1e5ae4b cc20f66 1e5ae4b 0c0f5cc 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b 0c0f5cc 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b 53a811b 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b 0c0f5cc 2d1d3d3 0c0f5cc 1e5ae4b 53a811b 1e5ae4b cc20f66 1e5ae4b cc20f66 1e5ae4b 0c0f5cc 2d1d3d3 0c0f5cc 1e5ae4b cc20f66 1e5ae4b 53a811b | 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 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 | import { Eye, EyeOff, Plus, Trash2 } from 'lucide-react';
import type { FormEvent } from 'react';
import { useMemo, useState } from 'react';
import { toast } from 'sonner';
import { ConfigError, Field, InfoHint } from '@/components/admin/admin-form-parts';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinner';
import {
emptyUserForm,
formatDate,
isUserActive,
roleLabel,
userToForm,
} from '@/lib/admin';
import {
createAdminUser,
deleteAdminUser,
updateAdminUser,
} from '@/lib/rag-client';
import type {
AdminRole,
AdminUser,
UserFilterForm,
UserForm,
} from '@/types/admin';
export function AdminUserCreateCard({
onCreated,
}: {
onCreated?: (user: AdminUser) => void;
}) {
const [formData, setFormData] = useState<UserForm>(emptyUserForm);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | undefined>();
function setField<K extends keyof UserForm>(
key: K,
value: UserForm[K],
): void {
setFormData((prev) => ({ ...prev, [key]: value }));
}
async function handleSubmit(
event: FormEvent<HTMLFormElement>,
): Promise<void> {
event.preventDefault();
setIsSubmitting(true);
setError(undefined);
try {
const payload = buildCreatePayload(formData);
const created = await createAdminUser(payload);
setFormData(emptyUserForm);
onCreated?.(created);
} catch (e) {
setError(
e instanceof Error ? e.message : 'Gagal membuat user.',
);
} finally {
setIsSubmitting(false);
}
}
return (
<Card className="border-(--lecturer-border) bg-(--lecturer-surface)">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Plus className="size-5 text-(--lecturer-primary)" />
Tambah User
</CardTitle>
<CardDescription>
Payload mengikuti schema UpsertUser dari API.
</CardDescription>
</CardHeader>
<CardContent>
<UserFormFields
data={formData}
error={error}
isSubmitting={isSubmitting}
setField={setField}
submitLabel="Buat User"
onSubmit={(e) => {
void handleSubmit(e);
}}
/>
</CardContent>
</Card>
);
}
export function AdminUserManagement({
users: initialUsers = [],
}: {
users?: AdminUser[];
}) {
const [users, setUsers] = useState<AdminUser[]>(initialUsers);
const [isCreating, setIsCreating] = useState(false);
const [createFormData, setCreateFormData] = useState<UserForm>(emptyUserForm);
const [isSubmittingCreate, setIsSubmittingCreate] = useState(false);
const [createError, setCreateError] = useState<string | undefined>();
const [editingUser, setEditingUser] = useState<AdminUser | null>(null);
const [editFormData, setEditFormData] = useState<UserForm>(emptyUserForm);
const [isEditing, setIsEditing] = useState(false);
const [editError, setEditError] = useState<string | undefined>();
const [filterForm, setFilterForm] = useState<UserFilterForm>({
email: '',
name: '',
role: 'all',
});
const userStats = useMemo(() => {
const adminCount = users.filter((user) => user.role === 'admin').length;
return {
adminCount,
total: users.length,
};
}, [users]);
const filteredUsers = useMemo(() => {
return users.filter((user) => {
const nameMatch =
filterForm.name === '' ||
(user.name ?? '').toLowerCase().includes(filterForm.name.toLowerCase());
const emailMatch =
filterForm.email === '' ||
(user.email ?? '').toLowerCase().includes(filterForm.email.toLowerCase());
const roleMatch =
filterForm.role === 'all' || user.role === filterForm.role;
return nameMatch && emailMatch && roleMatch;
});
}, [users, filterForm]);
function setCreateField<K extends keyof UserForm>(
key: K,
value: UserForm[K],
): void {
setCreateFormData((prev) => ({ ...prev, [key]: value }));
}
function setEditField<K extends keyof UserForm>(
key: K,
value: UserForm[K],
): void {
setEditFormData((prev) => ({ ...prev, [key]: value }));
}
function openEditUserDialog(user: AdminUser): void {
setEditingUser(user);
setEditFormData(userToForm(user));
setEditError(undefined);
}
async function handleCreateUser(
event: FormEvent<HTMLFormElement>,
): Promise<void> {
event.preventDefault();
setIsSubmittingCreate(true);
setCreateError(undefined);
try {
const payload = buildCreatePayload(createFormData);
const created = await createAdminUser(payload);
setUsers((prev) => [created, ...prev]);
setCreateFormData(emptyUserForm);
setIsCreating(false);
} catch (e) {
setCreateError(
e instanceof Error ? e.message : 'Gagal membuat user.',
);
} finally {
setIsSubmittingCreate(false);
}
}
async function handleUpdateUser(
event: FormEvent<HTMLFormElement>,
): Promise<void> {
event.preventDefault();
if (!editingUser) {
return;
}
setIsEditing(true);
setEditError(undefined);
try {
const payload = buildUpdatePayload(editFormData);
const updated = await updateAdminUser(editingUser.id, payload);
setUsers((prev) =>
prev.map((u) => (u.id === updated.id ? updated : u)),
);
setEditingUser(null);
} catch (e) {
setEditError(
e instanceof Error ? e.message : 'Gagal memperbarui user.',
);
} finally {
setIsEditing(false);
}
}
const [deletingUser, setDeletingUser] = useState<AdminUser | null>(null);
const [isDeleting, setIsDeleting] = useState(false);
async function handleDeleteUser(): Promise<void> {
if (!deletingUser) return;
setIsDeleting(true);
try {
await deleteAdminUser(deletingUser.id);
window.location.reload();
} catch (e) {
toast.error(
e instanceof Error ? e.message : 'Gagal menghapus user.',
);
setIsDeleting(false);
}
}
return (
<>
<Card className="border-(--lecturer-border) bg-(--lecturer-surface)">
<CardHeader>
<div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
<div>
<CardTitle>User Management</CardTitle>
<CardDescription>
Total {userStats.total} user,{' '}
{userStats.adminCount} admin.
</CardDescription>
</div>
<div className="flex flex-col gap-2">
<div className="flex justify-end">
<Button
onClick={() => {
setCreateFormData(emptyUserForm);
setCreateError(undefined);
setIsCreating(true);
}}
type="button"
>
<Plus className="size-4" />
Tambah User
</Button>
</div>
<div className="grid gap-2 sm:grid-cols-[1fr_1fr_160px]">
<Input
placeholder="Cari nama..."
value={filterForm.name}
onChange={(event) =>
setFilterForm((prev) => ({
...prev,
name: event.target.value,
}))
}
/>
<Input
placeholder="Cari email..."
value={filterForm.email}
onChange={(event) =>
setFilterForm((prev) => ({
...prev,
email: event.target.value,
}))
}
/>
<Select
value={filterForm.role}
onValueChange={(value) =>
setFilterForm((prev) => ({
...prev,
role: value as UserFilterForm['role'],
}))
}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="Role" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">
Semua role
</SelectItem>
<SelectItem value="student">
Mahasiswa
</SelectItem>
<SelectItem value="lecturer">
Dosen
</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
</CardHeader>
<CardContent>
<div className="overflow-hidden rounded-xl border border-(--lecturer-border)">
<div className="overflow-x-auto">
<table className="w-full min-w-190 text-sm">
<thead className="bg-muted/50 text-left text-muted-foreground">
<tr>
<th className="px-4 py-3">Nama</th>
<th className="px-4 py-3">Role</th>
<th className="px-4 py-3">Status</th>
<th className="px-4 py-3">
Superuser
</th>
<th className="px-4 py-3">Dibuat</th>
<th className="px-4 py-3 text-right">
Aksi
</th>
</tr>
</thead>
<tbody>
{filteredUsers.map((user) => (
<tr
className="border-t border-(--lecturer-border)"
key={user.id}
>
<td className="px-4 py-3">
<div className="font-medium">
{user.name ?? '-'}
</div>
<div className="text-muted-foreground">
{user.email ?? '-'}
</div>
</td>
<td className="px-4 py-3">
<Badge variant="outline">
{roleLabel(user.role)}
</Badge>
</td>
<td className="px-4 py-3">
<Badge
className={
isUserActive(user)
? 'bg-(--lecturer-primary-soft) text-(--lecturer-primary)'
: ''
}
variant={
isUserActive(user)
? 'secondary'
: 'outline'
}
>
{isUserActive(user)
? 'Aktif'
: 'Nonaktif'}
</Badge>
</td>
<td className="px-4 py-3">
{user.is_superuser
? 'Ya'
: 'Tidak'}
</td>
<td className="px-4 py-3">
{formatDate(user.created_at)}
</td>
<td className="px-4 py-3">
<div className="flex justify-end gap-2">
<Button
onClick={() =>
openEditUserDialog(
user,
)
}
size="sm"
type="button"
variant="outline"
>
Edit
</Button>
<Button
className="text-destructive hover:text-destructive"
onClick={() => setDeletingUser(user)}
size="sm"
type="button"
variant="outline"
>
<Trash2 className="size-4" />
</Button>
</div>
</td>
</tr>
))}
{filteredUsers.length === 0 ? (
<tr>
<td
className="px-4 py-8 text-center text-muted-foreground"
colSpan={6}
>
{users.length === 0
? 'Tidak ada user dari response backend.'
: 'Tidak ada user yang cocok dengan filter.'}
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</div>
</CardContent>
</Card>
<Dialog onOpenChange={setIsCreating} open={isCreating}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Tambah User</DialogTitle>
<DialogDescription>
Payload mengikuti schema UpsertUser dari API.
</DialogDescription>
</DialogHeader>
<UserFormFields
data={createFormData}
error={createError}
isSubmitting={isSubmittingCreate}
setField={setCreateField}
submitLabel="Buat User"
onSubmit={(e) => {
void handleCreateUser(e);
}}
/>
</DialogContent>
</Dialog>
<Dialog
onOpenChange={(open) => setEditingUser(open ? editingUser : null)}
open={editingUser !== null}
>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Edit User</DialogTitle>
<DialogDescription>
Perubahan dikirim ke endpoint update user backend.
</DialogDescription>
</DialogHeader>
<UserFormFields
data={editFormData}
error={editError}
isSubmitting={isEditing}
mode="edit"
setField={setEditField}
submitLabel="Simpan User"
onSubmit={(e) => {
void handleUpdateUser(e);
}}
/>
</DialogContent>
</Dialog>
<Dialog
open={deletingUser !== null}
onOpenChange={(open) => { if (!open) setDeletingUser(null); }}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Hapus user?</DialogTitle>
<DialogDescription>
Akun <span className="font-medium">{deletingUser?.email ?? '-'}</span> akan dihapus permanen dan tidak bisa dikembalikan.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
onClick={() => setDeletingUser(null)}
type="button"
variant="outline"
disabled={isDeleting}
>
Batal
</Button>
<Button
className="bg-destructive text-white hover:bg-destructive/90"
disabled={isDeleting}
onClick={() => { void handleDeleteUser(); }}
type="button"
>
{isDeleting ? <Spinner className="size-4" /> : null}
Hapus
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
function buildCreatePayload(form: UserForm): Record<string, unknown> {
// POST /auth/register — RegisterRequest schema
const payload: Record<string, unknown> = { role: form.role };
if (form.email) payload.email = form.email;
if (form.name) payload.name = form.name;
if (form.password) payload.password = form.password;
if (form.identity_number) payload.identity_number = form.identity_number;
if (form.phone) payload.phone = form.phone;
return payload;
}
function buildUpdatePayload(form: UserForm): Record<string, unknown> {
// PATCH /user/{id} — PatchUser schema (additionalProperties: false)
// Only: email, name, phone, role, is_active, password
const payload: Record<string, unknown> = {
is_active: form.is_active,
role: form.role,
};
if (form.email) payload.email = form.email;
if (form.name) payload.name = form.name;
if (form.phone) payload.phone = form.phone;
if (form.password) payload.password = form.password;
return payload;
}
function UserFormFields({
data,
error,
isSubmitting,
mode = 'create',
onSubmit,
setField,
submitLabel,
}: {
data: UserForm;
error?: string;
isSubmitting: boolean;
mode?: 'create' | 'edit';
onSubmit: (event: FormEvent<HTMLFormElement>) => void;
setField: <K extends keyof UserForm>(key: K, value: UserForm[K]) => void;
submitLabel: string;
}) {
const [showPassword, setShowPassword] = useState(false);
return (
<form className="grid gap-4" onSubmit={onSubmit}>
<ConfigError message={error} />
<div className="grid gap-3 md:grid-cols-2">
<Field label="Nama">
<Input
value={data.name}
onChange={(event) =>
setField('name', event.target.value)
}
/>
</Field>
<Field label="Email">
<Input
type="email"
value={data.email}
onChange={(event) =>
setField('email', event.target.value)
}
/>
</Field>
<Field
hint={
mode === 'edit'
? 'Kosongkan jika tidak ingin mengubah password.'
: 'Password untuk login user.'
}
label="Password"
>
<div className="relative">
<Input
autoComplete="off"
className="pr-10"
placeholder={mode === 'edit' ? '(tidak diubah)' : '••••••••'}
type={showPassword ? 'text' : 'password'}
value={data.password}
onChange={(event) =>
setField('password', event.target.value)
}
/>
<button
className="text-muted-foreground hover:text-foreground absolute right-3 top-1/2 -translate-y-1/2"
type="button"
onClick={() => setShowPassword((v) => !v)}
>
{showPassword ? (
<EyeOff className="size-4" />
) : (
<Eye className="size-4" />
)}
</button>
</div>
</Field>
<Field label="Nomor Identitas">
<Input
value={data.identity_number}
onChange={(event) =>
setField('identity_number', event.target.value)
}
/>
</Field>
<Field label="Telepon">
<Input
value={data.phone}
onChange={(event) =>
setField('phone', event.target.value)
}
/>
</Field>
<Field label="Role">
<Select
value={data.role}
onValueChange={(value) =>
setField('role', value as AdminRole)
}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="Pilih role" />
</SelectTrigger>
<SelectContent>
<SelectItem value="student">Mahasiswa</SelectItem>
<SelectItem value="lecturer">Dosen</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
</SelectContent>
</Select>
</Field>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<label className="flex items-center gap-3 rounded-lg border border-(--lecturer-border) p-3 text-sm">
<Checkbox
checked={data.is_active}
onCheckedChange={(value) =>
setField('is_active', value === true)
}
/>
<span className="flex items-center gap-1.5">
User aktif
<InfoHint>
User dapat login dan menggunakan sistem. Nonaktifkan untuk memblokir akses tanpa menghapus akun.
</InfoHint>
</span>
</label>
<label className="flex items-center gap-3 rounded-lg border border-(--lecturer-border) p-3 text-sm">
<Checkbox
checked={data.is_superuser}
onCheckedChange={(value) =>
setField('is_superuser', value === true)
}
/>
<span className="flex items-center gap-1.5">
Superuser
<InfoHint>
Memiliki hak akses penuh ke semua fitur sistem tanpa pembatasan role.
</InfoHint>
</span>
</label>
</div>
<div className="flex justify-end">
<Button disabled={isSubmitting} type="submit">
{isSubmitting ? <Spinner className="size-4" /> : null}
{submitLabel}
</Button>
</div>
</form>
);
}
|