Add automated content planning and image overlays

This commit is contained in:
Loma Bot Ops
2026-11-27 08:48:41 +07:00
parent bb840a54ff
commit 1d3bd3e7cd
10 changed files with 411 additions and 133 deletions
@@ -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;
+89 -79
View File
@@ -77,21 +77,21 @@ model User {
mustChangePassword Boolean @default(false) mustChangePassword Boolean @default(false)
lastLoginAt DateTime? lastLoginAt DateTime?
memberships PageMember[] memberships PageMember[]
postsCreated Post[] @relation("PostCreatedBy") postsCreated Post[] @relation("PostCreatedBy")
postsEdited Post[] @relation("PostLastEditedBy") postsEdited Post[] @relation("PostLastEditedBy")
approvals PostApproval[] approvals PostApproval[]
auditLogs AuditLog[] auditLogs AuditLog[]
metaConnections MetaConnection[] metaConnections MetaConnection[]
analyses PageAnalysis[] analyses PageAnalysis[]
identities UserIdentity[] identities UserIdentity[]
postGenerationJobs PostGenerationJob[] postGenerationJobs PostGenerationJob[]
ownedTeams Team[] @relation("TeamOwner") ownedTeams Team[] @relation("TeamOwner")
teamMemberships TeamMember[] teamMemberships TeamMember[]
teamInvitesSent TeamInvite[] @relation("TeamInviteSender") teamInvitesSent TeamInvite[] @relation("TeamInviteSender")
approvalAssignments ApprovalRequest[] @relation("ApprovalAssignee") approvalAssignments ApprovalRequest[] @relation("ApprovalAssignee")
approvalRequestsSent ApprovalRequest[] @relation("ApprovalRequester") approvalRequestsSent ApprovalRequest[] @relation("ApprovalRequester")
contentAutomations PageContentAutomation[] contentAutomations PageContentAutomation[]
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@ -158,17 +158,17 @@ model Page {
webhookSubscribedAt DateTime? webhookSubscribedAt DateTime?
tokenCheckedAt DateTime? tokenCheckedAt DateTime?
members PageMember[] members PageMember[]
posts Post[] posts Post[]
rules ReplyRule[] rules ReplyRule[]
conversations Conversation[] conversations Conversation[]
insights PageInsightSnapshot[] insights PageInsightSnapshot[]
auditLogs AuditLog[] auditLogs AuditLog[]
analyses PageAnalysis[] analyses PageAnalysis[]
profile PageProfile? profile PageProfile?
aiUsage AiUsage[] aiUsage AiUsage[]
generationJobs PostGenerationJob[] generationJobs PostGenerationJob[]
teamPage TeamPage? teamPage TeamPage?
contentAutomation PageContentAutomation? contentAutomation PageContentAutomation?
inboxAiAutomation PageInboxAiAutomation? inboxAiAutomation PageInboxAiAutomation?
@@ -225,10 +225,10 @@ model Post {
lastEditedBy User? @relation("PostLastEditedBy", fields: [lastEditedById], references: [id]) lastEditedBy User? @relation("PostLastEditedBy", fields: [lastEditedById], references: [id])
lastEditedAt DateTime? lastEditedAt DateTime?
approvals PostApproval[] approvals PostApproval[]
insights PostInsightSnapshot[] insights PostInsightSnapshot[]
auditLogs AuditLog[] auditLogs AuditLog[]
generationJob PostGenerationJob? generationJob PostGenerationJob?
approvalRequest ApprovalRequest? approvalRequest ApprovalRequest?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
@@ -239,15 +239,15 @@ model Post {
} }
model Team { model Team {
id String @id @default(cuid()) id String @id @default(cuid())
name String name String
ownerId 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[] members TeamMember[]
pages TeamPage[] pages TeamPage[]
invites TeamInvite[] invites TeamInvite[]
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
} }
model TeamMember { model TeamMember {
@@ -265,11 +265,11 @@ model TeamMember {
// A Page belongs to at most one team. PageMember remains the page permission source. // A Page belongs to at most one team. PageMember remains the page permission source.
model TeamPage { model TeamPage {
id String @id @default(cuid()) id String @id @default(cuid())
teamId String teamId String
team Team @relation(fields: [teamId], references: [id], onDelete: Cascade) team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
pageId String @unique pageId String @unique
page Page @relation(fields: [pageId], references: [id], onDelete: Cascade) page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now()) createdAt DateTime @default(now())
@@index([teamId]) @@index([teamId])
@@ -365,28 +365,28 @@ model Conversation {
// Per-page AI sales assistant. Message bodies remain live in Graph and are // Per-page AI sales assistant. Message bodies remain live in Graph and are
// never persisted here; only configuration and source-message dedupe are kept. // never persisted here; only configuration and source-message dedupe are kept.
model PageInboxAiAutomation { model PageInboxAiAutomation {
id String @id @default(cuid()) id String @id @default(cuid())
pageId String @unique pageId String @unique
page Page @relation(fields: [pageId], references: [id], onDelete: Cascade) page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
enabled Boolean @default(false) enabled Boolean @default(false)
personaName String @default("แอดมินพิม") personaName String @default("แอดมินพิม")
salesGoal String @default("") salesGoal String @default("")
instructions String @default("") instructions String @default("")
updatedById String? updatedById String?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
replies InboxAiReply[] replies InboxAiReply[]
} }
model InboxAiReply { model InboxAiReply {
id String @id @default(cuid()) id String @id @default(cuid())
automationId String automationId String
automation PageInboxAiAutomation @relation(fields: [automationId], references: [id], onDelete: Cascade) automation PageInboxAiAutomation @relation(fields: [automationId], references: [id], onDelete: Cascade)
sourceId String @unique sourceId String @unique
recipientId String recipientId String
outcome String outcome String
createdAt DateTime @default(now()) createdAt DateTime @default(now())
@@index([automationId, createdAt]) @@index([automationId, createdAt])
} }
@@ -485,18 +485,18 @@ model PageAnalysis {
// Shop facts and voice the AI assistant writes from. One per page. // Shop facts and voice the AI assistant writes from. One per page.
model PageProfile { model PageProfile {
id String @id @default(cuid()) id String @id @default(cuid())
pageId String @unique pageId String @unique
page Page @relation(fields: [pageId], references: [id], onDelete: Cascade) page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
business String business String
audience String @default("") audience String @default("")
tone String @default("") tone String @default("")
visualStyle String @default("") visualStyle String @default("")
website String @default("") website String @default("")
avoid String @default("") avoid String @default("")
cta String @default("") cta String @default("")
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
} }
// One row per successful AI call — the per-page daily limit counts these. // 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. // Recurring draft creation. The existing queue owns content and image generation.
model PageContentAutomation { model PageContentAutomation {
id String @id @default(cuid()) id String @id @default(cuid())
pageId String @unique pageId String @unique
page Page @relation(fields: [pageId], references: [id], onDelete: Cascade) page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
requestedById String requestedById String
requestedBy User @relation(fields: [requestedById], references: [id], onDelete: Restrict) requestedBy User @relation(fields: [requestedById], references: [id], onDelete: Restrict)
enabled Boolean @default(false) enabled Boolean @default(false)
weekdays Int[] @default([1, 2, 3, 4, 5]) scheduleMode ContentScheduleMode @default(FIXED)
times String[] @default(["09:00"]) weekdays Int[] @default([1, 2, 3, 4, 5])
brief String @default("") times String[] @default(["09:00"])
targets Platform[] @default([FACEBOOK]) randomPostsPerDay Int @default(1)
nextRunAt DateTime? articlePercent Int @default(40)
lastQueuedAt DateTime? knowledgePercent Int @default(40)
lastError String? salesPercent Int @default(20)
createdAt DateTime @default(now()) brief String @default("")
updatedAt DateTime @updatedAt targets Platform[] @default([FACEBOOK])
nextRunAt DateTime?
lastQueuedAt DateTime?
lastError String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([enabled, nextRunAt]) @@index([enabled, nextRunAt])
} }
enum ContentScheduleMode {
FIXED
RANDOM
}
// Durable creation queue. The output is always a draft and never a published post. // Durable creation queue. The output is always a draft and never a published post.
model PostGenerationJob { model PostGenerationJob {
id String @id @default(cuid()) id String @id @default(cuid())
+2 -1
View File
@@ -7,6 +7,7 @@ import { Icon } from "@/components/Icon";
import { WeekBoard } from "@/components/WeekBoard"; import { WeekBoard } from "@/components/WeekBoard";
import { WeekPlanAssistant } from "@/components/WeekPlanAssistant"; import { WeekPlanAssistant } from "@/components/WeekPlanAssistant";
import { roleAtLeast } from "@/lib/auth/roles"; import { roleAtLeast } from "@/lib/auth/roles";
import { ContentAutoLauncher } from "@/components/ContentAutoLauncher";
export default async function OverviewPage(props: PageProps<"/">) { export default async function OverviewPage(props: PageProps<"/">) {
const ctx = await getConsoleContext(); 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 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; const planFor = ctx.selected && editable.includes(ctx.selected.id) && openDays > 0 ? ctx.selected : null;
return <> return <>
<PageTitle title="แผนคอนเทนต์" subtitle={ctx.selected ? `จัดคิวโพสต์ของ ${ctx.selected.name}` : "ทุกไอเดีย ทุกเพจ ในแผนเดียว · เวลาไทย"} actions={editable.length > 0 ? <Link href="/posts/new" className="btn btn-primary"><Icon name="plus" /> สร้างโพสต์</Link> : undefined} /> <PageTitle title="แผนคอนเทนต์" subtitle={ctx.selected ? `จัดคิวโพสต์ของ ${ctx.selected.name}` : "ทุกไอเดีย ทุกเพจ ในแผนเดียว · เวลาไทย"} actions={editable.length > 0 ? <>{planFor && <ContentAutoLauncher pageId={planFor.id} />}<Link href="/posts/new" className="btn btn-primary"><Icon name="plus" /> สร้างโพสต์</Link></> : undefined} />
<div className="flex flex-wrap items-center gap-3 text-[12px] text-ink-3"> <div className="flex flex-wrap items-center gap-3 text-[12px] text-ink-3">
<span>{posts.length} โพสต์ในสัปดาห์นี้</span><span className="w-1 h-1 bg-line rounded-full" /><span>{tray.length}{tray.length === 50 ? "+" : ""} โพสต์ยังไม่วางวัน</span> <span>{posts.length} โพสต์ในสัปดาห์นี้</span><span className="w-1 h-1 bg-line rounded-full" /><span>{tray.length}{tray.length === 50 ? "+" : ""} โพสต์ยังไม่วางวัน</span>
{pending > 0 && <Link href="/posts?status=PENDING_APPROVAL" className="pill pill-amber">รออนุมัติ {pending}</Link>} {pending > 0 && <Link href="/posts?status=PENDING_APPROVAL" className="pill pill-amber">รออนุมัติ {pending}</Link>}
+13 -3
View File
@@ -10,10 +10,17 @@ import { nextContentRun } from "@/lib/ai/auto-schedule";
const Input = z.object({ const Input = z.object({
enabled: z.boolean(), enabled: z.boolean(),
scheduleMode: z.enum(["FIXED", "RANDOM"]),
weekdays: z.array(z.number().int().min(0).max(6)).min(1).max(7), 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), 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), brief: z.string().trim().max(1000),
targets: z.array(z.enum(["FACEBOOK", "INSTAGRAM"])).min(1).max(2), 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) { export async function GET(req: Request) {
@@ -33,7 +40,7 @@ export async function PUT(req: Request) {
if (!auth.ok) return auth.response; if (!auth.ok) return auth.response;
try { try {
const parsed = Input.safeParse(body); 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 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) => { const automation = await prisma.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai-post:${pageId}`}))`; 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 (!page.profile?.business.trim()) throw new UserFacingError("ตั้งค่าโปรไฟล์ร้านก่อนเปิด auto");
if (input.targets.includes("INSTAGRAM") && !page.igUserId) throw new UserFacingError("เพจนี้ยังไม่ได้ผูก Instagram"); 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 }); const saved = await tx.pageContentAutomation.upsert({ where: { pageId }, create: { pageId, ...data }, update: data, select: AUTOMATION_SELECT });
if (!input.enabled) { 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", 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); 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 saved;
}); });
return NextResponse.json({ automation }); return NextResponse.json({ automation });
+2 -1
View File
@@ -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). - 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 identifiable real people, celebrities or copyrighted characters. If people appear, keep them generic.
- No before/after imagery and no exaggerated results (cures, guaranteed outcomes). - 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}`; const IMAGE_SYSTEM = `${SYSTEM}\n${IMAGE_ART_DIRECTION}`;
/** /**
+41 -30
View File
@@ -5,15 +5,17 @@ import { withBase } from "@/lib/base-path";
import { Notice } from "./ui"; import { Notice } from "./ui";
type Settings = { 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")[]; targets: ("FACEBOOK" | "INSTAGRAM")[];
nextRunAt: string | null; lastQueuedAt: string | null; lastError: string | null; nextRunAt: string | null; lastQueuedAt: string | null; lastError: string | null;
}; };
const DAYS = ["อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส."]; const DAYS = ["อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส."];
const formatTime = (value: string) => new Date(value).toLocaleString("th-TH", { timeZone: "Asia/Bangkok", dateStyle: "medium", timeStyle: "short" }); 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 }) { 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 [settings, setSettings] = useState<Settings>(DEFAULT_SETTINGS);
const [loaded, setLoaded] = useState(false); const [loaded, setLoaded] = useState(false);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [error, setError] = useState(""); 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 response = await fetch(withBase(`/api/ai/content-auto?pageId=${encodeURIComponent(pageId)}`), { signal: controller.signal, cache: "no-store" });
const data = await response.json(); const data = await response.json();
if (!response.ok) throw new Error(data.error || "โหลดการตั้งค่า auto ไม่สำเร็จ"); 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); setLoaded(true);
} catch (failure) { } catch (failure) {
if (!controller.signal.aborted) setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้"); if (!controller.signal.aborted) setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้");
@@ -34,8 +36,13 @@ export function ContentAutoForm({ pageId }: { pageId: string }) {
return () => controller.abort(); return () => controller.abort();
}, [pageId]); }, [pageId]);
async function save() { const mixTotal = settings.articlePercent + settings.knowledgePercent + settings.salesPercent;
async function save(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!loaded || busy) return; 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(""); setBusy(true); setError(""); setMessage("");
try { try {
const response = await fetch(withBase("/api/ai/content-auto"), { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, ...settings }) }); 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); } finally { setBusy(false); }
} }
return <section className="border border-line rounded-xl p-4 flex flex-col gap-3 bg-paper" aria-label="สร้างเนื้อหาอัตโนมัติ"> return <section className="flex flex-col gap-4" aria-label="วางเนื้อหาอัตโนมัติ">
<h3 className="font-semibold text-[15px]">โหมด auto สร้างเนื้อหา</h3> <div><h3 className="font-semibold text-[18px]">วางเนื้อหาอัตโนมัติ</h3><p className="text-[13px] text-ink-2 mt-1">AI จะสร้างโพสต์เป็นฉบับร่างตามแผน ทุกชิ้นยังต้องผ่านการอนุมัติก่อนเผยแพร่</p></div>
<p className="text-[13px] text-ink-2">เลือกวันและเวลา ให้ AI คิดหัวข้อจากข้อมูลร้าน เขียนเนื้อหาและสร้างภาพ บันทึกเป็นฉบับร่างรออนุมัติ ปิดหน้าเว็บได้</p> <form onSubmit={save} noValidate className="flex flex-col gap-5">
<fieldset disabled={!loaded || busy} className="flex flex-col gap-3"> <fieldset disabled={!loaded || busy} className="contents">
<label className="flex items-center gap-2 text-[14px] font-medium"> <label className="flex items-start gap-3 rounded-xl border border-line bg-blue-soft p-3 text-[14px] font-medium cursor-pointer">
<input type="checkbox" role="switch" checked={settings.enabled} onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })} /> เปิดสร้างอัตโนมัติสำหรับเพจนี้ <input className="mt-0.5" type="checkbox" checked={settings.enabled} onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })} />
</label> <span><b className="block">เปิดใช้สำหรับเพจนี้</b><span className="text-[12px] text-ink-2 font-normal">ระบบทำงานตามแผนได้แม้ปิดหน้าเว็บ</span></span>
<fieldset className="flex flex-wrap gap-3"> </label>
<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"> <fieldset><legend className="font-semibold text-[14px] mb-2">1. เลือกวันที่ต้องการโพสต์</legend><div className="grid grid-cols-4 sm:grid-cols-7 gap-2">
<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} {DAYS.map((label, day) => <label key={day} className={`min-h-10 rounded-lg border grid place-items-center text-[13px] cursor-pointer ${settings.weekdays.includes(day) ? "border-blue bg-blue-soft text-blue-ink font-semibold" : "border-line bg-paper text-ink-2"}`}><input className="sr-only" 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>)}
</label>)} </div></fieldset>
<fieldset><legend className="font-semibold text-[14px] mb-2">2. กำหนดเวลา</legend><div className="grid sm:grid-cols-2 gap-2">
{(["FIXED", "RANDOM"] as const).map((mode) => <label key={mode} className={`rounded-xl border p-3 flex gap-2 cursor-pointer ${settings.scheduleMode === mode ? "border-blue bg-blue-soft" : "border-line"}`}><input type="radio" name="scheduleMode" value={mode} checked={settings.scheduleMode === mode} onChange={() => setSettings({ ...settings, scheduleMode: mode })} /><span><b className="block text-[13px]">{mode === "FIXED" ? "ระบุเวลาเอง" : "สุ่มเวลา"}</b><span className="text-[12px] text-ink-2">{mode === "FIXED" ? "เลือกเวลาแต่ละรอบได้ตรง ๆ" : "สุ่มช่วง 08:00–20:00 น."}</span></span></label>)}
</div></fieldset>
{settings.scheduleMode === "FIXED" ? <div className="flex flex-col gap-2">
{settings.times.map((time, index) => <div key={index} className="flex items-end gap-2"><label className="field flex-1"><span>เวลารอบที่ {index + 1}</span><input className="input num" 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" 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"] })}>เพิ่มรอบต่อวัน</button>}
</div> : <label className="field max-w-48"><span>จำนวนรอบต่อวัน</span><input className="input num" type="number" min={1} max={3} value={settings.randomPostsPerDay} onChange={(e) => setSettings({ ...settings, randomPostsPerDay: Number(e.target.value) })} /></label>}
<fieldset aria-describedby="content-mix-hint content-mix-error"><legend className="font-semibold text-[14px]">3. แบ่งสัดส่วนเนื้อหา</legend><p id="content-mix-hint" className="text-[12px] text-ink-2 mt-1 mb-3">ทั้ง 3 ประเภทผสมกันได้ และต้องรวมครบ 100%</p><div className="grid sm:grid-cols-3 gap-3">
{([{ key: "articlePercent", label: "บทความ", hint: "เล่าเรื่องเชิงลึก" }, { key: "knowledgePercent", label: "ความรู้ทั่วไป", hint: "เคล็ดลับที่นำไปใช้ได้" }, { key: "salesPercent", label: "ปิดงานขาย", hint: "เสนอสินค้าและชวนตัดสินใจ" }] as const).map((item) => <label key={item.key} className="field rounded-xl border border-line p-3"><span>{item.label}</span><small className="text-[11px] text-ink-3">{item.hint}</small><div className="flex items-center gap-2"><input className="input num" type="number" inputMode="numeric" min={0} max={100} step={5} value={settings[item.key]} aria-invalid={mixTotal !== 100} onChange={(e) => setSettings({ ...settings, [item.key]: Number(e.target.value) })} /><b className="text-[13px]">%</b></div></label>)}
</div><div className={`mt-3 rounded-lg px-3 py-2 text-[13px] flex justify-between ${mixTotal === 100 ? "bg-green-soft text-green-ink" : "bg-red-soft text-danger-ink"}`}><span>{mixTotal === 100 ? "สัดส่วนพร้อมใช้งาน" : "ยังแบ่งสัดส่วนไม่ครบ"}</span><b className="num">{mixTotal} / 100%</b></div>{mixTotal !== 100 && <p id="content-mix-error" className="text-[12px] text-danger-ink mt-1">ปรับตัวเลขให้ผลรวมเท่ากับ 100%</p>}</fieldset>
<label className="field"><span>คำแนะนำเพิ่มเติม (ไม่บังคับ)</span><textarea className="textarea" rows={2} value={settings.brief} onChange={(e) => setSettings({ ...settings, brief: e.target.value })} placeholder="เช่น เน้นสินค้ากลุ่มใหม่ ใช้น้ำเสียงเป็นกันเอง" /></label>
<fieldset className="text-[13px]"><legend className="font-semibold text-[14px] mb-2">4. ช่องทางของฉบับร่าง</legend><div className="flex flex-wrap gap-4">{(["FACEBOOK", "INSTAGRAM"] as const).map((target) => <label key={target} className="flex items-center gap-2 min-h-10 cursor-pointer"><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>)}</div></fieldset>
<button type="submit" className="btn btn-primary self-start" disabled={!loaded || busy}>{busy ? "กำลังบันทึก…" : "บันทึกแผนอัตโนมัติ"}</button>
</fieldset> </fieldset>
<div className="flex flex-col gap-2"> </form>
{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.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>} {settings.lastQueuedAt && <p className="text-[12px] text-ink-2">เข้าคิวล่าสุด: {formatTime(settings.lastQueuedAt)} · ดูผลในงานล่าสุดด้านล่าง</p>}
<p className="text-[12px] text-ink-2">ต้องเปิด worker และ login บัญชีสร้างภาพไว้ งานเริ่มตามคิว หาก worker หยุดจะรับเพียงรอบล่าสุดเมื่อกลับมา</p> <p className="text-[12px] text-ink-2">ต้องเปิด worker และ login บัญชีสร้างภาพไว้ งานเริ่มตามคิว หาก worker หยุดจะรับเพียงรอบล่าสุดเมื่อกลับมา</p>
+25
View File
@@ -0,0 +1,25 @@
"use client";
import { useEffect, useState } from "react";
import { Icon } from "./Icon";
import { ContentAutoForm } from "./ContentAutoForm";
export function ContentAutoLauncher({ pageId }: { pageId: string }) {
const [open, setOpen] = useState(false);
useEffect(() => {
if (!open) return;
const close = (event: KeyboardEvent) => { if (event.key === "Escape") setOpen(false); };
document.addEventListener("keydown", close);
return () => document.removeEventListener("keydown", close);
}, [open]);
return <>
<button type="button" className="btn btn-on-band" onClick={() => setOpen(true)} aria-haspopup="dialog"><Icon name="sparkle" /> วางเนื้อหาอัตโนมัติ</button>
{open && <div className="fixed inset-0 z-50 bg-ink/35 p-3 sm:p-6 overflow-y-auto" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) setOpen(false); }}>
<section role="dialog" aria-modal="true" aria-labelledby="content-auto-title" className="bg-paper border border-line rounded-2xl shadow-xl w-full max-w-3xl mx-auto my-4 p-4 sm:p-6">
<div className="flex items-center justify-between gap-3 mb-4 pb-3 border-b border-line"><h2 id="content-auto-title" className="font-semibold text-[16px]">ตั้งค่าแผนอัตโนมัติ</h2><button type="button" className="btn btn-ghost btn-sm" onClick={() => setOpen(false)} aria-label="ปิดหน้าต่าง">ปิด</button></div>
<ContentAutoForm pageId={pageId} />
</section>
</div>}
</>;
}
+182 -11
View File
@@ -2,13 +2,100 @@
/* eslint-disable @next/next/no-img-element -- generated image URLs, not optimisable */ /* eslint-disable @next/next/no-img-element -- generated image URLs, not optimisable */
import { withBase } from "@/lib/base-path"; import { withBase } from "@/lib/base-path";
import { useState } from "react"; import { useState, useEffect } from "react";
import Link from "next/link"; import Link from "next/link";
import { Icon } from "./Icon"; import { Icon } from "./Icon";
import { Notice } from "./ui"; import { Notice } from "./ui";
import { IMAGE_PROMPT_MAX, IMAGE_SIZES, type ImageSizeKey } from "@/lib/ai/image-shared"; import { IMAGE_PROMPT_MAX, IMAGE_SIZES, type ImageSizeKey } from "@/lib/ai/image-shared";
// (server-only helpers live in lib/ai/image.ts — never import that file here) // (server-only helpers live in lib/ai/image.ts — never import that file here)
type OverlayPos = "top" | "center" | "bottom";
function wrapText(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string[] {
const lines: string[] = [];
const paragraphs = text.split("\n");
for (const para of paragraphs) {
const words = para.split(" ");
let current = "";
for (const w of words) {
const test = current ? `${current} ${w}` : w;
if (ctx.measureText(test).width > maxWidth && current) {
lines.push(current);
current = w;
} else {
current = test;
}
}
if (current) lines.push(current);
}
return lines;
}
function buildComposite(imgUrl: string, text: string, pos: OverlayPos): Promise<string> {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext("2d");
if (!ctx) { reject(new Error("no canvas context")); return; }
ctx.drawImage(img, 0, 0);
const fontSize = Math.max(28, Math.round(img.naturalHeight * 0.065));
ctx.font = `bold ${fontSize}px 'Sarabun', 'Noto Sans Thai', 'Prompt', sans-serif`;
const maxW = img.naturalWidth * 0.84;
const lines = wrapText(ctx, text.trim(), maxW);
const lineH = fontSize * 1.55;
const pad = fontSize * 1.1;
const zoneH = lines.length * lineH + pad * 2;
let zoneY: number;
if (pos === "top") zoneY = 0;
else if (pos === "bottom") zoneY = img.naturalHeight - zoneH;
else zoneY = (img.naturalHeight - zoneH) / 2;
const grad = ctx.createLinearGradient(0, zoneY, 0, zoneY + zoneH);
if (pos === "top") {
grad.addColorStop(0, "rgba(0,0,0,0.75)");
grad.addColorStop(1, "rgba(0,0,0,0)");
} else if (pos === "bottom") {
grad.addColorStop(0, "rgba(0,0,0,0)");
grad.addColorStop(1, "rgba(0,0,0,0.75)");
} else {
grad.addColorStop(0, "rgba(0,0,0,0)");
grad.addColorStop(0.15, "rgba(0,0,0,0.65)");
grad.addColorStop(0.85, "rgba(0,0,0,0.65)");
grad.addColorStop(1, "rgba(0,0,0,0)");
}
ctx.fillStyle = grad;
ctx.fillRect(0, zoneY, img.naturalWidth, zoneH);
ctx.fillStyle = "#ffffff";
ctx.textAlign = "center";
ctx.shadowColor = "rgba(0,0,0,0.55)";
ctx.shadowBlur = fontSize * 0.28;
ctx.shadowOffsetY = 2;
const textStartY = pos === "top" ? pad + fontSize : zoneY + pad + fontSize;
lines.forEach((line, i) => {
ctx.fillText(line, img.naturalWidth / 2, textStartY + i * lineH);
});
canvas.toBlob(
(blob) => {
if (!blob) { reject(new Error("toBlob failed")); return; }
resolve(URL.createObjectURL(blob));
},
"image/jpeg",
0.93,
);
};
img.onerror = reject;
img.src = imgUrl;
});
}
async function post(body: Record<string, unknown>): Promise<{ ok: true; data: Record<string, unknown> } | { ok: false; error: string }> { async function post(body: Record<string, unknown>): Promise<{ ok: true; data: Record<string, unknown> } | { ok: false; error: string }> {
const res = await fetch(withBase("/api/ai/image"), { const res = await fetch(withBase("/api/ai/image"), {
method: "POST", method: "POST",
@@ -42,9 +129,12 @@ export function ImageAssistant({
const [prompt, setPrompt] = useState(""); const [prompt, setPrompt] = useState("");
const [size, setSize] = useState<ImageSizeKey>("square"); const [size, setSize] = useState<ImageSizeKey>("square");
const [result, setResult] = useState<string | null>(null); const [result, setResult] = useState<string | null>(null);
const [busy, setBusy] = useState<"prompt" | "generate" | null>(null); const [busy, setBusy] = useState<"prompt" | "generate" | "overlay" | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [profileMissing, setProfileMissing] = useState(false); const [profileMissing, setProfileMissing] = useState(false);
const [overlayText, setOverlayText] = useState("");
const [overlayPos, setOverlayPos] = useState<OverlayPos>("bottom");
const [overlayPreview, setOverlayPreview] = useState<string | null>(null);
async function draftPrompt() { async function draftPrompt() {
setBusy("prompt"); setBusy("prompt");
@@ -63,9 +153,56 @@ export function ImageAssistant({
const r = await post({ action: "generate", pageId, prompt, size }); const r = await post({ action: "generate", pageId, prompt, size });
setBusy(null); setBusy(null);
if (!r.ok) return setError(r.error); if (!r.ok) return setError(r.error);
setOverlayText("");
setOverlayPreview(null);
setResult(String(r.data.url ?? "")); setResult(String(r.data.url ?? ""));
} }
useEffect(() => {
if (!result || !overlayText.trim()) return;
let cancelled = false;
buildComposite(result, overlayText, overlayPos)
.then((url) => {
if (!cancelled) setOverlayPreview((prev) => { if (prev) URL.revokeObjectURL(prev); return url; });
})
.catch(() => {});
return () => { cancelled = true; };
}, [result, overlayText, overlayPos]);
async function handleUse() {
if (!result) return;
if (hasImage && !window.confirm("แทนที่รูปเดิมของโพสต์ด้วยรูปนี้?")) return;
if (!overlayText.trim()) {
onUse(result);
setResult(null);
setOpen(false);
return;
}
setBusy("overlay");
setError(null);
try {
const compositeUrl = overlayPreview ?? await buildComposite(result, overlayText, overlayPos);
const resp = await fetch(compositeUrl);
const blob = await resp.blob();
const file = new File([blob], "ai-image-overlay.jpg", { type: "image/jpeg" });
const form = new FormData();
form.append("pageId", pageId);
form.append("file", file);
const uploadRes = await fetch(withBase("/api/upload"), { method: "POST", body: form });
const data: Record<string, unknown> = await uploadRes.json().catch(() => ({}));
if (!uploadRes.ok) throw new Error(typeof data.error === "string" ? data.error : "อัปโหลดไม่สำเร็จ");
onUse(String(data.url));
setResult(null);
setOpen(false);
} catch (e) {
setError(e instanceof Error ? e.message : "เพิ่มข้อความบนรูปไม่สำเร็จ ลองใหม่");
} finally {
setBusy(null);
}
}
if (!open) { if (!open) {
return ( return (
<button <button
@@ -142,22 +279,56 @@ export function ImageAssistant({
{result && ( {result && (
<div className="rounded-[10px] border border-line bg-paper p-2 flex flex-col gap-2"> <div className="rounded-[10px] border border-line bg-paper p-2 flex flex-col gap-2">
<img src={result} alt="รูปที่ AI สร้าง" className="w-full max-h-[320px] object-contain rounded-[6px] bg-board" /> <img
src={(overlayText.trim() && overlayPreview) ? overlayPreview : result ?? undefined}
alt="รูปที่ AI สร้าง"
className="w-full max-h-[320px] object-contain rounded-[6px] bg-board"
/>
{/* text overlay controls */}
<div className="flex flex-col gap-2 pt-1">
<label className="field">
<span className="text-[12px]">ข้อความบนภาพ <span className="text-ink-4">(ไม่บังคับ)</span></span>
<textarea
className="textarea text-[13px]"
rows={2}
maxLength={120}
disabled={busy !== null}
placeholder="เช่น โปรพิเศษวันนี้เท่านั้น!"
value={overlayText}
onChange={(e) => setOverlayText(e.target.value)}
/>
</label>
{overlayText.trim() && (
<div className="flex gap-1.5 flex-wrap">
<span className="text-[12px] text-ink-3 self-center">ตำแหน่ง:</span>
{(["top", "center", "bottom"] as OverlayPos[]).map((p) => (
<button
key={p}
type="button"
className="chip"
aria-pressed={overlayPos === p}
disabled={busy !== null}
onClick={() => setOverlayPos(p)}
>
{p === "top" ? "บน" : p === "center" ? "กลาง" : "ล่าง"}
</button>
))}
</div>
)}
</div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<button <button
type="button" type="button"
className="btn btn-primary btn-sm" className="btn btn-primary btn-sm"
disabled={busy !== null} disabled={busy !== null}
onClick={() => { onClick={handleUse}
if (hasImage && !window.confirm("แทนที่รูปเดิมของโพสต์ด้วยรูปนี้?")) return;
onUse(result);
setResult(null);
setOpen(false);
}}
> >
<Icon name="check" size={14} /> ใช้รูปนี้ <Icon name="check" size={14} />
{busy === "overlay" ? "กำลังบันทึก…" : "ใช้รูปนี้"}
</button> </button>
<button type="button" className="btn btn-ghost btn-sm" disabled={busy !== null} onClick={() => setResult(null)}> <button type="button" className="btn btn-ghost btn-sm" disabled={busy !== null} onClick={() => { setResult(null); setOverlayPreview(null); setOverlayText(""); }}>
ทิ้ง ทิ้ง
</button> </button>
</div> </div>
+31 -4
View File
@@ -1,13 +1,40 @@
type Schedule = {
weekdays: number[];
times: string[];
mode?: "FIXED" | "RANDOM";
randomPostsPerDay?: number;
seed?: string;
};
function seededMinutes(seed: string, count: number): number[] {
let state = 2166136261;
for (const char of seed) state = Math.imul(state ^ char.charCodeAt(0), 16777619) >>> 0;
const slots = new Set<number>();
while (slots.size < count) {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
// 08:00–20:00, snapped to 5-minute increments for readable schedules.
slots.add(8 * 60 + (state % 145) * 5);
}
return [...slots].sort((a, b) => a - b);
}
/** Weekly slots in Asia/Bangkok (UTC+7, no daylight saving), strictly after now. */ /** Weekly slots in Asia/Bangkok (UTC+7, no daylight saving), strictly after now. */
export function nextContentRun(weekdays: number[], times: string[], now = new Date()): Date { export function nextContentRun(schedule: Schedule, now = new Date()): Date {
const { weekdays, times, mode = "FIXED", randomPostsPerDay = 1, seed = "content-auto" } = schedule;
const offset = 7 * 60 * 60_000; const offset = 7 * 60 * 60_000;
const local = new Date(now.getTime() + offset); const local = new Date(now.getTime() + offset);
for (let day = 0; day <= 7; day++) { for (let day = 0; day <= 7; day++) {
const midnight = Date.UTC(local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate() + day); const midnight = Date.UTC(local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate() + day);
if (!weekdays.includes(new Date(midnight).getUTCDay())) continue; if (!weekdays.includes(new Date(midnight).getUTCDay())) continue;
for (const time of [...times].sort()) { const dateKey = new Date(midnight).toISOString().slice(0, 10);
const [hours, minutes] = time.split(":").map(Number); const minutesOfDay = mode === "RANDOM"
const candidate = new Date(midnight + (hours * 60 + minutes) * 60_000 - offset); ? seededMinutes(`${seed}:${dateKey}`, Math.min(3, Math.max(1, randomPostsPerDay)))
: [...times].sort().map((time) => {
const [hours, minutes] = time.split(":").map(Number);
return hours * 60 + minutes;
});
for (const minutes of minutesOfDay) {
const candidate = new Date(midnight + minutes * 60_000 - offset);
if (candidate > now) return candidate; if (candidate > now) return candidate;
} }
} }
+18 -4
View File
@@ -5,10 +5,20 @@ import { IMAGE_DAILY_LIMIT_PER_PAGE } from "./image";
import { nextContentRun } from "./auto-schedule"; import { nextContentRun } from "./auto-schedule";
export const AUTOMATION_SELECT = { export const AUTOMATION_SELECT = {
enabled: true, weekdays: true, times: true, brief: true, targets: true, enabled: true, scheduleMode: true, weekdays: true, times: true, randomPostsPerDay: true,
articlePercent: true, knowledgePercent: true, salesPercent: true, brief: true, targets: true,
nextRunAt: true, lastQueuedAt: true, lastError: true, nextRunAt: true, lastQueuedAt: true, lastError: true,
} as const; } as const;
function selectContentType(config: { articlePercent: number; knowledgePercent: number; salesPercent: number }, seed: string) {
let value = 0;
for (const char of seed) value = (Math.imul(value, 31) + char.charCodeAt(0)) >>> 0;
const point = value % 100;
if (point < config.articlePercent) return "บทความ";
if (point < config.articlePercent + config.knowledgePercent) return "ความรู้ทั่วไป";
return "ปิดงานขาย";
}
/** The queue worker calls this even when no browser is viewing the page. */ /** The queue worker calls this even when no browser is viewing the page. */
export async function enqueueDueContent() { export async function enqueueDueContent() {
const now = new Date(); const now = new Date();
@@ -43,7 +53,10 @@ export async function enqueueDueContent() {
const pending = await tx.postGenerationJob.count({ where: { pageId, status: { in: ["QUEUED", "RUNNING"] } } }); const 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) } } }); 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. // Missed or blocked slots are skipped, never backfilled into a burst of image requests.
const nextRunAt = nextContentRun(config.weekdays, config.times, now); const nextRunAt = nextContentRun({
weekdays: config.weekdays, times: config.times, mode: config.scheduleMode,
randomPostsPerDay: config.randomPostsPerDay, seed: pageId,
}, now);
if (pending >= 5 || used + pending >= IMAGE_DAILY_LIMIT_PER_PAGE) { if (pending >= 5 || used + pending >= IMAGE_DAILY_LIMIT_PER_PAGE) {
const reason = pending >= 5 ? "ข้ามรอบนี้เพราะคิวเต็ม 5 งาน" : "ข้ามรอบนี้เพราะโควตาภาพเต็ม"; const reason = pending >= 5 ? "ข้ามรอบนี้เพราะคิวเต็ม 5 งาน" : "ข้ามรอบนี้เพราะโควตาภาพเต็ม";
await tx.pageContentAutomation.update({ where: { pageId }, data: { nextRunAt, lastError: reason } }); await tx.pageContentAutomation.update({ where: { pageId }, data: { nextRunAt, lastError: reason } });
@@ -51,14 +64,15 @@ export async function enqueueDueContent() {
return; return;
} }
const recent = await tx.post.findMany({ where: { pageId }, orderBy: { createdAt: "desc" }, take: 10, select: { title: true } }); const recent = await tx.post.findMany({ where: { pageId }, orderBy: { createdAt: "desc" }, take: 10, select: { title: true } });
const topic = `สร้างเนื้อหาอัตโนมัติ\nแนวเนื้อหา: ${config.brief || "เลือกจากข้อมูลร้าน"}\nหัวข้อล่าสุดที่ควรเลี่ยงซ้ำ:\n${recent.map((p) => p.title).join("\n")}`; const contentType = selectContentType(config, `${pageId}:${config.nextRunAt.toISOString()}`);
const topic = `สร้างเนื้อหาอัตโนมัติ\nประเภทเนื้อหา: ${contentType}\nแนวเนื้อหา: ${config.brief || "เลือกจากข้อมูลร้าน"}\nหัวข้อล่าสุดที่ควรเลี่ยงซ้ำ:\n${recent.map((p) => p.title).join("\n")}`;
const job = await tx.postGenerationJob.create({ data: { const job = await tx.postGenerationJob.create({ data: {
pageId, requestedById: config.requestedById, pageId, requestedById: config.requestedById,
requestKey: `auto:${config.id}:${config.nextRunAt.toISOString()}`, requestKey: `auto:${config.id}:${config.nextRunAt.toISOString()}`,
topic, targets: config.targets, profileSnapshot: page!.profile!, topic, targets: config.targets, profileSnapshot: page!.profile!,
} }); } });
await tx.pageContentAutomation.update({ where: { pageId }, data: { nextRunAt, lastQueuedAt: now, lastError: null } }); await tx.pageContentAutomation.update({ where: { pageId }, data: { nextRunAt, lastQueuedAt: now, lastError: null } });
await audit({ action: "AI_POST_QUEUED", actorId: config.requestedById, actorLabel: SYSTEM_ACTOR, pageId, detail: { jobId: job.id, source: "auto", slot: config.nextRunAt.toISOString() } }, tx); await audit({ action: "AI_POST_QUEUED", actorId: config.requestedById, actorLabel: SYSTEM_ACTOR, pageId, detail: { jobId: job.id, source: "auto", slot: config.nextRunAt.toISOString(), contentType } }, tx);
}); });
} catch (error) { console.error("[content-auto] enqueue failed", pageId, error); } } catch (error) { console.error("[content-auto] enqueue failed", pageId, error); }
} }