Files
PAGIVA/src/app/api/ai/content-auto/route.ts
T

62 lines
4.1 KiB
TypeScript

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"); }
}