"use client"; import { withBase } from "@/lib/base-path"; import { useState } from "react"; import { useRouter } from "next/navigation"; import type { GlobalRole, PageRole } from "@prisma/client"; import { PAGE_ROLE_LABEL } from "@/lib/auth/roles"; import { MIN_PASSWORD_LENGTH } from "@/lib/auth/policy"; import { Icon } from "./Icon"; import { formatDateTime, Notice } from "./ui"; interface UserRow { id: string; name: string; email: string; globalRole: GlobalRole; isActive: boolean; lastLoginAt: string | null; memberships: { role: PageRole; pageName: string }[]; } export function UsersManager({ users, currentUserId }: { users: UserRow[]; currentUserId: string }) { const router = useRouter(); const [form, setForm] = useState({ name: "", email: "", password: "", globalRole: "MEMBER" as GlobalRole }); const [error, setError] = useState(null); const [flash, setFlash] = useState(null); const [busy, setBusy] = useState(false); async function call(url: string, method: string, body: unknown, ok: string) { setBusy(true); setError(null); setFlash(null); const res = await fetch(withBase(url), { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); const data = await res.json().catch(() => ({})); setBusy(false); if (!res.ok) { setError(data.error ?? "ทำรายการไม่สำเร็จ"); return false; } setFlash(ok); router.refresh(); return true; } async function create(e: React.FormEvent) { e.preventDefault(); if (await call("/api/users", "POST", form, `สร้างบัญชี ${form.email} แล้ว — ผู้ใช้ต้องเปลี่ยนรหัสผ่านตอนเข้าครั้งแรก`)) { setForm({ name: "", email: "", password: "", globalRole: "MEMBER" }); } } function resetPassword(u: UserRow) { const password = window.prompt(`รหัสผ่านชั่วคราวใหม่ของ ${u.email} (อย่างน้อย ${MIN_PASSWORD_LENGTH} ตัวอักษร)`); if (password) call(`/api/users/${u.id}`, "PATCH", { password }, `ตั้งรหัสผ่านชั่วคราวให้ ${u.email} แล้ว`); } return (

บัญชีผู้ใช้ ({users.length})

{users.map((u) => ( ))}
ผู้ใช้ สิทธิ์ เพจ เข้าล่าสุด
{u.name}
{u.email}
{u.globalRole === "SUPERADMIN" ? ผู้ดูแลระบบ : สมาชิก} {!u.isActive && ปิดบัญชี} {u.globalRole === "SUPERADMIN" ? "ทุกเพจ" : u.memberships.map((m) => `${m.pageName} (${PAGE_ROLE_LABEL[m.role]})`).join(", ") || "—"} {formatDateTime(u.lastLoginAt)} {u.id !== currentUserId && (
)}

เพิ่มผู้ใช้

สิทธิ์ระบบ
{error && {error}} {flash && {flash}}
); }