Spaces:
Running
Running
File size: 17,841 Bytes
968ca90 f1ef83d 968ca90 f1ef83d 968ca90 f1ef83d 968ca90 f1ef83d 968ca90 f1ef83d 968ca90 f1ef83d 968ca90 f1ef83d 968ca90 | 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 | "use client";
import React, { useCallback, useEffect, useState } from "react";
import { Check, Edit3, Palette, Shield, ShieldAlert, Trash2, UserPlus } from "lucide-react";
import { appendActivity } from "@/features/activity";
import { useAuth } from "@/features/auth";
import { PermissionSet, PublicUser } from "@/shared/types/domain";
import { Badge, Button, EmptyState, Modal, Skeleton, useToast } from "@/shared/ui";
import {
ActiveUiVersion,
deleteUserAdmin,
getActiveUiAdmin,
listUsersAdmin,
saveUserAdmin,
setActiveUiAdmin,
} from "../api/adminApi";
interface FormState {
isEdit: boolean;
username: string;
displayName: string;
role: "admin" | "user";
password: string;
permissions: PermissionSet;
active: boolean;
}
const DEFAULT_FORM: FormState = {
isEdit: false,
username: "",
displayName: "",
role: "user",
password: "",
permissions: { can_upload: true, can_rename: false, can_delete: false },
active: true,
};
export function AdminUsersView() {
const { token, isAdmin } = useAuth();
const { notify } = useToast();
const [users, setUsers] = useState<PublicUser[]>([]);
const [loading, setLoading] = useState(true);
const [activeUi, setActiveUi] = useState<ActiveUiVersion>("v1");
const [switchingUi, setSwitchingUi] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
const [saving, setSaving] = useState(false);
const [form, setForm] = useState<FormState>(DEFAULT_FORM);
const loadUsers = useCallback(async () => {
if (!isAdmin) {
setLoading(false);
return;
}
setLoading(true);
try {
const [list, uiMode] = await Promise.all([
listUsersAdmin(token),
getActiveUiAdmin(token).catch(() => "v1" as ActiveUiVersion),
]);
setUsers(list);
setActiveUi(uiMode);
} catch (err) {
notify(err instanceof Error ? err.message : "Không thể tải danh sách người dùng.", "error");
} finally {
setLoading(false);
}
}, [isAdmin, notify, token]);
const handleSwitchUi = async (target: ActiveUiVersion) => {
if (switchingUi || target === activeUi) return;
setSwitchingUi(true);
try {
const updated = await setActiveUiAdmin(token, target);
setActiveUi(updated);
appendActivity(
"admin",
"Đổi giao diện hệ thống",
`Chuyển sang Frontend ${updated === "v2" ? "v2 (Editorial Studio Light)" : "v1 (Swiss-Obsidian Dark)"}`,
);
notify(`Đã chuyển giao diện hệ thống sang ${updated.toUpperCase()}. Đang tải lại...`, "success");
window.setTimeout(() => window.location.reload(), 450);
} catch (err) {
notify(err instanceof Error ? err.message : "Không thể đổi giao diện.", "error");
setSwitchingUi(false);
}
};
useEffect(() => {
loadUsers();
}, [loadUsers]);
if (!isAdmin) {
return (
<div className="p-6 max-w-2xl mx-auto w-full">
<EmptyState
icon={<ShieldAlert className="w-6 h-6 text-rose-400" aria-hidden="true" />}
title="Không có quyền truy cập khu vực Quản trị"
description="Chỉ tài khoản mang vai trò Admin mới có thể quản lý danh sách thành viên và cấp quyền RBAC."
/>
</div>
);
}
const openCreate = () => {
setForm(DEFAULT_FORM);
setModalOpen(true);
};
const openEdit = (u: PublicUser) => {
setForm({
isEdit: true,
username: u.username,
displayName: u.display_name,
role: u.role,
password: "",
permissions: { ...u.permissions },
active: u.active,
});
setModalOpen(true);
};
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
setSaving(true);
try {
const saved = await saveUserAdmin(token, {
username: form.username.trim(),
display_name: form.displayName.trim(),
role: form.role,
password: form.password.trim() || undefined,
permissions: form.permissions,
active: form.active,
});
appendActivity("admin", "Cập nhật người dùng RBAC", `@${saved.username} (${saved.role})`);
notify(`Đã lưu cấu hình tài khoản @${saved.username}.`, "success");
setModalOpen(false);
await loadUsers();
} catch (err) {
notify(err instanceof Error ? err.message : "Lưu người dùng thất bại.", "error");
} finally {
setSaving(false);
}
};
const handleDelete = async (username: string) => {
if (!window.confirm(`Xóa tài khoản @${username}?`)) return;
try {
await deleteUserAdmin(token, username);
appendActivity("admin", "Xóa tài khoản người dùng", `@${username}`);
notify(`Đã xóa @${username}.`, "success");
await loadUsers();
} catch (err) {
notify(err instanceof Error ? err.message : "Không thể xóa tài khoản.", "error");
}
};
return (
<div className="p-4 sm:p-6 lg:p-8 max-w-7xl mx-auto w-full space-y-6">
<div className="surface-panel rounded-2xl p-6 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<Badge tone="amber" className="mb-2">
<Shield className="w-3.5 h-3.5" aria-hidden="true" />
<span>RBAC ACCESS MATRIX</span>
</Badge>
<h1 className="text-xl sm:text-2xl font-extrabold text-white tracking-tight">
Quản trị Người dùng & Phân quyền
</h1>
<p className="text-xs sm:text-sm text-slate-400 mt-1">
Tạo tài khoản mới, khóa hoặc mở khóa thành viên và điều chỉnh chi tiết quyền Upload / Rename / Delete.
</p>
</div>
<Button variant="primary" size="sm" onClick={openCreate}>
<UserPlus className="w-4 h-4" aria-hidden="true" />
<span>Thêm thành viên</span>
</Button>
</div>
{/* Frontend UI Switcher */}
<section aria-labelledby="ui-switcher-heading" className="surface-panel rounded-2xl p-6 space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 id="ui-switcher-heading" className="text-sm font-bold text-white flex items-center gap-2">
<Palette className="w-4 h-4 text-sky-400" aria-hidden="true" />
<span>Giao diện Hệ thống (Frontend Switcher)</span>
</h2>
<p className="text-xs text-slate-400 mt-0.5">
Chuyển đổi trực tiếp giao diện phục vụ cho toàn bộ người dùng tại domain chính.
</p>
</div>
<Badge tone={activeUi === "v2" ? "emerald" : "cyan"}>
Đang chạy: {activeUi === "v2" ? "v2 Editorial Light" : "v1 Swiss-Obsidian Dark"}
</Badge>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{[
{
id: "v1" as const,
name: "v1 — Swiss-Obsidian Dark",
desc: "Giao diện tối tương phản cao, Sidebar bên trái, điểm nhấn Cyan & Emerald.",
previewClass: "bg-[#07090e] border-sky-500/40",
},
{
id: "v2" as const,
name: "v2 — Editorial Paper Studio Light",
desc: "Giao diện sáng nền giấy Alabaster, Top Command Bar, Inspector trực tiếp, điểm nhấn Đỏ Chu Sa.",
previewClass: "bg-[#fafaf8] text-[#111318] border-orange-400/50",
},
].map((opt) => {
const isCurrent = activeUi === opt.id;
return (
<div
key={opt.id}
className={`rounded-2xl p-5 border flex flex-col justify-between gap-4 transition ${
isCurrent
? "bg-sky-500/10 border-sky-400/50"
: "bg-slate-950/70 border-slate-800"
}`}
>
<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
<span className="text-sm font-bold text-white">{opt.name}</span>
{isCurrent && (
<Badge tone="emerald">
<Check className="w-3 h-3" aria-hidden="true" />
<span>Đang áp dụng</span>
</Badge>
)}
</div>
<p className="text-xs text-slate-400 leading-relaxed">{opt.desc}</p>
</div>
<div className="flex items-center justify-between gap-3 pt-1">
<span
aria-hidden="true"
className={`w-16 h-6 rounded-md border ${opt.previewClass}`}
/>
<Button
variant={isCurrent ? "secondary" : "primary"}
size="sm"
disabled={isCurrent || switchingUi}
onClick={() => handleSwitchUi(opt.id)}
>
{isCurrent
? "Đang sử dụng"
: switchingUi
? "Đang chuyển..."
: "Áp dụng giao diện này"}
</Button>
</div>
</div>
);
})}
</div>
</section>
{loading ? (
<div className="space-y-3">
<Skeleton className="h-14 w-full rounded-2xl" />
<Skeleton className="h-14 w-full rounded-2xl" />
<Skeleton className="h-14 w-full rounded-2xl" />
</div>
) : (
<div className="surface-panel rounded-2xl overflow-x-auto">
<table className="w-full text-left text-xs">
<thead className="border-b border-slate-800 text-slate-400 font-mono uppercase">
<tr>
<th className="py-3.5 px-4">Tài khoản</th>
<th className="py-3.5 px-4">Vai trò</th>
<th className="py-3.5 px-4">Quyền RBAC</th>
<th className="py-3.5 px-4">Trạng thái</th>
<th className="py-3.5 px-4 text-right">Thao tác</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-800/70">
{users.map((u) => (
<tr key={u.username} className="hover:bg-white/[0.02]">
<td className="py-3.5 px-4">
<p className="font-bold text-white">{u.display_name || u.username}</p>
<p className="font-mono text-[11px] text-slate-400">@{u.username}</p>
</td>
<td className="py-3.5 px-4">
<Badge tone={u.role === "admin" ? "amber" : "cyan"}>
{u.role.toUpperCase()}
</Badge>
</td>
<td className="py-3.5 px-4">
<div className="flex flex-wrap gap-1.5">
{u.permissions.can_upload && <Badge tone="emerald">Upload</Badge>}
{u.permissions.can_rename && <Badge tone="cyan">Rename</Badge>}
{u.permissions.can_delete && <Badge tone="rose">Delete</Badge>}
{!u.permissions.can_upload &&
!u.permissions.can_rename &&
!u.permissions.can_delete && <Badge tone="slate">Read Only</Badge>}
</div>
</td>
<td className="py-3.5 px-4">
<Badge tone={u.active ? "emerald" : "rose"}>
{u.active ? "Active" : "Disabled"}
</Badge>
</td>
<td className="py-3.5 px-4">
<div className="flex items-center justify-end gap-1.5">
<Button variant="secondary" size="sm" onClick={() => openEdit(u)}>
<Edit3 className="w-3.5 h-3.5" aria-hidden="true" />
<span>Sửa</span>
</Button>
{u.username.toLowerCase() !== "admin" && (
<Button
variant="danger"
size="sm"
onClick={() => handleDelete(u.username)}
>
<Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
</Button>
)}
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<Modal
open={modalOpen}
onClose={() => setModalOpen(false)}
title={form.isEdit ? `Chỉnh sửa @${form.username}` : "Tạo tài khoản mới"}
>
<form onSubmit={handleSave} className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="space-y-1">
<label htmlFor="adm-username" className="block text-xs font-semibold text-slate-300">
Username
</label>
<input
id="adm-username"
type="text"
required
disabled={form.isEdit}
value={form.username}
onChange={(e) => setForm((prev) => ({ ...prev, username: e.target.value }))}
className="w-full px-3.5 py-2 rounded-xl bg-slate-950 border border-slate-800 text-xs sm:text-sm text-white disabled:opacity-60"
/>
</div>
<div className="space-y-1">
<label htmlFor="adm-display" className="block text-xs font-semibold text-slate-300">
Tên hiển thị
</label>
<input
id="adm-display"
type="text"
value={form.displayName}
onChange={(e) => setForm((prev) => ({ ...prev, displayName: e.target.value }))}
className="w-full px-3.5 py-2 rounded-xl bg-slate-950 border border-slate-800 text-xs sm:text-sm text-white"
/>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="space-y-1">
<label htmlFor="adm-role" className="block text-xs font-semibold text-slate-300">
Vai trò
</label>
<select
id="adm-role"
value={form.role}
onChange={(e) =>
setForm((prev) => ({
...prev,
role: e.target.value === "admin" ? "admin" : "user",
}))
}
className="w-full px-3.5 py-2 rounded-xl bg-slate-950 border border-slate-800 text-xs sm:text-sm text-white"
>
<option value="user">user</option>
<option value="admin">admin</option>
</select>
</div>
<div className="space-y-1">
<label htmlFor="adm-pass" className="block text-xs font-semibold text-slate-300">
{form.isEdit ? "Mật khẩu mới (để trống nếu giữ nguyên)" : "Mật khẩu"}
</label>
<input
id="adm-pass"
type="password"
required={!form.isEdit}
value={form.password}
onChange={(e) => setForm((prev) => ({ ...prev, password: e.target.value }))}
className="w-full px-3.5 py-2 rounded-xl bg-slate-950 border border-slate-800 text-xs sm:text-sm text-white"
/>
</div>
</div>
<div className="grid grid-cols-2 gap-2.5 pt-1">
{[
{ key: "can_upload", label: "Quyền Upload" },
{ key: "can_rename", label: "Quyền Rename" },
{ key: "can_delete", label: "Quyền Delete" },
].map((item) => (
<label
key={item.key}
className="p-3 rounded-xl bg-slate-900/80 border border-slate-800 flex items-center justify-between text-xs cursor-pointer"
>
<span className="text-slate-200">{item.label}</span>
<input
type="checkbox"
checked={form.permissions[item.key as keyof PermissionSet]}
disabled={form.role === "admin"}
onChange={(e) =>
setForm((prev) => ({
...prev,
permissions: {
...prev.permissions,
[item.key]: e.target.checked,
},
}))
}
className="w-4 h-4 accent-sky-400"
/>
</label>
))}
<label className="p-3 rounded-xl bg-slate-900/80 border border-slate-800 flex items-center justify-between text-xs cursor-pointer">
<span className="text-slate-200">Kích hoạt</span>
<input
type="checkbox"
checked={form.active}
onChange={(e) => setForm((prev) => ({ ...prev, active: e.target.checked }))}
className="w-4 h-4 accent-emerald-400"
/>
</label>
</div>
<div className="flex justify-end gap-2.5 pt-2">
<Button variant="ghost" onClick={() => setModalOpen(false)}>
Hủy
</Button>
<Button type="submit" variant="primary" disabled={saving}>
{saving ? "Đang lưu..." : "Lưu tài khoản"}
</Button>
</div>
</form>
</Modal>
</div>
);
}
|