Add self-service teams and assigned post approvals
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { withBase } from "@/lib/base-path";
|
||||
import { Icon } from "./Icon";
|
||||
import { Notice } from "./ui";
|
||||
|
||||
type Info = { team: string; email: string; existingAccount: boolean };
|
||||
|
||||
export function JoinInvite({ token }: { token: string }) {
|
||||
const router = useRouter();
|
||||
const [info, setInfo] = useState<Info | null>(null);
|
||||
const [name, setName] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetch(withBase(`/api/team-invites/${token}`), { cache: "no-store" }).then(async (r) => {
|
||||
const data = await r.json();
|
||||
if (!r.ok) throw new Error(data.error ?? "ไม่พบคำเชิญ");
|
||||
setInfo(data);
|
||||
}).catch((e) => setError((e as Error).message)).finally(() => setLoading(false));
|
||||
}, [token]);
|
||||
|
||||
async function accept(e: React.FormEvent) {
|
||||
e.preventDefault(); setBusy(true); setError("");
|
||||
try {
|
||||
const res = await fetch(withBase(`/api/team-invites/${token}`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, password }) });
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error ?? "รับคำเชิญไม่สำเร็จ");
|
||||
router.replace("/teams"); router.refresh();
|
||||
} catch (e) { setError((e as Error).message); } finally { setBusy(false); }
|
||||
}
|
||||
|
||||
return <div className="max-w-lg mx-auto">
|
||||
<div className="flex items-center gap-3 mb-8"><span className="w-10 h-10 bg-blue rounded-xl text-white grid place-items-center"><Icon name="users" size={22} /></span><span className="font-bold text-lg">คำเชิญเข้าทีม</span></div>
|
||||
<section className="card"><div className="card-head"><h1 className="text-xl font-bold">ร่วมงานกับทีม</h1></div><div className="card-body flex flex-col gap-4">
|
||||
{loading && <p className="text-ink-3">กำลังตรวจคำเชิญ…</p>}
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
{info && <>
|
||||
<p>ทีม <strong>{info.team}</strong> เชิญ <strong>{info.email}</strong> เข้าร่วม</p>
|
||||
<form onSubmit={accept} className="flex flex-col gap-3">
|
||||
{info.existingAccount ? <p className="text-ink-2 text-[13px]">หากมีบัญชีอยู่แล้ว ให้เข้าสู่ระบบด้วยอีเมลนี้ก่อนกดรับคำเชิญ</p> : <>
|
||||
<label htmlFor="join-name" className="field"><span>ชื่อที่แสดง *</span><input id="join-name" className="input" value={name} onChange={(e) => setName(e.target.value)} required aria-required="true" maxLength={100} autoComplete="name" /></label>
|
||||
<label htmlFor="join-password" className="field"><span>รหัสผ่านใหม่ *</span><span className="text-ink-3 text-[12px]">ใช้อย่างน้อย 10 ตัวอักษร</span><input id="join-password" type="password" className="input" value={password} onChange={(e) => setPassword(e.target.value)} required aria-required="true" minLength={10} autoComplete="new-password" /></label>
|
||||
</>}
|
||||
<button type="submit" className="btn btn-primary" disabled={busy}>{busy ? "กำลังรับคำเชิญ…" : "รับคำเชิญ"}</button>
|
||||
</form>
|
||||
{info.existingAccount && <Link className="text-blue underline text-[13px]" href={`/login?from=${encodeURIComponent(`/join/${token}`)}`}>เข้าสู่ระบบด้วยอีเมลที่ได้รับคำเชิญ</Link>}
|
||||
</>}
|
||||
</div></section>
|
||||
</div>;
|
||||
}
|
||||
@@ -86,6 +86,8 @@ export function PostEditor({
|
||||
log = [],
|
||||
approvalsCount = 0,
|
||||
requiredApprovals = 1,
|
||||
approvers = [],
|
||||
approvalRequest = null,
|
||||
currentUserId,
|
||||
superadmin,
|
||||
initialDay,
|
||||
@@ -96,6 +98,8 @@ export function PostEditor({
|
||||
log?: EditorLogEntry[];
|
||||
approvalsCount?: number;
|
||||
requiredApprovals?: number;
|
||||
approvers?: { pageId: string; id: string; name: string; email: string; superadmin: boolean }[];
|
||||
approvalRequest?: { assigneeId: string; requesterId: string; status: string; assignee: { name: string } } | null;
|
||||
currentUserId: string;
|
||||
superadmin: boolean;
|
||||
initialDay?: string;
|
||||
@@ -113,16 +117,21 @@ export function PostEditor({
|
||||
const [targets, setTargets] = useState<Target[]>(post?.targets ?? ["FACEBOOK"]);
|
||||
const [scheduleAt, setScheduleAt] = useState(() => toBangkokInput(new Date(Date.now() + 60 * 60 * 1000)));
|
||||
const [note, setNote] = useState("");
|
||||
const [assigneeId, setAssigneeId] = useState(approvalRequest?.assigneeId ?? "");
|
||||
const [plannedDay, setPlannedDay] = useState(initialDay ?? "");
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const page = pages.find((p) => p.id === pageId) ?? null;
|
||||
const eligibleApprovers = approvers.filter((a) => a.pageId === pageId && (a.superadmin || (a.id !== currentUserId && a.id !== post?.createdById && a.id !== post?.lastEditedById)));
|
||||
const selectedAssigneeId = eligibleApprovers.some((a) => a.id === assigneeId) ? assigneeId : eligibleApprovers[0]?.id ?? "";
|
||||
const role = page?.role ?? null;
|
||||
const status: PostStatus = post?.status ?? "DRAFT";
|
||||
const editable = !post || EDITABLE.includes(status);
|
||||
const canEdit = roleAtLeast(role, "EDITOR") && editable;
|
||||
const canApprove = roleAtLeast(role, "APPROVER");
|
||||
const canDecide = canApprove && (!approvalRequest || approvalRequest.status !== "PENDING" || approvalRequest.assigneeId === currentUserId || superadmin);
|
||||
const canReassign = Boolean(post && status === "PENDING_APPROVAL" && roleAtLeast(role, "EDITOR") && (approvalRequest?.requesterId === currentUserId || role === "MANAGER" || superadmin));
|
||||
const ownWork = post && (post.lastEditedById === currentUserId || post.createdById === currentUserId);
|
||||
const selfBlocked = Boolean(ownWork && !superadmin);
|
||||
const dirty =
|
||||
@@ -178,9 +187,10 @@ export function PostEditor({
|
||||
|
||||
/** New post: create and submit in one tap. */
|
||||
async function saveAndSubmit() {
|
||||
if (!selectedAssigneeId) return setError("เลือกผู้อนุมัติก่อนส่งคำขอ");
|
||||
const id = await save({ navigate: false });
|
||||
if (!id) return;
|
||||
const body = await call("submit", `/api/posts/${id}`, { method: "POST", body: JSON.stringify({ action: "submit" }) });
|
||||
const body = await call("submit", `/api/posts/${id}`, { method: "POST", body: JSON.stringify({ action: "submit", assigneeId: selectedAssigneeId }) });
|
||||
toast.show(body ? "ส่งให้ผู้อนุมัติแล้ว" : "บันทึกฉบับร่างแล้ว แต่ส่งขออนุมัติไม่สำเร็จ", body ? "ok" : "warn");
|
||||
router.replace(`/posts/${id}`);
|
||||
}
|
||||
@@ -196,8 +206,15 @@ export function PostEditor({
|
||||
|
||||
async function act(action: string, extra: Record<string, unknown> = {}) {
|
||||
if (!post) return;
|
||||
if (dirty && canEdit && !(await save())) return;
|
||||
const body = await call(action, `/api/posts/${post.id}`, { method: "POST", body: JSON.stringify({ action, note: note || undefined, ...extra }) });
|
||||
if (dirty && canEdit) {
|
||||
if (!(await save())) return;
|
||||
if (["approve", "reject", "publish", "schedule"].includes(action)) {
|
||||
toast.show("บันทึกการแก้ไขแล้ว กรุณาส่งขออนุมัติใหม่", "warn");
|
||||
router.refresh();
|
||||
return;
|
||||
}
|
||||
}
|
||||
const body = await call(action, `/api/posts/${post.id}`, { method: "POST", body: JSON.stringify({ action, note: note || undefined, ...(action === "submit" ? { assigneeId: selectedAssigneeId } : {}), ...extra }) });
|
||||
if (body) {
|
||||
setNote("");
|
||||
toast.show(ACT_DONE[action] ?? "เรียบร้อย");
|
||||
@@ -216,7 +233,7 @@ export function PostEditor({
|
||||
? null
|
||||
: (status === "DRAFT" || status === "FAILED" || status === "CANCELLED") && roleAtLeast(role, "EDITOR")
|
||||
? { label: "ส่งขออนุมัติ", tone: "primary", run: () => act("submit") }
|
||||
: status === "PENDING_APPROVAL" && canApprove && !selfBlocked
|
||||
: status === "PENDING_APPROVAL" && canDecide && !selfBlocked
|
||||
? { label: "อนุมัติ", tone: "success", run: () => act("approve") }
|
||||
: status === "APPROVED" && canApprove
|
||||
? { label: "เผยแพร่ตอนนี้", tone: "success", run: () => act("publish") }
|
||||
@@ -358,6 +375,17 @@ export function PostEditor({
|
||||
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
|
||||
{canEdit && (status === "DRAFT" || status === "FAILED" || status === "CANCELLED") && (
|
||||
<div className="field">
|
||||
<label htmlFor="post-approver">ผู้อนุมัติ *</label>
|
||||
<select id="post-approver" className="input" value={selectedAssigneeId} onChange={(e) => setAssigneeId(e.target.value)} aria-required="true">
|
||||
{eligibleApprovers.length === 0 && <option value="">ยังไม่มีผู้อนุมัติในเพจนี้</option>}
|
||||
{eligibleApprovers.map((person) => <option key={person.id} value={person.id}>{person.name} ({person.email})</option>)}
|
||||
</select>
|
||||
{eligibleApprovers.length === 0 && <p className="text-ink-3 text-[13px]">ให้ผู้จัดการเพจเพิ่มผู้อนุมัติอีกคนก่อนส่งคำขอ</p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canEdit && (
|
||||
<div className="flex flex-wrap gap-2 pt-1">
|
||||
{/* On phones the save/submit pair lives in the action dock below. */}
|
||||
@@ -409,10 +437,18 @@ export function PostEditor({
|
||||
|
||||
{status === "PENDING_APPROVAL" && (
|
||||
<>
|
||||
{approvalRequest?.status === "PENDING" && <p className="text-ink-2 text-[13px]">ส่งถึง {approvalRequest.assignee.name}</p>}
|
||||
{canReassign && <div className="flex flex-col gap-2">
|
||||
<label htmlFor="reassign-approver" className="text-[13px] font-medium">เปลี่ยนผู้อนุมัติ</label>
|
||||
<select id="reassign-approver" className="input" value={selectedAssigneeId} onChange={(e) => setAssigneeId(e.target.value)}>
|
||||
{eligibleApprovers.map((person) => <option key={person.id} value={person.id}>{person.name} ({person.email})</option>)}
|
||||
</select>
|
||||
<button type="button" className="btn btn-ghost self-start" disabled={Boolean(busy) || !selectedAssigneeId || selectedAssigneeId === approvalRequest?.assigneeId} onClick={() => act("submit")}>ส่งให้ผู้อนุมัติคนใหม่</button>
|
||||
</div>}
|
||||
<p className="text-ink-2">
|
||||
อนุมัติแล้ว <b className="num">{approvalsCount}</b> / {requiredApprovals}
|
||||
</p>
|
||||
{canApprove ? (
|
||||
{canDecide ? (
|
||||
selfBlocked ? (
|
||||
<Notice tone="amber">คุณเป็นคนแก้โพสต์นี้ล่าสุด ต้องให้ผู้อนุมัติคนอื่นตรวจ</Notice>
|
||||
) : (
|
||||
@@ -429,7 +465,7 @@ export function PostEditor({
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<p className="text-ink-3 text-[13px]">รอผู้อนุมัติของเพจนี้ตรวจ</p>
|
||||
<p className="text-ink-3 text-[13px]">รอผู้อนุมัติที่ได้รับคำขอตรวจ</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -30,6 +30,7 @@ interface NavEntry {
|
||||
const WORK: NavEntry[] = [
|
||||
{ href: "/", label: "แผนคอนเทนต์", icon: "calendar", also: ["/calendar"] },
|
||||
{ href: "/posts", label: "โพสต์ทั้งหมด", icon: "post", count: "pendingApprovals" },
|
||||
{ href: "/approvals", label: "รอฉันอนุมัติ", icon: "check", count: "pendingApprovals" },
|
||||
{ href: "/inbox", label: "Inbox", icon: "inbox" },
|
||||
{ href: "/auto-reply", label: "Auto-reply", icon: "bolt" },
|
||||
{ href: "/insights", label: "Insights", icon: "chart" },
|
||||
@@ -37,6 +38,7 @@ const WORK: NavEntry[] = [
|
||||
];
|
||||
const SETTINGS: NavEntry[] = [
|
||||
{ href: "/account", label: "บัญชีของฉัน", icon: "users" },
|
||||
{ href: "/teams", label: "ทีมของฉัน", icon: "users" },
|
||||
{ href: "/pages", label: "เพจที่เชื่อม", icon: "pages" },
|
||||
{ href: "/profile", label: "โปรไฟล์ร้าน", icon: "store" },
|
||||
{ href: "/users", label: "ผู้ใช้", icon: "users", superadmin: true },
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
"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>;
|
||||
}
|
||||
Reference in New Issue
Block a user