Add review window and manual content generation

This commit is contained in:
Loma Bot Ops
2026-11-27 13:34:41 +07:00
parent 9d5bfe7d9d
commit 8086197f58
16 changed files with 357 additions and 62 deletions
+12 -1
View File
@@ -5,7 +5,7 @@ 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 { AUTOMATION_SELECT, enqueueContentNow } from "@/lib/ai/content-automation";
import { nextContentRun } from "@/lib/ai/auto-schedule";
const Input = z.object({
@@ -69,3 +69,14 @@ export async function PUT(req: Request) {
return NextResponse.json({ automation });
} catch (error) { return errorResponse(error, "content-auto:save"); }
}
export async function POST(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 result = await enqueueContentNow(pageId, auth.user.id, actorLabel(auth.user));
return NextResponse.json(result, { status: 202 });
} catch (error) { return errorResponse(error, "content-auto:run-now"); }
}
+2 -1
View File
@@ -2,7 +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";
import { enqueueDueContent, placeDueAutomaticDrafts } from "@/lib/ai/content-automation";
export const runtime = "nodejs";
export const maxDuration = 900;
@@ -14,5 +14,6 @@ export async function POST(req: Request) {
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();
await placeDueAutomaticDrafts();
return NextResponse.json(await processNextPostJob(appUrl(new URL(req.url).origin)));
}
+26 -9
View File
@@ -17,7 +17,7 @@ const DEFAULT_SETTINGS: Settings = { enabled: false, scheduleMode: "FIXED", week
export function ContentAutoForm({ pageId }: { pageId: string }) {
const [settings, setSettings] = useState<Settings>(DEFAULT_SETTINGS);
const [loaded, setLoaded] = useState(false);
const [busy, setBusy] = useState(false);
const [busy, setBusy] = useState<"save" | "run" | null>(null);
const [error, setError] = useState("");
const [message, setMessage] = useState("");
useEffect(() => {
@@ -43,21 +43,34 @@ export function ContentAutoForm({ pageId }: { pageId: string }) {
if (!loaded || busy) return;
if (mixTotal !== 100) { setError(`สัดส่วนเนื้อหารวม ${mixTotal}% ต้องปรับให้ครบ 100%`); return; }
if (settings.weekdays.length === 0 || settings.targets.length === 0) { setError("เลือกวันและช่องทางอย่างน้อย 1 รายการ"); return; }
setBusy(true); setError(""); setMessage("");
setBusy("save"); 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 แล้ว งานที่เริ่มสร้างไปแล้วจะทำจนจบ");
setMessage(data.automation.enabled ? "บันทึกแล้ว ระบบจะสร้างร่างเวลา 03:00 ล่วงหน้า 1 วัน และนำขึ้นตารางเวลา 08:00" : "ปิด auto แล้ว งานที่เริ่มสร้างไปแล้วจะทำจนจบ");
} catch (failure) { setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้"); }
finally { setBusy(false); }
finally { setBusy(null); }
}
async function runNow() {
if (!loaded || busy || !settings.enabled) return;
setBusy("run"); setError(""); setMessage("");
try {
const response = await fetch(withBase("/api/ai/content-auto"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId }) });
const data = await response.json();
if (!response.ok) throw new Error(data.error || "สร้างเนื้อหาตอนนี้ไม่สำเร็จ");
setSettings((current) => ({ ...current, lastQueuedAt: new Date().toISOString() }));
setMessage(`เข้าคิวสร้างเนื้อหาแล้ว ${data.queued} งาน ดูความคืบหน้าได้ในงานล่าสุดด้านล่าง`);
} catch (failure) { setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้"); }
finally { setBusy(null); }
}
return <section className="flex flex-col gap-4" aria-label="วางเนื้อหาอัตโนมัติ">
<div><h3 className="font-semibold text-[18px]">วางเนื้อหาอัตโนมัติ</h3><p className="text-[13px] text-ink-2 mt-1">AI จะสร้างโพสต์เป็นฉบับร่างตามแผน ทุกชิ้นยังต้องผ่านการอนุมัติก่อนเผยแพร่</p></div>
<div><h3 className="font-semibold text-[18px]">วางเนื้อหาอัตโนมัติ</h3><p className="text-[13px] text-ink-2 mt-1">ระบบสร้างฉบับร่างเวลา 03:00 ล่วงหน้า 1 วัน เพื่อให้ตรวจเนื้อหาก่อน และนำขึ้นตารางเวลา 08:00 โดยทุกชิ้นยังต้องผ่านการอนุมัติก่อนเผยแพร่</p></div>
<form onSubmit={save} noValidate className="flex flex-col gap-5">
<fieldset disabled={!loaded || busy} className="contents">
<fieldset disabled={!loaded || busy !== null} className="contents">
<label className="flex items-start gap-3 rounded-xl border border-line bg-blue-soft p-3 text-[14px] font-medium cursor-pointer">
<input className="mt-0.5" type="checkbox" checked={settings.enabled} onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })} />
<span><b className="block">เปิดใช้สำหรับเพจนี้</b><span className="text-[12px] text-ink-2 font-normal">ระบบทำงานตามแผนได้แม้ปิดหน้าเว็บ</span></span>
@@ -67,7 +80,7 @@ export function ContentAutoForm({ pageId }: { pageId: string }) {
{DAYS.map((label, day) => <label key={day} className={`min-h-10 rounded-lg border grid place-items-center text-[13px] cursor-pointer ${settings.weekdays.includes(day) ? "border-blue bg-blue-soft text-blue-ink font-semibold" : "border-line bg-paper text-ink-2"}`}><input className="sr-only" 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>)}
</div></fieldset>
<fieldset><legend className="font-semibold text-[14px] mb-2">2. กำหนดเวลา</legend><div className="grid sm:grid-cols-2 gap-2">
<fieldset><legend className="font-semibold text-[14px] mb-2">2. กำหนดเวลาเผยแพร่ตามแผน</legend><p className="text-[12px] text-ink-2 mb-2">เวลานี้ใช้วางโพสต์บนตารางของวันถัดไป ไม่ใช่เวลาสร้างฉบับร่าง</p><div className="grid sm:grid-cols-2 gap-2">
{(["FIXED", "RANDOM"] as const).map((mode) => <label key={mode} className={`rounded-xl border p-3 flex gap-2 cursor-pointer ${settings.scheduleMode === mode ? "border-blue bg-blue-soft" : "border-line"}`}><input type="radio" name="scheduleMode" value={mode} checked={settings.scheduleMode === mode} onChange={() => setSettings({ ...settings, scheduleMode: mode })} /><span><b className="block text-[13px]">{mode === "FIXED" ? "ระบุเวลาเอง" : "สุ่มเวลา"}</b><span className="text-[12px] text-ink-2">{mode === "FIXED" ? "เลือกเวลาแต่ละรอบได้ตรง ๆ" : "สุ่มช่วง 08:00–20:00 น."}</span></span></label>)}
</div></fieldset>
@@ -82,10 +95,14 @@ export function ContentAutoForm({ pageId }: { pageId: string }) {
<label className="field"><span>คำแนะนำเพิ่มเติม (ไม่บังคับ)</span><textarea className="textarea" rows={2} value={settings.brief} onChange={(e) => setSettings({ ...settings, brief: e.target.value })} placeholder="เช่น เน้นสินค้ากลุ่มใหม่ ใช้น้ำเสียงเป็นกันเอง" /></label>
<fieldset className="text-[13px]"><legend className="font-semibold text-[14px] mb-2">4. ช่องทางของฉบับร่าง</legend><div className="flex flex-wrap gap-4">{(["FACEBOOK", "INSTAGRAM"] as const).map((target) => <label key={target} className="flex items-center gap-2 min-h-10 cursor-pointer"><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>)}</div></fieldset>
<button type="submit" className="btn btn-primary self-start" disabled={!loaded || busy}>{busy ? "กำลังบันทึก…" : "บันทึกแผนอัตโนมัติ"}</button>
<div className="flex flex-wrap gap-2">
<button type="submit" className="btn btn-primary" disabled={!loaded || busy !== null}>{busy === "save" ? "กำลังบันทึก…" : "บันทึกแผนอัตโนมัติ"}</button>
<button type="button" className="btn btn-ghost" disabled={!loaded || busy !== null || !settings.enabled} onClick={runNow}>{busy === "run" ? "กำลังเข้าคิว…" : "สร้างเนื้อหาตอนนี้"}</button>
</div>
<p className="text-[12px] text-ink-2 -mt-3">ปุ่มสร้างตอนนี้ใช้ค่าที่บันทึกล่าสุด เหมาะสำหรับทดสอบโดยไม่ต้องรอเวลา 03:00</p>
</fieldset>
</form>
{settings.enabled && settings.nextRunAt && <p className="text-[12px] text-ink-2">รอบถัดไป: {formatTime(settings.nextRunAt)} · เวลาเริ่มเข้าคิว ไม่ใช่เวลาเผยแพร่</p>}
{settings.enabled && settings.nextRunAt && <p className="text-[12px] text-ink-2">สร้างร่างรอบถัดไป: {formatTime(settings.nextRunAt)} · ร่างจะขึ้นตารางตั้งแต่ 08:00 ของวันเดียวกัน</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>}
+20 -6
View File
@@ -11,6 +11,19 @@ import { IMAGE_PROMPT_MAX, IMAGE_SIZES, type ImageSizeKey } from "@/lib/ai/image
type OverlayPos = "top" | "center" | "bottom";
let sarabunFontPromise: Promise<FontFace> | null = null;
function loadSarabunFont() {
if (!sarabunFontPromise) {
const font = new FontFace("Sarabun", `url(${withBase("/fonts/sarabun/Sarabun-Bold.ttf")})`, { weight: "700" });
sarabunFontPromise = font.load().then((loaded) => {
document.fonts.add(loaded);
return loaded;
});
}
return sarabunFontPromise;
}
function wrapText(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string[] {
const lines: string[] = [];
const paragraphs = text.split("\n");
@@ -34,7 +47,8 @@ function wrapText(ctx: CanvasRenderingContext2D, text: string, maxWidth: number)
function buildComposite(imgUrl: string, text: string, pos: OverlayPos): Promise<string> {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
img.onload = async () => {
try { await loadSarabunFont(); } catch { /* Canvas will use the Thai fallback font. */ }
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
@@ -57,15 +71,15 @@ function buildComposite(imgUrl: string, text: string, pos: OverlayPos): Promise<
const grad = ctx.createLinearGradient(0, zoneY, 0, zoneY + zoneH);
if (pos === "top") {
grad.addColorStop(0, "rgba(0,0,0,0.75)");
grad.addColorStop(0, "rgba(0,0,0,0.48)");
grad.addColorStop(1, "rgba(0,0,0,0)");
} else if (pos === "bottom") {
grad.addColorStop(0, "rgba(0,0,0,0)");
grad.addColorStop(1, "rgba(0,0,0,0.75)");
grad.addColorStop(1, "rgba(0,0,0,0.48)");
} else {
grad.addColorStop(0, "rgba(0,0,0,0)");
grad.addColorStop(0.15, "rgba(0,0,0,0.65)");
grad.addColorStop(0.85, "rgba(0,0,0,0.65)");
grad.addColorStop(0.15, "rgba(0,0,0,0.42)");
grad.addColorStop(0.85, "rgba(0,0,0,0.42)");
grad.addColorStop(1, "rgba(0,0,0,0)");
}
ctx.fillStyle = grad;
@@ -73,7 +87,7 @@ function buildComposite(imgUrl: string, text: string, pos: OverlayPos): Promise<
ctx.fillStyle = "#ffffff";
ctx.textAlign = "center";
ctx.shadowColor = "rgba(0,0,0,0.55)";
ctx.shadowColor = "rgba(0,0,0,0.35)";
ctx.shadowBlur = fontSize * 0.28;
ctx.shadowOffsetY = 2;
+31 -15
View File
@@ -6,6 +6,10 @@ type Schedule = {
seed?: string;
};
const BANGKOK_OFFSET = 7 * 60 * 60_000;
const DRAFT_HOUR = 3;
const BOARD_HOUR = 8;
function seededMinutes(seed: string, count: number): number[] {
let state = 2166136261;
for (const char of seed) state = Math.imul(state ^ char.charCodeAt(0), 16777619) >>> 0;
@@ -19,24 +23,36 @@ function seededMinutes(seed: string, count: number): number[] {
}
/** Weekly slots in Asia/Bangkok (UTC+7, no daylight saving), strictly after now. */
export function contentSlotsForBangkokDay(schedule: Schedule, localDay: Date): Date[] {
const { times, mode = "FIXED", randomPostsPerDay = 1, seed = "content-auto" } = schedule;
const dateKey = localDay.toISOString().slice(0, 10);
const minutesOfDay = mode === "RANDOM"
? seededMinutes(`${seed}:${dateKey}`, Math.min(3, Math.max(1, randomPostsPerDay)))
: [...times].sort().map((time) => {
const [hours, minutes] = time.split(":").map(Number);
return hours * 60 + minutes;
});
const midnight = Date.UTC(localDay.getUTCFullYear(), localDay.getUTCMonth(), localDay.getUTCDate());
return minutesOfDay.map((minutes) => new Date(midnight + minutes * 60_000 - BANGKOK_OFFSET));
}
/** Next 03:00 draft run in Bangkok, one day before a selected publication day. */
export function nextContentRun(schedule: Schedule, now = new Date()): Date {
const { weekdays, times, mode = "FIXED", randomPostsPerDay = 1, seed = "content-auto" } = schedule;
const offset = 7 * 60 * 60_000;
const local = new Date(now.getTime() + offset);
const { weekdays } = schedule;
const local = new Date(now.getTime() + BANGKOK_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;
const dateKey = new Date(midnight).toISOString().slice(0, 10);
const minutesOfDay = mode === "RANDOM"
? seededMinutes(`${seed}:${dateKey}`, Math.min(3, Math.max(1, randomPostsPerDay)))
: [...times].sort().map((time) => {
const [hours, minutes] = time.split(":").map(Number);
return hours * 60 + minutes;
});
for (const minutes of minutesOfDay) {
const candidate = new Date(midnight + minutes * 60_000 - offset);
if (candidate > now) return candidate;
}
const publicationDay = new Date(midnight + 24 * 60 * 60_000).getUTCDay();
if (!weekdays.includes(publicationDay)) continue;
const candidate = new Date(midnight + DRAFT_HOUR * 60 * 60_000 - BANGKOK_OFFSET);
if (candidate > now) return candidate;
}
throw new Error("No valid weekly content slot");
}
export function automaticRunWindow(draftRunAt: Date, schedule: Schedule) {
const localDraftDay = new Date(draftRunAt.getTime() + BANGKOK_OFFSET);
const publicationDay = new Date(Date.UTC(localDraftDay.getUTCFullYear(), localDraftDay.getUTCMonth(), localDraftDay.getUTCDate() + 1));
const placeOnBoardAt = new Date(Date.UTC(localDraftDay.getUTCFullYear(), localDraftDay.getUTCMonth(), localDraftDay.getUTCDate(), BOARD_HOUR) - BANGKOK_OFFSET);
return { publicationSlots: contentSlotsForBangkokDay(schedule, publicationDay), placeOnBoardAt };
}
+95 -10
View File
@@ -2,7 +2,8 @@ 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";
import { automaticRunWindow, nextContentRun } from "./auto-schedule";
import { UserFacingError } from "@/lib/facebook/client";
export const AUTOMATION_SELECT = {
enabled: true, scheduleMode: true, weekdays: true, times: true, randomPostsPerDay: true,
@@ -33,6 +34,18 @@ export async function enqueueDueContent() {
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 runHourInBangkok = new Date(config.nextRunAt.getTime() + 7 * 60 * 60_000).getUTCHours();
// Plans saved before the review-window migration used the publication
// slot as nextRunAt. Rebase them once instead of generating for the
// wrong day during deployment.
if (runHourInBangkok !== 3) {
const nextRunAt = nextContentRun({
weekdays: config.weekdays, times: config.times, mode: config.scheduleMode,
randomPostsPerDay: config.randomPostsPerDay, seed: pageId,
}, now);
await tx.pageContentAutomation.update({ where: { pageId }, data: { nextRunAt } });
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 } },
@@ -57,23 +70,95 @@ export async function enqueueDueContent() {
weekdays: config.weekdays, times: config.times, mode: config.scheduleMode,
randomPostsPerDay: config.randomPostsPerDay, seed: pageId,
}, now);
if (pending >= 5 || used + pending >= IMAGE_DAILY_LIMIT_PER_PAGE) {
const runAt = config.nextRunAt;
const { publicationSlots, placeOnBoardAt } = automaticRunWindow(runAt, {
weekdays: config.weekdays, times: config.times, mode: config.scheduleMode,
randomPostsPerDay: config.randomPostsPerDay, seed: pageId,
});
const available = Math.max(0, Math.min(5 - pending, IMAGE_DAILY_LIMIT_PER_PAGE - used - pending));
if (available === 0) {
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 contentType = selectContentType(config, `${pageId}:${config.nextRunAt.toISOString()}`);
const topic = `สร้างเนื้อหาอัตโนมัติ\nประเภทเนื้อหา: ${contentType}\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!,
} });
for (const [index, plannedAt] of publicationSlots.slice(0, available).entries()) {
const contentType = selectContentType(config, `${pageId}:${runAt.toISOString()}:${index}`);
const topic = `สร้างเนื้อหาอัตโนมัติ\nประเภทเนื้อหา: ${contentType}\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}:${runAt.toISOString()}:${index}`,
topic, targets: config.targets, plannedAt, placeOnBoardAt, profileSnapshot: page!.profile!,
} });
await audit({ action: "AI_POST_QUEUED", actorId: config.requestedById, actorLabel: SYSTEM_ACTOR, pageId, detail: { jobId: job.id, source: "auto", draftRunAt: runAt.toISOString(), plannedAt: plannedAt.toISOString(), placeOnBoardAt: placeOnBoardAt.toISOString(), contentType } }, tx);
}
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(), contentType } }, tx);
});
} catch (error) { console.error("[content-auto] enqueue failed", pageId, error); }
}
}
/** Queue the next configured publication day immediately for manual testing. */
export async function enqueueContentNow(pageId: string, requestedById: string, requestedByLabel: string) {
const now = new Date();
return prisma.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai-post:${pageId}`}))`;
const config = await tx.pageContentAutomation.findUnique({ where: { pageId } });
if (!config?.enabled) throw new UserFacingError("เปิดและบันทึกแผนอัตโนมัติก่อนสร้างเนื้อหาตอนนี้");
const page = await tx.page.findUnique({ where: { id: pageId }, select: {
status: true, igUserId: true,
profile: { select: { business: true, audience: true, tone: true, visualStyle: true, website: true, avoid: true, cta: true } },
} });
if (!page || page.status !== "ACTIVE") throw new UserFacingError("เพจไม่พร้อมใช้งาน");
if (!page.profile?.business.trim()) throw new UserFacingError("ตั้งค่าโปรไฟล์ร้านก่อนสร้างเนื้อหา");
if (config.targets.includes("INSTAGRAM") && !page.igUserId) throw new UserFacingError("เพจนี้ยังไม่ได้ผูก Instagram");
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) } } });
const available = Math.max(0, Math.min(5 - pending, IMAGE_DAILY_LIMIT_PER_PAGE - used - pending));
if (!available) throw new UserFacingError(pending >= 5 ? "คิวเต็ม 5 งาน รอให้งานเดิมเสร็จก่อน" : "โควตาสร้างภาพของเพจเต็มแล้ว");
const schedule = {
weekdays: config.weekdays, times: config.times, mode: config.scheduleMode,
randomPostsPerDay: config.randomPostsPerDay, seed: pageId,
};
const draftRunAt = nextContentRun(schedule, now);
const { publicationSlots, placeOnBoardAt } = automaticRunWindow(draftRunAt, schedule);
const recent = await tx.post.findMany({ where: { pageId }, orderBy: { createdAt: "desc" }, take: 10, select: { title: true } });
const runKey = now.toISOString();
let queued = 0;
for (const [index, plannedAt] of publicationSlots.slice(0, available).entries()) {
const contentType = selectContentType(config, `${pageId}:${runKey}:${index}`);
const topic = `สร้างเนื้อหาอัตโนมัติ\nประเภทเนื้อหา: ${contentType}\nแนวเนื้อหา: ${config.brief || "เลือกจากข้อมูลร้าน"}\nหัวข้อล่าสุดที่ควรเลี่ยงซ้ำ:\n${recent.map((p) => p.title).join("\n")}`;
const job = await tx.postGenerationJob.create({ data: {
pageId, requestedById, requestKey: `auto-now:${config.id}:${runKey}:${index}`,
topic, targets: config.targets, plannedAt, placeOnBoardAt, profileSnapshot: page.profile,
} });
await audit({ action: "AI_POST_QUEUED", actorId: requestedById, actorLabel: requestedByLabel, pageId, detail: { jobId: job.id, source: "auto-run-now", plannedAt: plannedAt.toISOString(), placeOnBoardAt: placeOnBoardAt.toISOString(), contentType } }, tx);
queued++;
}
await tx.pageContentAutomation.update({ where: { pageId }, data: { lastQueuedAt: now, lastError: null } });
await audit({ action: "CONTENT_AUTO_RUN_NOW", actorId: requestedById, actorLabel: requestedByLabel, pageId, detail: { queued, draftRunAt: draftRunAt.toISOString() } }, tx);
return { queued, plannedFor: publicationSlots[0] };
});
}
/** Put completed automatic drafts on the calendar from 08:00 on the review day. */
export async function placeDueAutomaticDrafts(now = new Date()) {
const due = await prisma.postGenerationJob.findMany({
where: { status: "COMPLETED", placeOnBoardAt: { lte: now }, boardPlacedAt: null },
select: { id: true, pageId: true, postId: true, plannedAt: true }, take: 100,
});
for (const job of due) {
if (!job.postId || !job.plannedAt) continue;
const postId = job.postId;
const plannedAt = job.plannedAt;
await prisma.$transaction(async (tx) => {
const claimed = await tx.postGenerationJob.updateMany({ where: { id: job.id, boardPlacedAt: null }, data: { boardPlacedAt: now } });
if (!claimed.count) return;
await tx.post.updateMany({ where: { id: postId, plannedAt: null }, data: { plannedAt } });
await audit({ action: "POST_PLANNED", actorLabel: SYSTEM_ACTOR, pageId: job.pageId, postId, detail: { plannedAt: plannedAt.toISOString(), source: "content-auto" } }, tx);
});
}
}
+4 -2
View File
@@ -115,15 +115,17 @@ This automatic slot is a Thai editorial AI-news article grounded only in <foreig
});
const { user } = await assertJobAccess(job.pageId, job.requestedById);
await prisma.$transaction(async (tx) => {
const boardIsDue = !job.placeOnBoardAt || job.placeOnBoardAt <= new Date();
const post = await tx.post.create({ data: {
pageId: job.pageId, title: content.title, caption: content.caption, imageBlobUrl: blob.url,
targets: job.targets, plannedAt: job.plannedAt, aiAssisted: true,
targets: job.targets, plannedAt: boardIsDue ? job.plannedAt : null, aiAssisted: true,
createdById: user.id, lastEditedById: user.id, lastEditedAt: new Date(),
} });
const changed = await tx.postGenerationJob.updateMany({ where: { id: job.id, status: "RUNNING" }, data: { status: "COMPLETED", stage: "completed", postId: post.id, finishedAt: new Date(), error: null } });
const changed = await tx.postGenerationJob.updateMany({ where: { id: job.id, status: "RUNNING" }, data: { status: "COMPLETED", stage: "completed", postId: post.id, boardPlacedAt: boardIsDue && job.placeOnBoardAt ? new Date() : null, finishedAt: new Date(), error: null } });
if (changed.count !== 1) throw new Error("Queue job no longer owns its execution");
await audit({ action: "POST_CREATED", actorId: user.id, actorLabel: actorLabel(user), pageId: job.pageId, postId: post.id, detail: { aiAssisted: true, jobId: job.id } }, tx);
await audit({ action: "AI_POST_COMPLETED", actorId: user.id, actorLabel: actorLabel(user), pageId: job.pageId, postId: post.id, detail: { jobId: job.id, ...(researchSources.length ? { researchSources } : {}) } }, tx);
if (boardIsDue && job.placeOnBoardAt && job.plannedAt) await audit({ action: "POST_PLANNED", actorLabel: SYSTEM_ACTOR, pageId: job.pageId, postId: post.id, detail: { plannedAt: job.plannedAt.toISOString(), source: "content-auto" } }, tx);
});
return { processed: true, jobId: job.id, status: "COMPLETED" };
} catch (error) {
+1
View File
@@ -41,6 +41,7 @@ export type AuditAction =
| "CONTENT_AUTO_DISABLED"
| "CONTENT_AUTO_PAUSED"
| "CONTENT_AUTO_SKIPPED"
| "CONTENT_AUTO_RUN_NOW"
| "RULE_SAVED"
| "RULE_DELETED"
| "INBOX_AI_ENABLED"