"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(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(null); const [sourceErrors, setSourceErrors] = useState([]); const [picked, setPicked] = useState([]); const [focus, setFocus] = useState(null); const [health, setHealth] = useState>({}); const [members, setMembers] = useState(null); const [users, setUsers] = useState<{ id: string; name: string; email: string }[]>([]); const [newMember, setNewMember] = useState({ userId: "", role: "EDITOR" as PageRole }); const [busy, setBusy] = useState(null); const [error, setError] = useState(null); const [flash, setFlash] = useState(null); const focused = pages.find((p) => p.id === focus) ?? null; async function run(label: string, fn: () => Promise<{ ok: true; data: T } | { ok: false; error: string }>): Promise { 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(`/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 (
{fbError && {fbError}} {justConnected && !fbError && เลือกเพจที่จะใช้ในระบบด้านล่าง แล้วกดเชื่อม} {error && {error}} {flash && {flash}}

บัญชี Facebook

{appConfigured ? ( // Full navigation (not ): the start route redirects to facebook.com. {connections.length ? "เชื่อมบัญชีเพิ่ม / ขอสิทธิ์ใหม่" : "เข้าสู่ระบบด้วย Facebook"} ) : ( ยังไม่ได้ตั้ง META_APP_ID / SECRET )}
{connections.length === 0 && !systemUser ? ( ) : (
    {connections.map((c) => { const expSoon = c.expiresAt && new Date(c.expiresAt).getTime() - Date.now() < 7 * 86400000; return (
  • {c.name.slice(0, 1)} {c.name} ใช้กับ {c.pageCount} เพจ · สิทธิ์ {c.scopes.length} รายการ {c.expiresAt && <> · ดึงรายชื่อเพจได้ถึง {formatDateTime(c.expiresAt)}} {expSoon && ใกล้หมดอายุ — เชื่อมใหม่}
  • ); })} {systemUser && (
  • System user จาก META_SYSTEM_USER_TOKEN
  • )}
)}

เพจ ({pages.length})

{pages.length === 0 ? ( ) : (
    {pages.map((p) => (
  • ))}
)}
{available && (
{sourceErrors.length > 0 && (
{sourceErrors.join(" · ")}
)}

เพจที่บัญชี Facebook จัดการได้

{available.length === 0 ? ( ) : ( <>
    {available.map((a) => (
  • ))}
)}
)}
{focused ? (

{focused.name}

{busy === "health" &&

กำลังเช็ก token…

} {health[focused.id] && ( <> {health[focused.id].health.valid ? ( health[focused.id].health.missingScopes.length ? ( {health[focused.id].health.missingScopes.join(", ")} ) : ( permission ครบ ) ) : ( {health[focused.id].health.detail} — เช็กว่าเพจยัง assign ให้ system user แล้วกด “เชื่อมเพจ” เพื่อรีเฟรช token )}
Page ID
{focused.fbPageId}
Webhook fields
{health[focused.id].subscribedFields.join(", ") || ไม่ได้ subscribe}
เช็กล่าสุด
{formatDateTime(focused.tokenCheckedAt)}
)} {superadmin && (
)}
{members && (

สมาชิกเพจ

    {members.map((m) => (
  • {m.user.name.slice(0, 1)} {m.user.name} {m.user.email}
  • ))} {members.length === 0 &&
  • ยังไม่มีสมาชิก (ผู้ดูแลระบบเข้าได้ทุกเพจอยู่แล้ว)
  • }
)}
) : ( superadmin && (
ตั้งค่า Meta App (ครั้งเดียว)
  1. developers.facebook.com → App → Facebook Login → Settings → Valid OAuth Redirect URIs ใส่ {redirectUri}
  2. App อยู่โหมด Development: คนที่กด login ต้องมี role ในแอป (Admin/Developer/Tester) และเป็นแอดมินของเพจ
  3. กด “เข้าสู่ระบบด้วย Facebook” → อนุญาตสิทธิ์ → เลือกเพจ → กดเชื่อม
  4. รับข้อความ/คอมเมนต์: App → Webhooks ตั้ง URL {webhookUrl} (ต้องเป็น HTTPS สาธารณะ — localhost ใช้ไม่ได้)
) )}
); }