"use client"; import { useEffect, useRef, useState } from "react"; import Link from "next/link"; import { withBase } from "@/lib/base-path"; import { POST_JOB_STAGE, POST_JOB_STATUS, postJobProgress, type PostJobView } from "@/lib/ai/post-queue-shared"; import { Icon } from "./Icon"; import { Notice } from "./ui"; import { ContentAutoForm } from "./ContentAutoForm"; function duration(job: PostJobView): string { if (!job.finishedAt) return ""; const seconds = Math.max(0, Math.round((new Date(job.finishedAt).getTime() - new Date(job.createdAt).getTime()) / 1000)); return `${Math.floor(seconds / 60)} นาที ${seconds % 60} วินาที`; } function formatPlannedDay(value: string): string { const [year, month, day] = value.split("-").map(Number); if (!year || !month || !day) return value; return new Intl.DateTimeFormat("th-TH", { day: "numeric", month: "long", year: "numeric", timeZone: "Asia/Bangkok" }).format(new Date(Date.UTC(year, month - 1, day, -7))); } /** Server-persisted jobs are rediscovered after reload; the browser never executes the pipeline. */ export function PostGenerationQueue({ pageId, targets, plannedDay, initialTopic }: { pageId: string; targets: ("FACEBOOK" | "INSTAGRAM")[]; plannedDay: string; initialTopic: string; }) { const [topic, setTopic] = useState(initialTopic.slice(0, 1000)); const [jobs, setJobs] = useState([]); const [busy, setBusy] = useState(false); const [cancelling, setCancelling] = useState(null); const [error, setError] = useState(null); const [pollError, setPollError] = useState(false); const [message, setMessage] = useState(""); const requestKey = useRef(null); useEffect(() => { const controller = new AbortController(); let timer: ReturnType; async function refresh() { try { const response = await fetch(withBase(`/api/ai/post-jobs?pageId=${encodeURIComponent(pageId)}`), { signal: controller.signal, cache: "no-store" }); if (!response.ok) throw new Error("Queue unavailable"); const data = await response.json(); if (!controller.signal.aborted) { setJobs(data.jobs); setPollError(false); } } catch { if (!controller.signal.aborted) setPollError(true); } finally { if (!controller.signal.aborted) timer = setTimeout(refresh, 3000); } } void refresh(); return () => { controller.abort(); clearTimeout(timer); }; }, [pageId]); async function enqueue() { if (busy) return; setBusy(true); setError(null); setMessage(""); requestKey.current ??= crypto.randomUUID(); try { const response = await fetch(withBase("/api/ai/post-jobs"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, requestKey: requestKey.current, topic, targets, plannedDay }) }); const data = await response.json(); if (!response.ok) { if (response.status < 500) requestKey.current = null; throw new Error(data.error || "เพิ่มคิวไม่สำเร็จ"); } setJobs((current) => [data.job, ...current.filter((job) => job.id !== data.job.id)]); setTopic(""); requestKey.current = null; setMessage("รับงานเข้าคิวแล้ว กลับมาหน้านี้เพื่อติดตามและเปิดฉบับร่างเมื่อพร้อมได้"); } catch (failure) { setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้ กรุณาลองอีกครั้ง"); } finally { setBusy(false); } } async function cancel(id: string) { setCancelling(id); setError(null); try { const response = await fetch(withBase(`/api/ai/post-jobs/${id}`), { method: "DELETE" }); const data = await response.json(); if (!response.ok) throw new Error(data.error || "ยกเลิกไม่สำเร็จ"); setJobs((current) => current.map((job) => job.id === id ? { ...job, status: "CANCELLED" } : job)); setMessage("ยกเลิกงานที่รอคิวแล้ว"); } catch (failure) { setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้ กรุณาลองอีกครั้ง"); } finally { setCancelling(null); } } return (

สร้างทั้งโพสต์ด้วย AI

ให้ Codex เขียนเนื้อหาและ ChatGPT สร้างภาพ แล้วบันทึกเป็นฉบับร่างรอคุณตรวจ ปิดหน้านี้แล้วกลับมาดูคิวได้