Add self-service teams and assigned post approvals
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
import crypto from "node:crypto";
|
||||
import { NextResponse } from "next/server";
|
||||
import type { PageRole } from "@prisma/client";
|
||||
import { appUrl } from "@/lib/base-path";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { actorLabel, pageRoleOf } from "@/lib/auth/user";
|
||||
import { PAGE_ROLES, roleAtLeast } from "@/lib/auth/roles";
|
||||
import { requireTeamManager } from "@/lib/teams/access";
|
||||
import { audit } from "@/lib/audit";
|
||||
import { readJson, str } from "@/lib/http";
|
||||
|
||||
export async function POST(req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await ctx.params;
|
||||
const auth = await requireTeamManager(id);
|
||||
if (!auth.ok) return auth.response;
|
||||
const body = await readJson(req);
|
||||
const email = str(body.email).trim().toLowerCase();
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return NextResponse.json({ error: "กรอกอีเมลให้ถูกต้อง" }, { status: 400 });
|
||||
if (email === auth.user.email.toLowerCase()) return NextResponse.json({ error: "คุณอยู่ในทีมนี้แล้ว" }, { status: 400 });
|
||||
const existingUser = await prisma.user.findUnique({ where: { email }, select: { id: true } });
|
||||
if (existingUser && await prisma.teamMember.findUnique({ where: { teamId_userId: { teamId: id, userId: existingUser.id } } })) {
|
||||
return NextResponse.json({ error: "ผู้ใช้นี้อยู่ในทีมแล้ว" }, { status: 409 });
|
||||
}
|
||||
const rawRoles = Array.isArray(body.pageRoles) ? body.pageRoles : [];
|
||||
const pageRoles: { pageId: string; role: PageRole }[] = [];
|
||||
for (const row of rawRoles) {
|
||||
const pageId = str(row?.pageId);
|
||||
const role = str(row?.role) as PageRole;
|
||||
if (!pageId || !PAGE_ROLES.includes(role) || pageRoles.some((x) => x.pageId === pageId)) return NextResponse.json({ error: "สิทธิ์เพจไม่ถูกต้อง" }, { status: 400 });
|
||||
const teamPage = await prisma.teamPage.findUnique({ where: { pageId }, select: { teamId: true } });
|
||||
const inviterRole = await pageRoleOf(auth.user, pageId);
|
||||
if (teamPage?.teamId !== id || !roleAtLeast(inviterRole, "MANAGER")) return NextResponse.json({ error: "คุณไม่มีสิทธิ์ให้คนอื่นเข้าถึงเพจนี้" }, { status: 403 });
|
||||
pageRoles.push({ pageId, role });
|
||||
}
|
||||
const token = crypto.randomBytes(32).toString("base64url");
|
||||
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
|
||||
const invite = await prisma.$transaction(async (tx) => {
|
||||
await tx.teamInvite.updateMany({ where: { teamId: id, email, status: "PENDING" }, data: { status: "REVOKED" } });
|
||||
const created = await tx.teamInvite.create({ data: { teamId: id, email, tokenHash, invitedById: auth.user.id, pageRoles, expiresAt: new Date(Date.now() + 7 * 86400000) } });
|
||||
await audit({ action: "TEAM_INVITE_CREATED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { teamId: id, inviteId: created.id, email, pageRoles } }, tx);
|
||||
return created;
|
||||
});
|
||||
return NextResponse.json({ invite: { id: invite.id, email, expiresAt: invite.expiresAt }, url: `${appUrl(new URL(req.url).origin)}/join/${token}` }, { status: 201 });
|
||||
}
|
||||
|
||||
export async function DELETE(req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await ctx.params;
|
||||
const auth = await requireTeamManager(id);
|
||||
if (!auth.ok) return auth.response;
|
||||
const inviteId = new URL(req.url).searchParams.get("inviteId") ?? "";
|
||||
const changed = await prisma.teamInvite.updateMany({ where: { id: inviteId, teamId: id, status: "PENDING" }, data: { status: "REVOKED" } });
|
||||
if (!changed.count) return NextResponse.json({ error: "ไม่พบคำเชิญ" }, { status: 404 });
|
||||
await audit({ action: "TEAM_INVITE_REVOKED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { teamId: id, inviteId } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { PageRole } from "@prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { actorLabel, pageRoleOf } from "@/lib/auth/user";
|
||||
import { PAGE_ROLES } from "@/lib/auth/roles";
|
||||
import { requireTeamManager } from "@/lib/teams/access";
|
||||
import { audit } from "@/lib/audit";
|
||||
import { readJson, str } from "@/lib/http";
|
||||
|
||||
export async function PUT(req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await ctx.params;
|
||||
const auth = await requireTeamManager(id);
|
||||
if (!auth.ok) return auth.response;
|
||||
const body = await readJson(req);
|
||||
const userId = str(body.userId);
|
||||
const member = await prisma.teamMember.findUnique({ where: { teamId_userId: { teamId: id, userId } } });
|
||||
if (!member) return NextResponse.json({ error: "ไม่พบสมาชิกทีม" }, { status: 404 });
|
||||
const teamRole = str(body.teamRole);
|
||||
if (teamRole) {
|
||||
if (auth.user.id !== auth.team.ownerId || member.role === "OWNER" || !["ADMIN", "MEMBER"].includes(teamRole)) return NextResponse.json({ error: "เฉพาะเจ้าของทีมที่เปลี่ยนผู้ดูแลทีมได้" }, { status: 403 });
|
||||
await prisma.teamMember.update({ where: { id: member.id }, data: { role: teamRole as "ADMIN" | "MEMBER" } });
|
||||
await audit({ action: "TEAM_MEMBER_ROLE_SET", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { teamId: id, userId, teamRole } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
const pageId = str(body.pageId);
|
||||
const role = str(body.pageRole) as PageRole;
|
||||
const attached = await prisma.teamPage.findUnique({ where: { pageId }, select: { teamId: true } });
|
||||
if (attached?.teamId !== id || await pageRoleOf(auth.user, pageId) !== "MANAGER") return NextResponse.json({ error: "ไม่มีสิทธิ์จัดการสมาชิกของเพจนี้" }, { status: 403 });
|
||||
if (member.role === "OWNER") return NextResponse.json({ error: "เปลี่ยนสิทธิ์เจ้าของทีมในเพจนี้ไม่ได้" }, { status: 403 });
|
||||
if (role && !PAGE_ROLES.includes(role)) return NextResponse.json({ error: "สิทธิ์ไม่ถูกต้อง" }, { status: 400 });
|
||||
await prisma.$transaction(async (tx) => {
|
||||
if (role) await tx.pageMember.upsert({ where: { userId_pageId: { userId, pageId } }, create: { userId, pageId, role }, update: { role } });
|
||||
else await tx.pageMember.deleteMany({ where: { userId, pageId } });
|
||||
await audit({ action: role ? "PAGE_MEMBER_SET" : "PAGE_MEMBER_REMOVED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, detail: { teamId: id, userId, role: role || null } }, tx);
|
||||
});
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
export async function DELETE(req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await ctx.params;
|
||||
const auth = await requireTeamManager(id);
|
||||
if (!auth.ok) return auth.response;
|
||||
const userId = new URL(req.url).searchParams.get("userId") ?? "";
|
||||
const member = await prisma.teamMember.findUnique({ where: { teamId_userId: { teamId: id, userId } } });
|
||||
if (!member) return NextResponse.json({ error: "ไม่พบสมาชิกทีม" }, { status: 404 });
|
||||
if (member.role === "OWNER" || userId === auth.user.id || (member.role === "ADMIN" && auth.team.ownerId !== auth.user.id)) return NextResponse.json({ error: "ไม่มีสิทธิ์ถอดสมาชิกนี้" }, { status: 403 });
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const pages = await tx.teamPage.findMany({ where: { teamId: id }, select: { pageId: true } });
|
||||
await tx.pageMember.deleteMany({ where: { userId, pageId: { in: pages.map((p) => p.pageId) } } });
|
||||
await tx.teamMember.delete({ where: { id: member.id } });
|
||||
await audit({ action: "TEAM_MEMBER_REMOVED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { teamId: id, userId } }, tx);
|
||||
});
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { actorLabel, pageRoleOf } from "@/lib/auth/user";
|
||||
import { requireTeamManager } from "@/lib/teams/access";
|
||||
import { audit } from "@/lib/audit";
|
||||
import { readJson, str } from "@/lib/http";
|
||||
|
||||
export async function POST(req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await ctx.params;
|
||||
const auth = await requireTeamManager(id);
|
||||
if (!auth.ok) return auth.response;
|
||||
if (auth.team.ownerId !== auth.user.id && auth.user.globalRole !== "SUPERADMIN") return NextResponse.json({ error: "เฉพาะเจ้าของทีมที่เพิ่มเพจเข้าทีมได้" }, { status: 403 });
|
||||
const pageId = str((await readJson(req)).pageId);
|
||||
if (await pageRoleOf(auth.user, pageId) !== "MANAGER") return NextResponse.json({ error: "ต้องเป็นผู้จัดการเพจนี้ก่อนเพิ่มเข้าทีม" }, { status: 403 });
|
||||
const existing = await prisma.teamPage.findUnique({ where: { pageId } });
|
||||
if (existing) return NextResponse.json({ error: existing.teamId === id ? "เพจอยู่ในทีมนี้แล้ว" : "เพจนี้อยู่ในทีมอื่นแล้ว" }, { status: 409 });
|
||||
const pageMembers = await prisma.pageMember.findMany({ where: { pageId }, select: { userId: true } });
|
||||
const teamMembers = await prisma.teamMember.findMany({ where: { teamId: id }, select: { userId: true } });
|
||||
const members = new Set(teamMembers.map((m) => m.userId));
|
||||
if (pageMembers.some((m) => !members.has(m.userId))) return NextResponse.json({ error: "เพจนี้ยังมีผู้ใช้ที่ไม่ได้อยู่ในทีม ให้เชิญเข้าทีมก่อน" }, { status: 409 });
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.teamPage.create({ data: { teamId: id, pageId } });
|
||||
await audit({ action: "TEAM_PAGE_ADDED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, detail: { teamId: id } }, tx);
|
||||
});
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireUser } from "@/lib/auth/user";
|
||||
|
||||
export async function GET(_req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await ctx.params;
|
||||
const auth = await requireUser();
|
||||
if (!auth.ok) return auth.response;
|
||||
const team = await prisma.team.findFirst({
|
||||
where: { id, ...(auth.user.globalRole === "SUPERADMIN" ? {} : { members: { some: { userId: auth.user.id } } }) },
|
||||
select: {
|
||||
id: true, name: true, ownerId: true,
|
||||
members: { select: { userId: true, role: true, user: { select: { name: true, email: true, isActive: true } } }, orderBy: { createdAt: "asc" } },
|
||||
pages: {
|
||||
select: {
|
||||
pageId: true,
|
||||
page: { select: { name: true, pictureUrl: true, members: { select: { userId: true, role: true } } } },
|
||||
},
|
||||
},
|
||||
invites: { where: { status: "PENDING" }, select: { id: true, email: true, expiresAt: true, pageRoles: true }, orderBy: { createdAt: "desc" } },
|
||||
},
|
||||
});
|
||||
if (!team) return NextResponse.json({ error: "ไม่พบทีม" }, { status: 404 });
|
||||
return NextResponse.json({ team });
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { actorLabel, requireUser } from "@/lib/auth/user";
|
||||
import { audit } from "@/lib/audit";
|
||||
import { readJson, str } from "@/lib/http";
|
||||
|
||||
export async function GET() {
|
||||
const auth = await requireUser();
|
||||
if (!auth.ok) return auth.response;
|
||||
const teams = await prisma.team.findMany({
|
||||
where: auth.user.globalRole === "SUPERADMIN" ? undefined : { members: { some: { userId: auth.user.id } } },
|
||||
select: { id: true, name: true, ownerId: true, members: { select: { userId: true, role: true, user: { select: { name: true, email: true } } } }, pages: { select: { pageId: true, page: { select: { name: true } } } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return NextResponse.json({ teams });
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const auth = await requireUser();
|
||||
if (!auth.ok) return auth.response;
|
||||
const body = await readJson(req);
|
||||
const name = str(body.name).trim();
|
||||
if (name.length < 2 || name.length > 80) return NextResponse.json({ error: "ชื่อทีมต้องยาว 2–80 ตัวอักษร" }, { status: 400 });
|
||||
const team = await prisma.$transaction(async (tx) => {
|
||||
const created = await tx.team.create({ data: { name, ownerId: auth.user.id, members: { create: { userId: auth.user.id, role: "OWNER" } } } });
|
||||
await audit({ action: "TEAM_CREATED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { teamId: created.id, name } }, tx);
|
||||
return created;
|
||||
});
|
||||
return NextResponse.json({ team }, { status: 201 });
|
||||
}
|
||||
Reference in New Issue
Block a user