Add scheduled automatic content drafts with Codex and image automation
This commit is contained in:
@@ -34,6 +34,20 @@
|
||||
|
||||
## ตรวจสอบ
|
||||
|
||||
### โหมด auto ตามวันและเวลา
|
||||
|
||||
หน้า **สร้างโพสต์** → เลือกเพจ → **โหมด auto สร้างเนื้อหา** เลือกวันในสัปดาห์และเวลาไทยได้สูงสุด 3 รอบต่อวัน กรอกแนวเนื้อหาหรือเว้นว่างให้ AI เลือกจากโปรไฟล์ร้าน เลือกช่องทาง แล้วเปิดสวิตช์และกด **บันทึกโหมด auto** เวลาที่เลือกคือเวลาเข้าคิวสร้างฉบับร่าง ไม่ใช่เวลาเผยแพร่
|
||||
|
||||
- ตั้งค่าแยกต่อเพจใน `PageContentAutomation` ผู้มีสิทธิ์ EDITOR ขึ้นไปเปิด/ปิดได้ ต้องมีโปรไฟล์ร้านและเพจ ACTIVE
|
||||
- ใช้ `page-post-generation` worker เดิมเรียก scheduler ก่อนรับงาน ไม่ต้องเปิดหน้าเว็บทิ้งไว้ แต่ต้องเปิดทั้ง queue worker และ automation worker พร้อม login Codex/ChatGPT และ desktop ที่ปลดล็อก
|
||||
- Codex เลือกหัวข้อจากข้อมูลร้าน แนวเนื้อหา และชื่อโพสต์ 10 ชิ้นล่าสุดเพื่อเลี่ยงซ้ำ แล้วสร้าง caption/พรอมต์ ภาพใช้ browser automation เดิม ผลจบที่ DRAFT ไม่อนุมัติหรือเผยแพร่เอง
|
||||
- mutex รายเพจร่วมกับคิว manual + request key ตามรอบ ป้องกัน scheduler หลายตัวรับรอบเดียวซ้ำ คิว/โควตาภาพเต็มจะข้ามรอบและแสดงเหตุผล ไม่สะสมงานย้อนหลัง เมื่อ worker กลับมารับเฉพาะรอบค้างล่าสุดหนึ่งงานแล้วคำนวณเวลาถัดไปจากปัจจุบัน
|
||||
- บัญชีถูกปิด/ถอดสิทธิ์ เพจไม่พร้อม โปรไฟล์หาย หรือ IG ถูกถอด จะพัก auto และเก็บเหตุผล ต้องแก้แล้วเปิดใหม่ การเปลี่ยนตั้งค่าบันทึกผู้รับผิดชอบเป็นผู้กดล่าสุด
|
||||
- ปิด auto จะยกเลิกเฉพาะงาน auto ที่ยัง QUEUED งาน RUNNING ทำจนจบ งาน manual ไม่ได้รับผล ทุกการเปิด/ปิด พัก ข้ามรอบ และเปลี่ยนสถานะคิว append AuditLog
|
||||
- deploy ต้องรัน `npx prisma migrate deploy` เพื่อเพิ่ม migration `add_content_automation` ก่อนใช้
|
||||
|
||||
ทดสอบด้วย `CONTENT_AUTO_TEST_DATABASE_URL=<URL ฐาน local แยก> node scripts/check-content-auto.mjs` หลัง `npm run build` และ migrate ฐานทดสอบ สคริปต์เปิดเว็บที่พอร์ต 3217 ทดสอบ API จริงกับ DB local และ scheduler พร้อมกันหลายตัว รวมเวลาไทย ข้ามรอบค้าง สิทธิ์ โควตา ยกเลิก และ audit ไม่เรียก Codex/ภาพ/Graph เก็บ fixtures และ audit ไว้ในฐานทดสอบ
|
||||
|
||||
### คิวสร้างโพสต์ AI ทั้งเนื้อหาและภาพ
|
||||
|
||||
หน้า **สร้างโพสต์** → เลือกเพจ → กรอกหัวข้อใน **สร้างทั้งโพสต์ด้วย AI** → **เข้าคิวสร้างโพสต์** ระบบตอบรับทันที (202) แล้วบันทึก `PostGenerationJob` ใน PostgreSQL ปิดหน้าเว็บได้ กลับมาหน้าเดิม/เลือกเพจเดิมเพื่อดูสถานะและเปิดฉบับร่าง งานใช้ข้อมูลโปรไฟล์ร้าน ณ เวลารับคิว
|
||||
|
||||
@@ -208,6 +208,8 @@ scripts/analysis-worker.mjs (PM2) ─claim QUEUED→RUNNING─▶ codex exec --o
|
||||
|
||||
สถานะ QUEUED → RUNNING → COMPLETED/FAILED; ยกเลิก QUEUED เป็น CANCELLED ได้ ทุก transition append audit งาน RUNNING ที่ heartbeat หายเกิน 20 นาทีเป็น FAILED โดยไม่ retry ภาพเอง การบันทึก Post และ COMPLETED อยู่ใน transaction เดียวกันและยืนยัน ownership ของงานอีกครั้ง โพสต์จบที่ DRAFT และยังต้องผ่านอนุมัติเดิม
|
||||
|
||||
โหมด auto เก็บวันในสัปดาห์ เวลาไทย แนวเนื้อหา ช่องทาง ผู้รับผิดชอบ และ nextRunAt ใน `PageContentAutomation` (`add_content_automation`) ผ่าน `/api/ai/content-auto` สิทธิ์ EDITOR ขึ้นไป queue worker เรียก `enqueueDueContent` ก่อน claim ทุกครั้ง ใช้ advisory lock รายเพจร่วมกับ manual enqueue และการแก้ตั้งค่า รับหนึ่งงานต่อรอบแล้วเลื่อนไปเวลาถัดไปจากปัจจุบัน ไม่ไล่สร้างรอบที่พลาด ข้ามเมื่อคิว/โควตาเต็ม พักเมื่อผู้รับผิดชอบไม่มีสิทธิ์หรือเพจ/โปรไฟล์ไม่พร้อม เปิดใหม่ได้หลังแก้เหตุ ปิด auto ยกเลิกเฉพาะงาน auto ที่ยัง QUEUED ทุก transition มี audit ใช้ Codex และ browser automation เดิม ผลเป็น DRAFT เสมอ
|
||||
|
||||
## Env
|
||||
|
||||
```text
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "PageContentAutomation" (
|
||||
"id" TEXT NOT NULL,
|
||||
"pageId" TEXT NOT NULL,
|
||||
"requestedById" TEXT NOT NULL,
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"weekdays" INTEGER[] DEFAULT ARRAY[1, 2, 3, 4, 5]::INTEGER[],
|
||||
"times" TEXT[] DEFAULT ARRAY['09:00']::TEXT[],
|
||||
"brief" TEXT NOT NULL DEFAULT '',
|
||||
"targets" "Platform"[] DEFAULT ARRAY['FACEBOOK']::"Platform"[],
|
||||
"nextRunAt" TIMESTAMP(3),
|
||||
"lastQueuedAt" TIMESTAMP(3),
|
||||
"lastError" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "PageContentAutomation_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "PageContentAutomation_pageId_key" ON "PageContentAutomation"("pageId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "PageContentAutomation_enabled_nextRunAt_idx" ON "PageContentAutomation"("enabled", "nextRunAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PageContentAutomation" ADD CONSTRAINT "PageContentAutomation_pageId_fkey" FOREIGN KEY ("pageId") REFERENCES "Page"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PageContentAutomation" ADD CONSTRAINT "PageContentAutomation_requestedById_fkey" FOREIGN KEY ("requestedById") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -91,6 +91,7 @@ model User {
|
||||
teamInvitesSent TeamInvite[] @relation("TeamInviteSender")
|
||||
approvalAssignments ApprovalRequest[] @relation("ApprovalAssignee")
|
||||
approvalRequestsSent ApprovalRequest[] @relation("ApprovalRequester")
|
||||
contentAutomations PageContentAutomation[]
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -168,6 +169,7 @@ model Page {
|
||||
aiUsage AiUsage[]
|
||||
generationJobs PostGenerationJob[]
|
||||
teamPage TeamPage?
|
||||
contentAutomation PageContentAutomation?
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -489,6 +491,27 @@ enum PostGenerationStatus {
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
// Recurring draft creation. The existing queue owns content and image generation.
|
||||
model PageContentAutomation {
|
||||
id String @id @default(cuid())
|
||||
pageId String @unique
|
||||
page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
|
||||
requestedById String
|
||||
requestedBy User @relation(fields: [requestedById], references: [id], onDelete: Restrict)
|
||||
enabled Boolean @default(false)
|
||||
weekdays Int[] @default([1, 2, 3, 4, 5])
|
||||
times String[] @default(["09:00"])
|
||||
brief String @default("")
|
||||
targets Platform[] @default([FACEBOOK])
|
||||
nextRunAt DateTime?
|
||||
lastQueuedAt DateTime?
|
||||
lastError String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([enabled, nextRunAt])
|
||||
}
|
||||
|
||||
// Durable creation queue. The output is always a draft and never a published post.
|
||||
model PostGenerationJob {
|
||||
id String @id @default(cuid())
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomUUID, randomBytes } from "node:crypto";
|
||||
import { spawn } from "node:child_process";
|
||||
import { SignJWT } from "jose";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import ts from "typescript";
|
||||
|
||||
// Use only a dedicated local database migrated with prisma migrate dev/deploy.
|
||||
const databaseUrl = process.env.CONTENT_AUTO_TEST_DATABASE_URL;
|
||||
assert.ok(databaseUrl && ["localhost", "127.0.0.1"].includes(new URL(databaseUrl).hostname), "Set CONTENT_AUTO_TEST_DATABASE_URL to a dedicated local test database");
|
||||
const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString: databaseUrl }) });
|
||||
const secret = randomBytes(32).toString("hex");
|
||||
const basePath = JSON.parse(readFileSync(".next/required-server-files.json", "utf8")).config.basePath || "";
|
||||
const base = `http://127.0.0.1:3217${basePath}`;
|
||||
const suffix = randomUUID();
|
||||
|
||||
function load(file, dependencies) {
|
||||
const source = readFileSync(new URL(file, import.meta.url), "utf8");
|
||||
const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText;
|
||||
const exports = {};
|
||||
new Function("exports", "require", compiled)(exports, (name) => {
|
||||
assert.ok(name in dependencies, `Unexpected dependency: ${name}`);
|
||||
return dependencies[name];
|
||||
});
|
||||
return exports;
|
||||
}
|
||||
const schedule = load("../src/lib/ai/auto-schedule.ts", {});
|
||||
const { nextContentRun } = schedule;
|
||||
assert.equal(nextContentRun([1], ["09:00"], new Date("2026-11-22T23:00:00Z")).toISOString(), "2026-11-23T02:00:00.000Z");
|
||||
assert.equal(nextContentRun([1], ["09:00"], new Date("2026-11-23T02:00:00Z")).toISOString(), "2026-11-30T02:00:00.000Z");
|
||||
assert.equal(nextContentRun([0], ["00:15"], new Date("2026-11-28T17:00:00Z")).toISOString(), "2026-11-28T17:15:00.000Z");
|
||||
assert.equal(nextContentRun([1], ["15:00", "09:00"], new Date("2026-11-23T03:00:00Z")).toISOString(), "2026-11-23T08:00:00.000Z");
|
||||
assert.equal(nextContentRun([5], ["00:00"], new Date("2026-12-31T16:59:00Z")).toISOString(), "2026-12-31T17:00:00.000Z");
|
||||
console.log("PASS Bangkok weekly slots, exact boundary, multiple times, year rollover");
|
||||
|
||||
const roles = load("../src/lib/auth/roles.ts", {});
|
||||
const { enqueueDueContent } = load("../src/lib/ai/content-automation.ts", {
|
||||
"@/lib/db": { prisma },
|
||||
"@/lib/audit": { SYSTEM_ACTOR: "ระบบ", audit: (data, tx) => tx.auditLog.create({ data }) },
|
||||
"@/lib/auth/roles": roles,
|
||||
"./image": { IMAGE_DAILY_LIMIT_PER_PAGE: 10 },
|
||||
"./auto-schedule": schedule,
|
||||
});
|
||||
|
||||
// No automation endpoint is configured: this test never invokes Codex, images or Graph.
|
||||
const server = spawn(process.execPath, ["node_modules/next/dist/bin/next", "start", "-p", "3217", "-H", "127.0.0.1"], {
|
||||
windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
|
||||
env: { ...process.env, DATABASE_URL: databaseUrl, SESSION_SECRET: secret, NEXT_PUBLIC_BASE_PATH: basePath, NEXT_PUBLIC_APP_URL: base, AI_AUTOMATION_URL: "", AI_AUTOMATION_SECRET: "", POST_QUEUE_SECRET: secret },
|
||||
});
|
||||
let logs = "";
|
||||
server.stdout.on("data", (data) => { logs += data; });
|
||||
server.stderr.on("data", (data) => { logs += data; });
|
||||
async function api(method, route, cookie, body) {
|
||||
const response = await fetch(`${base}${route}`, { method, headers: { ...(cookie ? { Cookie: cookie } : {}), ...(body ? { "Content-Type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
|
||||
return { status: response.status, data: await response.json() };
|
||||
}
|
||||
function status(result, expected) { assert.equal(result.status, expected, JSON.stringify(result.data)); return result.data; }
|
||||
async function cookie(user) {
|
||||
const token = await new SignJWT({ role: user.globalRole, mustChangePassword: false }).setProtectedHeader({ alg: "HS256" }).setSubject(user.id).setIssuedAt().setExpirationTime("15m").sign(new TextEncoder().encode(secret));
|
||||
return `pm_session=${token}`;
|
||||
}
|
||||
try {
|
||||
let ready = false;
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
try { if ((await fetch(`${base}/api/health`)).ok) { ready = true; break; } } catch {}
|
||||
if (server.exitCode !== null) throw new Error(logs);
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
}
|
||||
assert.ok(ready, logs);
|
||||
const users = await Promise.all(["editor", "viewer", "outsider"].map((role) => prisma.user.create({ data: { name: role, email: `${role}-${suffix}@example.invalid`, passwordHash: "test-only", globalRole: "MEMBER" } })));
|
||||
const [editor, viewer] = users;
|
||||
const cookies = await Promise.all(users.map(cookie));
|
||||
const page = await prisma.page.create({ data: {
|
||||
name: "[Auto test] Fictional shop", fbPageId: `auto-test-${suffix}`, tokenCipher: "unused-test-only",
|
||||
profile: { create: { business: "ร้านสมมติ ขายกาแฟ", tone: "เป็นกันเอง", visualStyle: "Blue and white", website: "https://example.invalid/" } },
|
||||
members: { create: [{ userId: editor.id, role: "EDITOR" }, { userId: viewer.id, role: "VIEWER" }] },
|
||||
} });
|
||||
const route = "/api/ai/content-auto";
|
||||
const settings = { pageId: page.id, enabled: true, weekdays: [0, 1, 2, 3, 4, 5, 6], times: ["09:00", "15:00"], brief: "ให้ความรู้", targets: ["FACEBOOK"] };
|
||||
status(await api("PUT", route, null, settings), 401);
|
||||
status(await api("PUT", route, cookies[1], settings), 403);
|
||||
status(await api("PUT", route, cookies[2], settings), 404);
|
||||
status(await api("GET", `${route}?pageId=${page.id}`, cookies[2]), 404);
|
||||
status(await api("PUT", route, cookies[0], { ...settings, times: ["24:00"] }), 400);
|
||||
status(await api("PUT", route, cookies[0], { ...settings, weekdays: [] }), 400);
|
||||
status(await api("PUT", route, cookies[0], { ...settings, targets: ["INSTAGRAM"] }), 400);
|
||||
const saved = status(await api("PUT", route, cookies[0], settings), 200).automation;
|
||||
assert.ok(new Date(saved.nextRunAt) > new Date());
|
||||
assert.equal(status(await api("GET", `${route}?pageId=${page.id}`, cookies[0]), 200).automation.enabled, true);
|
||||
console.log("PASS API authentication, page membership, validation and saved schedule");
|
||||
|
||||
await enqueueDueContent();
|
||||
assert.equal(await prisma.postGenerationJob.count({ where: { pageId: page.id } }), 0);
|
||||
const makeDue = () => prisma.pageContentAutomation.update({ where: { pageId: page.id }, data: { enabled: true, nextRunAt: new Date(Date.now() - 7 * 86400_000) } });
|
||||
await makeDue();
|
||||
await Promise.all(Array.from({ length: 5 }, () => enqueueDueContent()));
|
||||
let jobs = await prisma.postGenerationJob.findMany({ where: { pageId: page.id } });
|
||||
assert.equal(jobs.length, 1);
|
||||
assert.ok(jobs[0].requestKey.startsWith("auto:"));
|
||||
assert.equal(jobs[0].profileSnapshot.business, "ร้านสมมติ ขายกาแฟ");
|
||||
assert.equal(jobs[0].profileSnapshot.visualStyle, "Blue and white");
|
||||
assert.equal(jobs[0].profileSnapshot.website, "https://example.invalid/");
|
||||
assert.ok((await prisma.pageContentAutomation.findUniqueOrThrow({ where: { pageId: page.id } })).nextRunAt > new Date());
|
||||
console.log("PASS concurrent enqueue deduplication and missed slots produce one job");
|
||||
|
||||
const manual = await prisma.postGenerationJob.create({ data: { pageId: page.id, requestedById: editor.id, requestKey: randomUUID(), topic: "manual", targets: ["FACEBOOK"], profileSnapshot: {} } });
|
||||
status(await api("PUT", route, cookies[0], { ...settings, enabled: false }), 200);
|
||||
assert.equal((await prisma.postGenerationJob.findUniqueOrThrow({ where: { id: jobs[0].id } })).status, "CANCELLED");
|
||||
assert.equal((await prisma.postGenerationJob.findUniqueOrThrow({ where: { id: manual.id } })).status, "QUEUED");
|
||||
console.log("PASS disabling auto cancels automatic queued jobs and preserves manual jobs");
|
||||
|
||||
await prisma.aiUsage.createMany({ data: Array.from({ length: 10 }, () => ({ pageId: page.id, kind: "image", inputTokens: 0, outputTokens: 0 })) });
|
||||
await makeDue(); await enqueueDueContent();
|
||||
assert.equal(await prisma.postGenerationJob.count({ where: { pageId: page.id } }), 2);
|
||||
assert.match((await prisma.pageContentAutomation.findUniqueOrThrow({ where: { pageId: page.id } })).lastError, /โควตา/);
|
||||
await prisma.pageMember.update({ where: { userId_pageId: { userId: editor.id, pageId: page.id } }, data: { role: "VIEWER" } });
|
||||
await makeDue(); await enqueueDueContent();
|
||||
const paused = await prisma.pageContentAutomation.findUniqueOrThrow({ where: { pageId: page.id } });
|
||||
assert.equal(paused.enabled, false);
|
||||
assert.equal(paused.nextRunAt, null);
|
||||
assert.match(paused.lastError, /สิทธิ์/);
|
||||
await prisma.pageMember.update({ where: { userId_pageId: { userId: editor.id, pageId: page.id } }, data: { role: "EDITOR" } });
|
||||
const team = await prisma.team.create({ data: { name: "Auto test team", ownerId: editor.id, pages: { create: { pageId: page.id } } } });
|
||||
await makeDue(); await enqueueDueContent();
|
||||
assert.equal((await prisma.pageContentAutomation.findUniqueOrThrow({ where: { pageId: page.id } })).enabled, false);
|
||||
status(await api("PUT", route, cookies[0], settings), 404);
|
||||
await prisma.teamMember.create({ data: { teamId: team.id, userId: editor.id, role: "OWNER" } });
|
||||
status(await api("PUT", route, cookies[0], settings), 200);
|
||||
status(await api("PUT", route, cookies[0], { ...settings, enabled: false }), 200);
|
||||
console.log("PASS team membership is required for scheduler and settings");
|
||||
const actions = (await prisma.auditLog.findMany({ where: { pageId: page.id }, select: { action: true } })).map((row) => row.action);
|
||||
for (const action of ["CONTENT_AUTO_ENABLED", "CONTENT_AUTO_DISABLED", "AI_POST_QUEUED", "AI_POST_CANCELLED", "CONTENT_AUTO_SKIPPED", "CONTENT_AUTO_PAUSED"]) assert.ok(actions.includes(action), action);
|
||||
assert.equal(await prisma.post.count({ where: { pageId: page.id } }), 0);
|
||||
console.log("PASS quota skip, permission revocation, append audit and no publication");
|
||||
console.log("All content auto checks passed; isolated fixtures and audit rows retained.");
|
||||
} finally {
|
||||
server.kill();
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import * as z from "zod/v4";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { actorLabel, requirePageAction } from "@/lib/auth/user";
|
||||
import { audit } from "@/lib/audit";
|
||||
import { errorResponse, readJson, str } from "@/lib/http";
|
||||
import { UserFacingError } from "@/lib/facebook/client";
|
||||
import { AUTOMATION_SELECT } from "@/lib/ai/content-automation";
|
||||
import { nextContentRun } from "@/lib/ai/auto-schedule";
|
||||
|
||||
const Input = z.object({
|
||||
enabled: z.boolean(),
|
||||
weekdays: z.array(z.number().int().min(0).max(6)).min(1).max(7),
|
||||
times: z.array(z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/)).min(1).max(3),
|
||||
brief: z.string().trim().max(1000),
|
||||
targets: z.array(z.enum(["FACEBOOK", "INSTAGRAM"])).min(1).max(2),
|
||||
});
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const pageId = new URL(req.url).searchParams.get("pageId") || "";
|
||||
const auth = await requirePageAction(pageId, "editPost");
|
||||
if (!auth.ok) return auth.response;
|
||||
try {
|
||||
const automation = await prisma.pageContentAutomation.findUnique({ where: { pageId }, select: AUTOMATION_SELECT });
|
||||
return NextResponse.json({ automation }, { headers: { "Cache-Control": "no-store" } });
|
||||
} catch (error) { return errorResponse(error, "content-auto:read"); }
|
||||
}
|
||||
|
||||
export async function PUT(req: Request) {
|
||||
const body = await readJson(req);
|
||||
const pageId = str(body.pageId);
|
||||
const auth = await requirePageAction(pageId, "editPost");
|
||||
if (!auth.ok) return auth.response;
|
||||
try {
|
||||
const parsed = Input.safeParse(body);
|
||||
if (!parsed.success) throw new UserFacingError("เลือกวัน เวลาไม่เกิน 3 ช่วง และช่องทางให้ครบ แนวเนื้อหาไม่เกิน 1,000 ตัวอักษร");
|
||||
const input = { ...parsed.data, weekdays: [...new Set(parsed.data.weekdays)].sort(), times: [...new Set(parsed.data.times)].sort(), targets: [...new Set(parsed.data.targets)] };
|
||||
const automation = await prisma.$transaction(async (tx) => {
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai-post:${pageId}`}))`;
|
||||
const page = await tx.page.findUnique({ where: { id: pageId }, select: { status: true, igUserId: true, profile: { select: { business: true } } } });
|
||||
if (!page) throw new UserFacingError("ไม่พบเพจ");
|
||||
if (input.enabled) {
|
||||
if (page.status !== "ACTIVE") throw new UserFacingError("เพจต้องพร้อมใช้งานก่อนเปิด auto");
|
||||
if (!page.profile?.business.trim()) throw new UserFacingError("ตั้งค่าโปรไฟล์ร้านก่อนเปิด auto");
|
||||
if (input.targets.includes("INSTAGRAM") && !page.igUserId) throw new UserFacingError("เพจนี้ยังไม่ได้ผูก Instagram");
|
||||
}
|
||||
const data = { ...input, requestedById: auth.user.id, nextRunAt: input.enabled ? nextContentRun(input.weekdays, input.times) : null, lastError: null };
|
||||
const saved = await tx.pageContentAutomation.upsert({ where: { pageId }, create: { pageId, ...data }, update: data, select: AUTOMATION_SELECT });
|
||||
if (!input.enabled) {
|
||||
const queued = await tx.postGenerationJob.findMany({ where: { pageId, status: "QUEUED", requestKey: { startsWith: "auto:" } }, select: { id: true } });
|
||||
for (const job of queued) {
|
||||
const changed = await tx.postGenerationJob.updateMany({ where: { id: job.id, status: "QUEUED" }, data: { status: "CANCELLED", finishedAt: new Date() } });
|
||||
if (changed.count) await audit({ action: "AI_POST_CANCELLED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, detail: { jobId: job.id, source: "auto-disabled" } }, tx);
|
||||
}
|
||||
}
|
||||
await audit({ action: input.enabled ? "CONTENT_AUTO_ENABLED" : "CONTENT_AUTO_DISABLED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, detail: { weekdays: input.weekdays, times: input.times, targets: input.targets } }, tx);
|
||||
return saved;
|
||||
});
|
||||
return NextResponse.json({ automation });
|
||||
} catch (error) { return errorResponse(error, "content-auto:save"); }
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { timingSafeEqual } from "node:crypto";
|
||||
import { NextResponse } from "next/server";
|
||||
import { appUrl } from "@/lib/base-path";
|
||||
import { processNextPostJob } from "@/lib/ai/post-queue";
|
||||
import { enqueueDueContent } from "@/lib/ai/content-automation";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const maxDuration = 900;
|
||||
@@ -12,5 +13,6 @@ export async function POST(req: Request) {
|
||||
const expected = Buffer.from(`Bearer ${secret || ""}`);
|
||||
const provided = Buffer.from(req.headers.get("authorization") || "");
|
||||
if (!secret || secret.length < 32 || expected.length !== provided.length || !timingSafeEqual(expected, provided)) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
|
||||
await enqueueDueContent();
|
||||
return NextResponse.json(await processNextPostJob(appUrl(new URL(req.url).origin)));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { withBase } from "@/lib/base-path";
|
||||
import { Notice } from "./ui";
|
||||
|
||||
type Settings = {
|
||||
enabled: boolean; weekdays: number[]; times: string[]; brief: string;
|
||||
targets: ("FACEBOOK" | "INSTAGRAM")[];
|
||||
nextRunAt: string | null; lastQueuedAt: string | null; lastError: string | null;
|
||||
};
|
||||
const DAYS = ["อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส."];
|
||||
const formatTime = (value: string) => new Date(value).toLocaleString("th-TH", { timeZone: "Asia/Bangkok", dateStyle: "medium", timeStyle: "short" });
|
||||
|
||||
export function ContentAutoForm({ pageId }: { pageId: string }) {
|
||||
const [settings, setSettings] = useState<Settings>({ enabled: false, weekdays: [1, 2, 3, 4, 5], times: ["09:00"], brief: "", targets: ["FACEBOOK"], nextRunAt: null, lastQueuedAt: null, lastError: null });
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [message, setMessage] = useState("");
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
void (async () => {
|
||||
try {
|
||||
const response = await fetch(withBase(`/api/ai/content-auto?pageId=${encodeURIComponent(pageId)}`), { signal: controller.signal, cache: "no-store" });
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || "โหลดการตั้งค่า auto ไม่สำเร็จ");
|
||||
if (data.automation) setSettings(data.automation);
|
||||
setLoaded(true);
|
||||
} catch (failure) {
|
||||
if (!controller.signal.aborted) setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้");
|
||||
}
|
||||
})();
|
||||
return () => controller.abort();
|
||||
}, [pageId]);
|
||||
|
||||
async function save() {
|
||||
if (!loaded || busy) return;
|
||||
setBusy(true); setError(""); setMessage("");
|
||||
try {
|
||||
const response = await fetch(withBase("/api/ai/content-auto"), { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, ...settings }) });
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || "บันทึก auto ไม่สำเร็จ");
|
||||
setSettings(data.automation);
|
||||
setMessage(data.automation.enabled ? "บันทึกแล้ว จะสร้างฉบับร่างตามวันและเวลาที่เลือก" : "ปิด auto แล้ว งานที่เริ่มสร้างไปแล้วจะทำจนจบ");
|
||||
} catch (failure) { setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้"); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
|
||||
return <section className="border border-line rounded-xl p-4 flex flex-col gap-3 bg-paper" aria-label="สร้างเนื้อหาอัตโนมัติ">
|
||||
<h3 className="font-semibold text-[15px]">โหมด auto สร้างเนื้อหา</h3>
|
||||
<p className="text-[13px] text-ink-2">เลือกวันและเวลา ให้ AI คิดหัวข้อจากข้อมูลร้าน เขียนเนื้อหาและสร้างภาพ บันทึกเป็นฉบับร่างรออนุมัติ ปิดหน้าเว็บได้</p>
|
||||
<fieldset disabled={!loaded || busy} className="flex flex-col gap-3">
|
||||
<label className="flex items-center gap-2 text-[14px] font-medium">
|
||||
<input type="checkbox" role="switch" checked={settings.enabled} onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })} /> เปิดสร้างอัตโนมัติสำหรับเพจนี้
|
||||
</label>
|
||||
<fieldset className="flex flex-wrap gap-3">
|
||||
<legend className="text-[13px] mb-2">วันสร้างเนื้อหา (เวลาไทย)</legend>
|
||||
{DAYS.map((label, day) => <label key={day} className="flex items-center gap-1.5 text-[13px] min-h-10">
|
||||
<input type="checkbox" checked={settings.weekdays.includes(day)} onChange={(e) => setSettings({ ...settings, weekdays: e.target.checked ? [...settings.weekdays, day] : settings.weekdays.filter((d) => d !== day) })} />{label}
|
||||
</label>)}
|
||||
</fieldset>
|
||||
<div className="flex flex-col gap-2">
|
||||
{settings.times.map((time, index) => <div key={index} className="flex flex-wrap items-end gap-2">
|
||||
<label className="field"><span>เวลาสร้างรอบที่ {index + 1}</span><input className="input" type="time" required value={time} onChange={(e) => setSettings({ ...settings, times: settings.times.map((t, i) => i === index ? e.target.value : t) })} /></label>
|
||||
{settings.times.length > 1 && <button type="button" className="btn btn-ghost btn-sm" aria-label={`ลบเวลารอบที่ ${index + 1}`} onClick={() => setSettings({ ...settings, times: settings.times.filter((_, i) => i !== index) })}>ลบเวลา</button>}
|
||||
</div>)}
|
||||
{settings.times.length < 3 && <button type="button" className="btn btn-ghost btn-sm self-start" onClick={() => setSettings({ ...settings, times: [...settings.times, "12:00"] })}>เพิ่มเวลา (สูงสุด 3 รอบต่อวัน)</button>}
|
||||
</div>
|
||||
<label className="field"><span>แนวเนื้อหา (เว้นว่างให้ AI เลือกจากข้อมูลร้าน)</span><textarea className="textarea" rows={2} maxLength={1000} value={settings.brief} onChange={(e) => setSettings({ ...settings, brief: e.target.value })} placeholder="เช่น สลับแนะนำสินค้า เคล็ดลับ และเรื่องราวของร้าน" /></label>
|
||||
<fieldset className="flex flex-wrap gap-3 text-[13px]">
|
||||
<legend className="mb-2">ช่องทางของฉบับร่าง auto</legend>
|
||||
{(["FACEBOOK", "INSTAGRAM"] as const).map((target) => <label key={target} className="flex items-center gap-1.5 min-h-10"><input type="checkbox" checked={settings.targets.includes(target)} onChange={(e) => setSettings({ ...settings, targets: e.target.checked ? [...settings.targets, target] : settings.targets.filter((t) => t !== target) })} />{target === "FACEBOOK" ? "Facebook" : "Instagram"}</label>)}
|
||||
</fieldset>
|
||||
<button type="button" className="btn btn-primary btn-sm self-start" onClick={save}>{busy ? "กำลังบันทึก…" : "บันทึกโหมด auto"}</button>
|
||||
</fieldset>
|
||||
{settings.enabled && settings.nextRunAt && <p className="text-[12px] text-ink-2">รอบถัดไป: {formatTime(settings.nextRunAt)} · เวลาเริ่มเข้าคิว ไม่ใช่เวลาเผยแพร่</p>}
|
||||
{settings.lastQueuedAt && <p className="text-[12px] text-ink-2">เข้าคิวล่าสุด: {formatTime(settings.lastQueuedAt)} · ดูผลในงานล่าสุดด้านล่าง</p>}
|
||||
<p className="text-[12px] text-ink-2">ต้องเปิด worker และ login บัญชีสร้างภาพไว้ งานเริ่มตามคิว หาก worker หยุดจะรับเพียงรอบล่าสุดเมื่อกลับมา</p>
|
||||
{settings.lastError && <Notice tone="red">{settings.lastError}</Notice>}
|
||||
{error && <Notice tone="red">{error}</Notice>}
|
||||
{message && <p role="status" className="text-[13px] text-ink-2">{message}</p>}
|
||||
</section>;
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { withBase } from "@/lib/base-path";
|
||||
import { POST_JOB_STAGE, POST_JOB_STATUS, postJobProgress, type PostJobView } from "@/lib/ai/post-queue-shared";
|
||||
import { Icon } from "./Icon";
|
||||
import { Notice } from "./ui";
|
||||
import { ContentAutoForm } from "./ContentAutoForm";
|
||||
|
||||
function duration(job: PostJobView): string {
|
||||
if (!job.finishedAt) return "";
|
||||
@@ -81,6 +82,7 @@ export function PostGenerationQueue({ pageId, targets, plannedDay, initialTopic
|
||||
|
||||
return (
|
||||
<section aria-label="คิวสร้างโพสต์ด้วย AI" className="border border-line rounded-xl p-4 flex flex-col gap-3 bg-board">
|
||||
<ContentAutoForm key={pageId} pageId={pageId} />
|
||||
<h3 className="font-semibold text-[15px]">สร้างทั้งโพสต์ด้วย AI</h3>
|
||||
<p className="text-[13px] text-ink-2">ให้ Codex เขียนเนื้อหาและ ChatGPT สร้างภาพ แล้วบันทึกเป็นฉบับร่างรอคุณตรวจ ปิดหน้านี้แล้วกลับมาดูคิวได้</p>
|
||||
<label className="field">
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
/** Weekly slots in Asia/Bangkok (UTC+7, no daylight saving), strictly after now. */
|
||||
export function nextContentRun(weekdays: number[], times: string[], now = new Date()): Date {
|
||||
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);
|
||||
if (candidate > now) return candidate;
|
||||
}
|
||||
}
|
||||
throw new Error("No valid weekly content slot");
|
||||
}
|
||||
@@ -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); }
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,7 @@ export async function processNextPostJob(baseUrl: string) {
|
||||
const logoPalette = await logoPalettePrompt(page.pictureUrl);
|
||||
const content = await generateStructured({
|
||||
kind: "post-generation", pageId: job.pageId, userId: job.requestedById,
|
||||
system: SYSTEM, effort: "medium", schema: Draft, waitForWorker: true,
|
||||
system: SYSTEM + (job.requestKey.startsWith("auto:") ? "\nThis is an automatic content slot. Choose a fresh, relevant topic from the shop profile and brief data. Avoid repeating the supplied recent topics. Never invent prices, promotions, availability or claims. The slot is creation time, not a publication promise." : ""), effort: "medium", schema: Draft, waitForWorker: true,
|
||||
prompt: `${profilePrompt(profile)}\n${logoPalette}\n\n${platformRule(job.targets.includes("INSTAGRAM"))}\n\n<topic>\n${job.topic}\n</topic>`,
|
||||
});
|
||||
if (job.targets.includes("INSTAGRAM") && content.caption.length > 2200) throw new UserFacingError("Caption ที่ AI สร้างยาวเกินข้อจำกัด Instagram กรุณาลองใหม่");
|
||||
|
||||
@@ -37,6 +37,10 @@ export type AuditAction =
|
||||
| "AI_POST_COMPLETED"
|
||||
| "AI_POST_FAILED"
|
||||
| "AI_POST_CANCELLED"
|
||||
| "CONTENT_AUTO_ENABLED"
|
||||
| "CONTENT_AUTO_DISABLED"
|
||||
| "CONTENT_AUTO_PAUSED"
|
||||
| "CONTENT_AUTO_SKIPPED"
|
||||
| "RULE_SAVED"
|
||||
| "RULE_DELETED"
|
||||
| "USER_CREATED"
|
||||
|
||||
Reference in New Issue
Block a user