From dd42b81639d6dc03aa3c837130e89f72d34ba96c Mon Sep 17 00:00:00 2001 From: chaloemphong Date: Wed, 25 Nov 2026 21:11:38 +0700 Subject: [PATCH] Add scheduled automatic content drafts with Codex and image automation --- docs/AI-AUTOMATION.md | 14 ++ docs/ARCHITECTURE.md | 2 + .../migration.sql | 30 ++++ prisma/schema.prisma | 23 +++ scripts/check-content-auto.mjs | 141 ++++++++++++++++++ src/app/api/ai/content-auto/route.ts | 61 ++++++++ src/app/api/cron/post-generation/route.ts | 2 + src/components/ContentAutoForm.tsx | 84 +++++++++++ src/components/PostGenerationQueue.tsx | 2 + src/lib/ai/auto-schedule.ts | 15 ++ src/lib/ai/content-automation.ts | 65 ++++++++ src/lib/ai/post-queue.ts | 2 +- src/lib/audit.ts | 4 + 13 files changed, 444 insertions(+), 1 deletion(-) create mode 100644 prisma/migrations/20261125140737_add_content_automation/migration.sql create mode 100644 scripts/check-content-auto.mjs create mode 100644 src/app/api/ai/content-auto/route.ts create mode 100644 src/components/ContentAutoForm.tsx create mode 100644 src/lib/ai/auto-schedule.ts create mode 100644 src/lib/ai/content-automation.ts diff --git a/docs/AI-AUTOMATION.md b/docs/AI-AUTOMATION.md index a350337..3c9be33 100644 --- a/docs/AI-AUTOMATION.md +++ b/docs/AI-AUTOMATION.md @@ -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= 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 ปิดหน้าเว็บได้ กลับมาหน้าเดิม/เลือกเพจเดิมเพื่อดูสถานะและเปิดฉบับร่าง งานใช้ข้อมูลโปรไฟล์ร้าน ณ เวลารับคิว diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 88d7886..7980b7d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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 diff --git a/prisma/migrations/20261125140737_add_content_automation/migration.sql b/prisma/migrations/20261125140737_add_content_automation/migration.sql new file mode 100644 index 0000000..ca41496 --- /dev/null +++ b/prisma/migrations/20261125140737_add_content_automation/migration.sql @@ -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; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index be789f6..a6f3a48 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -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()) diff --git a/scripts/check-content-auto.mjs b/scripts/check-content-auto.mjs new file mode 100644 index 0000000..ca2b5b2 --- /dev/null +++ b/scripts/check-content-auto.mjs @@ -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(); +} diff --git a/src/app/api/ai/content-auto/route.ts b/src/app/api/ai/content-auto/route.ts new file mode 100644 index 0000000..d2d9c8e --- /dev/null +++ b/src/app/api/ai/content-auto/route.ts @@ -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"); } +} diff --git a/src/app/api/cron/post-generation/route.ts b/src/app/api/cron/post-generation/route.ts index 7d24b30..4b56429 100644 --- a/src/app/api/cron/post-generation/route.ts +++ b/src/app/api/cron/post-generation/route.ts @@ -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))); } diff --git a/src/components/ContentAutoForm.tsx b/src/components/ContentAutoForm.tsx new file mode 100644 index 0000000..e88dfde --- /dev/null +++ b/src/components/ContentAutoForm.tsx @@ -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({ 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
+

โหมด auto สร้างเนื้อหา

+

เลือกวันและเวลา ให้ AI คิดหัวข้อจากข้อมูลร้าน เขียนเนื้อหาและสร้างภาพ บันทึกเป็นฉบับร่างรออนุมัติ ปิดหน้าเว็บได้

+
+ +
+ วันสร้างเนื้อหา (เวลาไทย) + {DAYS.map((label, day) => )} +
+
+ {settings.times.map((time, index) =>
+ + {settings.times.length > 1 && } +
)} + {settings.times.length < 3 && } +
+