"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 = { 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(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(post?.imageBlobUrl ?? null); const [targets, setTargets] = useState(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(null); const [error, setError] = useState(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 | 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 { 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 = { submit: "ส่งให้ผู้อนุมัติแล้ว", approve: "อนุมัติแล้ว", reject: "ตีกลับแล้ว", publish: "เผยแพร่แล้ว", schedule: "ตั้งเวลาแล้ว", cancel: "ยกเลิกการตั้งเวลาแล้ว", }; async function act(action: string, extra: Record = {}) { 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 (

{post ? "เนื้อหาโพสต์" : "โพสต์ใหม่"}

{aiAssisted && AI ช่วยร่าง} {post && }
{!editable && ( {status === "SCHEDULED" ? "โพสต์ตั้งเวลาไว้แล้ว — ยกเลิกการตั้งเวลาก่อนถึงจะแก้ได้" : "โพสต์เผยแพร่แล้ว แก้ไขในระบบไม่ได้"} )} {!post && } {canEdit && pageId && ( { setCaption(text); if (fromAi) setAiAssisted(true); }} /> )}