From a6e3d47b7c80f504bf89cdce8f91e6d1a3a2f3ff Mon Sep 17 00:00:00 2001 From: Loma Bot Ops Date: Sat, 28 Nov 2026 19:54:22 +0700 Subject: [PATCH] Schedule automatic content for publishing --- DESIGN.md | 2 +- next.config.ts | 5 ++- package-lock.json | 10 +++++ package.json | 1 + prisma/schema.prisma | 7 ++-- src/app/(console)/page.tsx | 3 +- src/app/api/ai/content-auto/route.ts | 11 ++++-- src/app/api/cron/post-generation/route.ts | 3 +- src/components/ContentAutoForm.tsx | 12 +++--- src/lib/ai/article-image.ts | 25 +++++++++++-- src/lib/ai/content-automation.ts | 45 ++++++++++++++++++++++- src/lib/ai/post-queue.ts | 31 ++++++++++++---- src/lib/posts/workflow.ts | 17 +++++++-- 13 files changed, 139 insertions(+), 33 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index ddc7f47..058f77f 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -58,7 +58,7 @@ Font: **Anuphan** ผ่าน `next/font/google`, 400 / 500 / 600 / 700 - วางวันเป็นแผนเท่านั้น ไม่ตั้งเวลา ไม่เผยแพร่ และไม่เปลี่ยนการอนุมัติ - ลากการ์ดหรือใช้ date input ได้ตามสิทธิ์เดิม -- ทุกโพสต์ผ่านขั้นอนุมัติก่อนเผยแพร่ คง separation of duty +- โพสต์ที่คนสร้างผ่านขั้นอนุมัติก่อนเผยแพร่ คง separation of duty; โหมดวางเนื้อหาอัตโนมัติเป็น opt-in ที่ข้ามการอนุมัติและตั้งเวลาเผยแพร่เอง - ทุก query จำกัดเพจตามสิทธิ์ ข้อมูล token อยู่ฝั่ง server - PWA manifest, app icon, offline page และ service worker cache version ใช้ธีมเดียวกัน diff --git a/next.config.ts b/next.config.ts index b80693b..e3d8ebf 100644 --- a/next.config.ts +++ b/next.config.ts @@ -9,7 +9,10 @@ const nextConfig: NextConfig = { outputFileTracingIncludes: { // Prisma 7 generates a hash-named client module that @vercel/nft can't // discover via static analysis — force-include it everywhere Prisma is used. - "/*": ["./node_modules/@prisma/client/**/*"], + "/*": [ + "./node_modules/@prisma/client/**/*", + "./node_modules/@fontsource/noto-sans-thai/files/noto-sans-thai-thai-{600,700}-normal.woff", + ], }, }; diff --git a/package-lock.json b/package-lock.json index 446fd00..8089621 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^1.12.0", + "@fontsource/noto-sans-thai": "^5.2.7", "@prisma/adapter-pg": "^7.9.1", "@prisma/client": "^7.9.1", "@vercel/blob": "^2.9.0", @@ -503,6 +504,15 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@fontsource/noto-sans-thai": { + "version": "5.2.7", + "resolved": "https://registry.npmjs.org/@fontsource/noto-sans-thai/-/noto-sans-thai-5.2.7.tgz", + "integrity": "sha512-MeqLHXD8Wr9mf7a+/VdhhWLfzYIUzzVJF+qSPUx5Dd1J0eJOj5CBDX1K3girqW1YVhiKPctxoGiB1bV9QGX4PA==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", diff --git a/package.json b/package.json index 2a541fb..9c98b2a 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ }, "dependencies": { "@anthropic-ai/sdk": "^1.12.0", + "@fontsource/noto-sans-thai": "^5.2.7", "@prisma/adapter-pg": "^7.9.1", "@prisma/client": "^7.9.1", "@vercel/blob": "^2.9.0", diff --git a/prisma/schema.prisma b/prisma/schema.prisma index bb7dc51..e9505d3 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -552,7 +552,8 @@ enum ContentScheduleMode { RANDOM } -// Durable creation queue. The output is always a draft and never a published post. +// Durable creation queue. Manual jobs output drafts; auto jobs bypass approval +// and are handed to the normal publishing workflow at their configured slot. model PostGenerationJob { id String @id @default(cuid()) pageId String @@ -563,8 +564,8 @@ model PostGenerationJob { topic String targets Platform[] plannedAt DateTime? - // Automatic drafts stay in the draft tray until this time. Once due, the - // worker copies plannedAt to Post.plannedAt and records boardPlacedAt. + // Legacy review-board placement fields retained for queued jobs created + // before auto-content began scheduling posts directly. placeOnBoardAt DateTime? boardPlacedAt DateTime? profileSnapshot Json diff --git a/src/app/(console)/page.tsx b/src/app/(console)/page.tsx index 526bee1..588d072 100644 --- a/src/app/(console)/page.tsx +++ b/src/app/(console)/page.tsx @@ -34,13 +34,14 @@ export default async function OverviewPage(props: PageProps<"/">) { prisma.post.count({ where: { ...scope, status: "FAILED" } }), ]); const editable = ctx.pages.filter(p => ids.includes(p.id) && roleAtLeast(p.role, "EDITOR")).map(p => p.id); + const autoPages = ctx.pages.filter(p => ids.includes(p.id) && roleAtLeast(p.role, "APPROVER")).map(p => p.id); const serialize = (p: (typeof posts)[number]) => ({ id: p.id, pageId: p.pageId, pageName: p.page.name, title: p.title, caption: p.caption, status: p.status, targets: p.targets, day: postBoardDate(p) ? bkkDayKey(postBoardDate(p)!) : null, scheduledAt: p.scheduledPublishAt?.toISOString() ?? null }); const unhealthy = ctx.pages.filter(p => ids.includes(p.id) && p.status !== "ACTIVE"); const today = bkkDayKey(new Date()); const openDays = Array.from({ length: 7 }, (_, i) => addDays(week, i)).filter(d => d >= today).length; const planFor = ctx.selected && editable.includes(ctx.selected.id) && openDays > 0 ? ctx.selected : null; return <> - 0 ? <> editable.includes(page.id)).map(({ id, name }) => ({ id, name }))} initialPageId={ctx.selected?.id} /> สร้างโพสต์ : undefined} /> + 0 ? <>{autoPages.length > 0 && autoPages.includes(page.id)).map(({ id, name }) => ({ id, name }))} initialPageId={ctx.selected && autoPages.includes(ctx.selected.id) ? ctx.selected.id : undefined} />} สร้างโพสต์ : undefined} />
{posts.length} โพสต์ในสัปดาห์นี้{tray.length}{tray.length === 50 ? "+" : ""} โพสต์ยังไม่วางวัน {pending > 0 && รออนุมัติ {pending}} diff --git a/src/app/api/ai/content-auto/route.ts b/src/app/api/ai/content-auto/route.ts index c6bfc34..9b58e5a 100644 --- a/src/app/api/ai/content-auto/route.ts +++ b/src/app/api/ai/content-auto/route.ts @@ -25,7 +25,7 @@ const Input = z.object({ export async function GET(req: Request) { const pageId = new URL(req.url).searchParams.get("pageId") || ""; - const auth = await requirePageAction(pageId, "editPost"); + const auth = await requirePageAction(pageId, "publishPost"); if (!auth.ok) return auth.response; try { const automation = await prisma.pageContentAutomation.findUnique({ where: { pageId }, select: AUTOMATION_SELECT }); @@ -36,7 +36,7 @@ export async function GET(req: Request) { export async function PUT(req: Request) { const body = await readJson(req); const pageId = str(body.pageId); - const auth = await requirePageAction(pageId, "editPost"); + const auth = await requirePageAction(pageId, "publishPost"); if (!auth.ok) return auth.response; try { const parsed = Input.safeParse(body); @@ -57,7 +57,10 @@ export async function PUT(req: Request) { }) : 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 } }); + const queued = await tx.postGenerationJob.findMany({ + where: { pageId, status: "QUEUED", OR: [{ requestKey: { startsWith: "auto:" } }, { requestKey: { startsWith: "auto-now:" } }] }, + 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); @@ -73,7 +76,7 @@ export async function PUT(req: Request) { export async function POST(req: Request) { const body = await readJson(req); const pageId = str(body.pageId); - const auth = await requirePageAction(pageId, "editPost"); + const auth = await requirePageAction(pageId, "publishPost"); if (!auth.ok) return auth.response; try { const result = await enqueueContentNow(pageId, auth.user.id, actorLabel(auth.user)); diff --git a/src/app/api/cron/post-generation/route.ts b/src/app/api/cron/post-generation/route.ts index 7838c1b..9ba4aee 100644 --- a/src/app/api/cron/post-generation/route.ts +++ b/src/app/api/cron/post-generation/route.ts @@ -2,7 +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, placeDueAutomaticDrafts } from "@/lib/ai/content-automation"; +import { enqueueDueContent, placeDueAutomaticDrafts, schedulePendingAutomaticPosts } from "@/lib/ai/content-automation"; export const runtime = "nodejs"; export const maxDuration = 900; @@ -15,5 +15,6 @@ export async function POST(req: Request) { if (!secret || secret.length < 32 || expected.length !== provided.length || !timingSafeEqual(expected, provided)) return NextResponse.json({ error: "unauthorized" }, { status: 401 }); await enqueueDueContent(); await placeDueAutomaticDrafts(); + await schedulePendingAutomaticPosts(); return NextResponse.json(await processNextPostJob(appUrl(new URL(req.url).origin))); } diff --git a/src/components/ContentAutoForm.tsx b/src/components/ContentAutoForm.tsx index 962f998..44698ef 100644 --- a/src/components/ContentAutoForm.tsx +++ b/src/components/ContentAutoForm.tsx @@ -49,7 +49,7 @@ export function ContentAutoForm({ pageId }: { pageId: string }) { const data = await response.json(); if (!response.ok) throw new Error(data.error || "บันทึก auto ไม่สำเร็จ"); setSettings(data.automation); - setMessage(data.automation.enabled ? "บันทึกแล้ว ระบบจะสร้างร่างเวลา 03:00 ล่วงหน้า 1 วัน และนำขึ้นตารางเวลา 08:00" : "ปิด auto แล้ว งานที่เริ่มสร้างไปแล้วจะทำจนจบ"); + setMessage(data.automation.enabled ? "บันทึกแล้ว ระบบจะสร้างเนื้อหาเวลา 03:00 ล่วงหน้า 1 วัน และตั้งเวลาเผยแพร่ให้อัตโนมัติ" : "ปิด auto แล้ว งานที่เริ่มสร้างไปแล้วจะทำจนจบ"); } catch (failure) { setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้"); } finally { setBusy(null); } } @@ -68,19 +68,19 @@ export function ContentAutoForm({ pageId }: { pageId: string }) { } return
-

วางเนื้อหาอัตโนมัติ

ระบบสร้างฉบับร่างเวลา 03:00 ล่วงหน้า 1 วัน เพื่อให้ตรวจเนื้อหาก่อน และนำขึ้นตารางเวลา 08:00 โดยทุกชิ้นยังต้องผ่านการอนุมัติก่อนเผยแพร่

+

วางเนื้อหาอัตโนมัติ

ระบบสร้างเนื้อหาเวลา 03:00 ล่วงหน้า 1 วัน แล้วตั้งเวลาเผยแพร่ตามแผนให้อัตโนมัติ โพสต์จากโหมดนี้ไม่ต้องรอคนอนุมัติ

1. เลือกวันที่ต้องการโพสต์
{DAYS.map((label, day) => )}
-
2. กำหนดเวลาเผยแพร่ตามแผน

เวลานี้ใช้วางโพสต์บนตารางของวันถัดไป ไม่ใช่เวลาสร้างฉบับร่าง

+
2. กำหนดเวลาเผยแพร่ตามแผน

ระบบจะเผยแพร่โพสต์ตามเวลานี้ ไม่ใช่เวลาที่เริ่มสร้างเนื้อหา

{(["FIXED", "RANDOM"] as const).map((mode) => )}
@@ -94,7 +94,7 @@ export function ContentAutoForm({ pageId }: { pageId: string }) {
{mixTotal === 100 ? "สัดส่วนพร้อมใช้งาน" : "ยังแบ่งสัดส่วนไม่ครบ"}{mixTotal} / 100%
{mixTotal !== 100 &&

ปรับตัวเลขให้ผลรวมเท่ากับ 100%

}