From 1d3bd3e7cd3166ae89e7d577ba154a06a76436b6 Mon Sep 17 00:00:00 2001 From: Loma Bot Ops Date: Fri, 27 Nov 2026 08:48:41 +0700 Subject: [PATCH] Add automated content planning and image overlays --- .../migration.sql | 8 + prisma/schema.prisma | 168 ++++++++------- src/app/(console)/page.tsx | 3 +- src/app/api/ai/content-auto/route.ts | 16 +- src/app/api/ai/image/route.ts | 3 +- src/components/ContentAutoForm.tsx | 71 ++++--- src/components/ContentAutoLauncher.tsx | 25 +++ src/components/ImageAssistant.tsx | 193 +++++++++++++++++- src/lib/ai/auto-schedule.ts | 35 +++- src/lib/ai/content-automation.ts | 22 +- 10 files changed, 411 insertions(+), 133 deletions(-) create mode 100644 prisma/migrations/20261127143000_add_content_auto_mix/migration.sql create mode 100644 src/components/ContentAutoLauncher.tsx diff --git a/prisma/migrations/20261127143000_add_content_auto_mix/migration.sql b/prisma/migrations/20261127143000_add_content_auto_mix/migration.sql new file mode 100644 index 0000000..05d70f1 --- /dev/null +++ b/prisma/migrations/20261127143000_add_content_auto_mix/migration.sql @@ -0,0 +1,8 @@ +CREATE TYPE "ContentScheduleMode" AS ENUM ('FIXED', 'RANDOM'); + +ALTER TABLE "PageContentAutomation" +ADD COLUMN "scheduleMode" "ContentScheduleMode" NOT NULL DEFAULT 'FIXED', +ADD COLUMN "randomPostsPerDay" INTEGER NOT NULL DEFAULT 1, +ADD COLUMN "articlePercent" INTEGER NOT NULL DEFAULT 40, +ADD COLUMN "knowledgePercent" INTEGER NOT NULL DEFAULT 40, +ADD COLUMN "salesPercent" INTEGER NOT NULL DEFAULT 20; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index d6fd780..0e0bcaf 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -77,21 +77,21 @@ model User { mustChangePassword Boolean @default(false) lastLoginAt DateTime? - memberships PageMember[] - postsCreated Post[] @relation("PostCreatedBy") - postsEdited Post[] @relation("PostLastEditedBy") - approvals PostApproval[] - auditLogs AuditLog[] - metaConnections MetaConnection[] - analyses PageAnalysis[] - identities UserIdentity[] - postGenerationJobs PostGenerationJob[] - ownedTeams Team[] @relation("TeamOwner") - teamMemberships TeamMember[] - teamInvitesSent TeamInvite[] @relation("TeamInviteSender") - approvalAssignments ApprovalRequest[] @relation("ApprovalAssignee") - approvalRequestsSent ApprovalRequest[] @relation("ApprovalRequester") - contentAutomations PageContentAutomation[] + memberships PageMember[] + postsCreated Post[] @relation("PostCreatedBy") + postsEdited Post[] @relation("PostLastEditedBy") + approvals PostApproval[] + auditLogs AuditLog[] + metaConnections MetaConnection[] + analyses PageAnalysis[] + identities UserIdentity[] + postGenerationJobs PostGenerationJob[] + ownedTeams Team[] @relation("TeamOwner") + teamMemberships TeamMember[] + teamInvitesSent TeamInvite[] @relation("TeamInviteSender") + approvalAssignments ApprovalRequest[] @relation("ApprovalAssignee") + approvalRequestsSent ApprovalRequest[] @relation("ApprovalRequester") + contentAutomations PageContentAutomation[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -158,17 +158,17 @@ model Page { webhookSubscribedAt DateTime? tokenCheckedAt DateTime? - members PageMember[] - posts Post[] - rules ReplyRule[] - conversations Conversation[] - insights PageInsightSnapshot[] - auditLogs AuditLog[] - analyses PageAnalysis[] - profile PageProfile? - aiUsage AiUsage[] - generationJobs PostGenerationJob[] - teamPage TeamPage? + members PageMember[] + posts Post[] + rules ReplyRule[] + conversations Conversation[] + insights PageInsightSnapshot[] + auditLogs AuditLog[] + analyses PageAnalysis[] + profile PageProfile? + aiUsage AiUsage[] + generationJobs PostGenerationJob[] + teamPage TeamPage? contentAutomation PageContentAutomation? inboxAiAutomation PageInboxAiAutomation? @@ -225,10 +225,10 @@ model Post { lastEditedBy User? @relation("PostLastEditedBy", fields: [lastEditedById], references: [id]) lastEditedAt DateTime? - approvals PostApproval[] - insights PostInsightSnapshot[] - auditLogs AuditLog[] - generationJob PostGenerationJob? + approvals PostApproval[] + insights PostInsightSnapshot[] + auditLogs AuditLog[] + generationJob PostGenerationJob? approvalRequest ApprovalRequest? createdAt DateTime @default(now()) @@ -239,15 +239,15 @@ model Post { } model Team { - id String @id @default(cuid()) + id String @id @default(cuid()) name String ownerId String - owner User @relation("TeamOwner", fields: [ownerId], references: [id], onDelete: Restrict) + owner User @relation("TeamOwner", fields: [ownerId], references: [id], onDelete: Restrict) members TeamMember[] pages TeamPage[] invites TeamInvite[] - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt } model TeamMember { @@ -265,11 +265,11 @@ model TeamMember { // A Page belongs to at most one team. PageMember remains the page permission source. model TeamPage { - id String @id @default(cuid()) + id String @id @default(cuid()) teamId String - team Team @relation(fields: [teamId], references: [id], onDelete: Cascade) - pageId String @unique - page Page @relation(fields: [pageId], references: [id], onDelete: Cascade) + team Team @relation(fields: [teamId], references: [id], onDelete: Cascade) + pageId String @unique + page Page @relation(fields: [pageId], references: [id], onDelete: Cascade) createdAt DateTime @default(now()) @@index([teamId]) @@ -365,28 +365,28 @@ model Conversation { // Per-page AI sales assistant. Message bodies remain live in Graph and are // never persisted here; only configuration and source-message dedupe are kept. model PageInboxAiAutomation { - id String @id @default(cuid()) - pageId String @unique - page Page @relation(fields: [pageId], references: [id], onDelete: Cascade) - enabled Boolean @default(false) - personaName String @default("แอดมินพิม") - salesGoal String @default("") - instructions String @default("") - updatedById String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + id String @id @default(cuid()) + pageId String @unique + page Page @relation(fields: [pageId], references: [id], onDelete: Cascade) + enabled Boolean @default(false) + personaName String @default("แอดมินพิม") + salesGoal String @default("") + instructions String @default("") + updatedById String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt replies InboxAiReply[] } model InboxAiReply { - id String @id @default(cuid()) + id String @id @default(cuid()) automationId String - automation PageInboxAiAutomation @relation(fields: [automationId], references: [id], onDelete: Cascade) - sourceId String @unique + automation PageInboxAiAutomation @relation(fields: [automationId], references: [id], onDelete: Cascade) + sourceId String @unique recipientId String outcome String - createdAt DateTime @default(now()) + createdAt DateTime @default(now()) @@index([automationId, createdAt]) } @@ -485,18 +485,18 @@ model PageAnalysis { // Shop facts and voice the AI assistant writes from. One per page. model PageProfile { - id String @id @default(cuid()) - pageId String @unique - page Page @relation(fields: [pageId], references: [id], onDelete: Cascade) - business String - audience String @default("") - tone String @default("") - visualStyle String @default("") - website String @default("") - avoid String @default("") - cta String @default("") - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + id String @id @default(cuid()) + pageId String @unique + page Page @relation(fields: [pageId], references: [id], onDelete: Cascade) + business String + audience String @default("") + tone String @default("") + visualStyle String @default("") + website String @default("") + avoid String @default("") + cta String @default("") + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt } // One row per successful AI call — the per-page daily limit counts these. @@ -523,25 +523,35 @@ enum PostGenerationStatus { // 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 + 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) + scheduleMode ContentScheduleMode @default(FIXED) + weekdays Int[] @default([1, 2, 3, 4, 5]) + times String[] @default(["09:00"]) + randomPostsPerDay Int @default(1) + articlePercent Int @default(40) + knowledgePercent Int @default(40) + salesPercent Int @default(20) + brief String @default("") + targets Platform[] @default([FACEBOOK]) + nextRunAt DateTime? + lastQueuedAt DateTime? + lastError String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt @@index([enabled, nextRunAt]) } +enum ContentScheduleMode { + FIXED + RANDOM +} + // Durable creation queue. The output is always a draft and never a published post. model PostGenerationJob { id String @id @default(cuid()) diff --git a/src/app/(console)/page.tsx b/src/app/(console)/page.tsx index 7e8fa88..c2d33fb 100644 --- a/src/app/(console)/page.tsx +++ b/src/app/(console)/page.tsx @@ -7,6 +7,7 @@ import { Icon } from "@/components/Icon"; import { WeekBoard } from "@/components/WeekBoard"; import { WeekPlanAssistant } from "@/components/WeekPlanAssistant"; import { roleAtLeast } from "@/lib/auth/roles"; +import { ContentAutoLauncher } from "@/components/ContentAutoLauncher"; export default async function OverviewPage(props: PageProps<"/">) { const ctx = await getConsoleContext(); @@ -39,7 +40,7 @@ export default async function OverviewPage(props: PageProps<"/">) { 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 ? สร้างโพสต์ : undefined} /> + 0 ? <>{planFor && } สร้างโพสต์ : 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 d2d9c8e..3e8dc54 100644 --- a/src/app/api/ai/content-auto/route.ts +++ b/src/app/api/ai/content-auto/route.ts @@ -10,10 +10,17 @@ import { nextContentRun } from "@/lib/ai/auto-schedule"; const Input = z.object({ enabled: z.boolean(), + scheduleMode: z.enum(["FIXED", "RANDOM"]), 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), + randomPostsPerDay: z.number().int().min(1).max(3), + articlePercent: z.number().int().min(0).max(100), + knowledgePercent: z.number().int().min(0).max(100), + salesPercent: z.number().int().min(0).max(100), brief: z.string().trim().max(1000), targets: z.array(z.enum(["FACEBOOK", "INSTAGRAM"])).min(1).max(2), +}).refine((data) => data.articlePercent + data.knowledgePercent + data.salesPercent === 100, { + message: "สัดส่วนเนื้อหาต้องรวมกันเท่ากับ 100%", }); export async function GET(req: Request) { @@ -33,7 +40,7 @@ export async function PUT(req: Request) { if (!auth.ok) return auth.response; try { const parsed = Input.safeParse(body); - if (!parsed.success) throw new UserFacingError("เลือกวัน เวลาไม่เกิน 3 ช่วง และช่องทางให้ครบ แนวเนื้อหาไม่เกิน 1,000 ตัวอักษร"); + if (!parsed.success) throw new UserFacingError(parsed.error.issues[0]?.message || "ตรวจวัน เวลา และช่องทางให้ครบ"); 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}`}))`; @@ -44,7 +51,10 @@ export async function PUT(req: Request) { 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 data = { ...input, requestedById: auth.user.id, nextRunAt: input.enabled ? nextContentRun({ + weekdays: input.weekdays, times: input.times, mode: input.scheduleMode, + randomPostsPerDay: input.randomPostsPerDay, seed: pageId, + }) : 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 } }); @@ -53,7 +63,7 @@ export async function PUT(req: Request) { 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); + await audit({ action: input.enabled ? "CONTENT_AUTO_ENABLED" : "CONTENT_AUTO_DISABLED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, detail: { scheduleMode: input.scheduleMode, weekdays: input.weekdays, times: input.times, randomPostsPerDay: input.randomPostsPerDay, contentMix: { article: input.articlePercent, knowledge: input.knowledgePercent, sales: input.salesPercent }, targets: input.targets } }, tx); return saved; }); return NextResponse.json({ automation }); diff --git a/src/app/api/ai/image/route.ts b/src/app/api/ai/image/route.ts index 2ed9f30..c8ffa67 100644 --- a/src/app/api/ai/image/route.ts +++ b/src/app/api/ai/image/route.ts @@ -26,7 +26,8 @@ const SYSTEM = `You write prompts for an AI image generator. The images illustra - Ask for no text, lettering, logos, watermarks or brand names inside the image (image models spell Thai badly; the caption carries the words). - No identifiable real people, celebrities or copyrighted characters. If people appear, keep them generic. - No before/after imagery and no exaggerated results (cures, guaranteed outcomes). -- Follow "สีและสไตล์ภาพของแบรนด์" exactly when supplied, especially its palette, medium, lighting and exclusions. Match the shop's tone and audience through the visual mood.`; +- Follow "สีและสไตล์ภาพของแบรนด์" exactly when supplied, especially its palette, medium, lighting and exclusions. Match the shop's tone and audience through the visual mood. +- When the shop operates in Thailand or targets Thai customers, ground the scene in Thailand: a Thai neighbourhood, local market, Thai-style home interior, tropical garden, wooden shophouse, or Southeast Asian textures and colour palette — so Thai viewers see something familiar and credible. Apply this only where it fits the product or service naturally; a tech or B2B brand may still prefer a neutral modern setting.`; const IMAGE_SYSTEM = `${SYSTEM}\n${IMAGE_ART_DIRECTION}`; /** diff --git a/src/components/ContentAutoForm.tsx b/src/components/ContentAutoForm.tsx index e88dfde..242ef72 100644 --- a/src/components/ContentAutoForm.tsx +++ b/src/components/ContentAutoForm.tsx @@ -5,15 +5,17 @@ import { withBase } from "@/lib/base-path"; import { Notice } from "./ui"; type Settings = { - enabled: boolean; weekdays: number[]; times: string[]; brief: string; + enabled: boolean; scheduleMode: "FIXED" | "RANDOM"; weekdays: number[]; times: string[]; + randomPostsPerDay: number; articlePercent: number; knowledgePercent: number; salesPercent: number; 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" }); +const DEFAULT_SETTINGS: Settings = { enabled: false, scheduleMode: "FIXED", weekdays: [1, 2, 3, 4, 5], times: ["09:00"], randomPostsPerDay: 1, articlePercent: 40, knowledgePercent: 40, salesPercent: 20, brief: "", targets: ["FACEBOOK"], nextRunAt: null, lastQueuedAt: null, lastError: null }; 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 [settings, setSettings] = useState(DEFAULT_SETTINGS); const [loaded, setLoaded] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); @@ -25,7 +27,7 @@ export function ContentAutoForm({ pageId }: { pageId: string }) { 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); + if (data.automation) setSettings({ ...DEFAULT_SETTINGS, ...data.automation }); setLoaded(true); } catch (failure) { if (!controller.signal.aborted) setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้"); @@ -34,8 +36,13 @@ export function ContentAutoForm({ pageId }: { pageId: string }) { return () => controller.abort(); }, [pageId]); - async function save() { + const mixTotal = settings.articlePercent + settings.knowledgePercent + settings.salesPercent; + + async function save(event: React.FormEvent) { + event.preventDefault(); if (!loaded || busy) return; + if (mixTotal !== 100) { setError(`สัดส่วนเนื้อหารวม ${mixTotal}% ต้องปรับให้ครบ 100%`); return; } + if (settings.weekdays.length === 0 || settings.targets.length === 0) { setError("เลือกวันและช่องทางอย่างน้อย 1 รายการ"); 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 }) }); @@ -47,33 +54,37 @@ export function ContentAutoForm({ pageId }: { pageId: string }) { finally { setBusy(false); } } - return
-

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

-

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

-
- -
- วันสร้างเนื้อหา (เวลาไทย) - {DAYS.map((label, day) => )} + return
+

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

AI จะสร้างโพสต์เป็นฉบับร่างตามแผน ทุกชิ้นยังต้องผ่านการอนุมัติก่อนเผยแพร่

+
+
+ + +
1. เลือกวันที่ต้องการโพสต์
+ {DAYS.map((label, day) => )} +
+ +
2. กำหนดเวลา
+ {(["FIXED", "RANDOM"] as const).map((mode) => )} +
+ + {settings.scheduleMode === "FIXED" ?
+ {settings.times.map((time, index) =>
{settings.times.length > 1 && }
)} + {settings.times.length < 3 && } +
: } + +
3. แบ่งสัดส่วนเนื้อหา

ทั้ง 3 ประเภทผสมกันได้ และต้องรวมครบ 100%

+ {([{ key: "articlePercent", label: "บทความ", hint: "เล่าเรื่องเชิงลึก" }, { key: "knowledgePercent", label: "ความรู้ทั่วไป", hint: "เคล็ดลับที่นำไปใช้ได้" }, { key: "salesPercent", label: "ปิดงานขาย", hint: "เสนอสินค้าและชวนตัดสินใจ" }] as const).map((item) => )} +
{mixTotal === 100 ? "สัดส่วนพร้อมใช้งาน" : "ยังแบ่งสัดส่วนไม่ครบ"}{mixTotal} / 100%
{mixTotal !== 100 &&

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

}
+ +