Schedule legacy automatic drafts
This commit is contained in:
@@ -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);
|
const placeOnBoardAt = new Date(Date.UTC(localDraftDay.getUTCFullYear(), localDraftDay.getUTCMonth(), localDraftDay.getUTCDate(), BOARD_HOUR) - BANGKOK_OFFSET);
|
||||||
return { publicationSlots: contentSlotsForBangkokDay(schedule, publicationDay), placeOnBoardAt };
|
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);
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { prisma } from "@/lib/db";
|
|||||||
import { audit, SYSTEM_ACTOR } from "@/lib/audit";
|
import { audit, SYSTEM_ACTOR } from "@/lib/audit";
|
||||||
import { roleAtLeast } from "@/lib/auth/roles";
|
import { roleAtLeast } from "@/lib/auth/roles";
|
||||||
import { IMAGE_DAILY_LIMIT_PER_PAGE } from "./image";
|
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 { UserFacingError } from "@/lib/facebook/client";
|
||||||
import { scheduleTimeProblem } from "@/lib/facebook/posts";
|
import { scheduleTimeProblem } from "@/lib/facebook/posts";
|
||||||
import { scheduleAutomaticPost } from "@/lib/posts/workflow";
|
import { scheduleAutomaticPost } from "@/lib/posts/workflow";
|
||||||
@@ -175,28 +175,59 @@ export async function schedulePendingAutomaticPosts(now = new Date()) {
|
|||||||
where: {
|
where: {
|
||||||
status: "COMPLETED",
|
status: "COMPLETED",
|
||||||
postId: { not: null },
|
postId: { not: null },
|
||||||
plannedAt: { not: null },
|
|
||||||
OR: [{ requestKey: { startsWith: "auto:" } }, { requestKey: { startsWith: "auto-now:" } }],
|
OR: [{ requestKey: { startsWith: "auto:" } }, { requestKey: { startsWith: "auto-now:" } }],
|
||||||
page: { contentAutomation: { enabled: true } },
|
page: { contentAutomation: { enabled: true } },
|
||||||
post: { status: "DRAFT" },
|
post: { status: "DRAFT" },
|
||||||
},
|
},
|
||||||
include: { post: true },
|
include: { post: true, page: { select: { contentAutomation: true } } },
|
||||||
orderBy: { plannedAt: "asc" },
|
orderBy: { finishedAt: "asc" },
|
||||||
take: 20,
|
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<string, Set<number>>();
|
||||||
|
for (const post of occupied) {
|
||||||
|
if (!post.scheduledPublishAt) continue;
|
||||||
|
const times = occupiedByPage.get(post.pageId) ?? new Set<number>();
|
||||||
|
times.add(post.scheduledPublishAt.getTime());
|
||||||
|
occupiedByPage.set(post.pageId, times);
|
||||||
|
}
|
||||||
|
const fallbackByPage = new Map<string, Date[]>();
|
||||||
let scheduled = 0;
|
let scheduled = 0;
|
||||||
for (const job of jobs) {
|
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<number>();
|
||||||
|
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 claimed = await prisma.$transaction(async (tx) => {
|
||||||
const changed = await tx.post.updateMany({ where: { id: job.post!.id, status: "DRAFT" }, data: { status: "APPROVED" } });
|
const changed = await tx.post.updateMany({ where: { id: job.post!.id, status: "DRAFT" }, data: { status: "APPROVED" } });
|
||||||
if (!changed.count) return false;
|
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_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;
|
return true;
|
||||||
});
|
});
|
||||||
if (!claimed) continue;
|
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 {
|
try {
|
||||||
await scheduleAutomaticPost({ ...job.post, status: "APPROVED" }, publishAt);
|
await scheduleAutomaticPost({ ...job.post, status: "APPROVED" }, effectivePublishAt);
|
||||||
scheduled++;
|
scheduled++;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
|||||||
Reference in New Issue
Block a user