4c691b5dde
Add percentage-by-stage progress in the queue UI, a progress rendering test script, and clearer Chrome focus error details in the ChatGPT worker. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
120 lines
9.0 KiB
TypeScript
120 lines
9.0 KiB
TypeScript
"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";
|
|
|
|
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} วินาที`;
|
|
}
|
|
|
|
/** 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<PostJobView[]>([]);
|
|
const [busy, setBusy] = useState(false);
|
|
const [cancelling, setCancelling] = useState<string | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [pollError, setPollError] = useState(false);
|
|
const [message, setMessage] = useState("");
|
|
const requestKey = useRef<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
const controller = new AbortController();
|
|
let timer: ReturnType<typeof setTimeout>;
|
|
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 (
|
|
<section aria-label="คิวสร้างโพสต์ด้วย AI" className="border border-line rounded-xl p-4 flex flex-col gap-3 bg-board">
|
|
<h3 className="font-semibold text-[15px]">สร้างทั้งโพสต์ด้วย AI</h3>
|
|
<p className="text-[13px] text-ink-2">ให้ Codex เขียนเนื้อหาและ ChatGPT สร้างภาพ แล้วบันทึกเป็นฉบับร่างรอคุณตรวจ ปิดหน้านี้แล้วกลับมาดูคิวได้</p>
|
|
<label className="field">
|
|
<span>หัวข้อโพสต์ที่จะเข้าคิว</span>
|
|
<textarea className="textarea" rows={2} value={topic} disabled={busy} maxLength={1000} onChange={(event) => { setTopic(event.target.value); requestKey.current = null; }} placeholder="เช่น แนะนำเมนูใหม่ พร้อมราคาและจุดเด่นที่ต้องการสื่อ" />
|
|
</label>
|
|
<p className="text-[12px] text-ink-2">ฉบับร่างสำหรับ {targets.length ? targets.map((target) => target === "FACEBOOK" ? "Facebook" : "Instagram").join(" + ") : "ยังไม่ได้เลือกช่องทาง"}{plannedDay ? ` · วันวางแผน ${plannedDay}` : " · ยังไม่วางวัน"}</p>
|
|
<div className="flex flex-wrap gap-2 items-center">
|
|
<button type="button" className="btn btn-primary btn-sm" disabled={busy || !topic.trim() || targets.length === 0} onClick={enqueue}>
|
|
<Icon name="sparkle" size={15} /> {busy ? "กำลังรับงาน…" : "เข้าคิวสร้างโพสต์"}
|
|
</button>
|
|
<Link href="/profile" prefetch={false} onClick={() => { document.cookie = `pm_page=${encodeURIComponent(pageId)}; path=/; max-age=31536000; samesite=lax`; }} className="text-[12px] underline text-ink-2">ตรวจข้อมูลร้านก่อนสร้าง</Link>
|
|
</div>
|
|
{message && <p role="status" className="text-[13px] text-ink-2">{message}</p>}
|
|
{error && <Notice tone="red">{error}</Notice>}
|
|
{pollError && <p role="status" className="text-[12px] text-ink-2">ยังอัปเดตคิวไม่ได้ ระบบกำลังลองเชื่อมต่อใหม่ งานที่รับไว้ยังอยู่ในคิว</p>}
|
|
{jobs.length > 0 && <>
|
|
<h4 className="font-semibold text-[13px] pt-2">งานล่าสุดของเพจนี้</h4>
|
|
<p className="text-[12px] text-ink-2">เปอร์เซ็นต์อิงตามขั้นตอน อาจคงที่ระหว่างรอสร้างภาพ</p>
|
|
<ul className="divide-y divide-line" aria-label="รายการคิวสร้างโพสต์">
|
|
{jobs.map((job) => <li key={job.id} className="py-3 flex flex-col gap-1.5">
|
|
<div className="flex flex-wrap items-start gap-2">
|
|
<span className="font-medium text-[13px] flex-1 min-w-0 break-words">{job.topic}</span>
|
|
<span role="status" className="text-[12px] text-ink-2">{POST_JOB_STATUS[job.status]}</span>
|
|
</div>
|
|
{job.status !== "CANCELLED" && job.status !== "FAILED" && <div className="flex items-center gap-3">
|
|
<progress className="h-2 w-full flex-1 min-w-0 appearance-none overflow-hidden rounded-full bg-line [&::-webkit-progress-bar]:bg-line [&::-webkit-progress-value]:bg-blue [&::-moz-progress-bar]:bg-blue" value={postJobProgress(job)} max={100} aria-label={`ความคืบหน้าของ ${job.topic}`} aria-valuetext={`${postJobProgress(job)}% · ${POST_JOB_STAGE[job.stage] || POST_JOB_STATUS[job.status]}`} />
|
|
<span className="text-[12px] font-semibold num text-ink-2">{postJobProgress(job)}%</span>
|
|
</div>}
|
|
{job.status === "RUNNING" && <p role="status" className="text-[12px] text-ink-2">{POST_JOB_STAGE[job.stage] || "กำลังทำงาน"}</p>}
|
|
{job.error && <p className="text-[12px] text-danger-ink">{job.error}</p>}
|
|
{job.status === "COMPLETED" && <div className="flex flex-wrap items-center gap-3">
|
|
{job.postId ? <Link href={`/posts/${job.postId}`} className="underline text-[13px] font-medium">เปิดฉบับร่าง</Link> : <span className="text-[12px]">ฉบับร่างถูกลบแล้ว</span>}
|
|
<span className="text-[12px] text-ink-2">รวมเวลารอคิว {duration(job)}</span>
|
|
</div>}
|
|
{job.status === "QUEUED" && <button type="button" className="btn btn-ghost btn-sm self-start" disabled={cancelling === job.id} onClick={() => cancel(job.id)}>{cancelling === job.id ? "กำลังยกเลิก…" : "ยกเลิกคิวนี้"}</button>}
|
|
</li>)}
|
|
</ul>
|
|
</>}
|
|
</section>
|
|
);
|
|
}
|