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
+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"