Add self-service teams and assigned post approvals

This commit is contained in:
Loma Bot Ops
2026-11-24 11:13:20 +07:00
parent b14a9286cd
commit 55235718c3
31 changed files with 958 additions and 28 deletions
+36
View File
@@ -0,0 +1,36 @@
import Link from "next/link";
import { prisma } from "@/lib/db";
import { getConsoleContext, scopedPageIds } from "@/lib/console";
import { EmptyState, PageTitle, formatDateTime } from "@/components/ui";
import { roleAtLeast } from "@/lib/auth/roles";
export default async function ApprovalsPage() {
const ctx = await getConsoleContext();
const pageIds = scopedPageIds(ctx);
const legacyPageIds = ctx.pages.filter((p) => roleAtLeast(p.role, "APPROVER") && pageIds.includes(p.id)).map((p) => p.id);
const [assigned, sent, legacyRows] = await Promise.all([
prisma.approvalRequest.findMany({
where: { assigneeId: ctx.user.id, status: "PENDING", post: { pageId: { in: pageIds }, status: "PENDING_APPROVAL" } },
select: { id: true, createdAt: true, requester: { select: { name: true } }, post: { select: { id: true, title: true, page: { select: { name: true } } } } },
orderBy: { createdAt: "desc" },
}),
prisma.approvalRequest.findMany({
where: { requesterId: ctx.user.id, status: "PENDING", post: { pageId: { in: pageIds }, status: "PENDING_APPROVAL" } },
select: { id: true, createdAt: true, assignee: { select: { name: true } }, post: { select: { id: true, title: true, page: { select: { name: true } } } } },
orderBy: { createdAt: "desc" },
}),
prisma.post.findMany({ where: { pageId: { in: legacyPageIds }, status: "PENDING_APPROVAL", approvalRequest: null }, select: { id: true, title: true, createdById: true, lastEditedById: true, updatedAt: true, page: { select: { name: true } } }, orderBy: { updatedAt: "desc" } }),
]);
const legacy = legacyRows.filter((p) => ctx.user.globalRole === "SUPERADMIN" || (p.createdById !== ctx.user.id && p.lastEditedById !== ctx.user.id));
return <>
<PageTitle title="คำขออนุมัติ" subtitle="ตรวจโพสต์ที่ส่งถึงคุณ และติดตามงานที่คุณส่งให้คนอื่น" />
<div className="grid gap-5 xl:grid-cols-2 items-start">
<section className="card"><div className="card-head"><h2>รอฉันอนุมัติ ({assigned.length + legacy.length})</h2></div>
{assigned.length || legacy.length ? <ul>{assigned.map((r) => <li key={r.id} className="border-b border-line-2 last:border-0"><Link href={`/posts/${r.post.id}`} className="block px-[18px] py-3 hover:bg-board"><span className="block font-semibold">{r.post.title}</span><span className="text-ink-3 text-[12px]">{r.post.page.name} · ส่งโดย {r.requester.name} · {formatDateTime(r.createdAt)}</span></Link></li>)}{legacy.map((p) => <li key={p.id} className="border-b border-line-2 last:border-0"><Link href={`/posts/${p.id}`} className="block px-[18px] py-3 hover:bg-board"><span className="block font-semibold">{p.title}</span><span className="text-ink-3 text-[12px]">{p.page.name} · งานเดิมที่ไม่ได้ระบุผู้รับ · {formatDateTime(p.updatedAt)}</span></Link></li>)}</ul> : <EmptyState icon="check" title="ไม่มีงานรออนุมัติ" hint="เมื่อมีคนส่งโพสต์ถึงคุณ งานจะปรากฏที่นี่" />}
</section>
<section className="card"><div className="card-head"><h2>คำขอที่ฉันส่ง ({sent.length})</h2></div>
{sent.length ? <ul>{sent.map((r) => <li key={r.id} className="border-b border-line-2 last:border-0"><Link href={`/posts/${r.post.id}`} className="block px-[18px] py-3 hover:bg-board"><span className="block font-semibold">{r.post.title}</span><span className="text-ink-3 text-[12px]">{r.post.page.name} · ส่งถึง {r.assignee.name} · {formatDateTime(r.createdAt)}</span></Link></li>)}</ul> : <EmptyState icon="send" title="ยังไม่มีคำขอที่ส่ง" hint="สร้างโพสต์แล้วเลือกผู้อนุมัติเพื่อส่งคำขอ" />}
</section>
</div>
</>;
}
+6 -2
View File
@@ -1,12 +1,16 @@
import { prisma } from "@/lib/db";
import { getConsoleContext, scopedPageIds } from "@/lib/console";
import { Shell } from "@/components/Shell";
import { roleAtLeast } from "@/lib/auth/roles";
export default async function ConsoleLayout({ children }: { children: React.ReactNode }) {
const ctx = await getConsoleContext();
const pendingApprovals = await prisma.post.count({
where: { pageId: { in: scopedPageIds(ctx) }, status: "PENDING_APPROVAL" },
const assignedCount = await prisma.approvalRequest.count({
where: { assigneeId: ctx.user.id, status: "PENDING", post: { pageId: { in: scopedPageIds(ctx) }, status: "PENDING_APPROVAL" } },
});
const legacyPages = ctx.pages.filter((p) => roleAtLeast(p.role, "APPROVER") && (!ctx.selected || p.id === ctx.selected.id)).map((p) => p.id);
const legacy = await prisma.post.findMany({ where: { pageId: { in: legacyPages }, status: "PENDING_APPROVAL", approvalRequest: null }, select: { createdById: true, lastEditedById: true } });
const pendingApprovals = assignedCount + legacy.filter((p) => ctx.user.globalRole === "SUPERADMIN" || (p.createdById !== ctx.user.id && p.lastEditedById !== ctx.user.id)).length;
return (
<Shell
+6 -1
View File
@@ -2,6 +2,7 @@ import { notFound } from "next/navigation";
import { prisma } from "@/lib/db";
import { getConsoleContext } from "@/lib/console";
import { REQUIRED_APPROVALS } from "@/lib/posts/workflow";
import { approversForPages } from "@/lib/posts/approvers";
import { PostEditor } from "@/components/PostEditor";
import { PageTitle } from "@/components/ui";
@@ -12,9 +13,11 @@ export default async function PostPage(props: PageProps<"/posts/[id]">) {
const page = post && ctx.pages.find((p) => p.id === post.pageId);
if (!post || !page) notFound();
const [approvalsCount, log] = await Promise.all([
const [approvalsCount, log, approvalRequest, approvers] = await Promise.all([
prisma.postApproval.count({ where: { postId: id } }),
prisma.auditLog.findMany({ where: { postId: id }, orderBy: { createdAt: "desc" }, take: 30 }),
prisma.approvalRequest.findUnique({ where: { postId: id }, select: { assigneeId: true, requesterId: true, status: true, assignee: { select: { name: true } } } }),
approversForPages([post.pageId]),
]);
return (
@@ -48,6 +51,8 @@ export default async function PostPage(props: PageProps<"/posts/[id]">) {
note: (l.detail as { note?: string } | null)?.note ?? null,
}))}
approvalsCount={approvalsCount}
approvers={approvers}
approvalRequest={approvalRequest}
requiredApprovals={REQUIRED_APPROVALS}
currentUserId={ctx.user.id}
superadmin={ctx.user.globalRole === "SUPERADMIN"}
+3
View File
@@ -6,6 +6,7 @@ import { PostEditor } from "@/components/PostEditor";
import { EmptyState, PageTitle } from "@/components/ui";
import { isDayKey } from "@/lib/board";
import type { AnalysisReport } from "@/lib/analysis/types";
import { approversForPages } from "@/lib/posts/approvers";
export default async function NewPostPage(props: PageProps<"/posts/new">) {
const sp = await props.searchParams;
@@ -34,6 +35,7 @@ export default async function NewPostPage(props: PageProps<"/posts/new">) {
// Put the idea's page, else the switcher's page, first so it is the default selection.
const firstId = ideaPageId ?? ctx.selected?.id ?? null;
const ordered = firstId ? [...editable.filter((p) => p.id === firstId), ...editable.filter((p) => p.id !== firstId)] : editable;
const approvers = await approversForPages(ordered.map((p) => p.id));
return (
<>
@@ -53,6 +55,7 @@ export default async function NewPostPage(props: PageProps<"/posts/new">) {
initialDraft={initialDraft}
pages={ordered.map(({ id, name, pictureUrl, igUsername, role }) => ({ id, name, pictureUrl, igUsername, role }))}
post={null}
approvers={approvers}
currentUserId={ctx.user.id}
superadmin={ctx.user.globalRole === "SUPERADMIN"}
/>
+17
View File
@@ -0,0 +1,17 @@
import { getConsoleContext } from "@/lib/console";
import { prisma } from "@/lib/db";
import { PageTitle } from "@/components/ui";
import { TeamsManager } from "@/components/TeamsManager";
export default async function TeamsPage() {
const ctx = await getConsoleContext();
const teams = await prisma.team.findMany({
where: ctx.user.globalRole === "SUPERADMIN" ? undefined : { members: { some: { userId: ctx.user.id } } },
select: { id: true, name: true, ownerId: true },
orderBy: { createdAt: "desc" },
});
return <>
<PageTitle title="ทีมของฉัน" subtitle="รวมคนและเพจที่ทำงานร่วมกัน ส่งงานให้ผู้อนุมัติในทีม" />
<TeamsManager currentUserId={ctx.user.id} superadmin={ctx.user.globalRole === "SUPERADMIN"} teams={teams} pages={ctx.pages.filter((p) => p.role === "MANAGER").map((p) => ({ id: p.id, name: p.name }))} />
</>;
}
+10
View File
@@ -31,6 +31,14 @@ export async function PUT(req: Request, ctx: RouteContext<"/api/pages/[id]/membe
const target = await prisma.user.findUnique({ where: { id: userId }, select: { id: true, isActive: true } });
if (!target?.isActive) return NextResponse.json({ error: "ไม่พบผู้ใช้" }, { status: 404 });
const teamPage = await prisma.teamPage.findUnique({ where: { pageId: id }, select: { teamId: true } });
if (teamPage && !await prisma.teamMember.findUnique({ where: { teamId_userId: { teamId: teamPage.teamId, userId } } })) {
return NextResponse.json({ error: "เชิญผู้ใช้นี้เข้าทีมก่อนให้สิทธิ์เพจ" }, { status: 409 });
}
if (teamPage) {
const team = await prisma.team.findUnique({ where: { id: teamPage.teamId }, select: { ownerId: true } });
if (team?.ownerId === userId && auth.user.globalRole !== "SUPERADMIN") return NextResponse.json({ error: "เปลี่ยนสิทธิ์เจ้าของทีมไม่ได้" }, { status: 403 });
}
await prisma.pageMember.upsert({
where: { userId_pageId: { userId, pageId: id } },
@@ -48,6 +56,8 @@ export async function DELETE(req: Request, ctx: RouteContext<"/api/pages/[id]/me
const userId = new URL(req.url).searchParams.get("userId") ?? "";
if (userId === auth.user.id) return NextResponse.json({ error: "ถอดสิทธิ์ตัวเองไม่ได้" }, { status: 400 });
const teamPage = await prisma.teamPage.findUnique({ where: { pageId: id }, select: { team: { select: { ownerId: true } } } });
if (teamPage?.team.ownerId === userId && auth.user.globalRole !== "SUPERADMIN") return NextResponse.json({ error: "ถอดสิทธิ์เจ้าของทีมไม่ได้" }, { status: 403 });
await prisma.pageMember.deleteMany({ where: { userId, pageId: id } });
await audit({ action: "PAGE_MEMBER_REMOVED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId: id, detail: { userId } });
return NextResponse.json({ ok: true });
+5
View File
@@ -86,6 +86,11 @@ export async function POST(req: Request) {
}
const prior = await prisma.page.findUnique({ where: { fbPageId }, select: { id: true, status: true, webhookSubscribedAt: true } });
if (prior && auth.user.globalRole !== "SUPERADMIN") {
const teamPage = await prisma.teamPage.findUnique({ where: { pageId: prior.id }, select: { teamId: true } });
if (teamPage && !await prisma.teamMember.findUnique({ where: { teamId_userId: { teamId: teamPage.teamId, userId: auth.user.id } } })) {
results.push({ fbPageId, name: a.name, ok: false, webhook: false, error: "เพจนี้อยู่ในทีมแล้ว ให้เจ้าของทีมเชิญคุณก่อน" });
continue;
}
const refreshToken = prior.status !== "ACTIVE";
if (refreshToken) {
await prisma.page.update({
+4 -3
View File
@@ -19,11 +19,12 @@ export async function GET(_req: Request, ctx: RouteContext<"/api/posts/[id]">) {
const auth = await requirePageAction(post.pageId, "view");
if (!auth.ok) return auth.response;
const [approvals, log] = await Promise.all([
const [approvals, log, approvalRequest] = await Promise.all([
prisma.postApproval.findMany({ where: { postId: id }, orderBy: { createdAt: "asc" } }),
prisma.auditLog.findMany({ where: { postId: id }, orderBy: { createdAt: "desc" }, take: 50 }),
prisma.approvalRequest.findUnique({ where: { postId: id }, select: { status: true, requesterId: true, assigneeId: true, assignee: { select: { name: true } }, createdAt: true, decidedAt: true } }),
]);
return NextResponse.json({ post, approvals, log, role: auth.role });
return NextResponse.json({ post, approvals, approvalRequest, log, role: auth.role });
}
export async function PATCH(req: Request, ctx: RouteContext<"/api/posts/[id]">) {
@@ -82,7 +83,7 @@ export async function POST(req: Request, ctx: RouteContext<"/api/posts/[id]">) {
updated = await planPost(post, auth.user, body.plannedAt ? new Date(str(body.plannedAt)) : null);
break;
case "submit":
updated = await submitForApproval(post, auth.user);
updated = await submitForApproval(post, auth.user, str(body.assigneeId));
break;
case "approve":
updated = await approvePost(post, auth.user, note);
+66
View File
@@ -0,0 +1,66 @@
import crypto from "node:crypto";
import { NextResponse } from "next/server";
import type { PageRole } from "@prisma/client";
import { prisma } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth/user";
import { hashPassword, passwordProblem } from "@/lib/auth/password";
import { createSessionToken, COOKIE_NAME, sessionCookieOptions } from "@/lib/auth/session";
import { audit } from "@/lib/audit";
import { readJson, str } from "@/lib/http";
const tokenHash = (token: string) => crypto.createHash("sha256").update(token).digest("hex");
async function validInvite(token: string) {
if (!/^[A-Za-z0-9_-]{40,60}$/.test(token)) return null;
return prisma.teamInvite.findFirst({
where: { tokenHash: tokenHash(token), status: "PENDING", expiresAt: { gt: new Date() } },
select: { id: true, teamId: true, email: true, pageRoles: true, team: { select: { name: true } } },
});
}
export async function GET(_req: Request, ctx: { params: Promise<{ token: string }> }) {
const { token } = await ctx.params;
const invite = await validInvite(token);
if (!invite) return NextResponse.json({ error: "คำเชิญหมดอายุหรือถูกยกเลิก" }, { status: 404 });
const existing = await prisma.user.findUnique({ where: { email: invite.email }, select: { id: true } });
return NextResponse.json({ team: invite.team.name, email: invite.email, existingAccount: Boolean(existing) });
}
export async function POST(req: Request, ctx: { params: Promise<{ token: string }> }) {
const { token } = await ctx.params;
const invite = await validInvite(token);
if (!invite) return NextResponse.json({ error: "คำเชิญหมดอายุหรือถูกยกเลิก" }, { status: 404 });
const current = await getCurrentUser();
const existing = await prisma.user.findUnique({ where: { email: invite.email }, select: { id: true, name: true, isActive: true } });
if (existing && (!current || current.id !== existing.id)) return NextResponse.json({ error: "กรุณาเข้าสู่ระบบด้วยอีเมลที่ได้รับคำเชิญก่อน" }, { status: 401 });
if (current && current.email.toLowerCase() !== invite.email) return NextResponse.json({ error: "คำเชิญนี้เป็นของอีเมลอื่น" }, { status: 403 });
if (existing && !existing.isActive) return NextResponse.json({ error: "บัญชีนี้ถูกปิดใช้งาน" }, { status: 403 });
const body = await readJson(req);
const name = str(body.name).trim();
const password = str(body.password);
if (!existing && (name.length < 2 || name.length > 100 || passwordProblem(password))) {
return NextResponse.json({ error: name.length < 2 ? "กรอกชื่ออย่างน้อย 2 ตัวอักษร" : passwordProblem(password) ?? "ชื่อยาวเกินไป" }, { status: 400 });
}
const roles = Array.isArray(invite.pageRoles) ? invite.pageRoles as { pageId: string; role: PageRole }[] : [];
try {
const user = await prisma.$transaction(async (tx) => {
const claimed = await tx.teamInvite.updateMany({ where: { id: invite.id, status: "PENDING", expiresAt: { gt: new Date() } }, data: { status: "ACCEPTED", acceptedAt: new Date() } });
if (!claimed.count) throw new Error("Invite already used");
const target = existing ?? await tx.user.create({ data: { email: invite.email, name, passwordHash: await hashPassword(password), globalRole: "MEMBER" }, select: { id: true, name: true, isActive: true } });
await tx.teamMember.upsert({ where: { teamId_userId: { teamId: invite.teamId, userId: target.id } }, create: { teamId: invite.teamId, userId: target.id, role: "MEMBER" }, update: {} });
for (const row of roles) {
const attached = await tx.teamPage.findUnique({ where: { pageId: row.pageId }, select: { teamId: true } });
if (attached?.teamId !== invite.teamId) continue;
await tx.pageMember.upsert({ where: { userId_pageId: { userId: target.id, pageId: row.pageId } }, create: { userId: target.id, pageId: row.pageId, role: row.role }, update: { role: row.role } });
await audit({ action: "PAGE_MEMBER_SET", actorId: target.id, actorLabel: target.name, pageId: row.pageId, detail: { teamId: invite.teamId, source: "TEAM_INVITE", role: row.role } }, tx);
}
await audit({ action: "TEAM_INVITE_ACCEPTED", actorId: target.id, actorLabel: target.name, detail: { teamId: invite.teamId, inviteId: invite.id } }, tx);
return target;
});
const response = NextResponse.json({ ok: true, teamId: invite.teamId });
if (!existing) response.cookies.set(COOKIE_NAME, await createSessionToken({ userId: user.id, email: invite.email, name: user.name, role: "MEMBER", mustChangePassword: false }), sessionCookieOptions(true));
return response;
} catch {
return NextResponse.json({ error: "รับคำเชิญไม่สำเร็จ กรุณาลองใหม่" }, { status: 409 });
}
}
+55
View File
@@ -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 });
}
+54
View File
@@ -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 });
}
+26
View File
@@ -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 });
}
+25
View File
@@ -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 });
}
+30
View File
@@ -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 });
}
+6
View File
@@ -0,0 +1,6 @@
import { JoinInvite } from "@/components/JoinInvite";
export default async function JoinPage(props: { params: Promise<{ token: string }> }) {
const { token } = await props.params;
return <main className="login-page"><JoinInvite token={token} /></main>;
}