Add automated content planning and image overlays

This commit is contained in:
Loma Bot Ops
2026-11-27 08:48:41 +07:00
parent bb840a54ff
commit 1d3bd3e7cd
10 changed files with 411 additions and 133 deletions
+31 -4
View File
@@ -1,13 +1,40 @@
type Schedule = {
weekdays: number[];
times: string[];
mode?: "FIXED" | "RANDOM";
randomPostsPerDay?: number;
seed?: string;
};
function seededMinutes(seed: string, count: number): number[] {
let state = 2166136261;
for (const char of seed) state = Math.imul(state ^ char.charCodeAt(0), 16777619) >>> 0;
const slots = new Set<number>();
while (slots.size < count) {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
// 08:00–20:00, snapped to 5-minute increments for readable schedules.
slots.add(8 * 60 + (state % 145) * 5);
}
return [...slots].sort((a, b) => a - b);
}
/** Weekly slots in Asia/Bangkok (UTC+7, no daylight saving), strictly after now. */
export function nextContentRun(weekdays: number[], times: string[], now = new Date()): Date {
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);
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);
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;
}
}
+18 -4
View File
@@ -5,10 +5,20 @@ 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,
enabled: true, scheduleMode: true, weekdays: true, times: true, randomPostsPerDay: true,
articlePercent: true, knowledgePercent: true, salesPercent: true, brief: true, targets: true,
nextRunAt: true, lastQueuedAt: true, lastError: true,
} as const;
function selectContentType(config: { articlePercent: number; knowledgePercent: number; salesPercent: number }, seed: string) {
let value = 0;
for (const char of seed) value = (Math.imul(value, 31) + char.charCodeAt(0)) >>> 0;
const point = value % 100;
if (point < config.articlePercent) return "บทความ";
if (point < config.articlePercent + config.knowledgePercent) return "ความรู้ทั่วไป";
return "ปิดงานขาย";
}
/** The queue worker calls this even when no browser is viewing the page. */
export async function enqueueDueContent() {
const now = new Date();
@@ -43,7 +53,10 @@ export async function enqueueDueContent() {
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);
const nextRunAt = nextContentRun({
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 reason = pending >= 5 ? "ข้ามรอบนี้เพราะคิวเต็ม 5 งาน" : "ข้ามรอบนี้เพราะโควตาภาพเต็ม";
await tx.pageContentAutomation.update({ where: { pageId }, data: { nextRunAt, lastError: reason } });
@@ -51,14 +64,15 @@ export async function enqueueDueContent() {
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 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!,
} });
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);
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); }
}