"use client"; import { useEffect, useState } from "react"; import { useRouter } from "next/navigation"; import { withBase } from "@/lib/base-path"; import { Icon } from "./Icon"; import { EmptyState, Notice } from "./ui"; type PageRole = "VIEWER" | "EDITOR" | "APPROVER" | "MANAGER"; type TeamRole = "OWNER" | "ADMIN" | "MEMBER"; type Team = { id: string; name: string; ownerId: string }; type Detail = Team & { members: { userId: string; role: TeamRole; user: { name: string; email: string; isActive: boolean } }[]; pages: { pageId: string; page: { name: string; members: { userId: string; role: PageRole }[] } }[]; invites: { id: string; email: string; expiresAt: string }[]; }; const ROLES: { value: PageRole; label: string }[] = [ { value: "VIEWER", label: "ดูอย่างเดียว" }, { value: "EDITOR", label: "ผู้เขียน" }, { value: "APPROVER", label: "ผู้อนุมัติ" }, { value: "MANAGER", label: "ผู้จัดการเพจ" }, ]; async function request(path: string, init?: RequestInit): Promise { const res = await fetch(withBase(path), { ...init, headers: { "Content-Type": "application/json" }, cache: "no-store" }); const body = await res.json().catch(() => ({})); if (!res.ok) throw new Error(body.error ?? "ทำรายการไม่สำเร็จ"); return body as T; } export function TeamsManager({ currentUserId, superadmin, teams: initialTeams, pages }: { currentUserId: string; superadmin: boolean; teams: Team[]; pages: { id: string; name: string }[] }) { const router = useRouter(); const [teams, setTeams] = useState(initialTeams); const [selected, setSelected] = useState(initialTeams[0]?.id ?? ""); const [detail, setDetail] = useState(null); const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [selectedPages, setSelectedPages] = useState>({}); const [pageToAttach, setPageToAttach] = useState(""); const [inviteUrl, setInviteUrl] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const [message, setMessage] = useState(""); const canManage = superadmin || detail?.ownerId === currentUserId || detail?.members.some((m) => m.userId === currentUserId && m.role === "ADMIN"); async function reload(id = selected) { const [list, one] = await Promise.all([ request<{ teams: Team[] }>("/api/teams"), id ? request<{ team: Detail }>(`/api/teams/${id}`) : Promise.resolve(null), ]); setTeams(list.teams); setDetail(one?.team ?? null); router.refresh(); } useEffect(() => { if (!selected) return; let active = true; request<{ team: Detail }>(`/api/teams/${selected}`).then((data) => { if (active) setDetail(data.team); }).catch((e) => { if (active) setError((e as Error).message); }); return () => { active = false; }; }, [selected]); async function run(fn: () => Promise) { setBusy(true); setError(""); setMessage(""); try { await fn(); } catch (e) { setError((e as Error).message); } finally { setBusy(false); } } async function createTeam(e: React.FormEvent) { e.preventDefault(); await run(async () => { const data = await request<{ team: Team }>("/api/teams", { method: "POST", body: JSON.stringify({ name }) }); setName(""); setSelected(data.team.id); await reload(data.team.id); setMessage("สร้างทีมแล้ว"); }); } async function attachPage(e: React.FormEvent) { e.preventDefault(); if (!selected || !pageToAttach) return; await run(async () => { await request(`/api/teams/${selected}/pages`, { method: "POST", body: JSON.stringify({ pageId: pageToAttach }) }); setPageToAttach(""); await reload(); setMessage("เพิ่มเพจเข้าทีมแล้ว"); }); } async function invite(e: React.FormEvent) { e.preventDefault(); if (!selected) return; await run(async () => { const pageRoles = Object.entries(selectedPages).map(([pageId, role]) => ({ pageId, role })); const data = await request<{ url: string }>(`/api/teams/${selected}/invites`, { method: "POST", body: JSON.stringify({ email, pageRoles }) }); setInviteUrl(data.url); setEmail(""); setSelectedPages({}); await reload(); setMessage("สร้างคำเชิญแล้ว คัดลอกลิงก์ส่งให้ผู้รับ"); }); } async function setRole(userId: string, pageId: string, pageRole: string) { await run(async () => { await request(`/api/teams/${selected}/members`, { method: "PUT", body: JSON.stringify({ userId, pageId, pageRole }) }); await reload(); setMessage("อัปเดตสิทธิ์แล้ว"); }); } async function removeMember(userId: string, name: string) { if (!window.confirm(`ถอด ${name} ออกจากทีมและทุกเพจในทีม?`)) return; await run(async () => { await request(`/api/teams/${selected}/members?userId=${encodeURIComponent(userId)}`, { method: "DELETE" }); await reload(); setMessage("ถอดสมาชิกแล้ว"); }); } return

ทีม

{teams.length ?
{teams.map((team) => )}
: }

สร้างทีมใหม่

{error && {error}} {message && {message}} {detail && <>

{detail.name}

{detail.members.length} คน · {detail.pages.length} เพจ

สมาชิกจะเห็นเฉพาะเพจที่ได้รับสิทธิ์ และรับคำขออนุมัติของเพจนั้นได้

{detail.pages.length === 0 ?

ยังไม่มีเพจในทีม เพิ่มเพจที่คุณเป็นผู้จัดการด้านล่าง

:
    {detail.pages.map((p) =>
  • {p.page.name}
  • )}
} {(detail.ownerId === currentUserId || superadmin) &&
}
{canManage &&

เชิญสมาชิก

ให้สิทธิ์ในเพจ {detail.pages.length === 0 &&

เชิญเข้าทีมก่อน แล้วค่อยเพิ่มสิทธิ์รายเพจได้

} {detail.pages.map((p) =>
{p.pageId in selectedPages && }
)}
{inviteUrl &&
}
}

สมาชิก

    {detail.members.map((m) =>
  • {m.user.name}{m.user.email}{m.role === "OWNER" ? "เจ้าของ" : m.role === "ADMIN" ? "ผู้ดูแลทีม" : "สมาชิก"}
    {canManage && m.role !== "OWNER" &&
    {detail.pages.map((p) => )} {detail.ownerId === currentUserId && }
    }
  • )}
{canManage && detail.invites.length > 0 &&

คำเชิญที่รอตอบรับ

    {detail.invites.map((i) =>
  • {i.email}
  • )}
} }
; }