9d32552457
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>
317 lines
14 KiB
TypeScript
317 lines
14 KiB
TypeScript
import type { Post, PostStatus } from "@prisma/client";
|
|
import { prisma } from "@/lib/db";
|
|
import { audit, SYSTEM_ACTOR } from "@/lib/audit";
|
|
import { actorLabel, isSuperadmin, type SessionUser } from "@/lib/auth/user";
|
|
import { getPageCredentials } from "@/lib/facebook/tokens";
|
|
import { cancelScheduledFacebookPost, publishToFacebook, scheduleTimeProblem } from "@/lib/facebook/posts";
|
|
import { publishToInstagram } from "@/lib/instagram/posts";
|
|
import { safeFacebookErrorMessage, UserFacingError } from "@/lib/facebook/client";
|
|
|
|
/** Approvals needed before a post can be published. */
|
|
export const REQUIRED_APPROVALS = 1;
|
|
|
|
export const EDITABLE_STATUSES: PostStatus[] = ["DRAFT", "PENDING_APPROVAL", "APPROVED", "FAILED", "CANCELLED"];
|
|
|
|
export interface PostContent {
|
|
title: string;
|
|
caption: string;
|
|
imageBlobUrl: string | null;
|
|
targets: ("FACEBOOK" | "INSTAGRAM")[];
|
|
}
|
|
|
|
export function contentProblem(c: PostContent): string | null {
|
|
if (!c.title.trim()) return "กรอกชื่อโพสต์";
|
|
if (!c.caption.trim() && !c.imageBlobUrl) return "ต้องมี caption หรือรูปอย่างน้อยหนึ่งอย่าง";
|
|
if (c.targets.length === 0) return "เลือกอย่างน้อยหนึ่งช่องทาง";
|
|
if (c.targets.includes("INSTAGRAM") && !c.imageBlobUrl) return "โพสต์ Instagram ต้องมีรูป";
|
|
if (c.caption.length > 63206) return "caption ยาวเกินที่ Facebook รับได้";
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Edits content. Changing content after approval voids every approval and
|
|
* returns the post to PENDING_APPROVAL. Scheduled/published posts are locked —
|
|
* cancel the schedule first.
|
|
*/
|
|
export async function editPost(post: Post, user: SessionUser, next: PostContent, opts: { aiAssisted?: boolean } = {}): Promise<Post> {
|
|
if (!EDITABLE_STATUSES.includes(post.status)) {
|
|
throw new UserFacingError("โพสต์ที่ตั้งเวลาหรือเผยแพร่แล้วแก้ไม่ได้ — ยกเลิกการตั้งเวลาก่อน");
|
|
}
|
|
const problem = contentProblem(next);
|
|
if (problem) throw new UserFacingError(problem);
|
|
|
|
const changed =
|
|
post.title !== next.title ||
|
|
post.caption !== next.caption ||
|
|
post.imageBlobUrl !== next.imageBlobUrl ||
|
|
post.targets.join() !== next.targets.join();
|
|
if (!changed) return post;
|
|
|
|
const voidsApproval = post.status === "APPROVED" || post.status === "PENDING_APPROVAL";
|
|
const backToDraft = post.status === "FAILED" || post.status === "CANCELLED";
|
|
const newlyAiAssisted = Boolean(opts.aiAssisted) && !post.aiAssisted;
|
|
const detail = {
|
|
...(voidsApproval && post.status === "APPROVED" ? { note: "การอนุมัติเดิมเป็นโมฆะ" } : {}),
|
|
...(newlyAiAssisted ? { aiAssisted: true } : {}),
|
|
};
|
|
return prisma.$transaction(async (tx) => {
|
|
if (voidsApproval) await tx.postApproval.deleteMany({ where: { postId: post.id } });
|
|
const updated = await tx.post.update({
|
|
where: { id: post.id },
|
|
data: {
|
|
...next,
|
|
status: voidsApproval ? "PENDING_APPROVAL" : backToDraft ? "DRAFT" : post.status,
|
|
...(backToDraft ? { lastError: null } : {}),
|
|
...(newlyAiAssisted ? { aiAssisted: true } : {}),
|
|
lastEditedById: user.id,
|
|
lastEditedAt: new Date(),
|
|
},
|
|
});
|
|
await audit(
|
|
{
|
|
action: "POST_EDITED",
|
|
actorId: user.id,
|
|
actorLabel: actorLabel(user),
|
|
pageId: post.pageId,
|
|
postId: post.id,
|
|
detail: Object.keys(detail).length ? detail : undefined,
|
|
},
|
|
tx
|
|
);
|
|
return updated;
|
|
});
|
|
}
|
|
|
|
export async function submitForApproval(post: Post, user: SessionUser): Promise<Post> {
|
|
if (post.status !== "DRAFT" && post.status !== "FAILED" && post.status !== "CANCELLED") {
|
|
throw new UserFacingError("ส่งขออนุมัติได้เฉพาะโพสต์ที่เป็นฉบับร่าง");
|
|
}
|
|
return prisma.$transaction(async (tx) => {
|
|
await tx.postApproval.deleteMany({ where: { postId: post.id } });
|
|
const updated = await tx.post.update({ where: { id: post.id }, data: { status: "PENDING_APPROVAL", lastError: null } });
|
|
await audit({ action: "POST_SUBMITTED", actorId: user.id, actorLabel: actorLabel(user), pageId: post.pageId, postId: post.id }, tx);
|
|
return updated;
|
|
});
|
|
}
|
|
|
|
/** Separation of duty: the last editor cannot approve their own edit (SUPERADMIN may, and the log says so). */
|
|
export function selfApprovalBlockReason(post: Post, user: SessionUser): string | null {
|
|
if (post.lastEditedById !== user.id && post.createdById !== user.id) return null;
|
|
if (isSuperadmin(user)) return null;
|
|
return "คุณเป็นคนแก้โพสต์นี้ล่าสุด ต้องให้คนอื่นอนุมัติ";
|
|
}
|
|
|
|
export async function approvePost(post: Post, user: SessionUser, note: string | null): Promise<Post> {
|
|
if (post.status !== "PENDING_APPROVAL") throw new UserFacingError("โพสต์นี้ไม่ได้อยู่ในสถานะรออนุมัติ");
|
|
const block = selfApprovalBlockReason(post, user);
|
|
if (block) throw new UserFacingError(block);
|
|
const ownWork = post.lastEditedById === user.id || post.createdById === user.id;
|
|
|
|
return prisma.$transaction(async (tx) => {
|
|
await tx.postApproval.upsert({
|
|
where: { postId_approverId: { postId: post.id, approverId: user.id } },
|
|
create: { postId: post.id, approverId: user.id, approverLabel: actorLabel(user), note },
|
|
update: { note },
|
|
});
|
|
const votes = await tx.postApproval.count({ where: { postId: post.id } });
|
|
const done = votes >= REQUIRED_APPROVALS;
|
|
const updated = done ? await tx.post.update({ where: { id: post.id }, data: { status: "APPROVED" } }) : post;
|
|
await audit(
|
|
{
|
|
action: "POST_APPROVED",
|
|
actorId: user.id,
|
|
actorLabel: actorLabel(user),
|
|
pageId: post.pageId,
|
|
postId: post.id,
|
|
detail: { note, votes, required: REQUIRED_APPROVALS, ...(ownWork ? { selfApproved: true } : {}) },
|
|
},
|
|
tx
|
|
);
|
|
return updated;
|
|
});
|
|
}
|
|
|
|
export async function rejectPost(post: Post, user: SessionUser, note: string | null): Promise<Post> {
|
|
if (post.status !== "PENDING_APPROVAL" && post.status !== "APPROVED") {
|
|
throw new UserFacingError("ตีกลับได้เฉพาะโพสต์ที่รออนุมัติหรืออนุมัติแล้ว");
|
|
}
|
|
return prisma.$transaction(async (tx) => {
|
|
await tx.postApproval.deleteMany({ where: { postId: post.id } });
|
|
const updated = await tx.post.update({ where: { id: post.id }, data: { status: "DRAFT", lastError: note ? `ตีกลับ: ${note}` : null } });
|
|
await audit({ action: "POST_REJECTED", actorId: user.id, actorLabel: actorLabel(user), pageId: post.pageId, postId: post.id, detail: { note } }, tx);
|
|
return updated;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Publishes now (scheduledAt = null) or schedules. Facebook holds scheduled
|
|
* posts itself; Instagram has no API scheduling, so a scheduled IG target is
|
|
* left for /api/cron/ig-publisher.
|
|
*/
|
|
export async function publishPost(post: Post, user: SessionUser, scheduledAt: Date | null): Promise<Post> {
|
|
if (post.status !== "APPROVED") throw new UserFacingError("ต้องอนุมัติก่อนถึงจะเผยแพร่หรือตั้งเวลาได้");
|
|
if (scheduledAt) {
|
|
const problem = scheduleTimeProblem(scheduledAt);
|
|
if (problem) throw new UserFacingError(problem);
|
|
}
|
|
|
|
// Atomic claim: blocks a double-click or a second approver racing the first
|
|
// into publishing the same post twice to Facebook/Instagram.
|
|
const claim = await prisma.post.updateMany({
|
|
where: { id: post.id, status: "APPROVED", publishingAt: null },
|
|
data: { publishingAt: new Date() },
|
|
});
|
|
if (claim.count === 0) {
|
|
throw new UserFacingError("โพสต์นี้กำลังถูกเผยแพร่อยู่ — รอสักครู่แล้วลองโหลดหน้าใหม่");
|
|
}
|
|
|
|
let settled = false;
|
|
try {
|
|
const page = await getPageCredentials(post.pageId);
|
|
const errors: string[] = [];
|
|
const data: Partial<Post> = { scheduledPublishAt: scheduledAt, lastError: null, publishingAt: null };
|
|
let anySuccess = false;
|
|
|
|
if (post.targets.includes("FACEBOOK")) {
|
|
try {
|
|
const fb = await publishToFacebook(page, { caption: post.caption, imageUrl: post.imageBlobUrl, scheduledAt });
|
|
data.fbPostId = fb.fbPostId;
|
|
data.fbPermalink = fb.permalink;
|
|
anySuccess = true;
|
|
} catch (e) {
|
|
errors.push(`Facebook: ${safeFacebookErrorMessage(e, "publish:fb")}`);
|
|
}
|
|
}
|
|
|
|
if (post.targets.includes("INSTAGRAM") && !scheduledAt) {
|
|
try {
|
|
const ig = await publishToInstagram(page, { imageUrl: post.imageBlobUrl!, caption: post.caption });
|
|
data.igMediaId = ig.mediaId;
|
|
data.igPermalink = ig.permalink;
|
|
anySuccess = true;
|
|
} catch (e) {
|
|
errors.push(`Instagram: ${safeFacebookErrorMessage(e, "publish:ig")}`);
|
|
}
|
|
} else if (post.targets.includes("INSTAGRAM")) {
|
|
anySuccess = true; // queued for the cron
|
|
}
|
|
|
|
data.status = !anySuccess ? "FAILED" : scheduledAt ? "SCHEDULED" : "PUBLISHED";
|
|
if (errors.length) data.lastError = errors.join(" · ");
|
|
|
|
const updated = await prisma.post.update({ where: { id: post.id }, data });
|
|
settled = true;
|
|
await audit({
|
|
action: data.status === "FAILED" ? "POST_FAILED" : scheduledAt ? "POST_SCHEDULED" : "POST_PUBLISHED",
|
|
actorId: user.id,
|
|
actorLabel: actorLabel(user),
|
|
pageId: post.pageId,
|
|
postId: post.id,
|
|
detail: { scheduledAt: scheduledAt?.toISOString() ?? null, errors },
|
|
});
|
|
if (data.status === "FAILED") throw new UserFacingError(data.lastError ?? "เผยแพร่ไม่สำเร็จ");
|
|
return updated;
|
|
} catch (e) {
|
|
if (settled) throw e; // DB already updated and the lock already released above
|
|
// Failed before the final update ran (e.g. getPageCredentials threw) — release the lock.
|
|
const msg = e instanceof UserFacingError ? e.message : safeFacebookErrorMessage(e, "publish:unexpected");
|
|
await prisma.post.update({ where: { id: post.id }, data: { status: "FAILED", publishingAt: null, lastError: msg } });
|
|
await audit({
|
|
action: "POST_FAILED",
|
|
actorId: user.id,
|
|
actorLabel: actorLabel(user),
|
|
pageId: post.pageId,
|
|
postId: post.id,
|
|
detail: { error: msg },
|
|
});
|
|
throw new UserFacingError(msg);
|
|
}
|
|
}
|
|
|
|
/** Cancels a schedule and returns the post to APPROVED so it can be rescheduled. */
|
|
export async function cancelSchedule(post: Post, user: SessionUser): Promise<Post> {
|
|
if (post.status !== "SCHEDULED") throw new UserFacingError("โพสต์นี้ไม่ได้ตั้งเวลาไว้");
|
|
if (post.fbPostId) {
|
|
const page = await getPageCredentials(post.pageId);
|
|
await cancelScheduledFacebookPost(page, post.fbPostId);
|
|
}
|
|
const updated = await prisma.post.update({
|
|
where: { id: post.id },
|
|
data: { status: "APPROVED", scheduledPublishAt: null, fbPostId: null, fbPermalink: null },
|
|
});
|
|
await audit({ action: "POST_CANCELLED", actorId: user.id, actorLabel: actorLabel(user), pageId: post.pageId, postId: post.id });
|
|
return updated;
|
|
}
|
|
|
|
/**
|
|
* Pins a post to a day on the board (or unpins with null). A plan only: it
|
|
* never publishes and never touches approval. Locked once Facebook holds it.
|
|
*/
|
|
export async function planPost(post: Post, user: SessionUser, plannedAt: Date | null): Promise<Post> {
|
|
if (post.status === "SCHEDULED" || post.status === "PUBLISHED") {
|
|
throw new UserFacingError("โพสต์นี้ตั้งเวลาหรือเผยแพร่แล้ว ย้ายวันไม่ได้ — ยกเลิกการตั้งเวลาก่อน");
|
|
}
|
|
if (plannedAt && Number.isNaN(plannedAt.getTime())) throw new UserFacingError("วันที่ไม่ถูกต้อง");
|
|
const updated = await prisma.post.update({ where: { id: post.id }, data: { plannedAt } });
|
|
await audit({
|
|
action: "POST_PLANNED",
|
|
actorId: user.id,
|
|
actorLabel: actorLabel(user),
|
|
pageId: post.pageId,
|
|
postId: post.id,
|
|
detail: { plannedAt: plannedAt?.toISOString() ?? null },
|
|
});
|
|
return updated;
|
|
}
|
|
|
|
// Longer than the ig-publisher route's maxDuration (300s), so a lock left behind
|
|
// by a crashed/timed-out run is reclaimable by the next one instead of stalling forever.
|
|
const PUBLISH_LOCK_STALE_MS = 10 * 60 * 1000;
|
|
|
|
/** Cron: publish Instagram targets whose scheduled time has come. */
|
|
export async function publishDueInstagramPosts(now = new Date()): Promise<{ published: number; failed: number }> {
|
|
const staleBefore = new Date(now.getTime() - PUBLISH_LOCK_STALE_MS);
|
|
const unclaimed = [{ publishingAt: null }, { publishingAt: { lt: staleBefore } }];
|
|
const due = await prisma.post.findMany({
|
|
where: {
|
|
status: "SCHEDULED",
|
|
scheduledPublishAt: { lte: now },
|
|
targets: { has: "INSTAGRAM" },
|
|
igMediaId: null,
|
|
OR: unclaimed,
|
|
},
|
|
take: 20,
|
|
});
|
|
let published = 0;
|
|
let failed = 0;
|
|
for (const post of due) {
|
|
// Atomic claim: a concurrent/overlapping cron run can't grab the same post.
|
|
const claim = await prisma.post.updateMany({
|
|
where: { id: post.id, status: "SCHEDULED", OR: unclaimed },
|
|
data: { publishingAt: now },
|
|
});
|
|
if (claim.count === 0) continue;
|
|
|
|
try {
|
|
const page = await getPageCredentials(post.pageId);
|
|
const ig = await publishToInstagram(page, { imageUrl: post.imageBlobUrl!, caption: post.caption });
|
|
await prisma.post.update({
|
|
where: { id: post.id },
|
|
data: { igMediaId: ig.mediaId, igPermalink: ig.permalink, status: "PUBLISHED", publishingAt: null },
|
|
});
|
|
await audit({ action: "POST_PUBLISHED", actorLabel: SYSTEM_ACTOR, pageId: post.pageId, postId: post.id, detail: { platform: "INSTAGRAM" } });
|
|
published++;
|
|
} catch (e) {
|
|
const msg = `Instagram: ${safeFacebookErrorMessage(e, "cron:ig-publisher")}`;
|
|
// FB may already be live via its own scheduler — only the IG part failed.
|
|
await prisma.post.update({
|
|
where: { id: post.id },
|
|
data: { lastError: msg, status: post.fbPostId ? "PUBLISHED" : "FAILED", publishingAt: null },
|
|
});
|
|
await audit({ action: "POST_FAILED", actorLabel: SYSTEM_ACTOR, pageId: post.pageId, postId: post.id, detail: { error: msg } });
|
|
failed++;
|
|
}
|
|
}
|
|
return { published, failed };
|
|
}
|