Initial commit: page-manager Next.js app with Coolify deploy support
Replace Vercel-specific infra (Cron, Blob) with self-hosted equivalents for deployment to Coolify: in-container cron scheduler (scripts/cron-runner.mjs) and disk-based upload storage served via /api/uploads/[...path]. Add Dockerfile, .dockerignore, and /api/health for container health checks. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { PageAvatar } from "./PageAvatar";
|
||||
import { Notice } from "./ui";
|
||||
import { useToast } from "./Toast";
|
||||
|
||||
export function AccountForm({ initial }: { initial: { name: string; email: string; bio: string; avatarUrl: string | null } }) {
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
const [name, setName] = useState(initial.name);
|
||||
const [bio, setBio] = useState(initial.bio);
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [preview, setPreview] = useState<string | null>(null);
|
||||
const [removeAvatar, setRemoveAvatar] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => () => { if (preview) URL.revokeObjectURL(preview); }, [preview]);
|
||||
|
||||
async function save(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const form = new FormData();
|
||||
form.set("name", name);
|
||||
form.set("bio", bio);
|
||||
form.set("removeAvatar", String(removeAvatar));
|
||||
if (file) form.set("avatar", file);
|
||||
try {
|
||||
const response = await fetch("/api/account", { method: "PUT", body: form });
|
||||
const json = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(json.error ?? "บันทึกไม่สำเร็จ");
|
||||
toast.show("บันทึกโปรไฟล์แล้ว");
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : "เชื่อมต่อไม่สำเร็จ ลองใหม่อีกครั้ง");
|
||||
} finally { setBusy(false); }
|
||||
}
|
||||
|
||||
return <form className="card max-w-[680px]" onSubmit={save}>
|
||||
<div className="card-head"><h2>โปรไฟล์ส่วนตัว</h2></div>
|
||||
<fieldset disabled={busy} className="card-body flex flex-col gap-5">
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<PageAvatar name={name || initial.email} src={removeAvatar ? null : preview ?? initial.avatarUrl} size={80} />
|
||||
<div className="flex-1 min-w-[200px]">
|
||||
<label className="field"><span>รูปโปรไฟล์</span>
|
||||
<input type="file" accept="image/jpeg,image/png,image/webp" aria-describedby="avatar-hint" onChange={(e) => {
|
||||
const next = e.target.files?.[0] ?? null;
|
||||
if (!next) return;
|
||||
if (!["image/jpeg", "image/png", "image/webp"].includes(next.type) || next.size > 2 * 1024 * 1024) {
|
||||
setError("ใช้รูป JPG, PNG หรือ WebP ขนาดไม่เกิน 2 MB"); e.target.value = ""; return;
|
||||
}
|
||||
setError(null); setFile(next); setPreview(URL.createObjectURL(next)); setRemoveAvatar(false); e.target.value = "";
|
||||
}} />
|
||||
</label>
|
||||
<p id="avatar-hint" className="text-[12px] text-ink-3 mt-1">JPG, PNG หรือ WebP ไม่เกิน 2 MB ระบบตัดรูปเป็นสี่เหลี่ยมจัตุรัส</p>
|
||||
{!removeAvatar && (initial.avatarUrl || file) && <button type="button" className="btn btn-ghost btn-sm mt-2" onClick={() => { setFile(null); setPreview(null); setRemoveAvatar(true); }}>ลบรูปโปรไฟล์</button>}
|
||||
</div>
|
||||
</div>
|
||||
<label className="field"><span>ชื่อที่แสดง</span><input className="input" autoComplete="name" required maxLength={100} value={name} onChange={(e) => setName(e.target.value)} /></label>
|
||||
<label className="field"><span>อีเมล</span><input className="input" type="email" value={initial.email} readOnly aria-describedby="email-hint" /><span id="email-hint" className="text-ink-3">ใช้เข้าสู่ระบบ ติดต่อผู้ดูแลระบบหากต้องเปลี่ยน</span></label>
|
||||
<label className="field"><span>แนะนำตัว</span><textarea className="textarea" rows={4} maxLength={500} value={bio} onChange={(e) => setBio(e.target.value)} placeholder="เช่น ดูแลคอนเทนต์และตอบแชทของร้าน" /><span className="text-ink-3">{bio.length}/500 ตัวอักษร</span></label>
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
<div><button className="btn btn-primary" disabled={busy}>{busy ? "กำลังบันทึก…" : "บันทึกโปรไฟล์"}</button></div>
|
||||
</fieldset>
|
||||
</form>;
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Icon } from "./Icon";
|
||||
import { EmptyState, formatDateTime, Notice, numberFmt } from "./ui";
|
||||
import type { AnalysisBrief, AnalysisReport } from "@/lib/analysis/types";
|
||||
|
||||
type Goal = AnalysisBrief["goal"];
|
||||
type Status = "QUEUED" | "RUNNING" | "COMPLETED" | "FAILED";
|
||||
|
||||
export interface AnalysisItem {
|
||||
id: string;
|
||||
status: Status;
|
||||
brief: AnalysisBrief;
|
||||
postCount: number;
|
||||
warnings: string[];
|
||||
report: AnalysisReport | null;
|
||||
budget: { testBaht: number; scaleBaht: number; reserveBaht: number; daily: number[] } | null;
|
||||
error: string | null;
|
||||
createdAt: string;
|
||||
finishedAt: string | null;
|
||||
requestedBy: string | null;
|
||||
}
|
||||
|
||||
// Keep in sync with GOALS in src/lib/analysis/plan.mjs.
|
||||
const GOAL_LABEL: Record<Goal, string> = { MESSAGES: "เพิ่มข้อความสอบถาม", SALES: "เพิ่มยอดขาย", AWARENESS: "เพิ่มการรับรู้" };
|
||||
|
||||
const STATUS_META: Record<Status, { label: string; pill: string }> = {
|
||||
QUEUED: { label: "รอคิว", pill: "pill-neutral" },
|
||||
RUNNING: { label: "กำลังวิเคราะห์", pill: "pill-blue" },
|
||||
COMPLETED: { label: "เสร็จแล้ว", pill: "pill-green" },
|
||||
FAILED: { label: "ไม่สำเร็จ", pill: "pill-red" },
|
||||
};
|
||||
|
||||
const baht = (n: number) => `${numberFmt.format(n)} บาท`;
|
||||
|
||||
export function AnalysisView({
|
||||
pageId,
|
||||
pageActive,
|
||||
canAnalyze,
|
||||
canWrite,
|
||||
briefDefaults,
|
||||
items,
|
||||
}: {
|
||||
pageId: string;
|
||||
pageActive: boolean;
|
||||
canAnalyze: boolean;
|
||||
/** Can create posts on this page — shows "ใช้ไอเดียนี้". */
|
||||
canWrite: boolean;
|
||||
/** Prefilled from the shop profile. */
|
||||
briefDefaults: { business: string; audience: string };
|
||||
items: AnalysisItem[];
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [selectedId, setSelectedId] = useState<string | null>(items[0]?.id ?? null);
|
||||
const selected = items.find((i) => i.id === selectedId) ?? items[0] ?? null;
|
||||
const pending = items.some((i) => i.status === "QUEUED" || i.status === "RUNNING");
|
||||
|
||||
// The worker updates rows out of band — poll while something is in flight.
|
||||
useEffect(() => {
|
||||
if (!pending) return;
|
||||
const t = setInterval(() => router.refresh(), 5000);
|
||||
return () => clearInterval(t);
|
||||
}, [pending, router]);
|
||||
|
||||
return (
|
||||
<div className="grid gap-5 grid-cols-[minmax(0,1fr)] xl:grid-cols-[380px_minmax(0,1fr)] items-start">
|
||||
<div className="flex flex-col gap-5 min-w-0">
|
||||
{canAnalyze ? (
|
||||
<BriefForm pageId={pageId} defaults={briefDefaults} disabled={!pageActive || pending} disabledReason={!pageActive ? "เพจนี้ยังเชื่อมไม่พร้อม — ไปแก้ที่หน้าเพจที่เชื่อมก่อน" : pending ? "รองานที่กำลังวิเคราะห์ให้เสร็จก่อน" : null} onQueued={(id) => { setSelectedId(id); router.refresh(); }} />
|
||||
) : (
|
||||
<Notice tone="blue" title="ดูผลได้อย่างเดียว">ผู้จัดการเพจเท่านั้นที่สั่งวิเคราะห์และวางงบได้</Notice>
|
||||
)}
|
||||
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>ประวัติการวิเคราะห์</h2>
|
||||
</div>
|
||||
{items.length === 0 ? (
|
||||
<EmptyState icon="target" title="ยังไม่เคยวิเคราะห์เพจนี้" hint="กรอกข้อมูลธุรกิจกับงบด้านบน แล้วกดเริ่มวิเคราะห์" />
|
||||
) : (
|
||||
<ul>
|
||||
{items.map((i) => (
|
||||
<li key={i.id}>
|
||||
<button
|
||||
type="button"
|
||||
className="w-full text-left flex items-start gap-3 px-[18px] py-3 border-b border-line-2 hover:bg-board aria-pressed:bg-board"
|
||||
aria-pressed={selected?.id === i.id}
|
||||
onClick={() => setSelectedId(i.id)}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<b className="num">{baht(i.brief.budgetBaht)}</b>
|
||||
<span className="text-ink-3 text-[13px] num">· {i.brief.days} วัน</span>
|
||||
<span className={`pill ${STATUS_META[i.status].pill}`}>{STATUS_META[i.status].label}</span>
|
||||
</div>
|
||||
<p className="text-[13px] text-ink-2 mt-1 truncate">{GOAL_LABEL[i.brief.goal]} — {i.brief.business}</p>
|
||||
<p className="text-[12px] text-ink-4 mt-0.5">{formatDateTime(i.createdAt)}{i.requestedBy ? ` · ${i.requestedBy}` : ""}</p>
|
||||
</div>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">{selected ? <ResultPanel item={selected} canWrite={canWrite} /> : null}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BriefForm({
|
||||
pageId,
|
||||
defaults,
|
||||
disabled,
|
||||
disabledReason,
|
||||
onQueued,
|
||||
}: {
|
||||
pageId: string;
|
||||
defaults: { business: string; audience: string };
|
||||
disabled: boolean;
|
||||
disabledReason: string | null;
|
||||
onQueued: (id: string) => void;
|
||||
}) {
|
||||
// Analysis caps these at 1,500 / 1,000 characters; the profile allows longer text.
|
||||
const [business, setBusiness] = useState(defaults.business.slice(0, 1500));
|
||||
const [audience, setAudience] = useState(defaults.audience.slice(0, 1000));
|
||||
const [goal, setGoal] = useState<Goal>("MESSAGES");
|
||||
const [budget, setBudget] = useState("");
|
||||
const [days, setDays] = useState("14");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
const res = await fetch("/api/analysis", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pageId, business, audience, goal, budgetBaht: Number(budget.replace(/,/g, "")), days: Number(days) }),
|
||||
}).catch(() => null);
|
||||
const body = res ? await res.json().catch(() => ({})) : {};
|
||||
setBusy(false);
|
||||
if (!res?.ok) return setError(body.error ?? "เริ่มวิเคราะห์ไม่สำเร็จ ลองใหม่อีกครั้ง");
|
||||
onQueued(body.id);
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="card" onSubmit={submit}>
|
||||
<div className="card-head">
|
||||
<h2>สั่งวิเคราะห์ใหม่</h2>
|
||||
</div>
|
||||
<div className="card-body flex flex-col gap-4">
|
||||
<label className="field">
|
||||
<span>ขายอะไร / ธุรกิจอะไร</span>
|
||||
<textarea className="textarea" rows={3} maxLength={1500} required value={business} onChange={(e) => setBusiness(e.target.value)} placeholder="เช่น ร้านเค้กโฮมเมด ส่งในกรุงเทพ ราคา 350–900 บาท" />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>กลุ่มลูกค้า (ถ้ารู้)</span>
|
||||
<textarea className="textarea" rows={2} maxLength={1000} value={audience} onChange={(e) => setAudience(e.target.value)} placeholder="เช่น ผู้หญิงวัยทำงาน 25–40 ซื้อเป็นของขวัญ" />
|
||||
</label>
|
||||
<div className="field">
|
||||
<span>เป้าหมายโฆษณา</span>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(Object.keys(GOAL_LABEL) as Goal[]).map((g) => (
|
||||
<button key={g} type="button" className="chip" aria-pressed={goal === g} onClick={() => setGoal(g)}>
|
||||
{GOAL_LABEL[g]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<label className="field">
|
||||
<span>งบรวมสูงสุด (บาท)</span>
|
||||
<input className="input num" inputMode="numeric" required value={budget} onChange={(e) => setBudget(e.target.value.replace(/[^\d,]/g, ""))} placeholder="5,000" />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>ระยะเวลา (วัน)</span>
|
||||
<input className="input num" type="number" min={1} max={90} required value={days} onChange={(e) => setDays(e.target.value)} />
|
||||
</label>
|
||||
</div>
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
{disabledReason && <p className="text-[13px] text-ink-3">{disabledReason}</p>}
|
||||
<button type="submit" className="btn btn-primary" disabled={disabled || busy}>
|
||||
<Icon name="target" size={16} /> {busy ? "กำลังดึงโพสต์จากเพจ…" : "เริ่มวิเคราะห์"}
|
||||
</button>
|
||||
<p className="text-[12px] text-ink-4">ใช้เวลาประมาณ 1–5 นาที ปิดหน้านี้ได้ ผลจะอยู่ในประวัติ</p>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function ResultPanel({ item, canWrite }: { item: AnalysisItem; canWrite: boolean }) {
|
||||
if (item.status === "QUEUED" || item.status === "RUNNING") {
|
||||
return (
|
||||
<section className="card">
|
||||
<EmptyState icon="clock" title={item.status === "QUEUED" ? "รอคิววิเคราะห์" : "กำลังวิเคราะห์โพสต์และวางแผน…"} hint={`อ่านโพสต์ ${numberFmt.format(item.postCount)} โพสต์ หน้านี้จะอัปเดตเองเมื่อเสร็จ`} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (item.status === "FAILED" || !item.report || !item.budget) {
|
||||
return (
|
||||
<section className="card card-body">
|
||||
<Notice tone="red" title="วิเคราะห์ไม่สำเร็จ">{item.error ?? "ไม่มีผลลัพธ์"}</Notice>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const { report, budget } = item;
|
||||
const spend = budget.testBaht + budget.scaleBaht;
|
||||
const minDaily = Math.min(...budget.daily);
|
||||
const maxDaily = Math.max(...budget.daily);
|
||||
const testDays = Math.max(1, Math.round((item.brief.days * report.budgetSplit.testPercent) / Math.max(1, report.budgetSplit.testPercent + report.budgetSplit.scalePercent)));
|
||||
const limitations = [...item.warnings, ...report.limitations];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>สรุป</h2>
|
||||
<span className="text-[12px] text-ink-4 ml-auto">{item.finishedAt ? formatDateTime(item.finishedAt) : ""}</span>
|
||||
</div>
|
||||
<div className="card-body flex flex-col gap-3">
|
||||
<p className="whitespace-pre-wrap leading-relaxed">{report.summary}</p>
|
||||
<p className="text-[12px] text-ink-4">ข้อเสนอจาก AI จากโพสต์ {numberFmt.format(item.postCount)} โพสต์ — เป็นประมาณการ ตรวจก่อนนำไปใช้</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>แบ่งงบ {baht(item.brief.budgetBaht)}</h2>
|
||||
</div>
|
||||
<div className="card-body flex flex-col gap-4">
|
||||
<div className="flex h-3 rounded-full overflow-hidden bg-board" aria-hidden>
|
||||
<span style={{ width: `${report.budgetSplit.testPercent}%`, background: "var(--m-yellow)" }} />
|
||||
<span style={{ width: `${report.budgetSplit.scalePercent}%`, background: "var(--m-green)" }} />
|
||||
<span style={{ width: `${report.budgetSplit.reservePercent}%`, background: "var(--line)" }} />
|
||||
</div>
|
||||
<dl className="grid grid-cols-1 sm:grid-cols-3 gap-3">
|
||||
<BudgetCell label="ทดสอบ" percent={report.budgetSplit.testPercent} amount={budget.testBaht} />
|
||||
<BudgetCell label="ขยายตัวที่ได้ผล" percent={report.budgetSplit.scalePercent} amount={budget.scaleBaht} />
|
||||
<BudgetCell label="สำรอง (ยังไม่ใช้)" percent={report.budgetSplit.reservePercent} amount={budget.reserveBaht} />
|
||||
</dl>
|
||||
<p className="text-[13px] text-ink-2 num">
|
||||
ใช้จริง {baht(spend)} ใน {item.brief.days} วัน ≈ {minDaily === maxDaily ? baht(minDaily) : `${numberFmt.format(minDaily)}–${baht(maxDaily)}`} ต่อวัน · ช่วงทดสอบประมาณ {testDays} วันแรก
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>แผนยิง Ads</h2>
|
||||
</div>
|
||||
<dl className="card-body grid gap-4">
|
||||
<Row label="Objective">{report.adsPlan.objective}</Row>
|
||||
<Row label="กลุ่มเป้าหมาย">{report.adsPlan.audience}</Row>
|
||||
<Row label="ชิ้นงานที่ควรทดสอบ">
|
||||
<ul className="list-disc pl-5 flex flex-col gap-1">
|
||||
{report.adsPlan.creatives.map((c, i) => (
|
||||
<li key={i}>{c}</li>
|
||||
))}
|
||||
</ul>
|
||||
</Row>
|
||||
<Row label="วิธีทดสอบ">{report.adsPlan.testPlan}</Row>
|
||||
<Row label="เมื่อไหร่ควรเพิ่มงบ">{report.adsPlan.scaleRule}</Row>
|
||||
<Row label="เมื่อไหร่ควรหยุด">{report.adsPlan.stopRule}</Row>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>สิ่งที่เห็นจากคอนเทนต์</h2>
|
||||
</div>
|
||||
<ul>
|
||||
{report.contentFindings.map((f, i) => (
|
||||
<li key={i} className="px-[18px] py-3.5 border-b border-line-2 last:border-0">
|
||||
<b>{f.finding}</b>
|
||||
<p className="text-[13px] text-ink-3 mt-1">หลักฐาน: {f.evidence}</p>
|
||||
<p className="text-[13px] text-ink-2 mt-1">
|
||||
<Icon name="right" size={13} className="inline -mt-0.5" /> {f.action}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>ไอเดียโพสต์ถัดไป</h2>
|
||||
</div>
|
||||
<div className="card-body grid gap-3 grid-cols-1 md:grid-cols-2">
|
||||
{report.contentIdeas.map((idea, i) => (
|
||||
<article key={i} className="rounded-lg border border-line p-3.5 flex flex-col gap-1.5">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<b>{idea.title}</b>
|
||||
<span className="pill pill-neutral">{idea.format}</span>
|
||||
</div>
|
||||
<p className="text-[13px] text-ink-2">Hook: {idea.hook}</p>
|
||||
<p className="text-[13px] text-ink-3">CTA: {idea.cta}</p>
|
||||
{canWrite && (
|
||||
<Link href={`/posts/new?analysis=${item.id}&idea=${i}`} className="btn btn-ghost btn-sm self-start mt-1">
|
||||
<Icon name="sparkle" size={14} /> ใช้ไอเดียนี้
|
||||
</Link>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>ตัวเลขที่ต้องติดตาม</h2>
|
||||
</div>
|
||||
<div className="card-body flex flex-wrap gap-2">
|
||||
{report.metricsToTrack.map((m, i) => (
|
||||
<span key={i} className="pill pill-blue">
|
||||
{m}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{limitations.length > 0 && (
|
||||
<Notice tone="amber" title="ข้อจำกัดของผลนี้">
|
||||
<ul className="list-disc pl-5 mt-1 flex flex-col gap-0.5">
|
||||
{limitations.map((l, i) => (
|
||||
<li key={i}>{l}</li>
|
||||
))}
|
||||
</ul>
|
||||
</Notice>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BudgetCell({ label, percent, amount }: { label: string; percent: number; amount: number }) {
|
||||
return (
|
||||
<div className="rounded-lg border border-line p-3">
|
||||
<dt className="text-[12px] text-ink-3">
|
||||
{label} <span className="num">{percent}%</span>
|
||||
</dt>
|
||||
<dd className="text-[18px] font-semibold num mt-0.5">{baht(amount)}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="grid gap-1 sm:grid-cols-[150px_minmax(0,1fr)]">
|
||||
<dt className="text-[13px] text-ink-3">{label}</dt>
|
||||
<dd className="text-[14px] whitespace-pre-wrap">{children}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Icon } from "./Icon";
|
||||
import { Notice } from "./ui";
|
||||
import { CAPTION_REFINEMENTS, type CaptionRefinement } from "@/lib/ai/shared";
|
||||
|
||||
interface Variant {
|
||||
angle: string;
|
||||
caption: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drafts or rewrites the caption with Claude. The chosen text only fills the
|
||||
* editor — saving and approval stay exactly as for hand-written posts.
|
||||
*/
|
||||
export function CaptionAssistant({
|
||||
pageId,
|
||||
targets,
|
||||
caption,
|
||||
initialTopic,
|
||||
onChange,
|
||||
}: {
|
||||
pageId: string;
|
||||
targets: string[];
|
||||
caption: string;
|
||||
initialTopic?: string;
|
||||
onChange: (text: string, fromAi: boolean) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(Boolean(initialTopic));
|
||||
const [topic, setTopic] = useState(initialTopic ?? "");
|
||||
const [variants, setVariants] = useState<Variant[]>([]);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [profileMissing, setProfileMissing] = useState(false);
|
||||
const [previous, setPrevious] = useState<string | null>(null);
|
||||
|
||||
async function run(input: { topic: string } | { refine: CaptionRefinement }) {
|
||||
const label = "refine" in input ? input.refine : "draft";
|
||||
setBusy(label);
|
||||
setError(null);
|
||||
const res = await fetch("/api/ai/caption", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pageId, targets, caption, ...input }),
|
||||
}).catch(() => null);
|
||||
const body = res ? await res.json().catch(() => ({})) : {};
|
||||
setBusy(null);
|
||||
if (!res?.ok) return setError(body.error ?? "AI ทำงานไม่สำเร็จ ลองใหม่อีกครั้ง");
|
||||
setVariants(body.variants ?? []);
|
||||
setProfileMissing(Boolean(body.profileMissing));
|
||||
}
|
||||
|
||||
function use(v: Variant) {
|
||||
setPrevious(caption);
|
||||
onChange(v.caption, true);
|
||||
setVariants([]);
|
||||
}
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<button type="button" className="btn btn-ghost btn-sm self-start" onClick={() => setOpen(true)}>
|
||||
<Icon name="sparkle" size={15} /> ให้ AI ช่วยเขียน caption
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="rounded-[12px] border border-line bg-board p-3.5 flex flex-col gap-3" aria-label="ผู้ช่วยเขียน caption">
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon name="sparkle" size={16} />
|
||||
<b className="text-[14px]">ให้ AI ช่วยเขียน</b>
|
||||
<button type="button" className="btn btn-ghost btn-sm ml-auto" onClick={() => setOpen(false)} aria-label="ปิดผู้ช่วย AI">
|
||||
<Icon name="x" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
<span>อยากโพสต์เรื่องอะไร</span>
|
||||
<textarea className="textarea" rows={2} maxLength={1000} value={topic} onChange={(e) => setTopic(e.target.value)} placeholder="เช่น โปรเค้กวันแม่ ลด 15% ถึง 12 ส.ค. สั่งล่วงหน้า 2 วัน" />
|
||||
</label>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button type="button" className="btn btn-primary btn-sm" disabled={busy !== null || !topic.trim()} onClick={() => run({ topic })}>
|
||||
<Icon name="sparkle" size={14} /> {busy === "draft" ? "AI กำลังเขียน…" : "เขียนให้ 3 แบบ"}
|
||||
</button>
|
||||
{caption.trim() && (
|
||||
<>
|
||||
<span className="text-[12px] text-ink-3 ml-1">ปรับข้อความที่มี:</span>
|
||||
{(Object.keys(CAPTION_REFINEMENTS) as CaptionRefinement[]).map((k) => (
|
||||
<button key={k} type="button" className="chip" disabled={busy !== null} onClick={() => run({ refine: k })}>
|
||||
{busy === k ? "กำลังปรับ…" : CAPTION_REFINEMENTS[k].label}
|
||||
</button>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
{profileMissing && (
|
||||
<p className="text-[12px] text-ink-3">
|
||||
ยังไม่มีโปรไฟล์ร้าน — <Link href="/profile" className="underline">ตั้งไว้</Link> แล้ว AI จะเขียนตรงกับร้านมากขึ้น
|
||||
</p>
|
||||
)}
|
||||
{previous !== null && variants.length === 0 && (
|
||||
<p className="text-[12px] text-ink-3">
|
||||
ใส่ข้อความจาก AI แล้ว ตรวจและแก้ได้ตามต้องการ ·{" "}
|
||||
<button type="button" className="underline" onClick={() => { onChange(previous, false); setPrevious(null); }}>
|
||||
เอาข้อความเดิมคืน
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{variants.length > 0 && (
|
||||
<ul className="flex flex-col gap-2">
|
||||
{variants.map((v, i) => (
|
||||
<li key={i} className="rounded-[10px] border border-line bg-paper p-3 flex flex-col gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="pill pill-blue">{v.angle || `แบบที่ ${i + 1}`}</span>
|
||||
<button type="button" className="btn btn-primary btn-sm ml-auto" onClick={() => use(v)}>
|
||||
{caption.trim() ? "แทนที่ด้วยแบบนี้" : "ใช้แบบนี้"}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-[14px] whitespace-pre-wrap break-words">{v.caption}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p className="text-[11px] text-ink-4">AI ร่างเท่านั้น — ตรวจราคาและข้อมูลในวงเล็บ [ ] ก่อนส่งอนุมัติ</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Small inline icon set (stroke icons, 24px grid) — no icon library dependency.
|
||||
const PATHS = {
|
||||
home: "M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z",
|
||||
post: "M4 4h16v16H4zM4 9h16M9 13h6M9 16h4",
|
||||
calendar: "M4 6h16v14H4zM4 10h16M8 3v4M16 3v4",
|
||||
inbox: "M4 5h16v11H9l-5 4zM8 10h8M8 13h5",
|
||||
bolt: "M13 2 4 14h7l-1 8 9-12h-7z",
|
||||
chart: "M4 20V10M10 20V4M16 20v-7M22 20H2",
|
||||
pages: "M5 3h10l4 4v14H5zM15 3v4h4M8 12h8M8 16h8",
|
||||
users: "M16 19v-1a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v1M9 10a3 3 0 1 0 0-6 3 3 0 0 0 0 6M22 19v-1a4 4 0 0 0-3-3.9M16 4.1a3 3 0 0 1 0 5.8",
|
||||
plus: "M12 5v14M5 12h14",
|
||||
check: "M5 12.5 10 17l9-10",
|
||||
x: "M6 6l12 12M18 6 6 18",
|
||||
clock: "M12 7v5l3 2M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18",
|
||||
alert: "M12 8v5M12 16.5v.5M10.3 3.9 2.4 18a2 2 0 0 0 1.7 3h15.8a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0",
|
||||
send: "M4 12 20 4l-6 16-3-7z",
|
||||
image: "M4 5h16v14H4zM4 15l5-5 4 4 3-3 4 4M15.5 9.5h.01",
|
||||
link: "M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1",
|
||||
refresh: "M20 11a8 8 0 0 0-14.9-3M4 4v4h4M4 13a8 8 0 0 0 14.9 3M20 20v-4h-4",
|
||||
trash: "M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3",
|
||||
menu: "M4 7h16M4 12h16M4 17h16",
|
||||
logout: "M15 4h4v16h-4M10 8l-4 4 4 4M6 12h10",
|
||||
chevron: "M8 10l4 4 4-4",
|
||||
left: "M15 6l-6 6 6 6",
|
||||
right: "M9 6l6 6-6 6",
|
||||
bot: "M12 3v3M6 8h12v10H6zM9 12h.01M15 12h.01M9 16h6M3 12v2M21 12v2",
|
||||
search: "M11 18a7 7 0 1 0 0-14 7 7 0 0 0 0 14M20 20l-4-4",
|
||||
shield: "M12 3 5 6v6c0 4 3 7.5 7 9 4-1.5 7-5 7-9V6z",
|
||||
target: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18M12 17a5 5 0 1 0 0-10 5 5 0 0 0 0 10M12 13a1 1 0 1 0 0-2 1 1 0 0 0 0 2",
|
||||
sparkle: "M11 3l1.8 5.2L18 10l-5.2 1.8L11 17l-1.8-5.2L4 10l5.2-1.8zM18.5 14.5l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8z",
|
||||
store: "M4 10v10h16V10M3 10l2-6h14l2 6zM9 20v-5h6v5",
|
||||
} as const;
|
||||
|
||||
export type IconName = keyof typeof PATHS;
|
||||
|
||||
export function Icon({ name, size = 18, className }: { name: IconName; size?: number; className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.8}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d={PATHS[name]} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
"use client";
|
||||
|
||||
/* eslint-disable @next/next/no-img-element -- Graph CDN attachment URLs */
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { isWithinMessagingWindow, MAX_MESSAGE_LENGTH, windowRemainingMs } from "@/lib/facebook/messagingWindow";
|
||||
import { Icon } from "./Icon";
|
||||
import { EmptyState, Notice } from "./ui";
|
||||
import { ReplyDrafts } from "./ReplyDrafts";
|
||||
|
||||
type Platform = "messenger" | "instagram";
|
||||
|
||||
interface Conversation {
|
||||
id: string;
|
||||
snippet: string;
|
||||
updatedTime: string;
|
||||
unreadCount: number;
|
||||
contacts: { id: string; name: string }[];
|
||||
}
|
||||
interface Message {
|
||||
id: string;
|
||||
createdTime: string;
|
||||
fromPage: boolean;
|
||||
fromName: string;
|
||||
text: string;
|
||||
imageUrls: string[];
|
||||
}
|
||||
interface Thread {
|
||||
messages: Message[];
|
||||
recipient: { id: string; name: string } | null;
|
||||
lastInboundAt: string | null;
|
||||
botEnabled: boolean;
|
||||
}
|
||||
|
||||
const timeFmt = new Intl.DateTimeFormat("th-TH", { dateStyle: "short", timeStyle: "short", timeZone: "Asia/Bangkok" });
|
||||
const POLL_MS = 30_000;
|
||||
|
||||
function remainingLabel(ms: number): string {
|
||||
const h = Math.floor(ms / 3600000);
|
||||
const m = Math.floor((ms % 3600000) / 60000);
|
||||
return h > 0 ? `${h} ชม. ${m} นาที` : `${m} นาที`;
|
||||
}
|
||||
|
||||
export function InboxView({ pageId, pageName, hasInstagram, canReply }: { pageId: string; pageName: string; hasInstagram: boolean; canReply: boolean }) {
|
||||
const [platform, setPlatform] = useState<Platform>("messenger");
|
||||
const [conversations, setConversations] = useState<Conversation[] | null>(null);
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
const [thread, setThread] = useState<Thread | null>(null);
|
||||
const [draft, setDraft] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [sending, setSending] = useState(false);
|
||||
|
||||
const base = `/api/inbox/${pageId}/conversations`;
|
||||
|
||||
// Fetchers return data; state is only set in their promise callbacks.
|
||||
const fetchList = useCallback(async (): Promise<{ conversations: Conversation[]; error?: string }> => {
|
||||
const res = await fetch(`${base}?platform=${platform}`, { cache: "no-store" });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
return res.ok ? { conversations: body.conversations } : { conversations: [], error: body.error ?? "โหลดรายการแชทไม่สำเร็จ" };
|
||||
}, [base, platform]);
|
||||
|
||||
const fetchThread = useCallback(
|
||||
async (id: string): Promise<{ thread?: Thread; error?: string }> => {
|
||||
const res = await fetch(`${base}/${id}?platform=${platform}`, { cache: "no-store" });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
return res.ok ? { thread: body } : { error: body.error ?? "โหลดข้อความไม่สำเร็จ" };
|
||||
},
|
||||
[base, platform]
|
||||
);
|
||||
|
||||
const loadList = useCallback(() => {
|
||||
fetchList().then((r) => {
|
||||
setConversations(r.conversations);
|
||||
if (r.error) setError(r.error);
|
||||
});
|
||||
}, [fetchList]);
|
||||
|
||||
const loadThread = useCallback(
|
||||
(id: string) => {
|
||||
fetchThread(id).then((r) => (r.thread ? setThread(r.thread) : setError(r.error ?? null)));
|
||||
},
|
||||
[fetchThread]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const tick = () =>
|
||||
fetchList().then((r) => {
|
||||
if (!alive) return;
|
||||
setConversations(r.conversations);
|
||||
if (r.error) setError(r.error);
|
||||
});
|
||||
tick();
|
||||
const t = setInterval(tick, POLL_MS);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(t);
|
||||
};
|
||||
}, [fetchList]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeId) return;
|
||||
let alive = true;
|
||||
const tick = () =>
|
||||
fetchThread(activeId).then((r) => {
|
||||
if (!alive) return;
|
||||
if (r.thread) setThread(r.thread);
|
||||
else setError(r.error ?? null);
|
||||
});
|
||||
tick();
|
||||
const t = setInterval(tick, POLL_MS);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(t);
|
||||
};
|
||||
}, [activeId, fetchThread]);
|
||||
|
||||
function switchPlatform(p: Platform) {
|
||||
if (p === platform) return;
|
||||
setConversations(null);
|
||||
setActiveId(null);
|
||||
setThread(null);
|
||||
setError(null);
|
||||
setPlatform(p);
|
||||
}
|
||||
|
||||
function openConversation(id: string) {
|
||||
if (id === activeId) return;
|
||||
setThread(null);
|
||||
setActiveId(id);
|
||||
}
|
||||
|
||||
async function send() {
|
||||
if (!activeId || !draft.trim()) return;
|
||||
setSending(true);
|
||||
setError(null);
|
||||
const res = await fetch(`${base}/${activeId}?platform=${platform}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ text: draft }),
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
setSending(false);
|
||||
if (!res.ok) return setError(body.error ?? "ส่งข้อความไม่สำเร็จ");
|
||||
setDraft("");
|
||||
loadThread(activeId);
|
||||
}
|
||||
|
||||
async function toggleBot() {
|
||||
if (!activeId || !thread) return;
|
||||
const next = !thread.botEnabled;
|
||||
const res = await fetch(`${base}/${activeId}?platform=${platform}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ botEnabled: next }),
|
||||
});
|
||||
if (res.ok) setThread({ ...thread, botEnabled: next });
|
||||
}
|
||||
|
||||
const inWindow = isWithinMessagingWindow(thread?.lastInboundAt ?? null);
|
||||
const remaining = windowRemainingMs(thread?.lastInboundAt ?? null);
|
||||
const active = conversations?.find((c) => c.id === activeId);
|
||||
|
||||
return (
|
||||
<section className="card grid grid-cols-[minmax(0,1fr)] lg:grid-cols-[300px_minmax(0,1fr)_260px] min-h-[calc(100dvh-260px)] lg:min-h-[620px] overflow-hidden">
|
||||
{/* list — on phones it gives way to the open thread */}
|
||||
<div className={`border-r border-line-2 flex-col min-h-0 ${activeId ? "hidden lg:flex" : "flex"}`}>
|
||||
<div className="card-head">
|
||||
<button type="button" className="chip" aria-pressed={platform === "messenger"} onClick={() => switchPlatform("messenger")}>
|
||||
Messenger
|
||||
</button>
|
||||
<button type="button" className="chip" aria-pressed={platform === "instagram"} disabled={!hasInstagram} onClick={() => switchPlatform("instagram")}>
|
||||
Instagram
|
||||
</button>
|
||||
<button type="button" className="ml-auto p-1.5 rounded-full hover:bg-board text-ink-3" onClick={loadList} aria-label="รีเฟรช">
|
||||
<Icon name="refresh" size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<ul className="overflow-y-auto flex-1 max-h-[560px]">
|
||||
{conversations === null && <li className="p-4 text-ink-3">กำลังโหลด…</li>}
|
||||
{error && !activeId && (
|
||||
<li className="p-3">
|
||||
<Notice tone="red">{error}</Notice>
|
||||
</li>
|
||||
)}
|
||||
{conversations?.length === 0 && !error && (
|
||||
<li>
|
||||
<EmptyState icon="inbox" title="ยังไม่มีแชท" good />
|
||||
</li>
|
||||
)}
|
||||
{conversations?.map((c) => {
|
||||
const name = c.contacts[0]?.name ?? "ไม่ทราบชื่อ";
|
||||
return (
|
||||
<li key={c.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openConversation(c.id)}
|
||||
className={`w-full text-left flex gap-3 px-4 py-3.5 border-b border-line-2 active:bg-board ${c.id === activeId ? "bg-board" : "hover:bg-board"}`}
|
||||
>
|
||||
<span className="avatar w-10 h-10">{name.slice(0, 1)}</span>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="flex items-center gap-2">
|
||||
<span className={`truncate ${c.unreadCount ? "font-semibold" : ""}`}>{name}</span>
|
||||
<span className="ml-auto num text-[11px] text-ink-4 shrink-0">{timeFmt.format(new Date(c.updatedTime))}</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="truncate text-[13px] text-ink-3">{c.snippet}</span>
|
||||
{c.unreadCount > 0 && <span className="ml-auto pill pill-blue h-5! px-2! num">{c.unreadCount}</span>}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* thread */}
|
||||
<div className={`flex-col min-h-0 border-r border-line-2 ${activeId ? "flex" : "hidden lg:flex"}`}>
|
||||
{!activeId ? (
|
||||
<div className="flex-1 grid place-items-center">
|
||||
<EmptyState icon="inbox" title="เลือกแชทเพื่อดูข้อความ" hint={pageName} />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="card-head">
|
||||
<button
|
||||
type="button"
|
||||
className="lg:hidden -ml-2 p-2 rounded-full text-ink-2 active:bg-board"
|
||||
onClick={() => {
|
||||
setActiveId(null);
|
||||
setThread(null);
|
||||
}}
|
||||
aria-label="กลับไปรายการแชท"
|
||||
>
|
||||
<Icon name="left" size={20} />
|
||||
</button>
|
||||
<h2 className="truncate flex-1 min-w-0">{active?.contacts[0]?.name ?? "แชท"}</h2>
|
||||
{thread && inWindow && (
|
||||
<span className="pill pill-amber num shrink-0">
|
||||
<Icon name="clock" size={13} /> <span className="hidden sm:inline">ตอบได้อีก</span> {remainingLabel(remaining)}
|
||||
</span>
|
||||
)}
|
||||
{thread?.recipient && (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={thread.botEnabled}
|
||||
aria-label={thread.botEnabled ? "บอทตอบอยู่ แตะเพื่อตอบเอง" : "คนตอบอยู่ แตะเพื่อให้บอทตอบ"}
|
||||
className={`lg:hidden pill shrink-0 h-8! ${thread.botEnabled ? "pill-green" : "pill-neutral"}`}
|
||||
disabled={!canReply}
|
||||
onClick={toggleBot}
|
||||
>
|
||||
<Icon name="bot" size={14} /> {thread.botEnabled ? "บอท" : "คน"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto p-4 flex flex-col gap-2 bg-board max-h-[calc(100dvh-420px)] lg:max-h-[460px] min-h-[240px]">
|
||||
{!thread && <p className="text-ink-3">กำลังโหลด…</p>}
|
||||
{thread?.messages.map((m) => (
|
||||
<div key={m.id} className={`max-w-[75%] flex flex-col gap-1 ${m.fromPage ? "self-end items-end" : "self-start items-start"}`}>
|
||||
{m.text && (
|
||||
<div className={`px-3.5 py-2 rounded-[18px] whitespace-pre-wrap break-words ${m.fromPage ? "bg-blue text-white" : "bg-white border border-line-2"}`}>{m.text}</div>
|
||||
)}
|
||||
{m.imageUrls.map((u) => (
|
||||
<img key={u} src={u} alt="ไฟล์แนบ" className="max-w-[240px] rounded-[14px] border border-line-2" />
|
||||
))}
|
||||
<span className="num text-[11px] text-ink-4">{timeFmt.format(new Date(m.createdTime))}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="p-3 border-t border-line-2 flex flex-col gap-2">
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
{thread && !inWindow ? (
|
||||
<Notice tone="amber">เลย 24 ชั่วโมงหลังข้อความล่าสุดของลูกค้า — Facebook ไม่อนุญาตให้ตอบจากระบบจนกว่าลูกค้าจะทักมาใหม่</Notice>
|
||||
) : canReply ? (
|
||||
<>
|
||||
{thread && <ReplyDrafts key={activeId} pageId={pageId} conversationId={activeId} onPick={setDraft} />}
|
||||
<div className="flex gap-2 items-end">
|
||||
<textarea
|
||||
className="textarea min-h-[44px]!"
|
||||
rows={2}
|
||||
maxLength={MAX_MESSAGE_LENGTH}
|
||||
placeholder="พิมพ์ข้อความ… (Enter ส่ง, Shift+Enter ขึ้นบรรทัด)"
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
|
||||
e.preventDefault();
|
||||
send();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button type="button" className="btn btn-primary" disabled={sending || !draft.trim()} onClick={send} aria-label="ส่ง">
|
||||
<Icon name="send" size={16} />
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-ink-3 text-[13px]">คุณมีสิทธิ์ดูอย่างเดียว</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* customer panel */}
|
||||
<aside className="hidden lg:flex flex-col gap-4 p-4">
|
||||
{thread?.recipient ? (
|
||||
<>
|
||||
<div className="flex flex-col items-center gap-2 text-center pt-2">
|
||||
<span className="avatar w-16 h-16 text-[24px]">{thread.recipient.name.slice(0, 1)}</span>
|
||||
<b>{thread.recipient.name}</b>
|
||||
<span className="text-[12px] text-ink-3">{platform === "instagram" ? "Instagram" : "Messenger"}</span>
|
||||
</div>
|
||||
<div className="rounded-[16px] border border-line-2 p-3 flex items-center gap-3">
|
||||
<Icon name="bot" />
|
||||
<div className="flex-1 leading-tight">
|
||||
<div className="font-medium">{thread.botEnabled ? "บอทตอบ" : "คนตอบ"}</div>
|
||||
<div className="text-[12px] text-ink-3">{thread.botEnabled ? "auto-reply ทำงานในแชทนี้" : "auto-reply หยุดในแชทนี้"}</div>
|
||||
</div>
|
||||
<button type="button" role="switch" aria-checked={thread.botEnabled} aria-label="เปิด/ปิดบอท" className="toggle" disabled={!canReply} onClick={toggleBot} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-ink-3 text-[13px]">ข้อมูลลูกค้าจะแสดงเมื่อเลือกแชท</p>
|
||||
)}
|
||||
</aside>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
|
||||
|
||||
interface Row {
|
||||
date: string;
|
||||
views: number;
|
||||
engagements: number;
|
||||
follows: number;
|
||||
followDelta: number;
|
||||
}
|
||||
|
||||
const short = (iso: string) => {
|
||||
const [, m, d] = iso.split("-");
|
||||
return `${Number(d)}/${Number(m)}`;
|
||||
};
|
||||
const nf = new Intl.NumberFormat("th-TH");
|
||||
const axis = { fontSize: 12, fill: "#69707c" };
|
||||
|
||||
export function InsightsCharts({ series }: { series: Row[] }) {
|
||||
return (
|
||||
<div className="grid gap-5 xl:grid-cols-2">
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>การเข้าชมและ engagement</h2>
|
||||
<span className="ml-auto flex gap-3 text-[12px] text-ink-2">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className="dot" style={{ background: "var(--m-blue)" }} /> เข้าชม
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className="dot" style={{ background: "var(--m-green)" }} /> Engagement
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="card-body h-[280px]">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={series} margin={{ top: 8, right: 8, left: -12, bottom: 0 }}>
|
||||
<defs>
|
||||
<linearGradient id="gViews" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor="#2d5bd2" stopOpacity={0.25} />
|
||||
<stop offset="100%" stopColor="#2d5bd2" stopOpacity={0} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid stroke="#e9ebee" vertical={false} />
|
||||
<XAxis dataKey="date" tickFormatter={short} tick={axis} axisLine={false} tickLine={false} />
|
||||
<YAxis tick={axis} axisLine={false} tickLine={false} tickFormatter={(v) => nf.format(v)} />
|
||||
<Tooltip labelFormatter={(l) => short(String(l))} formatter={(v) => nf.format(Number(v))} />
|
||||
<Area type="monotone" dataKey="views" name="เข้าชม" stroke="#2d5bd2" strokeWidth={2} fill="url(#gViews)" isAnimationActive={false} />
|
||||
<Area type="monotone" dataKey="engagements" name="Engagement" stroke="#1d9a56" strokeWidth={2} fill="transparent" isAnimationActive={false} />
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>ผู้ติดตามเพิ่ม/ลดรายวัน</h2>
|
||||
</div>
|
||||
<div className="card-body h-[280px]">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={series} margin={{ top: 8, right: 8, left: -12, bottom: 0 }}>
|
||||
<CartesianGrid stroke="#e9ebee" vertical={false} />
|
||||
<XAxis dataKey="date" tickFormatter={short} tick={axis} axisLine={false} tickLine={false} />
|
||||
<YAxis tick={axis} axisLine={false} tickLine={false} allowDecimals={false} />
|
||||
<Tooltip labelFormatter={(l) => short(String(l))} formatter={(v) => nf.format(Number(v))} />
|
||||
<Bar dataKey="followDelta" name="เพิ่ม/ลด" fill="#2d5bd2" radius={[6, 6, 0, 0]} isAnimationActive={false} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { Icon } from "@/components/Icon";
|
||||
|
||||
type Provider = "google" | "facebook";
|
||||
|
||||
const PROVIDER_LABEL: Record<Provider, string> = { google: "Google", facebook: "Facebook" };
|
||||
|
||||
/** Same-origin path only — "//host" and "/\host" would leave the site. */
|
||||
function safeFrom(raw: string | null): string {
|
||||
return raw && raw.startsWith("/") && !raw.startsWith("//") && !raw.startsWith("/\\") ? raw : "/";
|
||||
}
|
||||
|
||||
// Social callbacks redirect with a code, never free text, so the URL can't be
|
||||
// used to put arbitrary wording on the login page.
|
||||
function socialErrorMessage(params: URLSearchParams): string | null {
|
||||
const code = params.get("error");
|
||||
if (!code) return null;
|
||||
const p = params.get("provider");
|
||||
const label = p === "google" || p === "facebook" ? PROVIDER_LABEL[p] : "บัญชีนี้";
|
||||
const rawEmail = params.get("email") ?? "";
|
||||
const email = /^[^\s@<>]{1,64}@[^\s@<>]{1,190}$/.test(rawEmail) ? rawEmail : null;
|
||||
switch (code) {
|
||||
case "no_account":
|
||||
return `ยังไม่มีบัญชีของ ${email ?? "อีเมลนี้"} ในระบบ — ให้ผู้ดูแลระบบเพิ่มผู้ใช้ด้วยอีเมลนี้ก่อน แล้วกดเข้าสู่ระบบด้วย ${label} อีกครั้ง`;
|
||||
case "no_email":
|
||||
return `บัญชี ${label} นี้ไม่มีอีเมลที่ยืนยันแล้ว — เข้าสู่ระบบด้วยอีเมลและรหัสผ่านแทน`;
|
||||
case "linked_other":
|
||||
return `บัญชีนี้ผูกกับ ${label} อีกบัญชีไว้แล้ว — เลือกบัญชี ${label} เดิม หรือใช้อีเมลและรหัสผ่าน`;
|
||||
case "inactive":
|
||||
return "บัญชีนี้ถูกปิดใช้งาน ติดต่อผู้ดูแลระบบ";
|
||||
case "cancelled":
|
||||
return "ยกเลิกการเข้าสู่ระบบแล้ว";
|
||||
case "expired":
|
||||
return "ลิงก์เข้าสู่ระบบหมดอายุ กดอีกครั้ง";
|
||||
case "not_configured":
|
||||
return "ยังไม่ได้ตั้งค่าการเข้าสู่ระบบด้วยบัญชีนี้";
|
||||
default:
|
||||
return `เข้าสู่ระบบด้วย ${label} ไม่สำเร็จ ลองอีกครั้ง`;
|
||||
}
|
||||
}
|
||||
|
||||
function GoogleMark() {
|
||||
return (
|
||||
<svg viewBox="0 0 48 48" width={20} height={20} aria-hidden="true">
|
||||
<path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z" />
|
||||
<path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z" />
|
||||
<path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z" />
|
||||
<path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function FacebookMark() {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" width={20} height={20} aria-hidden="true">
|
||||
<path fill="#1877F2" d="M24 12.073C24 5.405 18.627 0 12 0S0 5.405 0 12.073C0 18.1 4.388 23.094 10.125 24v-8.437H7.078v-3.49h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.49h-2.796V24C19.612 23.094 24 18.1 24 12.073z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoginForm({ providers }: { providers: Provider[] }) {
|
||||
const router = useRouter();
|
||||
const params = useSearchParams();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [remember, setRemember] = useState(true);
|
||||
const [error, setError] = useState<string | null>(() => socialErrorMessage(params));
|
||||
const [busy, setBusy] = useState(false);
|
||||
const from = safeFrom(params.get("from"));
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password, remember }),
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
setBusy(false);
|
||||
if (!res.ok) {
|
||||
setError(body.error ?? "เข้าสู่ระบบไม่สำเร็จ");
|
||||
return;
|
||||
}
|
||||
router.replace(body.mustChangePassword ? "/change-password" : from);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
function socialHref(p: Provider): string {
|
||||
const q = new URLSearchParams({ from, remember: remember ? "1" : "0" });
|
||||
return `/api/auth/oauth/${p}/start?${q}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit} className="login-form">
|
||||
<div className="mb-3">
|
||||
<h1 className="text-[26px] font-bold">ยินดีต้อนรับกลับ</h1>
|
||||
<p className="text-ink-3 text-[13px] mt-2">เข้าสู่ระบบเพื่อดูแลเพจของคุณต่อ</p>
|
||||
</div>
|
||||
{providers.length > 0 && (
|
||||
<>
|
||||
<div className="flex flex-col gap-2.5">
|
||||
{providers.includes("google") && (
|
||||
<a className="btn btn-ghost btn-lg" href={socialHref("google")}>
|
||||
<GoogleMark /> เข้าสู่ระบบด้วย Google
|
||||
</a>
|
||||
)}
|
||||
{providers.includes("facebook") && (
|
||||
<a className="btn btn-ghost btn-lg" href={socialHref("facebook")}>
|
||||
<FacebookMark /> เข้าสู่ระบบด้วย Facebook
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
<div className="login-divider">หรือใช้อีเมล</div>
|
||||
</>
|
||||
)}
|
||||
<label className="field">
|
||||
<span>อีเมล</span>
|
||||
<input className="input" type="email" autoComplete="email" placeholder="name@company.com" required value={email} onChange={(e) => setEmail(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>รหัสผ่าน</span>
|
||||
<input className="input" type="password" autoComplete="current-password" placeholder="กรอกรหัสผ่านของคุณ" required value={password} onChange={(e) => setPassword(e.target.value)} />
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-[13px] text-ink-2 py-1">
|
||||
<input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
|
||||
จดจำการเข้าสู่ระบบ
|
||||
</label>
|
||||
{error && (
|
||||
<p className="notice notice-red" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button className="btn btn-primary btn-lg" disabled={busy}>
|
||||
{busy ? "กำลังเข้าสู่ระบบ…" : <>เข้าสู่ระบบ <Icon name="right" size={17} /></>}
|
||||
</button>
|
||||
<p className="flex justify-center gap-1.5 items-center text-[11px] text-ink-3 mt-3"><Icon name="shield" size={13} /> พื้นที่ทำงานสำหรับทีมของคุณ</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/* eslint-disable @next/next/no-img-element -- Graph CDN picture URLs are signed and short-lived; next/image would need every fbcdn host whitelisted */
|
||||
export function PageAvatar({ name, src, size = 32 }: { name: string; src: string | null; size?: number }) {
|
||||
if (src) {
|
||||
return <img src={src} alt="" width={size} height={size} className="avatar" style={{ width: size, height: size }} />;
|
||||
}
|
||||
return (
|
||||
<span className="avatar" style={{ width: size, height: size, fontSize: size * 0.42 }} aria-hidden="true">
|
||||
{name.slice(0, 1)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { PageAvatar } from "./PageAvatar";
|
||||
|
||||
/** Sets the rail's selected page (same cookie as the switcher) and re-renders. */
|
||||
export function PagePicker({ pages }: { pages: { id: string; name: string; pictureUrl: string | null }[] }) {
|
||||
const router = useRouter();
|
||||
return (
|
||||
<div className="grid gap-3 p-[18px] pt-0 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{pages.map((p) => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
className="flex items-center gap-3 p-3 rounded-[16px] border border-line hover:border-ink-3 hover:bg-board text-left"
|
||||
onClick={() => {
|
||||
document.cookie = `pm_page=${encodeURIComponent(p.id)}; path=/; max-age=31536000; samesite=lax`;
|
||||
router.refresh();
|
||||
}}
|
||||
>
|
||||
<PageAvatar name={p.name} src={p.pictureUrl} size={36} />
|
||||
<span className="truncate font-medium">{p.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
"use client";
|
||||
|
||||
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;
|
||||
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(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).map((a) => a.fbPageId));
|
||||
}
|
||||
|
||||
// Right after "Login with Facebook" returns, list the pages straight away.
|
||||
useEffect(() => {
|
||||
if (!justConnected || !superadmin) 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, superadmin]);
|
||||
|
||||
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>}
|
||||
|
||||
{superadmin && (
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>บัญชี Facebook</h2>
|
||||
{appConfigured ? (
|
||||
// Full navigation (not <Link>): the start route redirects to facebook.com.
|
||||
<a href="/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>
|
||||
{superadmin && (
|
||||
<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={superadmin ? "เข้าสู่ระบบด้วย 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"
|
||||
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.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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Icon } from "./Icon";
|
||||
import { Notice } from "./ui";
|
||||
|
||||
interface Issue {
|
||||
level: "high" | "medium" | "low";
|
||||
problem: string;
|
||||
suggestion: string;
|
||||
}
|
||||
|
||||
const LEVEL_META: Record<Issue["level"], { label: string; pill: string }> = {
|
||||
high: { label: "ต้องแก้", pill: "pill-red" },
|
||||
medium: { label: "ควรแก้", pill: "pill-amber" },
|
||||
low: { label: "เล็กน้อย", pill: "pill-neutral" },
|
||||
};
|
||||
|
||||
// Square-bracket gaps the AI leaves for facts it must not invent, e.g. [ราคา].
|
||||
const PLACEHOLDER = /\[[^\]\n]{1,40}\]/;
|
||||
|
||||
/** Pre-approval review of the editor's current caption. Advisory only — it never blocks approval. */
|
||||
export function PostCheck({ pageId, caption, targets, hasImage }: { pageId: string; caption: string; targets: string[]; hasImage: boolean }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [result, setResult] = useState<{ caption: string; summary: string; issues: Issue[] } | null>(null);
|
||||
|
||||
async function run() {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await fetch("/api/ai/check", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pageId, caption, targets, hasImage }),
|
||||
}).catch(() => null);
|
||||
const body = res ? await res.json().catch(() => ({})) : {};
|
||||
setBusy(false);
|
||||
if (!res?.ok) return setError(body.error ?? "AI ตรวจไม่สำเร็จ ลองใหม่อีกครั้ง");
|
||||
setResult({ caption, summary: body.summary ?? "", issues: body.issues ?? [] });
|
||||
}
|
||||
|
||||
const stale = result !== null && result.caption !== caption;
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
{PLACEHOLDER.test(caption) && (
|
||||
<p className="text-[12px] text-danger flex items-center gap-1.5">
|
||||
<Icon name="alert" size={14} /> ยังมีช่องในวงเล็บ [ ] ที่ต้องเติมก่อนเผยแพร่
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button type="button" className="btn btn-ghost btn-sm" disabled={busy || !caption.trim()} onClick={run}>
|
||||
<Icon name="shield" size={14} /> {busy ? "AI กำลังตรวจ…" : result ? "ตรวจอีกครั้ง" : "ให้ AI ตรวจก่อนส่ง"}
|
||||
</button>
|
||||
{stale && <span className="text-[12px] text-ink-3">ข้อความเปลี่ยนหลังตรวจ — ตรวจใหม่เพื่อดูผลล่าสุด</span>}
|
||||
</div>
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
{result && !stale && (
|
||||
<div className="rounded-[12px] border border-line bg-board p-3 flex flex-col gap-2">
|
||||
<p className="text-[13px] font-medium flex items-center gap-1.5">
|
||||
{result.issues.length === 0 && <Icon name="check" size={15} />}
|
||||
{result.summary || (result.issues.length ? "พบจุดที่ควรดู" : "ไม่พบปัญหา")}
|
||||
</p>
|
||||
{result.issues.length > 0 && (
|
||||
<ul className="flex flex-col gap-2">
|
||||
{result.issues.map((i, n) => (
|
||||
<li key={n} className="flex items-start gap-2 text-[13px]">
|
||||
<span className={`pill ${LEVEL_META[i.level].pill} shrink-0`}>{LEVEL_META[i.level].label}</span>
|
||||
<span className="flex-1 min-w-0">
|
||||
{i.problem}
|
||||
{i.suggestion && <span className="block text-ink-3">แก้: {i.suggestion}</span>}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p className="text-[11px] text-ink-4">AI ช่วยดูเบื้องต้นเท่านั้น ผู้อนุมัติยังต้องตรวจเอง</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,577 @@
|
||||
"use client";
|
||||
|
||||
/* eslint-disable @next/next/no-img-element -- Blob URLs and Graph CDN images, not optimisable */
|
||||
import { useRef, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { PageRole, PostStatus } from "@prisma/client";
|
||||
import { roleAtLeast } from "@/lib/auth/roles";
|
||||
import { bkkMidnight } from "@/lib/board";
|
||||
import { Icon } from "./Icon";
|
||||
import { CaptionAssistant } from "./CaptionAssistant";
|
||||
import { PostCheck } from "./PostCheck";
|
||||
import { PageAvatar } from "./PageAvatar";
|
||||
import { formatDateTime, Notice, StatusPill } from "./ui";
|
||||
import { useToast } from "./Toast";
|
||||
|
||||
type Target = "FACEBOOK" | "INSTAGRAM";
|
||||
|
||||
export interface EditorPage {
|
||||
id: string;
|
||||
name: string;
|
||||
pictureUrl: string | null;
|
||||
igUsername: string | null;
|
||||
role: PageRole;
|
||||
}
|
||||
|
||||
export interface EditorPost {
|
||||
id: string;
|
||||
pageId: string;
|
||||
title: string;
|
||||
caption: string;
|
||||
imageBlobUrl: string | null;
|
||||
targets: Target[];
|
||||
status: PostStatus;
|
||||
scheduledPublishAt: string | null;
|
||||
fbPermalink: string | null;
|
||||
igPermalink: string | null;
|
||||
lastError: string | null;
|
||||
lastEditedById: string | null;
|
||||
createdById: string | null;
|
||||
aiAssisted: boolean;
|
||||
}
|
||||
|
||||
export interface EditorLogEntry {
|
||||
id: string;
|
||||
action: string;
|
||||
actorLabel: string;
|
||||
createdAt: string;
|
||||
note: string | null;
|
||||
}
|
||||
|
||||
const ACTION_LABEL: Record<string, string> = {
|
||||
POST_CREATED: "สร้างโพสต์",
|
||||
POST_EDITED: "แก้ไขเนื้อหา",
|
||||
POST_PLANNED: "วางแผนวันโพสต์",
|
||||
POST_SUBMITTED: "ส่งขออนุมัติ",
|
||||
POST_APPROVED: "อนุมัติ",
|
||||
POST_REJECTED: "ตีกลับ",
|
||||
POST_SCHEDULED: "ตั้งเวลา",
|
||||
POST_PUBLISHED: "เผยแพร่",
|
||||
POST_FAILED: "เผยแพร่ล้มเหลว",
|
||||
POST_CANCELLED: "ยกเลิกการตั้งเวลา",
|
||||
};
|
||||
|
||||
const EDITABLE: PostStatus[] = ["DRAFT", "PENDING_APPROVAL", "APPROVED", "FAILED", "CANCELLED"];
|
||||
|
||||
function toLocalInput(d: Date): string {
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
export function PostEditor({
|
||||
pages,
|
||||
post,
|
||||
log = [],
|
||||
approvalsCount = 0,
|
||||
requiredApprovals = 1,
|
||||
currentUserId,
|
||||
superadmin,
|
||||
initialDay,
|
||||
initialDraft,
|
||||
}: {
|
||||
pages: EditorPage[];
|
||||
post: EditorPost | null;
|
||||
log?: EditorLogEntry[];
|
||||
approvalsCount?: number;
|
||||
requiredApprovals?: number;
|
||||
currentUserId: string;
|
||||
superadmin: boolean;
|
||||
initialDay?: string;
|
||||
/** New post started from an AI analysis idea. */
|
||||
initialDraft?: { title: string; caption: string; topic: string };
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const [pageId, setPageId] = useState(post?.pageId ?? pages[0]?.id ?? "");
|
||||
const [title, setTitle] = useState(post?.title ?? initialDraft?.title ?? "");
|
||||
const [caption, setCaption] = useState(post?.caption ?? initialDraft?.caption ?? "");
|
||||
const [aiAssisted, setAiAssisted] = useState(post?.aiAssisted ?? Boolean(initialDraft));
|
||||
const [imageUrl, setImageUrl] = useState<string | null>(post?.imageBlobUrl ?? null);
|
||||
const [targets, setTargets] = useState<Target[]>(post?.targets ?? ["FACEBOOK"]);
|
||||
const [scheduleAt, setScheduleAt] = useState(() => toLocalInput(new Date(Date.now() + 60 * 60 * 1000)));
|
||||
const [note, setNote] = useState("");
|
||||
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 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 ownWork = post && (post.lastEditedById === currentUserId || post.createdById === currentUserId);
|
||||
const selfBlocked = Boolean(ownWork && !superadmin);
|
||||
const dirty =
|
||||
!post ||
|
||||
post.title !== title ||
|
||||
post.caption !== caption ||
|
||||
post.imageBlobUrl !== imageUrl ||
|
||||
post.targets.join() !== targets.join();
|
||||
|
||||
async function call(label: string, url: string, init: RequestInit): Promise<Record<string, unknown> | null> {
|
||||
setBusy(label);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch(url, { ...init, headers: init.body instanceof FormData ? undefined : { "Content-Type": "application/json" } });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
setError(body.error ?? "ทำรายการไม่สำเร็จ");
|
||||
return null;
|
||||
}
|
||||
return body;
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function upload(file: File) {
|
||||
if (!pageId) return setError("เลือกเพจก่อนอัปโหลดรูป");
|
||||
const form = new FormData();
|
||||
form.set("pageId", pageId);
|
||||
form.set("file", file);
|
||||
const body = await call("upload", "/api/upload", { method: "POST", body: form });
|
||||
if (body?.url) setImageUrl(body.url as string);
|
||||
}
|
||||
|
||||
async function save(opts: { navigate?: boolean } = {}): Promise<string | null> {
|
||||
const payload = { pageId, title, caption, imageBlobUrl: imageUrl, targets, aiAssisted, plannedAt: plannedDay ? bkkMidnight(plannedDay).toISOString() : null };
|
||||
if (!post) {
|
||||
const body = await call("save", "/api/posts", { method: "POST", body: JSON.stringify(payload) });
|
||||
const id = (body?.post as { id: string } | undefined)?.id;
|
||||
if (id && opts.navigate !== false) {
|
||||
toast.show("บันทึกฉบับร่างแล้ว");
|
||||
router.replace(`/posts/${id}`);
|
||||
}
|
||||
return id ?? null;
|
||||
}
|
||||
if (!dirty) return post.id;
|
||||
const body = await call("save", `/api/posts/${post.id}`, { method: "PATCH", body: JSON.stringify(payload) });
|
||||
if (!body) return null;
|
||||
toast.show("บันทึกแล้ว");
|
||||
router.refresh();
|
||||
return post.id;
|
||||
}
|
||||
|
||||
/** New post: create and submit in one tap. */
|
||||
async function saveAndSubmit() {
|
||||
const id = await save({ navigate: false });
|
||||
if (!id) return;
|
||||
const body = await call("submit", `/api/posts/${id}`, { method: "POST", body: JSON.stringify({ action: "submit" }) });
|
||||
toast.show(body ? "ส่งให้ผู้อนุมัติแล้ว" : "บันทึกฉบับร่างแล้ว แต่ส่งขออนุมัติไม่สำเร็จ", body ? "ok" : "warn");
|
||||
router.replace(`/posts/${id}`);
|
||||
}
|
||||
|
||||
const ACT_DONE: Record<string, string> = {
|
||||
submit: "ส่งให้ผู้อนุมัติแล้ว",
|
||||
approve: "อนุมัติแล้ว",
|
||||
reject: "ตีกลับแล้ว",
|
||||
publish: "เผยแพร่แล้ว",
|
||||
schedule: "ตั้งเวลาแล้ว",
|
||||
cancel: "ยกเลิกการตั้งเวลาแล้ว",
|
||||
};
|
||||
|
||||
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 (body) {
|
||||
setNote("");
|
||||
toast.show(ACT_DONE[action] ?? "เรียบร้อย");
|
||||
router.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
function quickSchedule(dayOffset: number, hour: number) {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() + dayOffset);
|
||||
d.setHours(hour, 0, 0, 0);
|
||||
setScheduleAt(toLocalInput(d));
|
||||
}
|
||||
|
||||
// The one next step for this post, surfaced in the phone action dock.
|
||||
const nextStep: { label: string; tone: "primary" | "success"; run: () => void } | null = !post
|
||||
? null
|
||||
: (status === "DRAFT" || status === "FAILED" || status === "CANCELLED") && roleAtLeast(role, "EDITOR")
|
||||
? { label: "ส่งขออนุมัติ", tone: "primary", run: () => act("submit") }
|
||||
: status === "PENDING_APPROVAL" && canApprove && !selfBlocked
|
||||
? { label: "อนุมัติ", tone: "success", run: () => act("approve") }
|
||||
: status === "APPROVED" && canApprove
|
||||
? { label: "เผยแพร่ตอนนี้", tone: "success", run: () => act("publish") }
|
||||
: null;
|
||||
|
||||
async function remove() {
|
||||
if (!post || !window.confirm("ลบโพสต์นี้?")) return;
|
||||
const body = await call("delete", `/api/posts/${post.id}`, { method: "DELETE" });
|
||||
if (body) {
|
||||
router.replace("/posts");
|
||||
router.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTarget(t: Target) {
|
||||
setTargets((cur) => (cur.includes(t) ? cur.filter((x) => x !== t) : [...cur, t]));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-5 grid-cols-[minmax(0,1fr)] xl:grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)] items-start">
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>{post ? "เนื้อหาโพสต์" : "โพสต์ใหม่"}</h2>
|
||||
<span className="ml-auto flex items-center gap-2">
|
||||
{aiAssisted && <span className="pill pill-blue">AI ช่วยร่าง</span>}
|
||||
{post && <StatusPill status={status} />}
|
||||
</span>
|
||||
</div>
|
||||
<div className="card-body flex flex-col gap-4">
|
||||
{!editable && (
|
||||
<Notice tone="blue">
|
||||
{status === "SCHEDULED" ? "โพสต์ตั้งเวลาไว้แล้ว — ยกเลิกการตั้งเวลาก่อนถึงจะแก้ได้" : "โพสต์เผยแพร่แล้ว แก้ไขในระบบไม่ได้"}
|
||||
</Notice>
|
||||
)}
|
||||
|
||||
<label className="field">
|
||||
<span>เพจ</span>
|
||||
<select className="select" value={pageId} disabled={Boolean(post)} onChange={(e) => setPageId(e.target.value)}>
|
||||
{pages.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>ชื่อโพสต์ (ใช้ภายใน ไม่แสดงบนเพจ)</span>
|
||||
<input className="input" value={title} disabled={!canEdit} onChange={(e) => setTitle(e.target.value)} placeholder="เช่น โปรโมชั่นปลายเดือน" />
|
||||
</label>
|
||||
|
||||
{!post && <label className="field">
|
||||
<span>วันวางแผนโพสต์ (ยังไม่เผยแพร่)</span>
|
||||
<input className="input" type="date" value={plannedDay} disabled={!canEdit} onChange={e => setPlannedDay(e.target.value)} />
|
||||
<small className="text-ink-3">เว้นว่างเพื่อเลือกวันภายหลัง · อนุมัติก่อน แล้วเลือกเวลาเผยแพร่</small>
|
||||
</label>}
|
||||
|
||||
{canEdit && pageId && (
|
||||
<CaptionAssistant
|
||||
pageId={pageId}
|
||||
targets={targets}
|
||||
caption={caption}
|
||||
initialTopic={initialDraft?.topic}
|
||||
onChange={(text, fromAi) => {
|
||||
setCaption(text);
|
||||
if (fromAi) setAiAssisted(true);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<label className="field">
|
||||
<span className="flex">
|
||||
Caption <span className="ml-auto num text-ink-4">{caption.length.toLocaleString("th-TH")}</span>
|
||||
</span>
|
||||
<textarea className="textarea" rows={8} value={caption} disabled={!canEdit} onChange={(e) => setCaption(e.target.value)} placeholder="เขียนข้อความโพสต์…" />
|
||||
</label>
|
||||
{canEdit && pageId && <PostCheck pageId={pageId} caption={caption} targets={targets} hasImage={Boolean(imageUrl)} />}
|
||||
|
||||
<div className="field">
|
||||
<span>รูปภาพ (JPG/PNG ไม่เกิน 8MB)</span>
|
||||
{imageUrl ? (
|
||||
<div className="relative rounded-[16px] overflow-hidden border border-line bg-board">
|
||||
<img src={imageUrl} alt="รูปโพสต์" className="w-full max-h-[320px] object-contain" />
|
||||
{canEdit && (
|
||||
<button type="button" className="btn btn-sm btn-ghost absolute top-2 right-2" onClick={() => setImageUrl(null)}>
|
||||
<Icon name="x" size={14} /> เอารูปออก
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
disabled={!canEdit || busy === "upload"}
|
||||
className="h-28 rounded-[6px] border border-dashed border-line bg-paper hover:bg-board hover:border-ink-3 flex flex-col items-center justify-center gap-1 text-ink-3 disabled:opacity-50"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
>
|
||||
<Icon name="image" size={22} />
|
||||
{busy === "upload" ? "กำลังอัปโหลด…" : "เลือกรูป"}
|
||||
</button>
|
||||
)}
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png"
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0];
|
||||
if (f) upload(f);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="field">
|
||||
<span>ช่องทาง</span>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" className="chip" aria-pressed={targets.includes("FACEBOOK")} disabled={!canEdit} onClick={() => toggleTarget("FACEBOOK")}>
|
||||
Facebook
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="chip"
|
||||
aria-pressed={targets.includes("INSTAGRAM")}
|
||||
disabled={!canEdit || !page?.igUsername}
|
||||
title={page?.igUsername ? undefined : "เพจนี้ยังไม่ได้ผูก Instagram"}
|
||||
onClick={() => toggleTarget("INSTAGRAM")}
|
||||
>
|
||||
Instagram {page?.igUsername ? `@${page.igUsername}` : "(ไม่ได้ผูก)"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
|
||||
{canEdit && (
|
||||
<div className="flex flex-wrap gap-2 pt-1">
|
||||
{/* On phones the save/submit pair lives in the action dock below. */}
|
||||
{!post && (
|
||||
<button type="button" className="btn btn-primary hidden xl:inline-flex" disabled={Boolean(busy)} onClick={saveAndSubmit}>
|
||||
<Icon name="send" size={16} /> {busy === "submit" ? "กำลังส่ง…" : "บันทึกและส่งขออนุมัติ"}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${post ? "btn-primary" : "btn-ghost"} hidden xl:inline-flex`}
|
||||
disabled={Boolean(busy) || !dirty}
|
||||
onClick={() => save()}
|
||||
>
|
||||
{busy === "save" ? "กำลังบันทึก…" : post ? "บันทึกการแก้ไข" : "บันทึกเป็นฉบับร่าง"}
|
||||
</button>
|
||||
{post && (
|
||||
<button type="button" className="btn btn-danger ml-auto" disabled={Boolean(busy)} onClick={remove}>
|
||||
<Icon name="trash" size={16} /> ลบ
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{post && (status === "APPROVED" || status === "PENDING_APPROVAL") && canEdit && (
|
||||
<p className="text-[12px] text-ink-3">แก้เนื้อหาหลังอนุมัติ การอนุมัติเดิมจะเป็นโมฆะ และต้องอนุมัติใหม่</p>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="flex flex-col gap-5 min-w-0">
|
||||
{/* Phones: the workflow card comes before the preview. */}
|
||||
<div className="order-2 xl:order-none">
|
||||
<Preview pageName={page?.name ?? "เพจ"} pictureUrl={page?.pictureUrl ?? null} caption={caption} imageUrl={imageUrl} />
|
||||
</div>
|
||||
|
||||
{post && (
|
||||
<section className="card order-1 xl:order-none">
|
||||
<div className="card-head">
|
||||
<h2>ขั้นตอน</h2>
|
||||
</div>
|
||||
<div className="card-body flex flex-col gap-3">
|
||||
{post.lastError && <Notice tone={status === "FAILED" ? "red" : "amber"}>{post.lastError}</Notice>}
|
||||
|
||||
{(status === "DRAFT" || status === "FAILED" || status === "CANCELLED") && roleAtLeast(role, "EDITOR") && (
|
||||
<button type="button" className="btn btn-primary" disabled={Boolean(busy)} onClick={() => act("submit")}>
|
||||
<Icon name="send" size={16} /> ส่งขออนุมัติ
|
||||
</button>
|
||||
)}
|
||||
|
||||
{status === "PENDING_APPROVAL" && (
|
||||
<>
|
||||
<p className="text-ink-2">
|
||||
อนุมัติแล้ว <b className="num">{approvalsCount}</b> / {requiredApprovals}
|
||||
</p>
|
||||
{canApprove ? (
|
||||
selfBlocked ? (
|
||||
<Notice tone="amber">คุณเป็นคนแก้โพสต์นี้ล่าสุด ต้องให้ผู้อนุมัติคนอื่นตรวจ</Notice>
|
||||
) : (
|
||||
<>
|
||||
<input className="input" placeholder="หมายเหตุ (ไม่บังคับ)" value={note} onChange={(e) => setNote(e.target.value)} />
|
||||
<div className="flex gap-2">
|
||||
<button type="button" className="btn btn-success flex-1" disabled={Boolean(busy)} onClick={() => act("approve")}>
|
||||
<Icon name="check" size={16} /> อนุมัติ
|
||||
</button>
|
||||
<button type="button" className="btn btn-danger" disabled={Boolean(busy)} onClick={() => act("reject")}>
|
||||
ตีกลับ
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<p className="text-ink-3 text-[13px]">รอผู้อนุมัติของเพจนี้ตรวจ</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === "APPROVED" &&
|
||||
(canApprove ? (
|
||||
<>
|
||||
<button type="button" className="btn btn-success btn-lg" disabled={Boolean(busy)} onClick={() => act("publish")}>
|
||||
{busy === "publish" ? "กำลังเผยแพร่…" : "เผยแพร่ตอนนี้"}
|
||||
</button>
|
||||
<div className="field">
|
||||
<span>หรือตั้งเวลา (10 นาที – 28 วันล่วงหน้า)</span>
|
||||
<div className="chip-scroll">
|
||||
<button type="button" className="chip" onClick={() => quickSchedule(1, 9)}>
|
||||
พรุ่งนี้ 09:00
|
||||
</button>
|
||||
<button type="button" className="chip" onClick={() => quickSchedule(1, 12)}>
|
||||
พรุ่งนี้ 12:00
|
||||
</button>
|
||||
<button type="button" className="chip" onClick={() => quickSchedule(1, 19)}>
|
||||
พรุ่งนี้ 19:00
|
||||
</button>
|
||||
<button type="button" className="chip" onClick={() => quickSchedule(2, 19)}>
|
||||
มะรืน 19:00
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 items-end">
|
||||
<label className="field flex-1 min-w-0">
|
||||
<span className="sr-only">วันและเวลาที่จะเผยแพร่</span>
|
||||
<input className="input num" type="datetime-local" value={scheduleAt} onChange={(e) => setScheduleAt(e.target.value)} />
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
disabled={Boolean(busy) || !scheduleAt}
|
||||
onClick={() => act("schedule", { scheduledAt: new Date(scheduleAt).toISOString() })}
|
||||
>
|
||||
<Icon name="clock" size={16} /> ตั้งเวลา
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" className="btn btn-ghost btn-sm self-start" disabled={Boolean(busy)} onClick={() => act("reject")}>
|
||||
ถอนการอนุมัติ
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-ink-3 text-[13px]">อนุมัติแล้ว รอผู้อนุมัติเผยแพร่หรือตั้งเวลา</p>
|
||||
))}
|
||||
|
||||
{status === "SCHEDULED" && (
|
||||
<>
|
||||
<p>
|
||||
จะเผยแพร่ <b className="num">{formatDateTime(post.scheduledPublishAt)}</b>
|
||||
</p>
|
||||
{canApprove && (
|
||||
<button type="button" className="btn btn-danger self-start" disabled={Boolean(busy)} onClick={() => act("cancel")}>
|
||||
ยกเลิกการตั้งเวลา
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === "PUBLISHED" && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{post.fbPermalink && (
|
||||
<a href={post.fbPermalink} target="_blank" rel="noreferrer" className="btn btn-ghost btn-sm">
|
||||
<Icon name="link" size={14} /> ดูบน Facebook
|
||||
</a>
|
||||
)}
|
||||
{post.igPermalink && (
|
||||
<a href={post.igPermalink} target="_blank" rel="noreferrer" className="btn btn-ghost btn-sm">
|
||||
<Icon name="link" size={14} /> ดูบน Instagram
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{log.length > 0 && (
|
||||
<section className="card order-3 xl:order-none">
|
||||
<div className="card-head">
|
||||
<h2>ประวัติ</h2>
|
||||
</div>
|
||||
<ol className="card-body flex flex-col gap-3">
|
||||
{log.map((l) => (
|
||||
<li key={l.id} className="flex gap-3">
|
||||
<span className="dot mt-2" style={{ background: l.action.includes("FAILED") || l.action.includes("REJECTED") ? "var(--m-red)" : "var(--m-blue)" }} />
|
||||
<div className="min-w-0">
|
||||
<div>
|
||||
<b>{ACTION_LABEL[l.action] ?? l.action}</b> <span className="text-ink-3">โดย {l.actorLabel}</span>
|
||||
</div>
|
||||
{l.note && <div className="text-ink-2 text-[13px]">“{l.note}”</div>}
|
||||
<div className="num text-[12px] text-ink-4">{formatDateTime(l.createdAt)}</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Phone: save + the post's one next step, within thumb reach. */}
|
||||
{(canEdit || nextStep) && (
|
||||
<div className="action-dock xl:hidden">
|
||||
{!post ? (
|
||||
<>
|
||||
<button type="button" className="btn btn-ghost" disabled={Boolean(busy)} onClick={() => save()}>
|
||||
{busy === "save" ? "กำลังบันทึก…" : "บันทึกร่าง"}
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" disabled={Boolean(busy)} onClick={saveAndSubmit}>
|
||||
<Icon name="send" size={16} /> {busy === "submit" ? "กำลังส่ง…" : "ส่งขออนุมัติ"}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{canEdit && dirty && (
|
||||
<button type="button" className={`btn ${nextStep ? "btn-ghost" : "btn-primary"}`} disabled={Boolean(busy)} onClick={() => save()}>
|
||||
{busy === "save" ? "กำลังบันทึก…" : "บันทึก"}
|
||||
</button>
|
||||
)}
|
||||
{nextStep && (
|
||||
<button type="button" className={`btn btn-${nextStep.tone}`} disabled={Boolean(busy)} onClick={nextStep.run}>
|
||||
{busy ? "กำลังทำงาน…" : nextStep.label}
|
||||
</button>
|
||||
)}
|
||||
{!nextStep && !dirty && <p className="flex-1 self-center text-center text-ink-3 text-[13px]">ไม่มีขั้นตอนที่ต้องทำตอนนี้</p>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Preview({ pageName, pictureUrl, caption, imageUrl }: { pageName: string; pictureUrl: string | null; caption: string; imageUrl: string | null }) {
|
||||
return (
|
||||
<section className="card overflow-hidden">
|
||||
<div className="card-head">
|
||||
<h2>ตัวอย่างบน Facebook</h2>
|
||||
</div>
|
||||
<div className="p-4 flex items-center gap-3">
|
||||
<PageAvatar name={pageName} src={pictureUrl} size={40} />
|
||||
<div className="leading-tight">
|
||||
<div className="font-medium">{pageName}</div>
|
||||
<div className="text-[12px] text-ink-3">เมื่อสักครู่ · สาธารณะ</div>
|
||||
</div>
|
||||
</div>
|
||||
{caption ? (
|
||||
<p className="px-4 pb-3 whitespace-pre-wrap break-words">{caption}</p>
|
||||
) : (
|
||||
<p className="px-4 pb-3 text-ink-4">ข้อความโพสต์จะแสดงตรงนี้</p>
|
||||
)}
|
||||
{imageUrl && <img src={imageUrl} alt="" className="w-full max-h-[420px] object-cover bg-board" />}
|
||||
<div className="px-4 py-2.5 border-t border-line-2 flex justify-around text-ink-3 text-[13px]">
|
||||
<span>ถูกใจ</span>
|
||||
<span>แสดงความคิดเห็น</span>
|
||||
<span>แชร์</span>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Icon } from "./Icon";
|
||||
import { formatDateTime, Notice } from "./ui";
|
||||
import { useToast } from "./Toast";
|
||||
import { PROFILE_FIELDS, type ShopProfile } from "@/lib/ai/shared";
|
||||
|
||||
const EMPTY: ShopProfile = { business: "", audience: "", tone: "", avoid: "", cta: "" };
|
||||
|
||||
export function ProfileForm({
|
||||
pageId,
|
||||
canEdit,
|
||||
canDraft,
|
||||
initial,
|
||||
updatedAt,
|
||||
}: {
|
||||
pageId: string;
|
||||
canEdit: boolean;
|
||||
canDraft: boolean;
|
||||
initial: ShopProfile | null;
|
||||
updatedAt: string | null;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
const [values, setValues] = useState<ShopProfile>(initial ?? EMPTY);
|
||||
const [busy, setBusy] = useState<"save" | "draft" | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function request(path: string, method: string, body?: ShopProfile) {
|
||||
const res = await fetch(path, { method, headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined }).catch(() => null);
|
||||
const json = res ? await res.json().catch(() => ({})) : {};
|
||||
return { ok: Boolean(res?.ok), json };
|
||||
}
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy("save");
|
||||
setError(null);
|
||||
const { ok, json } = await request(`/api/pages/${pageId}/profile`, "PUT", values);
|
||||
setBusy(null);
|
||||
if (!ok) return setError(json.error ?? "บันทึกไม่สำเร็จ");
|
||||
toast.show("บันทึกโปรไฟล์ร้านแล้ว");
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function draft() {
|
||||
setBusy("draft");
|
||||
setError(null);
|
||||
const { ok, json } = await request(`/api/pages/${pageId}/profile/draft`, "POST");
|
||||
setBusy(null);
|
||||
if (!ok) return setError(json.error ?? "AI ร่างโปรไฟล์ไม่สำเร็จ");
|
||||
const drafted = json.profile as ShopProfile;
|
||||
// Keep what the owner already typed where the AI found nothing.
|
||||
setValues((cur) => {
|
||||
const next = { ...cur };
|
||||
for (const f of PROFILE_FIELDS) if (drafted[f.key]) next[f.key] = drafted[f.key];
|
||||
return next;
|
||||
});
|
||||
toast.show(`AI ร่างจาก ${json.postCount} โพสต์แล้ว — ตรวจแล้วกดบันทึก`, "warn");
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="card max-w-[780px]" onSubmit={save}>
|
||||
<div className="card-head">
|
||||
<h2>ข้อมูลร้าน</h2>
|
||||
{updatedAt && <span className="text-[12px] text-ink-4 ml-auto">บันทึกล่าสุด {formatDateTime(updatedAt)}</span>}
|
||||
</div>
|
||||
<div className="card-body flex flex-col gap-4">
|
||||
{!canEdit && <Notice tone="blue" title="ดูได้อย่างเดียว">ผู้อนุมัติขึ้นไปเท่านั้นที่แก้โปรไฟล์ร้านได้</Notice>}
|
||||
{canEdit && canDraft && (
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-[12px] border border-line bg-board p-3.5">
|
||||
<Icon name="sparkle" size={18} />
|
||||
<p className="flex-1 min-w-[220px] text-[13px] text-ink-2">ยังไม่รู้จะเขียนอะไร? ให้ AI อ่านโพสต์ 90 วันล่าสุดของเพจแล้วร่างให้ก่อน</p>
|
||||
<button type="button" className="btn btn-ghost btn-sm" disabled={busy !== null} onClick={draft}>
|
||||
{busy === "draft" ? "AI กำลังอ่านโพสต์…" : "ให้ AI ร่างจากโพสต์เดิม"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{PROFILE_FIELDS.map((f) => (
|
||||
<label key={f.key} className="field">
|
||||
<span className="flex">
|
||||
{f.label}
|
||||
{f.key === "business" && <span className="text-danger ml-1">*</span>}
|
||||
<span className="ml-auto num text-ink-4">{values[f.key].length.toLocaleString("th-TH")}/{f.max.toLocaleString("th-TH")}</span>
|
||||
</span>
|
||||
<textarea
|
||||
className="textarea"
|
||||
rows={f.rows}
|
||||
maxLength={f.max}
|
||||
required={f.key === "business"}
|
||||
disabled={!canEdit}
|
||||
value={values[f.key]}
|
||||
onChange={(e) => setValues({ ...values, [f.key]: e.target.value })}
|
||||
placeholder={f.hint}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
{canEdit && (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button type="submit" className="btn btn-primary" disabled={busy !== null}>
|
||||
{busy === "save" ? "กำลังบันทึก…" : "บันทึกโปรไฟล์"}
|
||||
</button>
|
||||
<p className="text-[12px] text-ink-4 flex-1 min-w-[220px]">ข้อมูลนี้และโพสต์ของเพจจะถูกส่งไปให้ AI (Anthropic) ประมวลผลตอนใช้ผู้ช่วย AI</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Icon } from "./Icon";
|
||||
import { useToast } from "./Toast";
|
||||
|
||||
export function RefreshInsightsButton({ pageId, variant = "on-band" }: { pageId: string | null; variant?: "on-band" | "primary" }) {
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function refresh() {
|
||||
setBusy(true);
|
||||
const res = await fetch("/api/insights/refresh", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pageId }),
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
setBusy(false);
|
||||
if (!res.ok || !body.ok) {
|
||||
toast.show(body.error ?? body.errors?.join(" · ") ?? "ดึงข้อมูลไม่สำเร็จ", "error");
|
||||
return;
|
||||
}
|
||||
toast.show(body.errors?.length ? `ดึงได้ ${body.refreshed} เพจ · ${body.errors.join(" · ")}` : "อัปเดตข้อมูลล่าสุดแล้ว", body.errors?.length ? "warn" : "ok");
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<button type="button" className={`btn ${variant === "primary" ? "btn-primary" : "btn-on-band"}`} disabled={busy} onClick={refresh}>
|
||||
<Icon name="refresh" size={16} className={busy ? "animate-spin" : undefined} />
|
||||
{busy ? "กำลังดึงข้อมูล…" : "ดึงข้อมูลตอนนี้"}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Icon } from "./Icon";
|
||||
import { Notice } from "./ui";
|
||||
|
||||
/** AI reply drafts for the open chat. Picking one only fills the composer — staff still press send. */
|
||||
export function ReplyDrafts({ pageId, conversationId, onPick }: { pageId: string; conversationId: string; onPick: (text: string) => void }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [replies, setReplies] = useState<string[]>([]);
|
||||
const [profileMissing, setProfileMissing] = useState(false);
|
||||
|
||||
async function draft() {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await fetch("/api/ai/reply", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pageId, conversationId }),
|
||||
}).catch(() => null);
|
||||
const body = res ? await res.json().catch(() => ({})) : {};
|
||||
setBusy(false);
|
||||
if (!res?.ok) return setError(body.error ?? "AI ร่างคำตอบไม่สำเร็จ");
|
||||
setReplies(body.replies ?? []);
|
||||
setProfileMissing(Boolean(body.profileMissing));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button type="button" className="btn btn-ghost btn-sm" disabled={busy} onClick={draft}>
|
||||
<Icon name="sparkle" size={14} /> {busy ? "AI กำลังร่าง…" : replies.length ? "ร่างใหม่" : "ร่างคำตอบด้วย AI"}
|
||||
</button>
|
||||
<span className="text-[11px] text-ink-4">ข้อความล่าสุดในแชทจะถูกส่งให้ AI ช่วยร่าง</span>
|
||||
</div>
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
{profileMissing && replies.length > 0 && (
|
||||
<p className="text-[12px] text-ink-3">
|
||||
ยังไม่มีโปรไฟล์ร้าน — <Link href="/profile" className="underline">ตั้งไว้</Link> แล้ว AI จะตอบเรื่องราคาและการสั่งซื้อได้ตรงขึ้น
|
||||
</p>
|
||||
)}
|
||||
{replies.map((r, i) => (
|
||||
<button
|
||||
key={i}
|
||||
type="button"
|
||||
className="text-left rounded-[12px] border border-line bg-paper hover:border-blue px-3 py-2 text-[14px] whitespace-pre-wrap break-words"
|
||||
onClick={() => {
|
||||
onPick(r);
|
||||
setReplies([]);
|
||||
}}
|
||||
>
|
||||
{r}
|
||||
<span className="block text-[11px] text-blue mt-1">แตะเพื่อใส่ในช่องพิมพ์</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Icon } from "./Icon";
|
||||
import { EmptyState, Notice, numberFmt } from "./ui";
|
||||
|
||||
type Kind = "DM" | "COMMENT";
|
||||
|
||||
interface Rule {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: Kind;
|
||||
keywords: string[];
|
||||
reply: string;
|
||||
imageUrl: string | null;
|
||||
publicAck: string | null;
|
||||
isActive: boolean;
|
||||
priority: number;
|
||||
sent: number;
|
||||
}
|
||||
|
||||
const EMPTY: Omit<Rule, "id" | "sent"> = { name: "", kind: "COMMENT", keywords: [], reply: "", imageUrl: null, publicAck: "ส่งรายละเอียดให้ทาง inbox แล้วนะคะ", isActive: true, priority: 0 };
|
||||
|
||||
const KIND_LABEL: Record<Kind, string> = { COMMENT: "คอมเมนต์ → ตอบทาง inbox", DM: "ข้อความ inbox → ตอบในแชท" };
|
||||
|
||||
export function RulesManager({ pageId, canEdit, rules }: { pageId: string; canEdit: boolean; rules: Rule[] }) {
|
||||
const router = useRouter();
|
||||
const [editing, setEditing] = useState<(Omit<Rule, "id" | "sent"> & { id?: string }) | null>(null);
|
||||
const [keywordsText, setKeywordsText] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
function open(rule: Rule | null) {
|
||||
setError(null);
|
||||
setEditing(rule ? { ...rule } : { ...EMPTY });
|
||||
setKeywordsText((rule?.keywords ?? []).join(", "));
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!editing) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await fetch("/api/reply-rules", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ ...editing, pageId, keywords: keywordsText }),
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
setBusy(false);
|
||||
if (!res.ok) return setError(body.error ?? "บันทึกไม่สำเร็จ");
|
||||
setEditing(null);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function toggle(rule: Rule) {
|
||||
await fetch("/api/reply-rules", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ ...rule, pageId, isActive: !rule.isActive }),
|
||||
});
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function remove(rule: Rule) {
|
||||
if (!window.confirm(`ลบกฎ "${rule.name}"?`)) return;
|
||||
await fetch(`/api/reply-rules?id=${rule.id}`, { method: "DELETE" });
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-5 grid-cols-[minmax(0,1fr)] xl:grid-cols-[minmax(0,1fr)_420px] items-start">
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>กฎทั้งหมด</h2>
|
||||
{canEdit && (
|
||||
<button type="button" className="btn btn-primary btn-sm ml-auto" onClick={() => open(null)}>
|
||||
<Icon name="plus" size={14} /> เพิ่มกฎ
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{rules.length === 0 ? (
|
||||
<EmptyState icon="bolt" title="ยังไม่มีกฎ" hint="เช่น คอมเมนต์ว่า “สนใจ” → ส่งรายละเอียดทาง inbox อัตโนมัติ" />
|
||||
) : (
|
||||
<ul>
|
||||
{rules.map((r) => (
|
||||
<li key={r.id} className="flex items-start gap-3 px-[18px] py-3.5 border-b border-line-2 last:border-0">
|
||||
<button type="button" role="switch" aria-checked={r.isActive} aria-label={`เปิด/ปิดกฎ ${r.name}`} className="toggle mt-0.5" disabled={!canEdit} onClick={() => toggle(r)} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<b>{r.name}</b>
|
||||
<span className={`pill ${r.kind === "COMMENT" ? "pill-blue" : "pill-green"}`}>{r.kind === "COMMENT" ? "คอมเมนต์" : "Inbox"}</span>
|
||||
{r.priority !== 0 && <span className="pill pill-neutral num">ลำดับ {r.priority}</span>}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1 mt-1.5">
|
||||
{r.keywords.map((k) => (
|
||||
<span key={k} className="pill pill-neutral">
|
||||
{k}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-[13px] text-ink-2 mt-1.5 line-clamp-2 whitespace-pre-wrap">{r.reply}</p>
|
||||
<p className="text-[12px] text-ink-4 mt-1 num">ส่งแล้ว {numberFmt.format(r.sent)} คน</p>
|
||||
</div>
|
||||
{canEdit && (
|
||||
<div className="flex gap-1">
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => open(r)}>
|
||||
แก้ไข
|
||||
</button>
|
||||
<button type="button" className="btn btn-danger btn-sm" onClick={() => remove(r)} aria-label="ลบ">
|
||||
<Icon name="trash" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{editing ? (
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>{editing.id ? "แก้ไขกฎ" : "กฎใหม่"}</h2>
|
||||
</div>
|
||||
<div className="card-body flex flex-col gap-4">
|
||||
<label className="field">
|
||||
<span>ชื่อกฎ</span>
|
||||
<input className="input" value={editing.name} onChange={(e) => setEditing({ ...editing, name: e.target.value })} placeholder="เช่น ส่งราคาเมื่อคอมเมนต์สนใจ" />
|
||||
</label>
|
||||
<div className="field">
|
||||
<span>ทำงานเมื่อ</span>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(["COMMENT", "DM"] as Kind[]).map((k) => (
|
||||
<button key={k} type="button" className="chip" aria-pressed={editing.kind === k} onClick={() => setEditing({ ...editing, kind: k })}>
|
||||
{KIND_LABEL[k]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<label className="field">
|
||||
<span>Keyword (คั่นด้วยจุลภาค — มีคำใดคำหนึ่งก็ทำงาน)</span>
|
||||
<input className="input" value={keywordsText} onChange={(e) => setKeywordsText(e.target.value)} placeholder="สนใจ, ราคา, inbox" />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>ข้อความตอบกลับ{editing.kind === "COMMENT" ? " (ส่งทาง inbox)" : ""}</span>
|
||||
<textarea className="textarea" rows={5} maxLength={2000} value={editing.reply} onChange={(e) => setEditing({ ...editing, reply: e.target.value })} />
|
||||
</label>
|
||||
{editing.kind === "COMMENT" && (
|
||||
<label className="field">
|
||||
<span>ตอบใต้คอมเมนต์ (ไม่บังคับ — คนอื่นเห็น)</span>
|
||||
<input className="input" value={editing.publicAck ?? ""} onChange={(e) => setEditing({ ...editing, publicAck: e.target.value || null })} />
|
||||
</label>
|
||||
)}
|
||||
{editing.kind === "DM" && (
|
||||
<label className="field">
|
||||
<span>รูปแนบ URL (ไม่บังคับ)</span>
|
||||
<input className="input" value={editing.imageUrl ?? ""} onChange={(e) => setEditing({ ...editing, imageUrl: e.target.value || null })} placeholder="https://…" />
|
||||
</label>
|
||||
)}
|
||||
<label className="field">
|
||||
<span>ลำดับความสำคัญ (เลขมากถูกเช็กก่อน)</span>
|
||||
<input className="input num" type="number" value={editing.priority} onChange={(e) => setEditing({ ...editing, priority: Number(e.target.value) })} />
|
||||
</label>
|
||||
{editing.kind === "COMMENT" && (
|
||||
<Notice tone="blue">ตอบทาง inbox ได้เฉพาะคอมเมนต์บนโพสต์ของเพจ ภายใน 7 วัน — คอมเมนต์ในกลุ่มตอบไม่ได้</Notice>
|
||||
)}
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
<div className="flex gap-2">
|
||||
<button type="button" className="btn btn-primary" disabled={busy} onClick={save}>
|
||||
{busy ? "กำลังบันทึก…" : "บันทึกกฎ"}
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost" onClick={() => setEditing(null)}>
|
||||
ยกเลิก
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
) : (
|
||||
<section className="card card-body text-ink-2 flex flex-col gap-2">
|
||||
<b className="text-ink">ทำงานยังไง</b>
|
||||
<p>ลูกค้าคอมเมนต์หรือทักมา → ระบบหา keyword ตามลำดับความสำคัญ → ตอบตามกฎแรกที่ตรง</p>
|
||||
<p>คนเดิมได้คำตอบจากกฎเดิมครั้งเดียว กันสแปม</p>
|
||||
<p>แชทที่สลับเป็น “คนตอบ” ใน Inbox บอทจะไม่ตอบ</p>
|
||||
{!canEdit && <p className="text-ink-3 text-[13px]">ต้องเป็นผู้อนุมัติขึ้นไปถึงจะแก้กฎได้</p>}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
/** Registers /sw.js in production only — in dev it would cache stale bundles across HMR. */
|
||||
export function ServiceWorker() {
|
||||
useEffect(() => {
|
||||
if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return;
|
||||
navigator.serviceWorker.register("/sw.js").catch((e) => console.error("[sw] register failed", e));
|
||||
}, []);
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Icon, type IconName } from "./Icon";
|
||||
import { PageAvatar } from "./PageAvatar";
|
||||
import { ToastProvider } from "./Toast";
|
||||
|
||||
interface ShellPage {
|
||||
id: string;
|
||||
name: string;
|
||||
pictureUrl: string | null;
|
||||
status: string;
|
||||
}
|
||||
|
||||
type CountKey = "pendingApprovals";
|
||||
|
||||
interface NavEntry {
|
||||
href: string;
|
||||
label: string;
|
||||
icon: IconName;
|
||||
superadmin?: boolean;
|
||||
count?: CountKey;
|
||||
/** Other sections that light this entry up. */
|
||||
also?: string[];
|
||||
}
|
||||
|
||||
const WORK: NavEntry[] = [
|
||||
{ href: "/", label: "แผนคอนเทนต์", icon: "calendar", also: ["/calendar"] },
|
||||
{ href: "/posts", label: "โพสต์ทั้งหมด", icon: "post", count: "pendingApprovals" },
|
||||
{ href: "/inbox", label: "Inbox", icon: "inbox" },
|
||||
{ href: "/auto-reply", label: "Auto-reply", icon: "bolt" },
|
||||
{ href: "/insights", label: "Insights", icon: "chart" },
|
||||
{ href: "/analysis", label: "วิเคราะห์ & Ads", icon: "target" },
|
||||
];
|
||||
const SETTINGS: NavEntry[] = [
|
||||
{ href: "/account", label: "บัญชีของฉัน", icon: "users" },
|
||||
{ href: "/pages", label: "เพจที่เชื่อม", icon: "pages" },
|
||||
{ href: "/profile", label: "โปรไฟล์ร้าน", icon: "store" },
|
||||
{ href: "/users", label: "ผู้ใช้", icon: "users", superadmin: true },
|
||||
];
|
||||
|
||||
// Thumb tabs on phones; everything else is in the "เมนู" drawer.
|
||||
const TABS: NavEntry[] = [WORK[0], WORK[1], WORK[2]];
|
||||
|
||||
function setSelectedPage(id: string | null) {
|
||||
document.cookie = id
|
||||
? `pm_page=${encodeURIComponent(id)}; path=/; max-age=31536000; samesite=lax`
|
||||
: "pm_page=; path=/; max-age=0; samesite=lax";
|
||||
}
|
||||
|
||||
function PageOptions({ pages, selectedId, onPick }: { pages: ShellPage[]; selectedId: string | null; onPick: (id: string | null) => void }) {
|
||||
return (
|
||||
<ul role="listbox" aria-label="เลือกเพจ" className="flex flex-col gap-0.5">
|
||||
<li>
|
||||
<button type="button" role="option" aria-selected={!selectedId} className="page-option" onClick={() => onPick(null)}>
|
||||
<span className="w-9 h-9 rounded-full bg-board border border-line grid place-items-center shrink-0 text-ink-2">
|
||||
<Icon name="pages" size={16} />
|
||||
</span>
|
||||
<span className="flex-1 text-left">ทุกเพจ</span>
|
||||
{!selectedId && <Icon name="check" size={18} />}
|
||||
</button>
|
||||
</li>
|
||||
{pages.map((p) => (
|
||||
<li key={p.id}>
|
||||
<button type="button" role="option" aria-selected={p.id === selectedId} className="page-option" onClick={() => onPick(p.id)}>
|
||||
<PageAvatar name={p.name} src={p.pictureUrl} size={36} />
|
||||
<span className="flex-1 min-w-0 text-left truncate">{p.name}</span>
|
||||
{p.status !== "ACTIVE" && <span className="pill pill-red">token มีปัญหา</span>}
|
||||
{p.id === selectedId && <Icon name="check" size={18} />}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{pages.length === 0 && <li className="p-3 text-ink-3 text-[13px]">ยังไม่มีเพจที่คุณเข้าถึงได้</li>}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
export function Shell({
|
||||
user,
|
||||
pages,
|
||||
selectedId,
|
||||
counts,
|
||||
children,
|
||||
}: {
|
||||
user: { name: string; email: string; avatarUrl: string | null; superadmin: boolean };
|
||||
pages: ShellPage[];
|
||||
selectedId: string | null;
|
||||
counts: Record<CountKey, number>;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const [frameOpen, setFrameOpen] = useState(false);
|
||||
const [switcherOpen, setSwitcherOpen] = useState(false);
|
||||
const [sheetOpen, setSheetOpen] = useState(false);
|
||||
const switcherRef = useRef<HTMLDivElement>(null);
|
||||
const selected = pages.find((p) => p.id === selectedId) ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!switcherOpen) return;
|
||||
const close = (e: MouseEvent) => {
|
||||
if (!switcherRef.current?.contains(e.target as Node)) setSwitcherOpen(false);
|
||||
};
|
||||
document.addEventListener("mousedown", close);
|
||||
return () => document.removeEventListener("mousedown", close);
|
||||
}, [switcherOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!sheetOpen && !frameOpen) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
setSheetOpen(false);
|
||||
setFrameOpen(false);
|
||||
}
|
||||
};
|
||||
document.addEventListener("keydown", onKey);
|
||||
return () => document.removeEventListener("keydown", onKey);
|
||||
}, [sheetOpen, frameOpen]);
|
||||
|
||||
function pick(id: string | null) {
|
||||
setSelectedPage(id);
|
||||
setSwitcherOpen(false);
|
||||
setSheetOpen(false);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
await fetch("/api/auth/logout", { method: "POST" });
|
||||
router.replace("/login");
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
const section = "/" + (pathname.split("/")[1] ?? "");
|
||||
const isActive = (n: NavEntry) => section === n.href || Boolean(n.also?.includes(section));
|
||||
const moreActive = !TABS.some(isActive);
|
||||
const sectionLabel = [...WORK, ...SETTINGS].find(isActive)?.label ?? "พื้นที่ทำงาน";
|
||||
|
||||
const navList = (entries: NavEntry[]) =>
|
||||
entries
|
||||
.filter((n) => !n.superadmin || user.superadmin)
|
||||
.map((n) => {
|
||||
const count = n.count ? counts[n.count] : 0;
|
||||
return (
|
||||
<Link key={n.href} href={n.href} className="nav-item" aria-current={isActive(n) ? "page" : undefined} onClick={() => setFrameOpen(false)}>
|
||||
<Icon name={n.icon} />
|
||||
{n.label}
|
||||
{count > 0 && (
|
||||
<span className="nav-count num" title="รออนุมัติ">
|
||||
{count}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
});
|
||||
|
||||
return (
|
||||
<ToastProvider>
|
||||
<div className="shell">
|
||||
<aside className="frame" data-open={frameOpen} aria-label="เมนูหลัก">
|
||||
<div className="flex items-center gap-3 px-1.5 pb-2">
|
||||
<span className="w-9 h-9 rounded-[10px] overflow-hidden shrink-0 shadow-sm">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element -- generated app icon route */}
|
||||
<img src="/icons/192" alt="" width={36} height={36} />
|
||||
</span>
|
||||
<div className="leading-tight flex-1 min-w-0">
|
||||
<div className="font-bold">ระบบจัดการเพจ</div>
|
||||
<div className="text-ink-3 text-[11px] mt-1">Content workspace</div>
|
||||
</div>
|
||||
<button type="button" className="min-[960px]:hidden p-2 -mr-1 rounded-full hover:bg-white/60" onClick={() => setFrameOpen(false)} aria-label="ปิดเมนู">
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="relative" ref={switcherRef}>
|
||||
<button type="button" className="page-tag" aria-haspopup="listbox" aria-expanded={switcherOpen} onClick={() => setSwitcherOpen((o) => !o)}>
|
||||
{selected ? (
|
||||
<PageAvatar name={selected.name} src={selected.pictureUrl} size={38} />
|
||||
) : (
|
||||
<span className="w-[38px] h-[38px] rounded-full bg-board border border-line grid place-items-center text-ink-2">
|
||||
<Icon name="pages" size={16} />
|
||||
</span>
|
||||
)}
|
||||
<span className="flex-1 min-w-0 leading-tight">
|
||||
<span className="block text-[11px] text-ink-3">กำลังดู</span>
|
||||
<span className="block truncate font-semibold">{selected?.name ?? "ทุกเพจ"}</span>
|
||||
</span>
|
||||
<Icon name="chevron" size={16} />
|
||||
</button>
|
||||
{switcherOpen && (
|
||||
<div className="absolute z-20 mt-2 w-full card p-1.5 max-h-80 overflow-auto">
|
||||
<PageOptions pages={pages} selectedId={selectedId} onPick={pick} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<nav className="flex flex-col gap-1" aria-label="งาน">
|
||||
<div className="frame-label mb-2">พื้นที่ทำงาน</div>
|
||||
{navList(WORK)}
|
||||
</nav>
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="frame-label">ตั้งค่า</div>
|
||||
<nav className="flex flex-col gap-1" aria-label="ตั้งค่า">
|
||||
{navList(SETTINGS)}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div className="mt-auto flex items-center gap-3 px-2 pt-3 border-t border-[var(--frame-edge)]">
|
||||
<Link href="/account" aria-label="ตั้งค่าโปรไฟล์ของฉัน" onClick={() => setFrameOpen(false)}><PageAvatar name={user.name || user.email} src={user.avatarUrl} size={36} /></Link>
|
||||
<div className="flex-1 min-w-0 leading-tight">
|
||||
<div className="truncate font-medium">{user.name}</div>
|
||||
<div className="truncate text-ink-3 text-[12px]">{user.superadmin ? "ผู้ดูแลระบบ" : user.email}</div>
|
||||
</div>
|
||||
<button type="button" className="p-2.5 rounded-full hover:bg-white/60 text-ink-2" onClick={logout} aria-label="ออกจากระบบ" title="ออกจากระบบ">
|
||||
<Icon name="logout" />
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{frameOpen && <div className="scrim min-[960px]:hidden" onClick={() => setFrameOpen(false)} />}
|
||||
|
||||
<div className="board">
|
||||
<header className="workspace-bar hidden min-[960px]:flex">
|
||||
<div className="flex items-center gap-2 text-[13px] text-ink-3"><Icon name="pages" size={16} /><span>พื้นที่ทำงาน</span><span className="text-ink-4">/</span><span className="text-ink font-medium">{sectionLabel}</span></div>
|
||||
<div className="flex items-center gap-3 ml-auto text-[12px] text-ink-3"><span>Facebook & Instagram</span><span className="w-1 h-1 rounded-full bg-line" /><span>{pages.length} เพจ</span><Link href="/account" aria-label="ตั้งค่าโปรไฟล์ของฉัน"><PageAvatar name={user.name || user.email} src={user.avatarUrl} size={32} /></Link></div>
|
||||
</header>
|
||||
{/* Phone top bar: the page chip is the context switch. */}
|
||||
<header className="topbar min-[960px]:hidden">
|
||||
<button type="button" className="page-chip" onClick={() => setSheetOpen(true)} aria-haspopup="dialog">
|
||||
{selected ? (
|
||||
<PageAvatar name={selected.name} src={selected.pictureUrl} size={30} />
|
||||
) : (
|
||||
<span className="w-[30px] h-[30px] rounded-full bg-board grid place-items-center text-ink-2">
|
||||
<Icon name="pages" size={14} />
|
||||
</span>
|
||||
)}
|
||||
<span className="truncate max-w-[56vw]">{selected?.name ?? "ทุกเพจ"}</span>
|
||||
<Icon name="chevron" size={15} />
|
||||
</button>
|
||||
</header>
|
||||
<main className="page-body">{children}</main>
|
||||
</div>
|
||||
|
||||
<nav className="tabbar min-[960px]:hidden" aria-label="เมนูลัด">
|
||||
{TABS.slice(0, 2).map((t) => (
|
||||
<TabLink key={t.href} entry={t} active={isActive(t)} count={t.count ? counts[t.count] : 0} />
|
||||
))}
|
||||
<Link href="/posts/new" className="tab-create" aria-label="สร้างโพสต์">
|
||||
<span className="tab-create-btn">
|
||||
<Icon name="plus" size={24} />
|
||||
</span>
|
||||
</Link>
|
||||
<TabLink entry={TABS[2]} active={isActive(TABS[2])} count={0} />
|
||||
<button type="button" className="tab" data-active={moreActive} onClick={() => setFrameOpen(true)}>
|
||||
<Icon name="menu" size={22} />
|
||||
<span>เมนู</span>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
{sheetOpen && (
|
||||
<div className="sheet-root min-[960px]:hidden" role="dialog" aria-modal="true" aria-label="เลือกเพจ">
|
||||
<div className="scrim" onClick={() => setSheetOpen(false)} />
|
||||
<div className="sheet">
|
||||
<div className="sheet-grip" aria-hidden="true" />
|
||||
<div className="flex items-center px-4 pb-2">
|
||||
<b className="text-[17px]">เลือกเพจ</b>
|
||||
<button type="button" className="ml-auto p-2 -mr-2 rounded-full text-ink-3" onClick={() => setSheetOpen(false)} aria-label="ปิด">
|
||||
<Icon name="x" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="px-2 pb-2 overflow-y-auto">
|
||||
<PageOptions pages={pages} selectedId={selectedId} onPick={pick} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ToastProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function TabLink({ entry, active, count }: { entry: NavEntry; active: boolean; count: number }) {
|
||||
return (
|
||||
<Link href={entry.href} className="tab" data-active={active} aria-current={active ? "page" : undefined}>
|
||||
<span className="relative">
|
||||
<Icon name={entry.icon} size={22} />
|
||||
{count > 0 && <span className="tab-badge num">{count > 99 ? "99+" : count}</span>}
|
||||
</span>
|
||||
<span>{entry.href === "/posts" ? "โพสต์" : entry.label}</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useCallback, useContext, useRef, useState } from "react";
|
||||
import { Icon } from "./Icon";
|
||||
|
||||
type Tone = "ok" | "warn" | "error";
|
||||
interface ToastItem {
|
||||
id: number;
|
||||
message: string;
|
||||
tone: Tone;
|
||||
}
|
||||
|
||||
const ToastContext = createContext<{ show: (message: string, tone?: Tone) => void }>({ show: () => {} });
|
||||
|
||||
export function useToast() {
|
||||
return useContext(ToastContext);
|
||||
}
|
||||
|
||||
/** Bottom toasts: above the mobile tab bar, bottom-right on desktop. */
|
||||
export function ToastProvider({ children }: { children: React.ReactNode }) {
|
||||
const [items, setItems] = useState<ToastItem[]>([]);
|
||||
const seq = useRef(0);
|
||||
|
||||
const show = useCallback((message: string, tone: Tone = "ok") => {
|
||||
const id = ++seq.current;
|
||||
setItems((cur) => [...cur.slice(-2), { id, message, tone }]);
|
||||
setTimeout(() => setItems((cur) => cur.filter((t) => t.id !== id)), tone === "error" ? 7000 : 3500);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={{ show }}>
|
||||
{children}
|
||||
<div className="toast-stack" role="status" aria-live="polite">
|
||||
{items.map((t) => (
|
||||
<div key={t.id} className={`toast toast-${t.tone}`}>
|
||||
<span className="toast-icon">
|
||||
<Icon name={t.tone === "ok" ? "check" : "alert"} size={15} />
|
||||
</span>
|
||||
<span className="flex-1">{t.message}</span>
|
||||
<button type="button" className="toast-close" aria-label="ปิด" onClick={() => setItems((cur) => cur.filter((x) => x.id !== t.id))}>
|
||||
<Icon name="x" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { GlobalRole, PageRole } from "@prisma/client";
|
||||
import { PAGE_ROLE_LABEL } from "@/lib/auth/roles";
|
||||
import { MIN_PASSWORD_LENGTH } from "@/lib/auth/policy";
|
||||
import { Icon } from "./Icon";
|
||||
import { formatDateTime, Notice } from "./ui";
|
||||
|
||||
interface UserRow {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
globalRole: GlobalRole;
|
||||
isActive: boolean;
|
||||
lastLoginAt: string | null;
|
||||
memberships: { role: PageRole; pageName: string }[];
|
||||
}
|
||||
|
||||
export function UsersManager({ users, currentUserId }: { users: UserRow[]; currentUserId: string }) {
|
||||
const router = useRouter();
|
||||
const [form, setForm] = useState({ name: "", email: "", password: "", globalRole: "MEMBER" as GlobalRole });
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [flash, setFlash] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function call(url: string, method: string, body: unknown, ok: string) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setFlash(null);
|
||||
const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setBusy(false);
|
||||
if (!res.ok) {
|
||||
setError(data.error ?? "ทำรายการไม่สำเร็จ");
|
||||
return false;
|
||||
}
|
||||
setFlash(ok);
|
||||
router.refresh();
|
||||
return true;
|
||||
}
|
||||
|
||||
async function create(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (await call("/api/users", "POST", form, `สร้างบัญชี ${form.email} แล้ว — ผู้ใช้ต้องเปลี่ยนรหัสผ่านตอนเข้าครั้งแรก`)) {
|
||||
setForm({ name: "", email: "", password: "", globalRole: "MEMBER" });
|
||||
}
|
||||
}
|
||||
|
||||
function resetPassword(u: UserRow) {
|
||||
const password = window.prompt(`รหัสผ่านชั่วคราวใหม่ของ ${u.email} (อย่างน้อย ${MIN_PASSWORD_LENGTH} ตัวอักษร)`);
|
||||
if (password) call(`/api/users/${u.id}`, "PATCH", { password }, `ตั้งรหัสผ่านชั่วคราวให้ ${u.email} แล้ว`);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-5 grid-cols-[minmax(0,1fr)] xl:grid-cols-[minmax(0,1fr)_380px] items-start">
|
||||
<section className="card">
|
||||
<div className="card-head">
|
||||
<h2>บัญชีผู้ใช้ ({users.length})</h2>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ผู้ใช้</th>
|
||||
<th>สิทธิ์</th>
|
||||
<th>เพจ</th>
|
||||
<th>เข้าล่าสุด</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((u) => (
|
||||
<tr key={u.id} className={u.isActive ? "" : "opacity-55"}>
|
||||
<td>
|
||||
<div className="font-medium">{u.name}</div>
|
||||
<div className="text-[12px] text-ink-3">{u.email}</div>
|
||||
</td>
|
||||
<td>
|
||||
{u.globalRole === "SUPERADMIN" ? <span className="pill pill-blue">ผู้ดูแลระบบ</span> : <span className="pill pill-neutral">สมาชิก</span>}
|
||||
{!u.isActive && <span className="pill pill-red ml-1">ปิดบัญชี</span>}
|
||||
</td>
|
||||
<td className="text-[12px] text-ink-2 max-w-[240px]">
|
||||
{u.globalRole === "SUPERADMIN" ? "ทุกเพจ" : u.memberships.map((m) => `${m.pageName} (${PAGE_ROLE_LABEL[m.role]})`).join(", ") || "—"}
|
||||
</td>
|
||||
<td className="num text-[13px] text-ink-2 whitespace-nowrap">{formatDateTime(u.lastLoginAt)}</td>
|
||||
<td>
|
||||
{u.id !== currentUserId && (
|
||||
<div className="flex gap-1 justify-end">
|
||||
<button type="button" className="btn btn-ghost btn-sm" disabled={busy} onClick={() => resetPassword(u)}>
|
||||
รีเซ็ตรหัส
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm"
|
||||
disabled={busy}
|
||||
onClick={() => call(`/api/users/${u.id}`, "PATCH", { globalRole: u.globalRole === "SUPERADMIN" ? "MEMBER" : "SUPERADMIN" }, "เปลี่ยนสิทธิ์แล้ว")}
|
||||
>
|
||||
{u.globalRole === "SUPERADMIN" ? "ลดเป็นสมาชิก" : "ตั้งเป็นผู้ดูแล"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-sm ${u.isActive ? "btn-danger" : "btn-ghost"}`}
|
||||
disabled={busy}
|
||||
onClick={() => call(`/api/users/${u.id}`, "PATCH", { isActive: !u.isActive }, u.isActive ? "ปิดบัญชีแล้ว" : "เปิดบัญชีแล้ว")}
|
||||
>
|
||||
{u.isActive ? "ปิดบัญชี" : "เปิดบัญชี"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<form className="card" onSubmit={create}>
|
||||
<div className="card-head">
|
||||
<h2>เพิ่มผู้ใช้</h2>
|
||||
</div>
|
||||
<div className="card-body flex flex-col gap-4">
|
||||
<label className="field">
|
||||
<span>ชื่อ</span>
|
||||
<input className="input" required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>อีเมล</span>
|
||||
<input className="input" type="email" required value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
|
||||
<small className="text-ink-3">ใช้อีเมลเดียวกับบัญชี Google หรือ Facebook ของผู้ใช้ เพื่อให้กดเข้าสู่ระบบด้วยบัญชีนั้นได้</small>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>รหัสผ่านชั่วคราว (อย่างน้อย {MIN_PASSWORD_LENGTH} ตัว)</span>
|
||||
<input className="input" type="text" required minLength={MIN_PASSWORD_LENGTH} autoComplete="off" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} />
|
||||
</label>
|
||||
<div className="field">
|
||||
<span>สิทธิ์ระบบ</span>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" className="chip" aria-pressed={form.globalRole === "MEMBER"} onClick={() => setForm({ ...form, globalRole: "MEMBER" })}>
|
||||
สมาชิก
|
||||
</button>
|
||||
<button type="button" className="chip" aria-pressed={form.globalRole === "SUPERADMIN"} onClick={() => setForm({ ...form, globalRole: "SUPERADMIN" })}>
|
||||
ผู้ดูแลระบบ
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
{flash && <Notice tone="blue">{flash}</Notice>}
|
||||
<button className="btn btn-primary" disabled={busy}>
|
||||
<Icon name="plus" size={16} /> สร้างบัญชี
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { PostStatus } from "@prisma/client";
|
||||
import { addDays, bkkMidnight } from "@/lib/board";
|
||||
import { Icon } from "./Icon";
|
||||
import { POST_STATUS_META, StatusPill } from "./ui";
|
||||
import { useToast } from "./Toast";
|
||||
|
||||
interface BoardPost {
|
||||
id: string;
|
||||
pageId: string;
|
||||
pageName: string;
|
||||
title: string;
|
||||
caption: string;
|
||||
status: PostStatus;
|
||||
targets: string[];
|
||||
day: string | null;
|
||||
scheduledAt: string | null;
|
||||
}
|
||||
|
||||
const dayFmt = new Intl.DateTimeFormat("th-TH", { weekday: "short", timeZone: "Asia/Bangkok" });
|
||||
const rangeFmt = new Intl.DateTimeFormat("th-TH", { day: "numeric", month: "short", timeZone: "Asia/Bangkok" });
|
||||
const timeFmt = new Intl.DateTimeFormat("th-TH", { hour: "2-digit", minute: "2-digit", timeZone: "Asia/Bangkok" });
|
||||
|
||||
export function WeekBoard({ week, today, posts, tray, editablePageIds, nextId }: {
|
||||
week: string; today: string; posts: BoardPost[]; tray: BoardPost[]; editablePageIds: string[]; nextId: string | null;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [over, setOver] = useState<string | null>(null);
|
||||
const [dragging, setDragging] = useState<string | null>(null);
|
||||
const days = Array.from({ length: 7 }, (_, i) => addDays(week, i));
|
||||
const canMove = (p: BoardPost) => editablePageIds.includes(p.pageId) && p.status !== "SCHEDULED" && p.status !== "PUBLISHED";
|
||||
|
||||
async function plan(id: string, day: string | null) {
|
||||
const post = [...posts, ...tray].find(p => p.id === id);
|
||||
if (busy || !post || !canMove(post) || post.day === day) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch(`/api/posts/${id}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "plan", plannedAt: day ? bkkMidnight(day).toISOString() : null }) });
|
||||
const body = await res.json();
|
||||
if (!res.ok) throw new Error(body.error ?? "วางวันไม่สำเร็จ");
|
||||
toast.show(day ? "วางวันแล้ว · ยังไม่ได้ตั้งเวลาเผยแพร่" : "ย้ายกลับคิวที่ยังไม่วางแผนแล้ว");
|
||||
router.refresh();
|
||||
} catch (e) {
|
||||
toast.show(e instanceof Error ? e.message : "เชื่อมต่อไม่ได้ ลองอีกครั้ง", "error");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function card(p: BoardPost) {
|
||||
const movable = canMove(p);
|
||||
return <article key={p.id} className="post-card p-3" draggable={movable && !busy} data-next={p.id === nextId} data-dragging={dragging === p.id}
|
||||
onDragStart={e => { e.dataTransfer.setData("text/plain", p.id); e.dataTransfer.effectAllowed = "move"; setDragging(p.id); }}
|
||||
onDragEnd={() => { setDragging(null); setOver(null); }}>
|
||||
{p.id === nextId && <span className="next-flag mb-2">โพสต์ถัดไป</span>}
|
||||
<Link href={`/posts/${p.id}`} className="block group">
|
||||
<div className="text-[11px] text-ink-3 truncate">{p.pageName}</div>
|
||||
<h3 className="text-[13px] font-semibold leading-relaxed break-words group-hover:underline mt-1">{p.title}</h3>
|
||||
<p className="line-clamp-2 text-[12px] text-ink-3 mt-1 break-words">{p.caption || "โพสต์รูปภาพ"}</p>
|
||||
<div className="mt-3"><StatusPill status={p.status} /></div>
|
||||
<div className="flex flex-wrap gap-2 text-[11px] text-ink-3 mt-2">
|
||||
<span>{p.targets.map(t => t === "FACEBOOK" ? "FB" : "IG").join(" + ")}</span>
|
||||
{p.scheduledAt && <span className="num">{timeFmt.format(new Date(p.scheduledAt))} น.</span>}
|
||||
{p.day && !p.scheduledAt && p.status !== "PUBLISHED" && <span>แผนเท่านั้น</span>}
|
||||
</div>
|
||||
</Link>
|
||||
{movable && <details className="plan-date">
|
||||
<summary><Icon name="calendar" size={13} /><span>{p.day ? "เปลี่ยนวัน" : "เลือกวัน"}</span><Icon name="chevron" size={12} /></summary>
|
||||
<div className="plan-date-popover">
|
||||
<label className="field"><span>วันวางแผน</span><input aria-label={`วางวัน ${p.title}`} type="date" className="input" value={p.day ?? ""} disabled={busy} onChange={e => void plan(p.id, e.target.value || null)} /></label>
|
||||
{p.day && <button type="button" className="text-[12px] text-ink-3 mt-3 hover:text-blue" disabled={busy} onClick={() => void plan(p.id, null)}>ย้ายกลับคิวที่ยังไม่วางแผน</button>}
|
||||
</div>
|
||||
</details>}
|
||||
</article>;
|
||||
}
|
||||
|
||||
const drop = (day: string | null) => ({
|
||||
onDragOver: (e: React.DragEvent) => { if (dragging && !busy) { e.preventDefault(); e.dataTransfer.dropEffect = "move"; setOver(day ?? "tray"); } },
|
||||
onDragLeave: (e: React.DragEvent) => { if (!e.currentTarget.contains(e.relatedTarget as Node)) setOver(null); },
|
||||
onDrop: (e: React.DragEvent) => { e.preventDefault(); setOver(null); setDragging(null); void plan(e.dataTransfer.getData("text/plain"), day); },
|
||||
});
|
||||
|
||||
return <section aria-label="แผนโพสต์รายสัปดาห์" aria-busy={busy} className="planner">
|
||||
<div className="planner-toolbar">
|
||||
<nav className="planner-tabs" aria-label="มุมมองปฏิทิน"><span aria-current="page">สัปดาห์</span><Link href="/calendar">เดือน</Link></nav>
|
||||
<nav aria-label="เลือกสัปดาห์" className="flex items-center gap-2">
|
||||
<Link className="btn btn-ghost btn-sm" href={`/?w=${addDays(week, -7)}`} aria-label="สัปดาห์ก่อน"><Icon name="left" size={16} /></Link>
|
||||
<h2 className="text-[14px] font-semibold px-1">{rangeFmt.format(bkkMidnight(week))} – {rangeFmt.format(bkkMidnight(addDays(week, 6)))}</h2>
|
||||
<Link className="btn btn-ghost btn-sm" href={`/?w=${addDays(week, 7)}`} aria-label="สัปดาห์ถัดไป"><Icon name="right" size={16} /></Link>
|
||||
<Link className="btn btn-ghost btn-sm hidden sm:inline-flex" href="/">วันนี้</Link>
|
||||
</nav>
|
||||
</div>
|
||||
<div className="board-layout">
|
||||
<div className="board-scroll">
|
||||
<div className="week">
|
||||
{days.map(day => {
|
||||
const items = posts.filter(p => p.day === day);
|
||||
return <section key={day} className="day" data-over={over === day} data-today={day === today} aria-label={`${dayFmt.format(bkkMidnight(day))} ${day}`} {...drop(day)}>
|
||||
<header className="day-heading">
|
||||
<h3>{dayFmt.format(bkkMidnight(day))}{day === today ? " · วันนี้" : ""}</h3>
|
||||
<span className="day-number num">{Number(day.slice(-2))}</span>
|
||||
</header>
|
||||
{items.map(card)}
|
||||
{editablePageIds.length > 0 ? <Link href={`/posts/new?day=${day}`} className="day-slot" aria-label={`สร้างโพสต์วันที่ ${day}`}><span className="flex items-center gap-1"><Icon name="plus" size={14} /> เพิ่มโพสต์</span></Link> : items.length === 0 && <p className="text-center text-[12px] text-ink-4 py-4">ไม่มีโพสต์</p>}
|
||||
</section>;
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<aside className="draft-tray" data-over={over === "tray"} {...drop(null)}>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div><h2 className="section-label"><Icon name="post" size={17} /> โพสต์ที่ยังไม่วางแผน <span className="pill pill-neutral num">{tray.length}{tray.length === 50 ? "+" : ""}</span></h2><p className="text-[12px] text-ink-3 mt-1">ลากลงปฏิทิน หรือเลือกวันจากการ์ด · ต้องอนุมัติก่อนตั้งเวลาเผยแพร่</p></div>
|
||||
<Link href="/posts" className="shrink-0 text-[12px] text-blue font-medium">ดูทั้งหมด →</Link>
|
||||
</div>
|
||||
{tray.length > 0 ? <div className="draft-cards">{tray.map(card)}</div> : <div className="queue-empty"><Icon name="calendar" size={24} /><p className="text-[13px]">เริ่มจากไอเดีย แล้วเลือกวันที่อยากโพสต์</p>{editablePageIds.length > 0 && <Link href="/posts/new" className="text-[13px] font-medium text-blue mt-1">+ สร้างโพสต์แรก</Link>}</div>}
|
||||
</aside>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-[11px] text-ink-3" aria-label="สีสถานะของโพสต์">
|
||||
{(["DRAFT", "PENDING_APPROVAL", "APPROVED", "SCHEDULED", "PUBLISHED", "FAILED"] as const).map(s => <span key={s} className="flex items-center gap-1.5"><span aria-hidden="true" className={`magnet ${POST_STATUS_META[s].magnet}`} style={{width: 6, height: 6}} />{POST_STATUS_META[s].label}</span>)}
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { bkkMidnight } from "@/lib/board";
|
||||
import { Icon } from "./Icon";
|
||||
import { Notice } from "./ui";
|
||||
import { useToast } from "./Toast";
|
||||
|
||||
interface Proposal {
|
||||
day: string;
|
||||
title: string;
|
||||
pillar: string;
|
||||
caption: string;
|
||||
}
|
||||
|
||||
const dayLabel = new Intl.DateTimeFormat("th-TH", { weekday: "short", day: "numeric", month: "short", timeZone: "Asia/Bangkok" });
|
||||
|
||||
/**
|
||||
* AI proposes posts for the open days of the shown week; the ticked ones become
|
||||
* Facebook drafts pinned to their day. Approval is unchanged.
|
||||
*/
|
||||
export function WeekPlanAssistant({ pageId, pageName, week, openDays }: { pageId: string; pageName: string; week: string; openDays: number }) {
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [goal, setGoal] = useState("");
|
||||
const [count, setCount] = useState(Math.min(5, Math.max(openDays, 3)));
|
||||
const [busy, setBusy] = useState<"plan" | "create" | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [proposals, setProposals] = useState<Proposal[]>([]);
|
||||
const [picked, setPicked] = useState<boolean[]>([]);
|
||||
const [profileMissing, setProfileMissing] = useState(false);
|
||||
|
||||
async function plan() {
|
||||
setBusy("plan");
|
||||
setError(null);
|
||||
const res = await fetch("/api/ai/week-plan", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pageId, week, goal, count }),
|
||||
}).catch(() => null);
|
||||
const body = res ? await res.json().catch(() => ({})) : {};
|
||||
setBusy(null);
|
||||
if (!res?.ok) return setError(body.error ?? "AI วางแผนไม่สำเร็จ ลองใหม่อีกครั้ง");
|
||||
setProposals(body.posts ?? []);
|
||||
setPicked((body.posts ?? []).map(() => true));
|
||||
setProfileMissing(Boolean(body.profileMissing));
|
||||
}
|
||||
|
||||
async function createDrafts() {
|
||||
const chosen = proposals.filter((_, i) => picked[i]);
|
||||
setBusy("create");
|
||||
setError(null);
|
||||
let created = 0;
|
||||
let firstError: string | null = null;
|
||||
for (const p of chosen) {
|
||||
const res = await fetch("/api/posts", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pageId, title: p.title, caption: p.caption, targets: ["FACEBOOK"], aiAssisted: true, plannedAt: bkkMidnight(p.day).toISOString() }),
|
||||
}).catch(() => null);
|
||||
if (res?.ok) created++;
|
||||
else firstError ??= (res ? await res.json().catch(() => ({})) : {}).error ?? "สร้างฉบับร่างไม่สำเร็จ";
|
||||
}
|
||||
setBusy(null);
|
||||
if (created === 0) return setError(firstError);
|
||||
toast.show(firstError ? `สร้างฉบับร่างได้ ${created} จาก ${chosen.length} โพสต์ — ${firstError}` : `สร้างฉบับร่าง ${created} โพสต์ลงกระดานแล้ว`, firstError ? "warn" : "ok");
|
||||
setProposals([]);
|
||||
setPicked([]);
|
||||
setOpen(false);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<button type="button" className="btn btn-ghost self-start" onClick={() => setOpen(true)}>
|
||||
<Icon name="sparkle" size={16} /> ให้ AI ช่วยวางแผนสัปดาห์นี้
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const chosenCount = picked.filter(Boolean).length;
|
||||
return (
|
||||
<section className="card" aria-label="AI วางแผนสัปดาห์">
|
||||
<div className="card-head">
|
||||
<Icon name="sparkle" size={16} />
|
||||
<h2>AI วางแผนสัปดาห์ · {pageName}</h2>
|
||||
<button type="button" className="btn btn-ghost btn-sm ml-auto" onClick={() => setOpen(false)} aria-label="ปิด">
|
||||
<Icon name="x" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="card-body flex flex-col gap-4">
|
||||
<div className="grid gap-3 grid-cols-[minmax(0,1fr)] sm:grid-cols-[minmax(0,1fr)_140px] items-end">
|
||||
<label className="field">
|
||||
<span>สัปดาห์นี้อยากเน้นอะไร</span>
|
||||
<textarea className="textarea" rows={2} maxLength={500} value={goal} onChange={(e) => setGoal(e.target.value)} placeholder="เช่น โปรปลายเดือนลด 10% / เปิดตัวรสใหม่ / ไม่มีอะไรพิเศษ ให้ AI จัดสมดุลเอง" />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>จำนวนโพสต์</span>
|
||||
<select className="select" value={count} onChange={(e) => setCount(Number(e.target.value))}>
|
||||
{[1, 2, 3, 4, 5, 6, 7].map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n} โพสต์
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button type="button" className="btn btn-primary" disabled={busy !== null} onClick={plan}>
|
||||
<Icon name="sparkle" size={16} /> {busy === "plan" ? "AI กำลังวางแผน…" : proposals.length ? "เสนอแผนใหม่" : "ให้ AI เสนอแผน"}
|
||||
</button>
|
||||
<span className="text-[12px] text-ink-3">ใช้เฉพาะวันที่ยังไม่ผ่านของสัปดาห์นี้ ({openDays} วัน)</span>
|
||||
</div>
|
||||
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
{profileMissing && (
|
||||
<p className="text-[12px] text-ink-3">
|
||||
ยังไม่มีโปรไฟล์ร้าน — <Link href="/profile" className="underline">ตั้งไว้</Link> แล้วแผนจะตรงกับร้านมากขึ้น
|
||||
</p>
|
||||
)}
|
||||
|
||||
{proposals.length > 0 && (
|
||||
<>
|
||||
<ul className="flex flex-col gap-2">
|
||||
{proposals.map((p, i) => (
|
||||
<li key={i}>
|
||||
<label className="flex gap-3 rounded-[12px] border border-line bg-paper p-3 cursor-pointer has-[:checked]:border-blue">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-1 w-4 h-4 shrink-0"
|
||||
checked={picked[i] ?? false}
|
||||
onChange={(e) => setPicked((cur) => cur.map((v, j) => (j === i ? e.target.checked : v)))}
|
||||
/>
|
||||
<span className="flex-1 min-w-0 flex flex-col gap-1">
|
||||
<span className="flex flex-wrap items-center gap-2">
|
||||
<span className="num text-[13px] font-semibold">{dayLabel.format(bkkMidnight(p.day))}</span>
|
||||
<span className="pill pill-blue">{p.pillar}</span>
|
||||
<b className="text-[14px]">{p.title}</b>
|
||||
</span>
|
||||
<span className="text-[13px] text-ink-2 whitespace-pre-wrap break-words line-clamp-4">{p.caption}</span>
|
||||
</span>
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button type="button" className="btn btn-primary" disabled={busy !== null || chosenCount === 0} onClick={createDrafts}>
|
||||
{busy === "create" ? "กำลังสร้าง…" : `สร้างเป็นฉบับร่าง ${chosenCount} โพสต์`}
|
||||
</button>
|
||||
<p className="text-[12px] text-ink-3 flex-1 min-w-[220px]">สร้างเป็นฉบับร่าง Facebook วางตามวันในกระดาน — เพิ่มรูป เลือก Instagram และแก้ข้อความได้ในหน้าโพสต์ ทุกโพสต์ยังต้องผ่านอนุมัติ</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { PostStatus } from "@prisma/client";
|
||||
import { Icon, type IconName } from "./Icon";
|
||||
|
||||
export function PageTitle({ title, subtitle, actions }: { title: string; subtitle?: string; actions?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="page-titlebar">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h1>{title}</h1>
|
||||
{subtitle && <p>{subtitle}</p>}
|
||||
</div>
|
||||
{actions && <div className="flex flex-wrap items-center gap-2">{actions}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Every publishing state pairs a colour with a readable label. */
|
||||
export const POST_STATUS_META: Record<PostStatus, { label: string; pill: string; magnet: string; dot: string }> = {
|
||||
DRAFT: { label: "ฉบับร่าง", pill: "pill-neutral", magnet: "magnet-draft", dot: "var(--ink-4)" },
|
||||
PENDING_APPROVAL: { label: "รออนุมัติ", pill: "pill-amber", magnet: "magnet-pending", dot: "var(--m-yellow)" },
|
||||
APPROVED: { label: "อนุมัติแล้ว", pill: "pill-green", magnet: "magnet-approved", dot: "var(--m-green)" },
|
||||
SCHEDULED: { label: "ตั้งเวลาแล้ว", pill: "pill-blue", magnet: "magnet-scheduled", dot: "var(--m-blue)" },
|
||||
PUBLISHED: { label: "เผยแพร่แล้ว", pill: "pill-green", magnet: "magnet-published", dot: "var(--m-green)" },
|
||||
FAILED: { label: "ล้มเหลว", pill: "pill-red", magnet: "magnet-failed", dot: "var(--m-red)" },
|
||||
CANCELLED: { label: "ยกเลิก", pill: "pill-neutral", magnet: "magnet-cancelled", dot: "var(--ink-4)" },
|
||||
};
|
||||
|
||||
export function StatusPill({ status }: { status: PostStatus }) {
|
||||
const m = POST_STATUS_META[status];
|
||||
return (
|
||||
<span className={`pill ${m.pill}`}>
|
||||
<span className={`magnet ${m.magnet}`} style={{ width: 6, height: 6 }} aria-hidden="true" />
|
||||
{m.label}
|
||||
{status === "SCHEDULED" && <Icon name="clock" size={12} />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptyState({ icon, title, hint, good, children }: { icon: IconName; title: string; hint?: string; good?: boolean; children?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="empty">
|
||||
<div className="empty-well" style={good ? { background: "var(--m-green-soft)", color: "var(--m-green-ink)", borderStyle: "solid", borderColor: "transparent" } : undefined}>
|
||||
<Icon name={icon} size={24} />
|
||||
</div>
|
||||
<b>{title}</b>
|
||||
{hint && <span className="max-w-[46ch]">{hint}</span>}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Notice({ tone, title, children }: { tone: "amber" | "red" | "blue"; title?: string; children?: React.ReactNode }) {
|
||||
const well =
|
||||
tone === "amber"
|
||||
? { background: "var(--m-yellow)", color: "var(--m-yellow-ink)" }
|
||||
: tone === "red"
|
||||
? { background: "var(--m-red)", color: "#fff" }
|
||||
: { background: "var(--ink)", color: "#fff" };
|
||||
return (
|
||||
<div className={`notice notice-${tone}`} role={tone === "red" ? "alert" : undefined}>
|
||||
<span className="icon-well" style={well}>
|
||||
<Icon name={tone === "blue" ? "shield" : "alert"} size={15} />
|
||||
</span>
|
||||
<div className="flex-1 min-w-0 pt-0.5">
|
||||
{title && <div className="font-semibold">{title}</div>}
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const dateFmt = new Intl.DateTimeFormat("th-TH", { dateStyle: "medium", timeStyle: "short", timeZone: "Asia/Bangkok" });
|
||||
export function formatDateTime(d: Date | string | null | undefined): string {
|
||||
if (!d) return "—";
|
||||
return dateFmt.format(typeof d === "string" ? new Date(d) : d);
|
||||
}
|
||||
|
||||
export const numberFmt = new Intl.NumberFormat("th-TH");
|
||||
Reference in New Issue
Block a user