diff --git a/src/lib/ai/auto-schedule.ts b/src/lib/ai/auto-schedule.ts index cde6b1a..8259739 100644 --- a/src/lib/ai/auto-schedule.ts +++ b/src/lib/ai/auto-schedule.ts @@ -56,3 +56,15 @@ export function automaticRunWindow(draftRunAt: Date, schedule: Schedule) { const placeOnBoardAt = new Date(Date.UTC(localDraftDay.getUTCFullYear(), localDraftDay.getUTCMonth(), localDraftDay.getUTCDate(), BOARD_HOUR) - BANGKOK_OFFSET); return { publicationSlots: contentSlotsForBangkokDay(schedule, publicationDay), placeOnBoardAt }; } + +/** Future configured publication slots, used to place legacy auto drafts that predate plannedAt. */ +export function upcomingContentSlots(schedule: Schedule, now = new Date(), limit = 20): Date[] { + const localNow = new Date(now.getTime() + BANGKOK_OFFSET); + const slots: Date[] = []; + for (let day = 0; day <= 28 && slots.length < limit; day++) { + const localDay = new Date(Date.UTC(localNow.getUTCFullYear(), localNow.getUTCMonth(), localNow.getUTCDate() + day)); + if (!schedule.weekdays.includes(localDay.getUTCDay())) continue; + slots.push(...contentSlotsForBangkokDay(schedule, localDay).filter((slot) => slot.getTime() - now.getTime() >= 10 * 60_000)); + } + return slots.sort((a, b) => a.getTime() - b.getTime()).slice(0, limit); +} diff --git a/src/lib/ai/content-automation.ts b/src/lib/ai/content-automation.ts index e418e46..51b9776 100644 --- a/src/lib/ai/content-automation.ts +++ b/src/lib/ai/content-automation.ts @@ -2,7 +2,7 @@ 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 { automaticRunWindow, nextContentRun } from "./auto-schedule"; +import { automaticRunWindow, nextContentRun, upcomingContentSlots } from "./auto-schedule"; import { UserFacingError } from "@/lib/facebook/client"; import { scheduleTimeProblem } from "@/lib/facebook/posts"; import { scheduleAutomaticPost } from "@/lib/posts/workflow"; @@ -175,28 +175,59 @@ export async function schedulePendingAutomaticPosts(now = new Date()) { where: { status: "COMPLETED", postId: { not: null }, - plannedAt: { not: null }, OR: [{ requestKey: { startsWith: "auto:" } }, { requestKey: { startsWith: "auto-now:" } }], page: { contentAutomation: { enabled: true } }, post: { status: "DRAFT" }, }, - include: { post: true }, - orderBy: { plannedAt: "asc" }, + include: { post: true, page: { select: { contentAutomation: true } } }, + orderBy: { finishedAt: "asc" }, take: 20, }); + const occupied = await prisma.post.findMany({ + where: { pageId: { in: [...new Set(jobs.map((job) => job.pageId))] }, status: "SCHEDULED", scheduledPublishAt: { gt: now } }, + select: { pageId: true, scheduledPublishAt: true }, + }); + const occupiedByPage = new Map>(); + for (const post of occupied) { + if (!post.scheduledPublishAt) continue; + const times = occupiedByPage.get(post.pageId) ?? new Set(); + times.add(post.scheduledPublishAt.getTime()); + occupiedByPage.set(post.pageId, times); + } + const fallbackByPage = new Map(); let scheduled = 0; for (const job of jobs) { - if (!job.post || !job.plannedAt) continue; + if (!job.post) continue; + const config = job.page.contentAutomation; + if (!config) continue; + const occupiedTimes = occupiedByPage.get(job.pageId) ?? new Set(); + let publishAt = job.plannedAt; + if (!publishAt) { + let fallback = fallbackByPage.get(job.pageId); + if (!fallback) { + fallback = upcomingContentSlots({ + weekdays: config.weekdays, times: config.times, mode: config.scheduleMode, + randomPostsPerDay: config.randomPostsPerDay, seed: job.pageId, + }, now, 28).filter((slot) => !occupiedTimes.has(slot.getTime())); + fallbackByPage.set(job.pageId, fallback); + } + publishAt = fallback.shift() ?? null; + } + if (!publishAt) continue; const claimed = await prisma.$transaction(async (tx) => { const changed = await tx.post.updateMany({ where: { id: job.post!.id, status: "DRAFT" }, data: { status: "APPROVED" } }); if (!changed.count) return false; + await tx.postGenerationJob.update({ where: { id: job.id }, data: { plannedAt: publishAt, boardPlacedAt: now } }); await audit({ action: "POST_APPROVED", actorLabel: SYSTEM_ACTOR, pageId: job.pageId, postId: job.post!.id, detail: { automatic: true, approvalBypassed: true, source: "content-auto-recovery" } }, tx); + await audit({ action: "POST_PLANNED", actorLabel: SYSTEM_ACTOR, pageId: job.pageId, postId: job.post!.id, detail: { plannedAt: publishAt.toISOString(), source: "content-auto-recovery" } }, tx); return true; }); if (!claimed) continue; - const publishAt = scheduleTimeProblem(job.plannedAt, now) ? null : job.plannedAt; + occupiedTimes.add(publishAt.getTime()); + occupiedByPage.set(job.pageId, occupiedTimes); + const effectivePublishAt = scheduleTimeProblem(publishAt, now) ? null : publishAt; try { - await scheduleAutomaticPost({ ...job.post, status: "APPROVED" }, publishAt); + await scheduleAutomaticPost({ ...job.post, status: "APPROVED" }, effectivePublishAt); scheduled++; } catch (error) { const message = error instanceof Error ? error.message : String(error);