Files
PAGIVA/src/components/PostEditor.tsx
T
chaloemphong 9d32552457 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>
2026-11-22 11:52:17 +07:00

578 lines
26 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"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>
);
}