Initial commit: page-manager Next.js app with Coolify deploy support
Replace Vercel-specific infra (Cron, Blob) with self-hosted equivalents for deployment to Coolify: in-container cron scheduler (scripts/cron-runner.mjs) and disk-based upload storage served via /api/uploads/[...path]. Add Dockerfile, .dockerignore, and /api/health for container health checks. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { actorLabel, requirePageAction } from "@/lib/auth/user";
|
||||
import { approvePost, cancelSchedule, editPost, planPost, publishPost, rejectPost, submitForApproval } from "@/lib/posts/workflow";
|
||||
import { audit } from "@/lib/audit";
|
||||
import { errorResponse, optStr, readJson, str } from "@/lib/http";
|
||||
import type { PageAction } from "@/lib/auth/roles";
|
||||
|
||||
async function loadPost(id: string) {
|
||||
return prisma.post.findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
const notFound = () => NextResponse.json({ error: "ไม่พบโพสต์" }, { status: 404 });
|
||||
|
||||
export async function GET(_req: Request, ctx: RouteContext<"/api/posts/[id]">) {
|
||||
const { id } = await ctx.params;
|
||||
const post = await loadPost(id);
|
||||
if (!post) return notFound();
|
||||
const auth = await requirePageAction(post.pageId, "view");
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const [approvals, log] = await Promise.all([
|
||||
prisma.postApproval.findMany({ where: { postId: id }, orderBy: { createdAt: "asc" } }),
|
||||
prisma.auditLog.findMany({ where: { postId: id }, orderBy: { createdAt: "desc" }, take: 50 }),
|
||||
]);
|
||||
return NextResponse.json({ post, approvals, log, role: auth.role });
|
||||
}
|
||||
|
||||
export async function PATCH(req: Request, ctx: RouteContext<"/api/posts/[id]">) {
|
||||
const { id } = await ctx.params;
|
||||
const post = await loadPost(id);
|
||||
if (!post) return notFound();
|
||||
const auth = await requirePageAction(post.pageId, "editPost");
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const body = await readJson(req);
|
||||
const targets = Array.isArray(body.targets)
|
||||
? (["FACEBOOK", "INSTAGRAM"] as const).filter((p) => (body.targets as unknown[]).includes(p))
|
||||
: post.targets;
|
||||
try {
|
||||
const updated = await editPost(post, auth.user, {
|
||||
title: typeof body.title === "string" ? body.title.trim() : post.title,
|
||||
caption: typeof body.caption === "string" ? body.caption : post.caption,
|
||||
imageBlobUrl: "imageBlobUrl" in body ? optStr(body.imageBlobUrl) : post.imageBlobUrl,
|
||||
targets,
|
||||
}, { aiAssisted: body.aiAssisted === true });
|
||||
return NextResponse.json({ post: updated });
|
||||
} catch (e) {
|
||||
return errorResponse(e, "posts:edit");
|
||||
}
|
||||
}
|
||||
|
||||
const ACTION_PERMISSION: Record<string, PageAction> = {
|
||||
plan: "editPost",
|
||||
submit: "editPost",
|
||||
approve: "approvePost",
|
||||
reject: "approvePost",
|
||||
publish: "publishPost",
|
||||
schedule: "publishPost",
|
||||
cancel: "publishPost",
|
||||
};
|
||||
|
||||
/** Workflow transitions: `{ action: plan|submit|approve|reject|publish|schedule|cancel, note?, scheduledAt?, plannedAt? }`. */
|
||||
export async function POST(req: Request, ctx: RouteContext<"/api/posts/[id]">) {
|
||||
const { id } = await ctx.params;
|
||||
const post = await loadPost(id);
|
||||
if (!post) return notFound();
|
||||
|
||||
const body = await readJson(req);
|
||||
const action = str(body.action);
|
||||
const permission = ACTION_PERMISSION[action];
|
||||
if (!permission) return NextResponse.json({ error: "unknown action" }, { status: 400 });
|
||||
|
||||
const auth = await requirePageAction(post.pageId, permission);
|
||||
if (!auth.ok) return auth.response;
|
||||
const note = optStr(body.note);
|
||||
|
||||
try {
|
||||
let updated;
|
||||
switch (action) {
|
||||
case "plan":
|
||||
updated = await planPost(post, auth.user, body.plannedAt ? new Date(str(body.plannedAt)) : null);
|
||||
break;
|
||||
case "submit":
|
||||
updated = await submitForApproval(post, auth.user);
|
||||
break;
|
||||
case "approve":
|
||||
updated = await approvePost(post, auth.user, note);
|
||||
break;
|
||||
case "reject":
|
||||
updated = await rejectPost(post, auth.user, note);
|
||||
break;
|
||||
case "publish":
|
||||
updated = await publishPost(post, auth.user, null);
|
||||
break;
|
||||
case "schedule": {
|
||||
const when = new Date(str(body.scheduledAt));
|
||||
updated = await publishPost(post, auth.user, when);
|
||||
break;
|
||||
}
|
||||
case "cancel":
|
||||
updated = await cancelSchedule(post, auth.user);
|
||||
break;
|
||||
}
|
||||
return NextResponse.json({ post: updated });
|
||||
} catch (e) {
|
||||
return errorResponse(e, `posts:${action}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Only unpublished, unscheduled posts can be deleted. */
|
||||
export async function DELETE(_req: Request, ctx: RouteContext<"/api/posts/[id]">) {
|
||||
const { id } = await ctx.params;
|
||||
const post = await loadPost(id);
|
||||
if (!post) return notFound();
|
||||
const auth = await requirePageAction(post.pageId, "editPost");
|
||||
if (!auth.ok) return auth.response;
|
||||
if (post.status === "SCHEDULED" || post.status === "PUBLISHED") {
|
||||
return NextResponse.json({ error: "โพสต์ที่ตั้งเวลาหรือเผยแพร่แล้วลบไม่ได้" }, { status: 400 });
|
||||
}
|
||||
await audit({ action: "POST_DELETED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId: post.pageId, detail: { title: post.title } });
|
||||
await prisma.post.delete({ where: { id } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { Platform, PostStatus } from "@prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { accessiblePageIds, actorLabel, requirePageAction, requireUser } from "@/lib/auth/user";
|
||||
import { contentProblem } from "@/lib/posts/workflow";
|
||||
import { audit } from "@/lib/audit";
|
||||
import { optStr, readJson, str } from "@/lib/http";
|
||||
|
||||
const STATUSES: PostStatus[] = ["DRAFT", "PENDING_APPROVAL", "APPROVED", "SCHEDULED", "PUBLISHED", "FAILED", "CANCELLED"];
|
||||
|
||||
/** `?pageId=&status=&from=&to=` — always restricted to pages the caller can see. */
|
||||
export async function GET(req: Request) {
|
||||
const auth = await requireUser();
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const q = new URL(req.url).searchParams;
|
||||
const ids = await accessiblePageIds(auth.user);
|
||||
const pageId = q.get("pageId");
|
||||
if (pageId && ids && !ids.includes(pageId)) return NextResponse.json({ posts: [] });
|
||||
|
||||
const status = q.get("status") as PostStatus | null;
|
||||
const from = q.get("from");
|
||||
const to = q.get("to");
|
||||
|
||||
const posts = await prisma.post.findMany({
|
||||
where: {
|
||||
pageId: pageId ?? (ids ? { in: ids } : undefined),
|
||||
page: { status: { not: "DISCONNECTED" } },
|
||||
...(status && STATUSES.includes(status) ? { status } : {}),
|
||||
...(from || to
|
||||
? {
|
||||
OR: [
|
||||
{ scheduledPublishAt: { gte: from ? new Date(from) : undefined, lte: to ? new Date(to) : undefined } },
|
||||
{ scheduledPublishAt: null, updatedAt: { gte: from ? new Date(from) : undefined, lte: to ? new Date(to) : undefined } },
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
pageId: true,
|
||||
title: true,
|
||||
caption: true,
|
||||
imageBlobUrl: true,
|
||||
targets: true,
|
||||
status: true,
|
||||
scheduledPublishAt: true,
|
||||
plannedAt: true,
|
||||
fbPermalink: true,
|
||||
igPermalink: true,
|
||||
lastError: true,
|
||||
updatedAt: true,
|
||||
page: { select: { name: true, pictureUrl: true } },
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: 300,
|
||||
});
|
||||
return NextResponse.json({ posts });
|
||||
}
|
||||
|
||||
function parseTargets(v: unknown): Platform[] {
|
||||
const arr = Array.isArray(v) ? v : [];
|
||||
return (["FACEBOOK", "INSTAGRAM"] as const).filter((p) => arr.includes(p));
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const body = await readJson(req);
|
||||
const pageId = str(body.pageId);
|
||||
const auth = await requirePageAction(pageId, "editPost");
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
const content = {
|
||||
title: str(body.title).trim(),
|
||||
caption: str(body.caption),
|
||||
imageBlobUrl: optStr(body.imageBlobUrl),
|
||||
targets: parseTargets(body.targets),
|
||||
};
|
||||
const problem = contentProblem(content);
|
||||
if (problem) return NextResponse.json({ error: problem }, { status: 400 });
|
||||
|
||||
const page = await prisma.page.findUnique({ where: { id: pageId }, select: { igUserId: true } });
|
||||
if (content.targets.includes("INSTAGRAM") && !page?.igUserId) {
|
||||
return NextResponse.json({ error: "เพจนี้ยังไม่ได้ผูก Instagram" }, { status: 400 });
|
||||
}
|
||||
|
||||
const planned = optStr(body.plannedAt) ? new Date(str(body.plannedAt)) : null;
|
||||
if (planned && Number.isNaN(planned.getTime())) return NextResponse.json({ error: "วันที่ไม่ถูกต้อง" }, { status: 400 });
|
||||
const aiAssisted = body.aiAssisted === true;
|
||||
const post = await prisma.post.create({
|
||||
data: {
|
||||
...content,
|
||||
pageId,
|
||||
plannedAt: planned,
|
||||
aiAssisted,
|
||||
createdById: auth.user.id,
|
||||
lastEditedById: auth.user.id,
|
||||
lastEditedAt: new Date(),
|
||||
},
|
||||
});
|
||||
await audit({ action: "POST_CREATED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, postId: post.id, detail: aiAssisted ? { aiAssisted: true } : undefined });
|
||||
return NextResponse.json({ post }, { status: 201 });
|
||||
}
|
||||
Reference in New Issue
Block a user