Add self-service teams and assigned post approvals
This commit is contained in:
@@ -53,9 +53,10 @@ export async function claimPostJob() {
|
||||
|
||||
async function assertJobAccess(pageId: string, userId: string) {
|
||||
const user = await prisma.user.findUnique({ where: { id: userId }, select: { id: true, name: true, email: true, isActive: true, globalRole: true } });
|
||||
const page = await prisma.page.findUnique({ where: { id: pageId }, select: { status: true, igUserId: true, pictureUrl: true } });
|
||||
const page = await prisma.page.findUnique({ where: { id: pageId }, select: { status: true, igUserId: true, pictureUrl: true, teamPage: { select: { teamId: true } } } });
|
||||
const member = await prisma.pageMember.findUnique({ where: { userId_pageId: { userId, pageId } }, select: { role: true } });
|
||||
if (!user?.isActive || !page || page.status === "DISCONNECTED" || (user.globalRole !== "SUPERADMIN" && !roleAtLeast(member?.role, "EDITOR"))) {
|
||||
const teamMember = page?.teamPage ? await prisma.teamMember.findUnique({ where: { teamId_userId: { teamId: page.teamPage.teamId, userId } }, select: { id: true } }) : null;
|
||||
if (!user?.isActive || !page || page.status === "DISCONNECTED" || (user.globalRole !== "SUPERADMIN" && (!roleAtLeast(member?.role, "EDITOR") || (page.teamPage && !teamMember)))) {
|
||||
throw new UserFacingError("ผู้สั่งงานไม่มีสิทธิ์สร้างโพสต์ในเพจนี้แล้ว");
|
||||
}
|
||||
return { user, page };
|
||||
|
||||
@@ -12,6 +12,13 @@ export type AuditAction =
|
||||
| "PAGE_TOKEN_INVALID"
|
||||
| "PAGE_MEMBER_SET"
|
||||
| "PAGE_MEMBER_REMOVED"
|
||||
| "TEAM_CREATED"
|
||||
| "TEAM_PAGE_ADDED"
|
||||
| "TEAM_INVITE_CREATED"
|
||||
| "TEAM_INVITE_REVOKED"
|
||||
| "TEAM_INVITE_ACCEPTED"
|
||||
| "TEAM_MEMBER_ROLE_SET"
|
||||
| "TEAM_MEMBER_REMOVED"
|
||||
| "PAGE_ANALYSIS_REQUESTED"
|
||||
| "PAGE_PROFILE_SAVED"
|
||||
| "POST_CREATED"
|
||||
|
||||
+11
-3
@@ -30,16 +30,24 @@ export async function pageRoleOf(user: SessionUser, pageId: string): Promise<Pag
|
||||
if (isSuperadmin(user)) return "MANAGER";
|
||||
const m = await prisma.pageMember.findUnique({
|
||||
where: { userId_pageId: { userId: user.id, pageId } },
|
||||
select: { role: true },
|
||||
select: { role: true, page: { select: { teamPage: { select: { teamId: true } } } } },
|
||||
});
|
||||
if (m?.page.teamPage) {
|
||||
const inTeam = await prisma.teamMember.findUnique({ where: { teamId_userId: { teamId: m.page.teamPage.teamId, userId: user.id } }, select: { id: true } });
|
||||
if (!inTeam) return null;
|
||||
}
|
||||
return m?.role ?? null;
|
||||
}
|
||||
|
||||
/** Page ids the user can see (null = all pages, for SUPERADMIN). */
|
||||
export async function accessiblePageIds(user: SessionUser): Promise<string[] | null> {
|
||||
if (isSuperadmin(user)) return null;
|
||||
const rows = await prisma.pageMember.findMany({ where: { userId: user.id }, select: { pageId: true } });
|
||||
return rows.map((r) => r.pageId);
|
||||
const [rows, teams] = await Promise.all([
|
||||
prisma.pageMember.findMany({ where: { userId: user.id }, select: { pageId: true, page: { select: { teamPage: { select: { teamId: true } } } } } }),
|
||||
prisma.teamMember.findMany({ where: { userId: user.id }, select: { teamId: true } }),
|
||||
]);
|
||||
const teamIds = new Set(teams.map((t) => t.teamId));
|
||||
return rows.filter((r) => !r.page.teamPage || teamIds.has(r.page.teamPage.teamId)).map((r) => r.pageId);
|
||||
}
|
||||
|
||||
/** Prisma `where` fragment restricting to pages the user can see. */
|
||||
|
||||
+3
-2
@@ -3,7 +3,7 @@ import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import type { PageRole } from "@prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getCurrentUser, isSuperadmin, type SessionUser } from "@/lib/auth/user";
|
||||
import { accessiblePageIds, getCurrentUser, isSuperadmin, type SessionUser } from "@/lib/auth/user";
|
||||
|
||||
export const SELECTED_PAGE_COOKIE = "pm_page";
|
||||
|
||||
@@ -39,8 +39,9 @@ export const getConsoleContext = cache(async (): Promise<ConsoleContext> => {
|
||||
});
|
||||
pages = rows.map((p) => ({ ...p, role: "MANAGER" as const }));
|
||||
} else {
|
||||
const ids = await accessiblePageIds(user);
|
||||
const rows = await prisma.pageMember.findMany({
|
||||
where: { userId: user.id, page: where },
|
||||
where: { userId: user.id, pageId: { in: ids ?? [] }, page: where },
|
||||
select: { role: true, page: { select: { id: true, fbPageId: true, name: true, pictureUrl: true, igUsername: true, status: true } } },
|
||||
orderBy: { page: { name: "asc" } },
|
||||
});
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { roleAtLeast } from "@/lib/auth/roles";
|
||||
|
||||
export async function approversForPages(pageIds: string[]) {
|
||||
if (!pageIds.length) return [];
|
||||
const [pages, users] = await Promise.all([
|
||||
prisma.page.findMany({ where: { id: { in: pageIds } }, select: { id: true, teamPage: { select: { teamId: true } } } }),
|
||||
prisma.user.findMany({
|
||||
where: { isActive: true, OR: [{ globalRole: "SUPERADMIN" }, { memberships: { some: { pageId: { in: pageIds }, role: { in: ["APPROVER", "MANAGER"] } } } }] },
|
||||
select: { id: true, name: true, email: true, globalRole: true, memberships: { where: { pageId: { in: pageIds } }, select: { pageId: true, role: true } }, teamMemberships: { select: { teamId: true } } },
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
]);
|
||||
return pages.flatMap((page) => users.filter((user) =>
|
||||
user.globalRole === "SUPERADMIN" ||
|
||||
((!page.teamPage || user.teamMemberships.some((m) => m.teamId === page.teamPage!.teamId)) && user.memberships.some((m) => m.pageId === page.id && roleAtLeast(m.role, "APPROVER")))
|
||||
).map((user) => ({ pageId: page.id, id: user.id, name: user.name, email: user.email, superadmin: user.globalRole === "SUPERADMIN" })));
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
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 { actorLabel, isSuperadmin, pageRoleOf, type SessionUser } from "@/lib/auth/user";
|
||||
import { roleAtLeast } from "@/lib/auth/roles";
|
||||
import { getPageCredentials } from "@/lib/facebook/tokens";
|
||||
import { cancelScheduledFacebookPost, publishToFacebook, scheduleTimeProblem } from "@/lib/facebook/posts";
|
||||
import { publishToInstagram } from "@/lib/instagram/posts";
|
||||
@@ -55,12 +56,15 @@ export async function editPost(post: Post, user: SessionUser, next: PostContent,
|
||||
...(newlyAiAssisted ? { aiAssisted: true } : {}),
|
||||
};
|
||||
return prisma.$transaction(async (tx) => {
|
||||
if (voidsApproval) await tx.postApproval.deleteMany({ where: { postId: post.id } });
|
||||
if (voidsApproval) {
|
||||
await tx.postApproval.deleteMany({ where: { postId: post.id } });
|
||||
await tx.approvalRequest.updateMany({ where: { postId: post.id, status: { in: ["PENDING", "APPROVED"] } }, data: { status: "CANCELLED", decidedAt: new Date() } });
|
||||
}
|
||||
const updated = await tx.post.update({
|
||||
where: { id: post.id },
|
||||
data: {
|
||||
...next,
|
||||
status: voidsApproval ? "PENDING_APPROVAL" : backToDraft ? "DRAFT" : post.status,
|
||||
status: voidsApproval || backToDraft ? "DRAFT" : post.status,
|
||||
...(backToDraft ? { lastError: null } : {}),
|
||||
...(newlyAiAssisted ? { aiAssisted: true } : {}),
|
||||
lastEditedById: user.id,
|
||||
@@ -82,14 +86,33 @@ export async function editPost(post: Post, user: SessionUser, next: PostContent,
|
||||
});
|
||||
}
|
||||
|
||||
export async function submitForApproval(post: Post, user: SessionUser): Promise<Post> {
|
||||
if (post.status !== "DRAFT" && post.status !== "FAILED" && post.status !== "CANCELLED") {
|
||||
export async function submitForApproval(post: Post, user: SessionUser, assigneeId: string): Promise<Post> {
|
||||
if (post.status !== "DRAFT" && post.status !== "FAILED" && post.status !== "CANCELLED" && post.status !== "PENDING_APPROVAL") {
|
||||
throw new UserFacingError("ส่งขออนุมัติได้เฉพาะโพสต์ที่เป็นฉบับร่าง");
|
||||
}
|
||||
if (post.status === "PENDING_APPROVAL") {
|
||||
const prior = await prisma.approvalRequest.findUnique({ where: { postId: post.id }, select: { requesterId: true } });
|
||||
if (prior?.requesterId !== user.id && await pageRoleOf(user, post.pageId) !== "MANAGER") throw new UserFacingError("เฉพาะผู้ส่งหรือผู้จัดการเพจที่เปลี่ยนผู้อนุมัติได้");
|
||||
}
|
||||
const assignee = await prisma.user.findUnique({ where: { id: assigneeId }, select: { id: true, isActive: true, globalRole: true } });
|
||||
if (!assignee?.isActive || !roleAtLeast(await pageRoleOf({ ...user, id: assigneeId, globalRole: assignee.globalRole }, post.pageId), "APPROVER")) {
|
||||
throw new UserFacingError("เลือกผู้อนุมัติที่มีสิทธิ์ในเพจนี้");
|
||||
}
|
||||
if (assigneeId === user.id && !isSuperadmin(user)) throw new UserFacingError("ต้องเลือกผู้อนุมัติคนอื่น");
|
||||
if (assignee.globalRole !== "SUPERADMIN" && (assigneeId === post.createdById || assigneeId === post.lastEditedById)) {
|
||||
throw new UserFacingError("ผู้สร้างหรือผู้แก้โพสต์ล่าสุดอนุมัติงานนี้ไม่ได้ เลือกคนอื่น");
|
||||
}
|
||||
return prisma.$transaction(async (tx) => {
|
||||
const claim = await tx.post.updateMany({ where: { id: post.id, status: post.status }, data: { status: "PENDING_APPROVAL", lastError: null } });
|
||||
if (!claim.count) throw new UserFacingError("สถานะโพสต์เปลี่ยนไปแล้ว กรุณาโหลดหน้าใหม่");
|
||||
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);
|
||||
await tx.approvalRequest.upsert({
|
||||
where: { postId: post.id },
|
||||
create: { postId: post.id, requesterId: user.id, assigneeId, status: "PENDING" },
|
||||
update: { requesterId: user.id, assigneeId, status: "PENDING", note: null, decidedAt: null },
|
||||
});
|
||||
const updated = await tx.post.findUniqueOrThrow({ where: { id: post.id } });
|
||||
await audit({ action: "POST_SUBMITTED", actorId: user.id, actorLabel: actorLabel(user), pageId: post.pageId, postId: post.id, detail: { assigneeId } }, tx);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
@@ -103,6 +126,8 @@ export function selfApprovalBlockReason(post: Post, user: SessionUser): string |
|
||||
|
||||
export async function approvePost(post: Post, user: SessionUser, note: string | null): Promise<Post> {
|
||||
if (post.status !== "PENDING_APPROVAL") throw new UserFacingError("โพสต์นี้ไม่ได้อยู่ในสถานะรออนุมัติ");
|
||||
const request = await prisma.approvalRequest.findUnique({ where: { postId: post.id }, select: { assigneeId: true, status: true } });
|
||||
if (request && (request.status !== "PENDING" || (request.assigneeId !== user.id && !isSuperadmin(user)))) throw new UserFacingError("คำขอนี้ไม่ได้ส่งถึงคุณ");
|
||||
const block = selfApprovalBlockReason(post, user);
|
||||
if (block) throw new UserFacingError(block);
|
||||
const ownWork = post.lastEditedById === user.id || post.createdById === user.id;
|
||||
@@ -116,6 +141,7 @@ export async function approvePost(post: Post, user: SessionUser, note: string |
|
||||
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;
|
||||
if (done) await tx.approvalRequest.updateMany({ where: { postId: post.id, status: "PENDING" }, data: { status: "APPROVED", note, decidedAt: new Date() } });
|
||||
await audit(
|
||||
{
|
||||
action: "POST_APPROVED",
|
||||
@@ -135,8 +161,11 @@ export async function rejectPost(post: Post, user: SessionUser, note: string | n
|
||||
if (post.status !== "PENDING_APPROVAL" && post.status !== "APPROVED") {
|
||||
throw new UserFacingError("ตีกลับได้เฉพาะโพสต์ที่รออนุมัติหรืออนุมัติแล้ว");
|
||||
}
|
||||
const request = await prisma.approvalRequest.findUnique({ where: { postId: post.id }, select: { assigneeId: true, status: true } });
|
||||
if (request && request.assigneeId !== user.id && !isSuperadmin(user)) throw new UserFacingError("คำขอนี้ไม่ได้ส่งถึงคุณ");
|
||||
return prisma.$transaction(async (tx) => {
|
||||
await tx.postApproval.deleteMany({ where: { postId: post.id } });
|
||||
await tx.approvalRequest.updateMany({ where: { postId: post.id, status: "PENDING" }, data: { status: "REJECTED", note, decidedAt: new Date() } });
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireUser } from "@/lib/auth/user";
|
||||
|
||||
export async function requireTeamManager(teamId: string) {
|
||||
const auth = await requireUser();
|
||||
if (!auth.ok) return auth;
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: { teamId_userId: { teamId, userId: auth.user.id } },
|
||||
select: { role: true },
|
||||
});
|
||||
if (auth.user.globalRole !== "SUPERADMIN" && member?.role !== "OWNER" && member?.role !== "ADMIN") {
|
||||
return { ok: false as const, response: NextResponse.json({ error: "ไม่มีสิทธิ์จัดการทีมนี้" }, { status: 404 }) };
|
||||
}
|
||||
const team = await prisma.team.findUnique({ where: { id: teamId }, select: { id: true, ownerId: true } });
|
||||
if (!team) return { ok: false as const, response: NextResponse.json({ error: "ไม่พบทีม" }, { status: 404 }) };
|
||||
return { ok: true as const, user: auth.user, team, member };
|
||||
}
|
||||
Reference in New Issue
Block a user