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