488 lines
24 KiB
TypeScript
488 lines
24 KiB
TypeScript
"use client";
|
|
import { withBase } from "@/lib/base-path";
|
|
|
|
import { useEffect, useState } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import type { PageRole } from "@prisma/client";
|
|
import { PAGE_ROLE_LABEL, PAGE_ROLES, roleAtLeast } from "@/lib/auth/roles";
|
|
import { Icon } from "./Icon";
|
|
import { PageAvatar } from "./PageAvatar";
|
|
import { EmptyState, formatDateTime, Notice } from "./ui";
|
|
|
|
interface PageRow {
|
|
id: string;
|
|
fbPageId: string;
|
|
name: string;
|
|
pictureUrl: string | null;
|
|
igUsername: string | null;
|
|
status: "ACTIVE" | "TOKEN_INVALID" | "DISCONNECTED";
|
|
statusDetail: string | null;
|
|
webhookSubscribedAt: string | null;
|
|
tokenCheckedAt: string | null;
|
|
memberCount: number;
|
|
role: PageRole;
|
|
}
|
|
|
|
interface Available {
|
|
fbPageId: string;
|
|
name: string;
|
|
pictureUrl: string | null;
|
|
igUsername: string | null;
|
|
connected: boolean;
|
|
canManage: boolean;
|
|
via: string | null;
|
|
}
|
|
|
|
interface Health {
|
|
health: { valid: boolean; scopes: string[]; missingScopes: string[]; detail: string | null };
|
|
subscribedFields: string[];
|
|
}
|
|
|
|
interface Member {
|
|
role: PageRole;
|
|
user: { id: string; name: string; email: string; isActive: boolean };
|
|
}
|
|
|
|
async function api<T>(url: string, init?: RequestInit): Promise<{ ok: true; data: T } | { ok: false; error: string }> {
|
|
const res = await fetch(withBase(url), { ...init, headers: { "Content-Type": "application/json" } });
|
|
const body = await res.json().catch(() => ({}));
|
|
return res.ok ? { ok: true, data: body as T } : { ok: false, error: body.error ?? "ทำรายการไม่สำเร็จ" };
|
|
}
|
|
|
|
interface Connection {
|
|
id: string;
|
|
name: string;
|
|
scopes: string[];
|
|
expiresAt: string | null;
|
|
pageCount: number;
|
|
}
|
|
|
|
export function PagesManager({
|
|
pages,
|
|
superadmin,
|
|
webhookUrl,
|
|
redirectUri,
|
|
connections,
|
|
systemUser,
|
|
appConfigured,
|
|
justConnected,
|
|
fbError,
|
|
}: {
|
|
pages: PageRow[];
|
|
superadmin: boolean;
|
|
webhookUrl: string;
|
|
redirectUri: string;
|
|
connections: Connection[];
|
|
systemUser: boolean;
|
|
appConfigured: boolean;
|
|
justConnected: boolean;
|
|
fbError: string | null;
|
|
}) {
|
|
const router = useRouter();
|
|
const [available, setAvailable] = useState<Available[] | null>(null);
|
|
const [sourceErrors, setSourceErrors] = useState<string[]>([]);
|
|
const [picked, setPicked] = useState<string[]>([]);
|
|
const [focus, setFocus] = useState<string | null>(null);
|
|
const [health, setHealth] = useState<Record<string, Health>>({});
|
|
const [members, setMembers] = useState<Member[] | null>(null);
|
|
const [users, setUsers] = useState<{ id: string; name: string; email: string }[]>([]);
|
|
const [newMember, setNewMember] = useState({ userId: "", role: "EDITOR" as PageRole });
|
|
const [busy, setBusy] = useState<string | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [flash, setFlash] = useState<string | null>(null);
|
|
|
|
const focused = pages.find((p) => p.id === focus) ?? null;
|
|
|
|
async function run<T>(label: string, fn: () => Promise<{ ok: true; data: T } | { ok: false; error: string }>): Promise<T | null> {
|
|
setBusy(label);
|
|
setError(null);
|
|
setFlash(null);
|
|
const r = await fn();
|
|
setBusy(null);
|
|
if (!r.ok) {
|
|
setError(r.error);
|
|
return null;
|
|
}
|
|
return r.data;
|
|
}
|
|
|
|
async function loadAvailable() {
|
|
const data = await run("available", () => api<{ available: Available[]; errors: string[]; noSource?: boolean }>("/api/pages?available=1"));
|
|
if (data) applyAvailable(data);
|
|
}
|
|
|
|
function applyAvailable(data: { available: Available[]; errors: string[]; noSource?: boolean }) {
|
|
if (data.noSource) {
|
|
setError("ยังไม่มีบัญชี Facebook ที่เชื่อม — กด “เข้าสู่ระบบด้วย Facebook” ก่อน");
|
|
return;
|
|
}
|
|
setAvailable(data.available);
|
|
setSourceErrors(data.errors ?? []);
|
|
setPicked(data.available.filter((a) => !a.connected && a.canManage).map((a) => a.fbPageId));
|
|
}
|
|
|
|
// Right after "Login with Facebook" returns, list the pages straight away.
|
|
useEffect(() => {
|
|
if (!justConnected) return;
|
|
let alive = true;
|
|
api<{ available: Available[]; errors: string[]; noSource?: boolean }>("/api/pages?available=1").then((r) => {
|
|
if (!alive) return;
|
|
if (r.ok) applyAvailable(r.data);
|
|
else setError(r.error);
|
|
});
|
|
return () => {
|
|
alive = false;
|
|
};
|
|
}, [justConnected]);
|
|
|
|
async function removeConnection(c: Connection) {
|
|
if (!window.confirm(`เลิกใช้บัญชี Facebook "${c.name}"? เพจที่เชื่อมแล้วยังทำงานต่อได้ แต่จะดึงรายชื่อเพจจากบัญชีนี้ไม่ได้`)) return;
|
|
if (await run("conn", () => api(`/api/facebook/connections?id=${c.id}`, { method: "DELETE" }))) router.refresh();
|
|
}
|
|
|
|
async function connect() {
|
|
const data = await run("connect", () =>
|
|
api<{ results: { name: string; ok: boolean; webhook: boolean; error?: string }[] }>("/api/pages", { method: "POST", body: JSON.stringify({ fbPageIds: picked }) })
|
|
);
|
|
if (!data) return;
|
|
const failed = data.results.filter((r) => !r.ok || !r.webhook);
|
|
setFlash(
|
|
failed.length
|
|
? `เชื่อมแล้ว แต่มีปัญหา: ${failed.map((f) => `${f.name} (${f.error ?? "subscribe webhook ไม่สำเร็จ"})`).join(", ")}`
|
|
: `เชื่อม ${data.results.length} เพจแล้ว`
|
|
);
|
|
setAvailable(null);
|
|
router.refresh();
|
|
}
|
|
|
|
async function openPage(id: string) {
|
|
setFocus(id);
|
|
setMembers(null);
|
|
const page = pages.find((p) => p.id === id)!;
|
|
const [h, m] = await Promise.all([
|
|
run("health", () => api<Health>(`/api/pages/${id}`)),
|
|
roleAtLeast(page.role, "MANAGER") ? api<{ members: Member[] }>(`/api/pages/${id}/members`) : Promise.resolve(null),
|
|
]);
|
|
if (h) setHealth((cur) => ({ ...cur, [id]: h }));
|
|
if (m?.ok) {
|
|
setMembers(m.data.members);
|
|
if (users.length === 0) {
|
|
const u = await api<{ users: { id: string; name: string; email: string }[] }>("/api/users");
|
|
if (u.ok) setUsers(u.data.users);
|
|
}
|
|
}
|
|
router.refresh();
|
|
}
|
|
|
|
async function resubscribe(id: string) {
|
|
if (await run("subscribe", () => api(`/api/pages/${id}`, { method: "POST", body: JSON.stringify({ action: "subscribe" }) }))) {
|
|
setFlash("subscribe webhook แล้ว");
|
|
openPage(id);
|
|
}
|
|
}
|
|
|
|
async function disconnect(page: PageRow) {
|
|
if (!window.confirm(`ถอดเพจ "${page.name}"? โพสต์และประวัติยังเก็บไว้ แต่ระบบจะหยุดรับข้อความและโพสต์ไม่ได้`)) return;
|
|
if (await run("disconnect", () => api(`/api/pages/${page.id}`, { method: "DELETE" }))) {
|
|
setFocus(null);
|
|
router.refresh();
|
|
}
|
|
}
|
|
|
|
async function setMember(userId: string, role: PageRole) {
|
|
if (!focus) return;
|
|
if (await run("member", () => api(`/api/pages/${focus}/members`, { method: "PUT", body: JSON.stringify({ userId, role }) }))) openPage(focus);
|
|
}
|
|
|
|
async function removeMember(userId: string) {
|
|
if (!focus) return;
|
|
if (await run("member", () => api(`/api/pages/${focus}/members?userId=${userId}`, { method: "DELETE" }))) openPage(focus);
|
|
}
|
|
|
|
return (
|
|
<div className="grid gap-5 grid-cols-[minmax(0,1fr)] xl:grid-cols-[minmax(0,1fr)_440px] items-start">
|
|
<div className="flex flex-col gap-5">
|
|
{fbError && <Notice tone="red" title="เชื่อม Facebook ไม่สำเร็จ">{fbError}</Notice>}
|
|
{justConnected && !fbError && <Notice tone="blue" title="เชื่อมบัญชี Facebook แล้ว">เลือกเพจที่จะใช้ในระบบด้านล่าง แล้วกดเชื่อม</Notice>}
|
|
{error && <Notice tone="red">{error}</Notice>}
|
|
{flash && <Notice tone="blue">{flash}</Notice>}
|
|
|
|
<section className="card">
|
|
<div className="card-head">
|
|
<h2>บัญชี Facebook</h2>
|
|
{appConfigured ? (
|
|
// Full navigation (not <Link>): the start route redirects to facebook.com.
|
|
<a href={withBase("/api/facebook/oauth/start")} className="btn btn-primary btn-sm ml-auto">
|
|
<Icon name="link" size={14} /> {connections.length ? "เชื่อมบัญชีเพิ่ม / ขอสิทธิ์ใหม่" : "เข้าสู่ระบบด้วย Facebook"}
|
|
</a>
|
|
) : (
|
|
<span className="pill pill-amber ml-auto">ยังไม่ได้ตั้ง META_APP_ID / SECRET</span>
|
|
)}
|
|
</div>
|
|
{connections.length === 0 && !systemUser ? (
|
|
<EmptyState icon="link" title="ยังไม่ได้เชื่อม Facebook" hint="เข้าสู่ระบบด้วยบัญชีที่เป็นแอดมินของเพจ แล้วเลือกเพจที่จะจัดการ" />
|
|
) : (
|
|
<ul>
|
|
{connections.map((c) => {
|
|
const expSoon = c.expiresAt && new Date(c.expiresAt).getTime() - Date.now() < 7 * 86400000;
|
|
return (
|
|
<li key={c.id} className="flex items-center gap-3 px-[18px] py-3 border-b border-line-2 last:border-0">
|
|
<span className="avatar w-9 h-9">{c.name.slice(0, 1)}</span>
|
|
<span className="flex-1 min-w-0">
|
|
<span className="block font-medium truncate">{c.name}</span>
|
|
<span className="block text-[12px] text-ink-3">
|
|
ใช้กับ {c.pageCount} เพจ · สิทธิ์ {c.scopes.length} รายการ
|
|
{c.expiresAt && <> · ดึงรายชื่อเพจได้ถึง {formatDateTime(c.expiresAt)}</>}
|
|
</span>
|
|
</span>
|
|
{expSoon && <span className="pill pill-amber">ใกล้หมดอายุ — เชื่อมใหม่</span>}
|
|
<button type="button" className="btn btn-ghost btn-sm" disabled={Boolean(busy)} onClick={loadAvailable}>
|
|
ดูเพจ
|
|
</button>
|
|
<button type="button" className="p-1.5 rounded-full text-ink-3 hover:text-danger" onClick={() => removeConnection(c)} aria-label={`เลิกใช้ ${c.name}`}>
|
|
<Icon name="x" size={14} />
|
|
</button>
|
|
</li>
|
|
);
|
|
})}
|
|
{systemUser && (
|
|
<li className="flex items-center gap-3 px-[18px] py-3">
|
|
<span className="avatar w-9 h-9">
|
|
<Icon name="shield" size={16} />
|
|
</span>
|
|
<span className="flex-1">
|
|
<span className="block font-medium">System user</span>
|
|
<span className="block text-[12px] text-ink-3">จาก META_SYSTEM_USER_TOKEN</span>
|
|
</span>
|
|
</li>
|
|
)}
|
|
</ul>
|
|
)}
|
|
</section>
|
|
|
|
<section className="card">
|
|
<div className="card-head">
|
|
<h2>เพจ ({pages.length})</h2>
|
|
<button type="button" className="btn btn-primary btn-sm ml-auto" disabled={busy === "available"} onClick={loadAvailable}>
|
|
<Icon name="plus" size={14} /> {busy === "available" ? "กำลังดึงรายชื่อเพจ…" : "เชื่อมเพจ"}
|
|
</button>
|
|
</div>
|
|
{pages.length === 0 ? (
|
|
<EmptyState icon="pages" title="ยังไม่มีเพจ" hint="เชื่อมบัญชี Facebook ของคุณแล้วเลือกเพจ หรือให้ผู้จัดการเพจเพิ่มสิทธิ์คุณ" />
|
|
) : (
|
|
<ul>
|
|
{pages.map((p) => (
|
|
<li key={p.id}>
|
|
<button
|
|
type="button"
|
|
onClick={() => openPage(p.id)}
|
|
className={`w-full text-left flex items-center gap-3 px-[18px] py-3.5 border-b border-line-2 ${focus === p.id ? "bg-board" : "hover:bg-board"}`}
|
|
>
|
|
<PageAvatar name={p.name} src={p.pictureUrl} size={40} />
|
|
<span className="flex-1 min-w-0">
|
|
<span className="block font-medium truncate">{p.name}</span>
|
|
<span className="block text-[12px] text-ink-3 truncate">
|
|
{p.igUsername ? `IG @${p.igUsername}` : "ไม่ได้ผูก Instagram"} · สมาชิก {p.memberCount} คน · {PAGE_ROLE_LABEL[p.role]}
|
|
</span>
|
|
</span>
|
|
{p.status === "ACTIVE" ? (
|
|
p.statusDetail ? (
|
|
<span className="pill pill-amber">permission ไม่ครบ</span>
|
|
) : (
|
|
<span className="pill pill-green">
|
|
<span className="dot bg-green" /> ปกติ
|
|
</span>
|
|
)
|
|
) : (
|
|
<span className="pill pill-red">token ใช้ไม่ได้</span>
|
|
)}
|
|
{!p.webhookSubscribedAt && <span className="pill pill-amber">ไม่ได้ subscribe</span>}
|
|
</button>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
</section>
|
|
|
|
{available && (
|
|
<section className="card">
|
|
{sourceErrors.length > 0 && (
|
|
<div className="p-3">
|
|
<Notice tone="amber" title="ดึงเพจจากบางบัญชีไม่สำเร็จ">{sourceErrors.join(" · ")}</Notice>
|
|
</div>
|
|
)}
|
|
<div className="card-head">
|
|
<h2>เพจที่บัญชี Facebook จัดการได้</h2>
|
|
<button type="button" className="ml-auto p-1.5 rounded-full hover:bg-board" onClick={() => setAvailable(null)} aria-label="ปิด">
|
|
<Icon name="x" size={16} />
|
|
</button>
|
|
</div>
|
|
{available.length === 0 ? (
|
|
<EmptyState icon="pages" title="ไม่พบเพจ" hint="บัญชีที่เชื่อมต้องเป็นแอดมินของเพจ และตอน login ต้องติ๊กเลือกเพจให้แอป — กดเชื่อมบัญชีใหม่เพื่อเลือกเพจเพิ่ม" />
|
|
) : (
|
|
<>
|
|
<ul>
|
|
{available.map((a) => (
|
|
<li key={a.fbPageId}>
|
|
<label className="flex items-center gap-3 px-[18px] py-3 border-b border-line-2 cursor-pointer hover:bg-board">
|
|
<input
|
|
type="checkbox"
|
|
disabled={!a.canManage}
|
|
checked={picked.includes(a.fbPageId)}
|
|
onChange={(e) => setPicked((cur) => (e.target.checked ? [...cur, a.fbPageId] : cur.filter((x) => x !== a.fbPageId)))}
|
|
/>
|
|
<PageAvatar name={a.name} src={a.pictureUrl} size={32} />
|
|
<span className="flex-1 min-w-0">
|
|
<span className="block truncate">{a.name}</span>
|
|
<span className="block text-[12px] text-ink-3">
|
|
{a.igUsername ? `IG @${a.igUsername}` : "ไม่มี Instagram"}
|
|
{a.via && <> · ผ่าน {a.via}</>}
|
|
</span>
|
|
</span>
|
|
{!a.canManage && <span className="text-[12px] text-ink-3">ต้องมีสิทธิ์จัดการเพจบน Facebook</span>}
|
|
{a.connected && <span className="pill pill-blue">เชื่อมแล้ว (กดเพื่อรีเฟรช token)</span>}
|
|
</label>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
<div className="card-body flex justify-end">
|
|
<button type="button" className="btn btn-primary" disabled={picked.length === 0 || busy === "connect"} onClick={connect}>
|
|
{busy === "connect" ? "กำลังเชื่อม…" : `เชื่อม ${picked.length} เพจ`}
|
|
</button>
|
|
</div>
|
|
</>
|
|
)}
|
|
</section>
|
|
)}
|
|
</div>
|
|
|
|
{focused ? (
|
|
<div className="flex flex-col gap-5">
|
|
<section className="card">
|
|
<div className="card-head">
|
|
<PageAvatar name={focused.name} src={focused.pictureUrl} size={28} />
|
|
<h2 className="truncate">{focused.name}</h2>
|
|
</div>
|
|
<div className="card-body flex flex-col gap-3">
|
|
{busy === "health" && <p className="text-ink-3">กำลังเช็ก token…</p>}
|
|
{health[focused.id] && (
|
|
<>
|
|
{health[focused.id].health.valid ? (
|
|
health[focused.id].health.missingScopes.length ? (
|
|
<Notice tone="amber" title="permission ไม่ครบ">
|
|
{health[focused.id].health.missingScopes.join(", ")}
|
|
</Notice>
|
|
) : (
|
|
<Notice tone="blue" title="token ใช้งานได้">
|
|
permission ครบ
|
|
</Notice>
|
|
)
|
|
) : (
|
|
<Notice tone="red" title="token ใช้ไม่ได้">
|
|
{health[focused.id].health.detail} — เช็กว่าเพจยัง assign ให้ system user แล้วกด “เชื่อมเพจ” เพื่อรีเฟรช token
|
|
</Notice>
|
|
)}
|
|
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5 text-[13px]">
|
|
<dt className="text-ink-3">Page ID</dt>
|
|
<dd className="num">{focused.fbPageId}</dd>
|
|
<dt className="text-ink-3">Webhook fields</dt>
|
|
<dd>{health[focused.id].subscribedFields.join(", ") || <span className="text-danger">ไม่ได้ subscribe</span>}</dd>
|
|
<dt className="text-ink-3">เช็กล่าสุด</dt>
|
|
<dd className="num">{formatDateTime(focused.tokenCheckedAt)}</dd>
|
|
</dl>
|
|
</>
|
|
)}
|
|
{superadmin && (
|
|
<div className="flex flex-wrap gap-2 pt-1">
|
|
<button type="button" className="btn btn-ghost btn-sm" disabled={Boolean(busy)} onClick={() => resubscribe(focused.id)}>
|
|
<Icon name="refresh" size={14} /> subscribe webhook ใหม่
|
|
</button>
|
|
<button type="button" className="btn btn-danger btn-sm ml-auto" disabled={Boolean(busy)} onClick={() => disconnect(focused)}>
|
|
ถอดเพจ
|
|
</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</section>
|
|
|
|
{members && (
|
|
<section className="card">
|
|
<div className="card-head">
|
|
<h2>สมาชิกเพจ</h2>
|
|
</div>
|
|
<ul>
|
|
{members.map((m) => (
|
|
<li key={m.user.id} className="flex items-center gap-3 px-[18px] py-2.5 border-b border-line-2">
|
|
<span className="avatar w-8 h-8">{m.user.name.slice(0, 1)}</span>
|
|
<span className="flex-1 min-w-0">
|
|
<span className="block truncate">{m.user.name}</span>
|
|
<span className="block text-[12px] text-ink-3 truncate">{m.user.email}</span>
|
|
</span>
|
|
<select className="select h-8! w-auto! text-[13px]" value={m.role} onChange={(e) => setMember(m.user.id, e.target.value as PageRole)}>
|
|
{PAGE_ROLES.map((r) => (
|
|
<option key={r} value={r}>
|
|
{PAGE_ROLE_LABEL[r]}
|
|
</option>
|
|
))}
|
|
</select>
|
|
<button type="button" className="p-1.5 rounded-full text-ink-3 hover:text-danger" onClick={() => removeMember(m.user.id)} aria-label={`ถอด ${m.user.name}`}>
|
|
<Icon name="x" size={14} />
|
|
</button>
|
|
</li>
|
|
))}
|
|
{members.length === 0 && <li className="px-[18px] py-3 text-ink-3">ยังไม่มีสมาชิก (ผู้ดูแลระบบเข้าได้ทุกเพจอยู่แล้ว)</li>}
|
|
</ul>
|
|
<div className="card-body flex gap-2">
|
|
<select className="select flex-1" value={newMember.userId} onChange={(e) => setNewMember({ ...newMember, userId: e.target.value })}>
|
|
<option value="">เลือกผู้ใช้…</option>
|
|
{users
|
|
.filter((u) => !members.some((m) => m.user.id === u.id))
|
|
.map((u) => (
|
|
<option key={u.id} value={u.id}>
|
|
{u.name} ({u.email})
|
|
</option>
|
|
))}
|
|
</select>
|
|
<select className="select w-auto!" value={newMember.role} onChange={(e) => setNewMember({ ...newMember, role: e.target.value as PageRole })}>
|
|
{PAGE_ROLES.map((r) => (
|
|
<option key={r} value={r}>
|
|
{PAGE_ROLE_LABEL[r]}
|
|
</option>
|
|
))}
|
|
</select>
|
|
<button
|
|
type="button"
|
|
className="btn btn-primary"
|
|
disabled={!newMember.userId || Boolean(busy)}
|
|
onClick={() => {
|
|
setMember(newMember.userId, newMember.role);
|
|
setNewMember({ userId: "", role: "EDITOR" });
|
|
}}
|
|
>
|
|
เพิ่ม
|
|
</button>
|
|
</div>
|
|
</section>
|
|
)}
|
|
</div>
|
|
) : (
|
|
superadmin && (
|
|
<section className="card card-body flex flex-col gap-2 text-ink-2">
|
|
<b className="text-ink">ตั้งค่า Meta App (ครั้งเดียว)</b>
|
|
<ol className="list-decimal pl-5 flex flex-col gap-1.5">
|
|
<li>
|
|
developers.facebook.com → App → Facebook Login → Settings → Valid OAuth Redirect URIs ใส่ <code className="break-all">{redirectUri}</code>
|
|
</li>
|
|
<li>App อยู่โหมด Development: คนที่กด login ต้องมี role ในแอป (Admin/Developer/Tester) และเป็นแอดมินของเพจ</li>
|
|
<li>กด “เข้าสู่ระบบด้วย Facebook” → อนุญาตสิทธิ์ → เลือกเพจ → กดเชื่อม</li>
|
|
<li>
|
|
รับข้อความ/คอมเมนต์: App → Webhooks ตั้ง URL <code className="break-all">{webhookUrl}</code> (ต้องเป็น HTTPS สาธารณะ — localhost ใช้ไม่ได้)
|
|
</li>
|
|
</ol>
|
|
</section>
|
|
)
|
|
)}
|
|
</div>
|
|
);
|
|
}
|