|
|
|
@@ -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); }
|
|
|
|
|
}
|
|
|
|
|
}
|