Add scheduled automatic content drafts with Codex and image automation

This commit is contained in:
chaloemphong
2026-11-25 21:11:38 +07:00
parent 55235718c3
commit dd42b81639
13 changed files with 444 additions and 1 deletions
+61
View File
@@ -0,0 +1,61 @@
import { NextResponse } from "next/server";
import * as z from "zod/v4";
import { prisma } from "@/lib/db";
import { actorLabel, requirePageAction } from "@/lib/auth/user";
import { audit } from "@/lib/audit";
import { errorResponse, readJson, str } from "@/lib/http";
import { UserFacingError } from "@/lib/facebook/client";
import { AUTOMATION_SELECT } from "@/lib/ai/content-automation";
import { nextContentRun } from "@/lib/ai/auto-schedule";
const Input = z.object({
enabled: z.boolean(),
weekdays: z.array(z.number().int().min(0).max(6)).min(1).max(7),
times: z.array(z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/)).min(1).max(3),
brief: z.string().trim().max(1000),
targets: z.array(z.enum(["FACEBOOK", "INSTAGRAM"])).min(1).max(2),
});
export async function GET(req: Request) {
const pageId = new URL(req.url).searchParams.get("pageId") || "";
const auth = await requirePageAction(pageId, "editPost");
if (!auth.ok) return auth.response;
try {
const automation = await prisma.pageContentAutomation.findUnique({ where: { pageId }, select: AUTOMATION_SELECT });
return NextResponse.json({ automation }, { headers: { "Cache-Control": "no-store" } });
} catch (error) { return errorResponse(error, "content-auto:read"); }
}
export async function PUT(req: Request) {
const body = await readJson(req);
const pageId = str(body.pageId);
const auth = await requirePageAction(pageId, "editPost");
if (!auth.ok) return auth.response;
try {
const parsed = Input.safeParse(body);
if (!parsed.success) throw new UserFacingError("เลือกวัน เวลาไม่เกิน 3 ช่วง และช่องทางให้ครบ แนวเนื้อหาไม่เกิน 1,000 ตัวอักษร");
const input = { ...parsed.data, weekdays: [...new Set(parsed.data.weekdays)].sort(), times: [...new Set(parsed.data.times)].sort(), targets: [...new Set(parsed.data.targets)] };
const automation = await prisma.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai-post:${pageId}`}))`;
const page = await tx.page.findUnique({ where: { id: pageId }, select: { status: true, igUserId: true, profile: { select: { business: true } } } });
if (!page) throw new UserFacingError("ไม่พบเพจ");
if (input.enabled) {
if (page.status !== "ACTIVE") throw new UserFacingError("เพจต้องพร้อมใช้งานก่อนเปิด auto");
if (!page.profile?.business.trim()) throw new UserFacingError("ตั้งค่าโปรไฟล์ร้านก่อนเปิด auto");
if (input.targets.includes("INSTAGRAM") && !page.igUserId) throw new UserFacingError("เพจนี้ยังไม่ได้ผูก Instagram");
}
const data = { ...input, requestedById: auth.user.id, nextRunAt: input.enabled ? nextContentRun(input.weekdays, input.times) : null, lastError: null };
const saved = await tx.pageContentAutomation.upsert({ where: { pageId }, create: { pageId, ...data }, update: data, select: AUTOMATION_SELECT });
if (!input.enabled) {
const queued = await tx.postGenerationJob.findMany({ where: { pageId, status: "QUEUED", requestKey: { startsWith: "auto:" } }, select: { id: true } });
for (const job of queued) {
const changed = await tx.postGenerationJob.updateMany({ where: { id: job.id, status: "QUEUED" }, data: { status: "CANCELLED", finishedAt: new Date() } });
if (changed.count) await audit({ action: "AI_POST_CANCELLED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, detail: { jobId: job.id, source: "auto-disabled" } }, tx);
}
}
await audit({ action: input.enabled ? "CONTENT_AUTO_ENABLED" : "CONTENT_AUTO_DISABLED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, detail: { weekdays: input.weekdays, times: input.times, targets: input.targets } }, tx);
return saved;
});
return NextResponse.json({ automation });
} catch (error) { return errorResponse(error, "content-auto:save"); }
}
@@ -2,6 +2,7 @@ import { timingSafeEqual } from "node:crypto";
import { NextResponse } from "next/server";
import { appUrl } from "@/lib/base-path";
import { processNextPostJob } from "@/lib/ai/post-queue";
import { enqueueDueContent } from "@/lib/ai/content-automation";
export const runtime = "nodejs";
export const maxDuration = 900;
@@ -12,5 +13,6 @@ export async function POST(req: Request) {
const expected = Buffer.from(`Bearer ${secret || ""}`);
const provided = Buffer.from(req.headers.get("authorization") || "");
if (!secret || secret.length < 32 || expected.length !== provided.length || !timingSafeEqual(expected, provided)) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
await enqueueDueContent();
return NextResponse.json(await processNextPostJob(appUrl(new URL(req.url).origin)));
}
+84
View File
@@ -0,0 +1,84 @@
"use client";
import { useEffect, useState } from "react";
import { withBase } from "@/lib/base-path";
import { Notice } from "./ui";
type Settings = {
enabled: boolean; weekdays: number[]; times: string[]; brief: string;
targets: ("FACEBOOK" | "INSTAGRAM")[];
nextRunAt: string | null; lastQueuedAt: string | null; lastError: string | null;
};
const DAYS = ["อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส."];
const formatTime = (value: string) => new Date(value).toLocaleString("th-TH", { timeZone: "Asia/Bangkok", dateStyle: "medium", timeStyle: "short" });
export function ContentAutoForm({ pageId }: { pageId: string }) {
const [settings, setSettings] = useState<Settings>({ enabled: false, weekdays: [1, 2, 3, 4, 5], times: ["09:00"], brief: "", targets: ["FACEBOOK"], nextRunAt: null, lastQueuedAt: null, lastError: null });
const [loaded, setLoaded] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [message, setMessage] = useState("");
useEffect(() => {
const controller = new AbortController();
void (async () => {
try {
const response = await fetch(withBase(`/api/ai/content-auto?pageId=${encodeURIComponent(pageId)}`), { signal: controller.signal, cache: "no-store" });
const data = await response.json();
if (!response.ok) throw new Error(data.error || "โหลดการตั้งค่า auto ไม่สำเร็จ");
if (data.automation) setSettings(data.automation);
setLoaded(true);
} catch (failure) {
if (!controller.signal.aborted) setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้");
}
})();
return () => controller.abort();
}, [pageId]);
async function save() {
if (!loaded || busy) return;
setBusy(true); setError(""); setMessage("");
try {
const response = await fetch(withBase("/api/ai/content-auto"), { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, ...settings }) });
const data = await response.json();
if (!response.ok) throw new Error(data.error || "บันทึก auto ไม่สำเร็จ");
setSettings(data.automation);
setMessage(data.automation.enabled ? "บันทึกแล้ว จะสร้างฉบับร่างตามวันและเวลาที่เลือก" : "ปิด auto แล้ว งานที่เริ่มสร้างไปแล้วจะทำจนจบ");
} catch (failure) { setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้"); }
finally { setBusy(false); }
}
return <section className="border border-line rounded-xl p-4 flex flex-col gap-3 bg-paper" aria-label="สร้างเนื้อหาอัตโนมัติ">
<h3 className="font-semibold text-[15px]">โหมด auto สร้างเนื้อหา</h3>
<p className="text-[13px] text-ink-2">เลือกวันและเวลา ให้ AI คิดหัวข้อจากข้อมูลร้าน เขียนเนื้อหาและสร้างภาพ บันทึกเป็นฉบับร่างรออนุมัติ ปิดหน้าเว็บได้</p>
<fieldset disabled={!loaded || busy} className="flex flex-col gap-3">
<label className="flex items-center gap-2 text-[14px] font-medium">
<input type="checkbox" role="switch" checked={settings.enabled} onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })} /> เปิดสร้างอัตโนมัติสำหรับเพจนี้
</label>
<fieldset className="flex flex-wrap gap-3">
<legend className="text-[13px] mb-2">วันสร้างเนื้อหา (เวลาไทย)</legend>
{DAYS.map((label, day) => <label key={day} className="flex items-center gap-1.5 text-[13px] min-h-10">
<input type="checkbox" checked={settings.weekdays.includes(day)} onChange={(e) => setSettings({ ...settings, weekdays: e.target.checked ? [...settings.weekdays, day] : settings.weekdays.filter((d) => d !== day) })} />{label}
</label>)}
</fieldset>
<div className="flex flex-col gap-2">
{settings.times.map((time, index) => <div key={index} className="flex flex-wrap items-end gap-2">
<label className="field"><span>เวลาสร้างรอบที่ {index + 1}</span><input className="input" type="time" required value={time} onChange={(e) => setSettings({ ...settings, times: settings.times.map((t, i) => i === index ? e.target.value : t) })} /></label>
{settings.times.length > 1 && <button type="button" className="btn btn-ghost btn-sm" aria-label={`ลบเวลารอบที่ ${index + 1}`} onClick={() => setSettings({ ...settings, times: settings.times.filter((_, i) => i !== index) })}>ลบเวลา</button>}
</div>)}
{settings.times.length < 3 && <button type="button" className="btn btn-ghost btn-sm self-start" onClick={() => setSettings({ ...settings, times: [...settings.times, "12:00"] })}>เพิ่มเวลา (สูงสุด 3 รอบต่อวัน)</button>}
</div>
<label className="field"><span>แนวเนื้อหา (เว้นว่างให้ AI เลือกจากข้อมูลร้าน)</span><textarea className="textarea" rows={2} maxLength={1000} value={settings.brief} onChange={(e) => setSettings({ ...settings, brief: e.target.value })} placeholder="เช่น สลับแนะนำสินค้า เคล็ดลับ และเรื่องราวของร้าน" /></label>
<fieldset className="flex flex-wrap gap-3 text-[13px]">
<legend className="mb-2">ช่องทางของฉบับร่าง auto</legend>
{(["FACEBOOK", "INSTAGRAM"] as const).map((target) => <label key={target} className="flex items-center gap-1.5 min-h-10"><input type="checkbox" checked={settings.targets.includes(target)} onChange={(e) => setSettings({ ...settings, targets: e.target.checked ? [...settings.targets, target] : settings.targets.filter((t) => t !== target) })} />{target === "FACEBOOK" ? "Facebook" : "Instagram"}</label>)}
</fieldset>
<button type="button" className="btn btn-primary btn-sm self-start" onClick={save}>{busy ? "กำลังบันทึก…" : "บันทึกโหมด auto"}</button>
</fieldset>
{settings.enabled && settings.nextRunAt && <p className="text-[12px] text-ink-2">รอบถัดไป: {formatTime(settings.nextRunAt)} · เวลาเริ่มเข้าคิว ไม่ใช่เวลาเผยแพร่</p>}
{settings.lastQueuedAt && <p className="text-[12px] text-ink-2">เข้าคิวล่าสุด: {formatTime(settings.lastQueuedAt)} · ดูผลในงานล่าสุดด้านล่าง</p>}
<p className="text-[12px] text-ink-2">ต้องเปิด worker และ login บัญชีสร้างภาพไว้ งานเริ่มตามคิว หาก worker หยุดจะรับเพียงรอบล่าสุดเมื่อกลับมา</p>
{settings.lastError && <Notice tone="red">{settings.lastError}</Notice>}
{error && <Notice tone="red">{error}</Notice>}
{message && <p role="status" className="text-[13px] text-ink-2">{message}</p>}
</section>;
}
+2
View File
@@ -6,6 +6,7 @@ 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 "";
@@ -81,6 +82,7 @@ export function PostGenerationQueue({ pageId, targets, plannedDay, initialTopic
return (
<section aria-label="คิวสร้างโพสต์ด้วย AI" className="border border-line rounded-xl p-4 flex flex-col gap-3 bg-board">
<ContentAutoForm key={pageId} pageId={pageId} />
<h3 className="font-semibold text-[15px]">สร้างทั้งโพสต์ด้วย AI</h3>
<p className="text-[13px] text-ink-2">ให้ Codex เขียนเนื้อหาและ ChatGPT สร้างภาพ แล้วบันทึกเป็นฉบับร่างรอคุณตรวจ ปิดหน้านี้แล้วกลับมาดูคิวได้</p>
<label className="field">
+15
View File
@@ -0,0 +1,15 @@
/** Weekly slots in Asia/Bangkok (UTC+7, no daylight saving), strictly after now. */
export function nextContentRun(weekdays: number[], times: string[], now = new Date()): Date {
const offset = 7 * 60 * 60_000;
const local = new Date(now.getTime() + offset);
for (let day = 0; day <= 7; day++) {
const midnight = Date.UTC(local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate() + day);
if (!weekdays.includes(new Date(midnight).getUTCDay())) continue;
for (const time of [...times].sort()) {
const [hours, minutes] = time.split(":").map(Number);
const candidate = new Date(midnight + (hours * 60 + minutes) * 60_000 - offset);
if (candidate > now) return candidate;
}
}
throw new Error("No valid weekly content slot");
}
+65
View File
@@ -0,0 +1,65 @@
import { prisma } from "@/lib/db";
import { audit, SYSTEM_ACTOR } from "@/lib/audit";
import { roleAtLeast } from "@/lib/auth/roles";
import { IMAGE_DAILY_LIMIT_PER_PAGE } from "./image";
import { nextContentRun } from "./auto-schedule";
export const AUTOMATION_SELECT = {
enabled: true, weekdays: true, times: true, brief: true, targets: true,
nextRunAt: true, lastQueuedAt: true, lastError: true,
} as const;
/** The queue worker calls this even when no browser is viewing the page. */
export async function enqueueDueContent() {
const now = new Date();
const due = await prisma.pageContentAutomation.findMany({
where: { enabled: true, nextRunAt: { lte: now } }, select: { pageId: true },
orderBy: { nextRunAt: "asc" }, take: 50,
});
for (const { pageId } of due) {
try {
await prisma.$transaction(async (tx) => {
// Same mutex as manual enqueue and settings changes: quota and disable are atomic.
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai-post:${pageId}`}))`;
const config = await tx.pageContentAutomation.findUnique({ where: { pageId } });
if (!config?.enabled || !config.nextRunAt || config.nextRunAt > now) return;
const page = await tx.page.findUnique({ where: { id: pageId }, select: {
status: true, igUserId: true, teamPage: { select: { teamId: true } },
profile: { select: { business: true, audience: true, tone: true, visualStyle: true, website: true, avoid: true, cta: true } },
} });
const user = await tx.user.findUnique({ where: { id: config.requestedById }, select: { isActive: true, globalRole: true } });
const member = await tx.pageMember.findUnique({ where: { userId_pageId: { userId: config.requestedById, pageId } }, select: { role: true } });
const teamMember = page?.teamPage ? await tx.teamMember.findUnique({ where: { teamId_userId: { teamId: page.teamPage.teamId, userId: config.requestedById } }, select: { id: true } }) : null;
let problem = "";
if (!user?.isActive || (user.globalRole !== "SUPERADMIN" && (!roleAtLeast(member?.role, "EDITOR") || (page?.teamPage && !teamMember)))) problem = "ผู้เปิดโหมด auto ไม่มีสิทธิ์สร้างโพสต์แล้ว เปิดใหม่ด้วยผู้มีสิทธิ์";
else if (!page || page.status !== "ACTIVE") problem = "เพจไม่พร้อมใช้งาน เชื่อมเพจให้พร้อมแล้วเปิด auto ใหม่";
else if (!page.profile?.business.trim()) problem = "ตั้งค่าโปรไฟล์ร้านแล้วเปิด auto ใหม่";
else if (config.targets.includes("INSTAGRAM") && !page.igUserId) problem = "เพจไม่ได้ผูก Instagram แล้ว เลือกช่องทางและเปิด auto ใหม่";
if (problem) {
await tx.pageContentAutomation.update({ where: { pageId }, data: { enabled: false, nextRunAt: null, lastError: problem } });
await audit({ action: "CONTENT_AUTO_PAUSED", actorLabel: SYSTEM_ACTOR, pageId, detail: { reason: problem } }, tx);
return;
}
const pending = await tx.postGenerationJob.count({ where: { pageId, status: { in: ["QUEUED", "RUNNING"] } } });
const used = await tx.aiUsage.count({ where: { pageId, kind: "image", createdAt: { gte: new Date(now.getTime() - 24 * 60 * 60_000) } } });
// Missed or blocked slots are skipped, never backfilled into a burst of image requests.
const nextRunAt = nextContentRun(config.weekdays, config.times, now);
if (pending >= 5 || used + pending >= IMAGE_DAILY_LIMIT_PER_PAGE) {
const reason = pending >= 5 ? "ข้ามรอบนี้เพราะคิวเต็ม 5 งาน" : "ข้ามรอบนี้เพราะโควตาภาพเต็ม";
await tx.pageContentAutomation.update({ where: { pageId }, data: { nextRunAt, lastError: reason } });
await audit({ action: "CONTENT_AUTO_SKIPPED", actorLabel: SYSTEM_ACTOR, pageId, detail: { reason } }, tx);
return;
}
const recent = await tx.post.findMany({ where: { pageId }, orderBy: { createdAt: "desc" }, take: 10, select: { title: true } });
const topic = `สร้างเนื้อหาอัตโนมัติ\nแนวเนื้อหา: ${config.brief || "เลือกจากข้อมูลร้าน"}\nหัวข้อล่าสุดที่ควรเลี่ยงซ้ำ:\n${recent.map((p) => p.title).join("\n")}`;
const job = await tx.postGenerationJob.create({ data: {
pageId, requestedById: config.requestedById,
requestKey: `auto:${config.id}:${config.nextRunAt.toISOString()}`,
topic, targets: config.targets, profileSnapshot: page!.profile!,
} });
await tx.pageContentAutomation.update({ where: { pageId }, data: { nextRunAt, lastQueuedAt: now, lastError: null } });
await audit({ action: "AI_POST_QUEUED", actorId: config.requestedById, actorLabel: SYSTEM_ACTOR, pageId, detail: { jobId: job.id, source: "auto", slot: config.nextRunAt.toISOString() } }, tx);
});
} catch (error) { console.error("[content-auto] enqueue failed", pageId, error); }
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ export async function processNextPostJob(baseUrl: string) {
const logoPalette = await logoPalettePrompt(page.pictureUrl);
const content = await generateStructured({
kind: "post-generation", pageId: job.pageId, userId: job.requestedById,
system: SYSTEM, effort: "medium", schema: Draft, waitForWorker: true,
system: SYSTEM + (job.requestKey.startsWith("auto:") ? "\nThis is an automatic content slot. Choose a fresh, relevant topic from the shop profile and brief data. Avoid repeating the supplied recent topics. Never invent prices, promotions, availability or claims. The slot is creation time, not a publication promise." : ""), effort: "medium", schema: Draft, waitForWorker: true,
prompt: `${profilePrompt(profile)}\n${logoPalette}\n\n${platformRule(job.targets.includes("INSTAGRAM"))}\n\n<topic>\n${job.topic}\n</topic>`,
});
if (job.targets.includes("INSTAGRAM") && content.caption.length > 2200) throw new UserFacingError("Caption ที่ AI สร้างยาวเกินข้อจำกัด Instagram กรุณาลองใหม่");
+4
View File
@@ -37,6 +37,10 @@ export type AuditAction =
| "AI_POST_COMPLETED"
| "AI_POST_FAILED"
| "AI_POST_CANCELLED"
| "CONTENT_AUTO_ENABLED"
| "CONTENT_AUTO_DISABLED"
| "CONTENT_AUTO_PAUSED"
| "CONTENT_AUTO_SKIPPED"
| "RULE_SAVED"
| "RULE_DELETED"
| "USER_CREATED"