174 lines
13 KiB
TypeScript
174 lines
13 KiB
TypeScript
"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<T>(path: string, init?: RequestInit): Promise<T> {
|
||
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<Detail | null>(null);
|
||
const [name, setName] = useState("");
|
||
const [email, setEmail] = useState("");
|
||
const [selectedPages, setSelectedPages] = useState<Record<string, PageRole>>({});
|
||
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<void>) {
|
||
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 <div className="grid gap-5 xl:grid-cols-[300px_minmax(0,1fr)] items-start">
|
||
<div className="flex flex-col gap-5">
|
||
<section className="card">
|
||
<div className="card-head"><h2>ทีม</h2></div>
|
||
{teams.length ? <div className="card-body flex flex-col gap-2">{teams.map((team) =>
|
||
<button key={team.id} type="button" className={`btn justify-start ${selected === team.id ? "btn-primary" : "btn-ghost"}`} onClick={() => { setSelected(team.id); setDetail(null); setInviteUrl(""); setSelectedPages({}); setPageToAttach(""); setEmail(""); }}>{team.name}</button>
|
||
)}</div> : <EmptyState icon="users" title="ยังไม่มีทีม" hint="ตั้งชื่อทีมเพื่อเริ่มชวนคนทำงานร่วมกัน" />}
|
||
</section>
|
||
<section className="card">
|
||
<div className="card-head"><h2>สร้างทีมใหม่</h2></div>
|
||
<form className="card-body flex flex-col gap-3" onSubmit={createTeam}>
|
||
<label htmlFor="team-name" className="field"><span>ชื่อทีม *</span><span className="text-ink-3 text-[12px]">2–80 ตัวอักษร</span><input id="team-name" className="input" value={name} onChange={(e) => setName(e.target.value)} required aria-required="true" /></label>
|
||
<button type="submit" className="btn btn-primary" disabled={busy}><Icon name="plus" size={16} /> สร้างทีม</button>
|
||
</form>
|
||
</section>
|
||
</div>
|
||
<div className="flex flex-col gap-5">
|
||
{error && <Notice tone="red">{error}</Notice>}
|
||
{message && <Notice tone="blue">{message}</Notice>}
|
||
{detail && <>
|
||
<section className="card">
|
||
<div className="card-head"><h2>{detail.name}</h2><span className="ml-auto text-ink-3 text-[13px]">{detail.members.length} คน · {detail.pages.length} เพจ</span></div>
|
||
<div className="card-body flex flex-col gap-3">
|
||
<p className="text-ink-2 text-[13px]">สมาชิกจะเห็นเฉพาะเพจที่ได้รับสิทธิ์ และรับคำขออนุมัติของเพจนั้นได้</p>
|
||
{detail.pages.length === 0 ? <p className="text-ink-3 text-[13px]">ยังไม่มีเพจในทีม เพิ่มเพจที่คุณเป็นผู้จัดการด้านล่าง</p> : <ul className="flex flex-wrap gap-2">{detail.pages.map((p) => <li key={p.pageId} className="pill pill-blue">{p.page.name}</li>)}</ul>}
|
||
{(detail.ownerId === currentUserId || superadmin) && <form className="flex flex-col sm:flex-row gap-2" onSubmit={attachPage}>
|
||
<label htmlFor="team-page" className="sr-only">เพจที่จะเพิ่มเข้าทีม</label>
|
||
<select id="team-page" className="input flex-1" value={pageToAttach} onChange={(e) => setPageToAttach(e.target.value)} required>
|
||
<option value="">เลือกเพจที่จะเพิ่ม</option>
|
||
{pages.filter((p) => !detail.pages.some((x) => x.pageId === p.id)).map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
|
||
</select>
|
||
<button type="submit" className="btn btn-primary" disabled={busy}>เพิ่มเพจ</button>
|
||
</form>}
|
||
</div>
|
||
</section>
|
||
{canManage && <section className="card">
|
||
<div className="card-head"><h2>เชิญสมาชิก</h2></div>
|
||
<form className="card-body flex flex-col gap-3" onSubmit={invite}>
|
||
<label htmlFor="team-invite-email" className="field"><span>อีเมลผู้รับ *</span><input id="team-invite-email" type="email" inputMode="email" autoComplete="email" className="input" value={email} onChange={(e) => setEmail(e.target.value)} required aria-required="true" /></label>
|
||
<fieldset className="flex flex-col gap-2"><legend className="font-medium mb-2">ให้สิทธิ์ในเพจ</legend>
|
||
{detail.pages.length === 0 && <p className="text-ink-3 text-[13px]">เชิญเข้าทีมก่อน แล้วค่อยเพิ่มสิทธิ์รายเพจได้</p>}
|
||
{detail.pages.map((p) => <div key={p.pageId} className="flex flex-col sm:flex-row sm:items-center gap-2">
|
||
<label className="flex items-center gap-2 flex-1"><input type="checkbox" checked={p.pageId in selectedPages} onChange={(e) => setSelectedPages((cur) => { const next = { ...cur }; if (e.target.checked) next[p.pageId] = "EDITOR"; else delete next[p.pageId]; return next; })} />{p.page.name}</label>
|
||
{p.pageId in selectedPages && <select className="input" aria-label={`สิทธิ์ในเพจ ${p.page.name}`} value={selectedPages[p.pageId]} onChange={(e) => setSelectedPages((cur) => ({ ...cur, [p.pageId]: e.target.value as PageRole }))}>{ROLES.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}</select>}
|
||
</div>)}
|
||
</fieldset>
|
||
<button type="submit" className="btn btn-primary self-start" disabled={busy}><Icon name="link" size={16} /> สร้างลิงก์คำเชิญ</button>
|
||
{inviteUrl && <div className="flex flex-col sm:flex-row gap-2"><input className="input flex-1" readOnly value={inviteUrl} aria-label="ลิงก์คำเชิญ" /><button type="button" className="btn btn-ghost" onClick={() => navigator.clipboard.writeText(inviteUrl).then(() => setMessage("คัดลอกลิงก์แล้ว")).catch(() => setError("คัดลอกไม่ได้ กรุณาคัดลอกจากช่องลิงก์"))}>คัดลอก</button></div>}
|
||
</form>
|
||
</section>}
|
||
<section className="card">
|
||
<div className="card-head"><h2>สมาชิก</h2></div>
|
||
<ul>{detail.members.map((m) => <li key={m.userId} className="px-[18px] py-3 border-b border-line-2 last:border-0 flex flex-col gap-2">
|
||
<div className="flex items-center gap-2"><span className="font-medium">{m.user.name}</span><span className="text-ink-3 text-[12px]">{m.user.email}</span><span className="pill pill-blue ml-auto">{m.role === "OWNER" ? "เจ้าของ" : m.role === "ADMIN" ? "ผู้ดูแลทีม" : "สมาชิก"}</span></div>
|
||
{canManage && m.role !== "OWNER" && <div className="flex flex-wrap items-center gap-2">
|
||
{detail.pages.map((p) => <label key={p.pageId} className="flex items-center gap-1 text-[12px]">{p.page.name}<select className="input" value={p.page.members.find((x) => x.userId === m.userId)?.role ?? ""} onChange={(e) => setRole(m.userId, p.pageId, e.target.value)} disabled={busy}><option value="">ไม่ให้สิทธิ์</option>{ROLES.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}</select></label>)}
|
||
{detail.ownerId === currentUserId && <select className="input" aria-label={`สิทธิ์ในทีมของ ${m.user.name}`} value={m.role} disabled={busy} onChange={(e) => run(async () => { await request(`/api/teams/${selected}/members`, { method: "PUT", body: JSON.stringify({ userId: m.userId, teamRole: e.target.value }) }); await reload(); })}><option value="MEMBER">สมาชิก</option><option value="ADMIN">ผู้ดูแลทีม</option></select>}
|
||
<button type="button" className="btn btn-ghost btn-sm text-danger" disabled={busy} onClick={() => removeMember(m.userId, m.user.name)}>ถอดออก</button>
|
||
</div>}
|
||
</li>)}</ul>
|
||
</section>
|
||
{canManage && detail.invites.length > 0 && <section className="card"><div className="card-head"><h2>คำเชิญที่รอตอบรับ</h2></div><ul>{detail.invites.map((i) => <li key={i.id} className="px-[18px] py-3 flex items-center gap-2 border-b border-line-2 last:border-0"><span className="flex-1">{i.email}</span><button type="button" className="btn btn-ghost btn-sm" disabled={busy} onClick={() => run(async () => { await request(`/api/teams/${selected}/invites?inviteId=${i.id}`, { method: "DELETE" }); await reload(); })}>ยกเลิก</button></li>)}</ul></section>}
|
||
</>}
|
||
</div>
|
||
</div>;
|
||
}
|