diff --git a/README.md b/README.md
index 397a422..9c9e36d 100644
--- a/README.md
+++ b/README.md
@@ -27,7 +27,11 @@ npm run dev # http://localhost:3000
ผู้ใช้ที่สร้างจาก CLI หรือหน้า `/users` ต้องเปลี่ยนรหัสผ่านตอนเข้าครั้งแรก
-**เข้าสู่ระบบด้วย Google / Facebook** (ไม่บังคับ) — ใช้ได้กับบัญชีที่มีอยู่แล้วเท่านั้น (ไม่มีสมัครเอง): แอดมินสร้างผู้ใช้ด้วยอีเมลเดียวกับบัญชี Google/Facebook ของคนนั้น → ครั้งแรกที่กดปุ่ม ระบบผูกบัญชีให้จากอีเมลที่ยืนยันแล้ว → ครั้งต่อไปจำจาก ID ของ provider. เข้าด้วยวิธีนี้ไม่ต้องเปลี่ยนรหัสผ่านชั่วคราว (แต่ถ้าเข้าด้วยรหัสผ่านยังต้องเปลี่ยน)
+**เข้าสู่ระบบด้วย Google / Facebook** (ไม่บังคับ) — ใช้ได้กับบัญชีที่มีอยู่แล้วเท่านั้น: แอดมินสร้างผู้ใช้ด้วยอีเมลเดียวกับบัญชี Google/Facebook ของคนนั้น → ครั้งแรกที่กดปุ่ม ระบบผูกบัญชีให้จากอีเมลที่ยืนยันแล้ว → ครั้งต่อไปจำจาก ID ของ provider. เข้าด้วยวิธีนี้ไม่ต้องเปลี่ยนรหัสผ่านชั่วคราว (แต่ถ้าเข้าด้วยรหัสผ่านยังต้องเปลี่ยน)
+
+**ทีมและคำเชิญ** — ผู้ใช้ล็อกอินแล้วสร้างทีมที่ `/teams` ได้ เจ้าของทีมเพิ่มเพจที่ตนเป็น `MANAGER`, เชิญสมาชิกด้วยอีเมลและคัดลอกลิงก์ไปส่ง ผู้รับที่มีบัญชีแล้วต้องล็อกอินด้วยอีเมลนั้น ส่วนผู้รับใหม่ตั้งชื่อ/รหัสผ่านจากลิงก์คำเชิญ ลิงก์ใช้ครั้งเดียวและหมดอายุใน 7 วัน การรับคำเชิญให้สิทธิ์เฉพาะเพจที่ระบุในคำเชิญ; ทีมไม่มีบริการส่งอีเมลอัตโนมัติ
+
+**คำขออนุมัติ** — ผู้เขียนเลือกผู้อนุมัติของเพจก่อนส่งงาน ผู้รับเห็นงานที่ `/approvals`; ผู้ส่งติดตามและเปลี่ยนผู้รับได้ ผู้สร้างหรือผู้แก้ล่าสุดอนุมัติงานตัวเองไม่ได้ แก้เนื้อหาแล้วคำขอเดิมหมดผลและโพสต์กลับเป็นฉบับร่าง
## Env
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 7660242..88d7886 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -136,7 +136,15 @@ model PostInsightSnapshot { postId, date @db.Date, impressions, engaged, reactio
- `MEMBER` เชื่อม Facebook ของตนและเลือกเพจที่บัญชีนั้นมีงาน `MANAGE` หรือสิทธิ์จัดการเต็มรูปแบบ เมื่อเชื่อมจะได้ `PageMember: MANAGER` ของเพจนั้น; เพจที่เชื่อมอยู่แล้วเพิ่มสิทธิ์ให้ผู้เชื่อมโดยไม่เขียนทับ token เดิม
- `SUPERADMIN` เข้าได้ทุกเพจ + เชื่อม/ถอดเพจ + จัดการผู้ใช้
- **Separation of duty**: คนที่แก้ล่าสุดอนุมัติโพสต์ตัวเองไม่ได้ (ยกเว้น SUPERADMIN และต้องบันทึกใน AuditLog ว่าอนุมัติงานตัวเอง)
-- แก้ caption/รูปหลังอนุมัติ → ลบ `PostApproval` ทั้งหมด กลับเป็น `PENDING_APPROVAL`
+- แก้ caption/รูปหลังส่งหรืออนุมัติ → ลบ `PostApproval` ทั้งหมด ยกเลิก `ApprovalRequest` ที่ค้าง และกลับเป็น `DRAFT` เพื่อเลือกผู้อนุมัติแล้วส่งใหม่
+
+### ทีมและผู้รับคำขออนุมัติ
+
+- `Team` มีเจ้าของและสมาชิก (`TeamMember`: OWNER/ADMIN/MEMBER) ผู้ใช้หนึ่งคนอยู่หลายทีมได้ เพจหนึ่งอยู่ได้ทีมเดียว (`TeamPage`)
+- `PageMember` ยังเป็นสิทธิ์รายเพจหลัก; เมื่อเพจอยู่ในทีม ผู้ใช้ทั่วไปต้องมีทั้ง `PageMember` และ `TeamMember` ของทีมนั้นจึงเข้าถึงได้ `SUPERADMIN` ยังดูแลทุกเพจ
+- เพิ่มเพจเข้าทีมได้เมื่อผู้เพิ่มเป็น `MANAGER` และผู้ที่มี `PageMember` อยู่ก่อนทั้งหมดอยู่ในทีมแล้ว เพื่อไม่ตัดสิทธิ์เพจเดิมโดยไม่ตั้งใจ
+- `TeamInvite` เก็บ hash ของลิงก์ 256-bit, อีเมล, สิทธิ์เพจ, วันหมดอายุ 7 วัน; ลิงก์รับได้ครั้งเดียว ผู้มีบัญชีต้องล็อกอินด้วยอีเมลนั้น ผู้รับใหม่สร้างบัญชีจากลิงก์ได้ หน้า UI ให้คัดลอกลิงก์ไปส่งเอง
+- `ApprovalRequest` ผูกโพสต์กับผู้รับหนึ่งคนและผู้ส่งหนึ่งคน; ผู้รับต้องมี `APPROVER` ขึ้นไปในเพจนั้น การอนุมัติ/ตีกลับตรวจผู้รับซ้ำที่ server; ผู้ส่งหรือผู้จัดการเพจเปลี่ยนผู้รับได้
- เช็กสิทธิ์ใน route handler ทุกตัวด้วย `requirePageRole(session, pageId, minRole)` — proxy เช็กแค่ว่า login แล้ว
## Flow โพสต์
diff --git a/prisma/migrations/20261124110000_teams_and_approval_requests/migration.sql b/prisma/migrations/20261124110000_teams_and_approval_requests/migration.sql
new file mode 100644
index 0000000..f55d864
--- /dev/null
+++ b/prisma/migrations/20261124110000_teams_and_approval_requests/migration.sql
@@ -0,0 +1,125 @@
+-- CreateEnum
+CREATE TYPE "TeamRole" AS ENUM ('OWNER', 'ADMIN', 'MEMBER');
+
+-- CreateEnum
+CREATE TYPE "TeamInviteStatus" AS ENUM ('PENDING', 'ACCEPTED', 'REVOKED');
+
+-- CreateEnum
+CREATE TYPE "ApprovalRequestStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED', 'CANCELLED');
+
+-- CreateTable
+CREATE TABLE "Team" (
+ "id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "ownerId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "Team_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "TeamMember" (
+ "id" TEXT NOT NULL,
+ "teamId" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "role" "TeamRole" NOT NULL DEFAULT 'MEMBER',
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "TeamMember_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "TeamPage" (
+ "id" TEXT NOT NULL,
+ "teamId" TEXT NOT NULL,
+ "pageId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "TeamPage_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "TeamInvite" (
+ "id" TEXT NOT NULL,
+ "teamId" TEXT NOT NULL,
+ "email" TEXT NOT NULL,
+ "tokenHash" TEXT NOT NULL,
+ "status" "TeamInviteStatus" NOT NULL DEFAULT 'PENDING',
+ "invitedById" TEXT NOT NULL,
+ "pageRoles" JSONB NOT NULL,
+ "expiresAt" TIMESTAMP(3) NOT NULL,
+ "acceptedAt" TIMESTAMP(3),
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "TeamInvite_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "ApprovalRequest" (
+ "id" TEXT NOT NULL,
+ "postId" TEXT NOT NULL,
+ "assigneeId" TEXT NOT NULL,
+ "requesterId" TEXT NOT NULL,
+ "status" "ApprovalRequestStatus" NOT NULL DEFAULT 'PENDING',
+ "note" TEXT,
+ "decidedAt" TIMESTAMP(3),
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "ApprovalRequest_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "TeamMember_userId_idx" ON "TeamMember"("userId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "TeamMember_teamId_userId_key" ON "TeamMember"("teamId", "userId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "TeamPage_pageId_key" ON "TeamPage"("pageId");
+
+-- CreateIndex
+CREATE INDEX "TeamPage_teamId_idx" ON "TeamPage"("teamId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "TeamInvite_tokenHash_key" ON "TeamInvite"("tokenHash");
+
+-- CreateIndex
+CREATE INDEX "TeamInvite_teamId_email_idx" ON "TeamInvite"("teamId", "email");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "ApprovalRequest_postId_key" ON "ApprovalRequest"("postId");
+
+-- CreateIndex
+CREATE INDEX "ApprovalRequest_assigneeId_status_idx" ON "ApprovalRequest"("assigneeId", "status");
+
+-- AddForeignKey
+ALTER TABLE "Team" ADD CONSTRAINT "Team_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "TeamMember" ADD CONSTRAINT "TeamMember_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "TeamMember" ADD CONSTRAINT "TeamMember_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "TeamPage" ADD CONSTRAINT "TeamPage_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "TeamPage" ADD CONSTRAINT "TeamPage_pageId_fkey" FOREIGN KEY ("pageId") REFERENCES "Page"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "TeamInvite" ADD CONSTRAINT "TeamInvite_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "TeamInvite" ADD CONSTRAINT "TeamInvite_invitedById_fkey" FOREIGN KEY ("invitedById") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "ApprovalRequest" ADD CONSTRAINT "ApprovalRequest_postId_fkey" FOREIGN KEY ("postId") REFERENCES "Post"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "ApprovalRequest" ADD CONSTRAINT "ApprovalRequest_assigneeId_fkey" FOREIGN KEY ("assigneeId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "ApprovalRequest" ADD CONSTRAINT "ApprovalRequest_requesterId_fkey" FOREIGN KEY ("requesterId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index b789adb..be789f6 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -18,6 +18,25 @@ enum PageRole {
MANAGER // + manage page members
}
+enum TeamRole {
+ OWNER
+ ADMIN
+ MEMBER
+}
+
+enum TeamInviteStatus {
+ PENDING
+ ACCEPTED
+ REVOKED
+}
+
+enum ApprovalRequestStatus {
+ PENDING
+ APPROVED
+ REJECTED
+ CANCELLED
+}
+
enum PageStatus {
ACTIVE
TOKEN_INVALID
@@ -67,6 +86,11 @@ model User {
analyses PageAnalysis[]
identities UserIdentity[]
postGenerationJobs PostGenerationJob[]
+ ownedTeams Team[] @relation("TeamOwner")
+ teamMemberships TeamMember[]
+ teamInvitesSent TeamInvite[] @relation("TeamInviteSender")
+ approvalAssignments ApprovalRequest[] @relation("ApprovalAssignee")
+ approvalRequestsSent ApprovalRequest[] @relation("ApprovalRequester")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -143,6 +167,7 @@ model Page {
profile PageProfile?
aiUsage AiUsage[]
generationJobs PostGenerationJob[]
+ teamPage TeamPage?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -201,6 +226,7 @@ model Post {
insights PostInsightSnapshot[]
auditLogs AuditLog[]
generationJob PostGenerationJob?
+ approvalRequest ApprovalRequest?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -209,6 +235,78 @@ model Post {
@@index([status, scheduledPublishAt])
}
+model Team {
+ id String @id @default(cuid())
+ name String
+ ownerId String
+ owner User @relation("TeamOwner", fields: [ownerId], references: [id], onDelete: Restrict)
+ members TeamMember[]
+ pages TeamPage[]
+ invites TeamInvite[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+}
+
+model TeamMember {
+ id String @id @default(cuid())
+ teamId String
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ role TeamRole @default(MEMBER)
+ createdAt DateTime @default(now())
+
+ @@unique([teamId, userId])
+ @@index([userId])
+}
+
+// A Page belongs to at most one team. PageMember remains the page permission source.
+model TeamPage {
+ id String @id @default(cuid())
+ teamId String
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ pageId String @unique
+ page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
+ createdAt DateTime @default(now())
+
+ @@index([teamId])
+}
+
+model TeamInvite {
+ id String @id @default(cuid())
+ teamId String
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ email String
+ tokenHash String @unique
+ status TeamInviteStatus @default(PENDING)
+ invitedById String
+ invitedBy User @relation("TeamInviteSender", fields: [invitedById], references: [id], onDelete: Restrict)
+ pageRoles Json
+ expiresAt DateTime
+ acceptedAt DateTime?
+ createdAt DateTime @default(now())
+
+ @@index([teamId, email])
+}
+
+// One active assignment per post. Edits cancel it; resubmission replaces it.
+model ApprovalRequest {
+ id String @id @default(cuid())
+ postId String @unique
+ post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
+ assigneeId String
+ assignee User @relation("ApprovalAssignee", fields: [assigneeId], references: [id], onDelete: Restrict)
+ requesterId String
+ requester User @relation("ApprovalRequester", fields: [requesterId], references: [id], onDelete: Restrict)
+ status ApprovalRequestStatus @default(PENDING)
+ note String?
+ decidedAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([assigneeId, status])
+}
+
// One approver's vote. Rows are deleted whenever the content changes or the
// post is rejected, which restarts the approval round.
model PostApproval {
diff --git a/src/app/(console)/approvals/page.tsx b/src/app/(console)/approvals/page.tsx
new file mode 100644
index 0000000..735be6b
--- /dev/null
+++ b/src/app/(console)/approvals/page.tsx
@@ -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 <>
+
+
+
รอฉันอนุมัติ ({assigned.length + legacy.length})
+ {assigned.length || legacy.length ? {assigned.map((r) => - {r.post.title}{r.post.page.name} · ส่งโดย {r.requester.name} · {formatDateTime(r.createdAt)}
)}{legacy.map((p) => - {p.title}{p.page.name} · งานเดิมที่ไม่ได้ระบุผู้รับ · {formatDateTime(p.updatedAt)}
)}
: }
+
+
คำขอที่ฉันส่ง ({sent.length})
+ {sent.length ? {sent.map((r) => - {r.post.title}{r.post.page.name} · ส่งถึง {r.assignee.name} · {formatDateTime(r.createdAt)}
)}
: }
+
+
+ >;
+}
diff --git a/src/app/(console)/layout.tsx b/src/app/(console)/layout.tsx
index 702de3f..278c150 100644
--- a/src/app/(console)/layout.tsx
+++ b/src/app/(console)/layout.tsx
@@ -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 (
) {
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"}
diff --git a/src/app/(console)/posts/new/page.tsx b/src/app/(console)/posts/new/page.tsx
index a1d8bd4..91bf931 100644
--- a/src/app/(console)/posts/new/page.tsx
+++ b/src/app/(console)/posts/new/page.tsx
@@ -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"}
/>
diff --git a/src/app/(console)/teams/page.tsx b/src/app/(console)/teams/page.tsx
new file mode 100644
index 0000000..31f264c
--- /dev/null
+++ b/src/app/(console)/teams/page.tsx
@@ -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 <>
+
+ p.role === "MANAGER").map((p) => ({ id: p.id, name: p.name }))} />
+ >;
+}
diff --git a/src/app/api/pages/[id]/members/route.ts b/src/app/api/pages/[id]/members/route.ts
index d8eef1c..1d3637f 100644
--- a/src/app/api/pages/[id]/members/route.ts
+++ b/src/app/api/pages/[id]/members/route.ts
@@ -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 });
diff --git a/src/app/api/pages/route.ts b/src/app/api/pages/route.ts
index d5fa730..dc7225d 100644
--- a/src/app/api/pages/route.ts
+++ b/src/app/api/pages/route.ts
@@ -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({
diff --git a/src/app/api/posts/[id]/route.ts b/src/app/api/posts/[id]/route.ts
index ff35cfb..c0cacbd 100644
--- a/src/app/api/posts/[id]/route.ts
+++ b/src/app/api/posts/[id]/route.ts
@@ -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);
diff --git a/src/app/api/team-invites/[token]/route.ts b/src/app/api/team-invites/[token]/route.ts
new file mode 100644
index 0000000..1774d42
--- /dev/null
+++ b/src/app/api/team-invites/[token]/route.ts
@@ -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 });
+ }
+}
diff --git a/src/app/api/teams/[id]/invites/route.ts b/src/app/api/teams/[id]/invites/route.ts
new file mode 100644
index 0000000..2cae3b2
--- /dev/null
+++ b/src/app/api/teams/[id]/invites/route.ts
@@ -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 });
+}
diff --git a/src/app/api/teams/[id]/members/route.ts b/src/app/api/teams/[id]/members/route.ts
new file mode 100644
index 0000000..de1e8a6
--- /dev/null
+++ b/src/app/api/teams/[id]/members/route.ts
@@ -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 });
+}
diff --git a/src/app/api/teams/[id]/pages/route.ts b/src/app/api/teams/[id]/pages/route.ts
new file mode 100644
index 0000000..9101bcc
--- /dev/null
+++ b/src/app/api/teams/[id]/pages/route.ts
@@ -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 });
+}
diff --git a/src/app/api/teams/[id]/route.ts b/src/app/api/teams/[id]/route.ts
new file mode 100644
index 0000000..f30a4b7
--- /dev/null
+++ b/src/app/api/teams/[id]/route.ts
@@ -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 });
+}
diff --git a/src/app/api/teams/route.ts b/src/app/api/teams/route.ts
new file mode 100644
index 0000000..402f887
--- /dev/null
+++ b/src/app/api/teams/route.ts
@@ -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 });
+}
diff --git a/src/app/join/[token]/page.tsx b/src/app/join/[token]/page.tsx
new file mode 100644
index 0000000..eff9609
--- /dev/null
+++ b/src/app/join/[token]/page.tsx
@@ -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 ;
+}
diff --git a/src/components/JoinInvite.tsx b/src/components/JoinInvite.tsx
new file mode 100644
index 0000000..a60c964
--- /dev/null
+++ b/src/components/JoinInvite.tsx
@@ -0,0 +1,57 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
+import { withBase } from "@/lib/base-path";
+import { Icon } from "./Icon";
+import { Notice } from "./ui";
+
+type Info = { team: string; email: string; existingAccount: boolean };
+
+export function JoinInvite({ token }: { token: string }) {
+ const router = useRouter();
+ const [info, setInfo] = useState(null);
+ const [name, setName] = useState("");
+ const [password, setPassword] = useState("");
+ const [error, setError] = useState("");
+ const [loading, setLoading] = useState(true);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ fetch(withBase(`/api/team-invites/${token}`), { cache: "no-store" }).then(async (r) => {
+ const data = await r.json();
+ if (!r.ok) throw new Error(data.error ?? "ไม่พบคำเชิญ");
+ setInfo(data);
+ }).catch((e) => setError((e as Error).message)).finally(() => setLoading(false));
+ }, [token]);
+
+ async function accept(e: React.FormEvent) {
+ e.preventDefault(); setBusy(true); setError("");
+ try {
+ const res = await fetch(withBase(`/api/team-invites/${token}`), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, password }) });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error ?? "รับคำเชิญไม่สำเร็จ");
+ router.replace("/teams"); router.refresh();
+ } catch (e) { setError((e as Error).message); } finally { setBusy(false); }
+ }
+
+ return
+
คำเชิญเข้าทีม
+
ร่วมงานกับทีม
+ {loading &&
กำลังตรวจคำเชิญ…
}
+ {error &&
{error}}
+ {info && <>
+
ทีม {info.team} เชิญ {info.email} เข้าร่วม
+
+ {info.existingAccount &&
เข้าสู่ระบบด้วยอีเมลที่ได้รับคำเชิญ}
+ >}
+
+
;
+}
diff --git a/src/components/PostEditor.tsx b/src/components/PostEditor.tsx
index a080b52..564c61a 100644
--- a/src/components/PostEditor.tsx
+++ b/src/components/PostEditor.tsx
@@ -86,6 +86,8 @@ export function PostEditor({
log = [],
approvalsCount = 0,
requiredApprovals = 1,
+ approvers = [],
+ approvalRequest = null,
currentUserId,
superadmin,
initialDay,
@@ -96,6 +98,8 @@ export function PostEditor({
log?: EditorLogEntry[];
approvalsCount?: number;
requiredApprovals?: number;
+ approvers?: { pageId: string; id: string; name: string; email: string; superadmin: boolean }[];
+ approvalRequest?: { assigneeId: string; requesterId: string; status: string; assignee: { name: string } } | null;
currentUserId: string;
superadmin: boolean;
initialDay?: string;
@@ -113,16 +117,21 @@ export function PostEditor({
const [targets, setTargets] = useState(post?.targets ?? ["FACEBOOK"]);
const [scheduleAt, setScheduleAt] = useState(() => toBangkokInput(new Date(Date.now() + 60 * 60 * 1000)));
const [note, setNote] = useState("");
+ const [assigneeId, setAssigneeId] = useState(approvalRequest?.assigneeId ?? "");
const [plannedDay, setPlannedDay] = useState(initialDay ?? "");
const [busy, setBusy] = useState(null);
const [error, setError] = useState(null);
const page = pages.find((p) => p.id === pageId) ?? null;
+ const eligibleApprovers = approvers.filter((a) => a.pageId === pageId && (a.superadmin || (a.id !== currentUserId && a.id !== post?.createdById && a.id !== post?.lastEditedById)));
+ const selectedAssigneeId = eligibleApprovers.some((a) => a.id === assigneeId) ? assigneeId : eligibleApprovers[0]?.id ?? "";
const role = page?.role ?? null;
const status: PostStatus = post?.status ?? "DRAFT";
const editable = !post || EDITABLE.includes(status);
const canEdit = roleAtLeast(role, "EDITOR") && editable;
const canApprove = roleAtLeast(role, "APPROVER");
+ const canDecide = canApprove && (!approvalRequest || approvalRequest.status !== "PENDING" || approvalRequest.assigneeId === currentUserId || superadmin);
+ const canReassign = Boolean(post && status === "PENDING_APPROVAL" && roleAtLeast(role, "EDITOR") && (approvalRequest?.requesterId === currentUserId || role === "MANAGER" || superadmin));
const ownWork = post && (post.lastEditedById === currentUserId || post.createdById === currentUserId);
const selfBlocked = Boolean(ownWork && !superadmin);
const dirty =
@@ -178,9 +187,10 @@ export function PostEditor({
/** New post: create and submit in one tap. */
async function saveAndSubmit() {
+ if (!selectedAssigneeId) return setError("เลือกผู้อนุมัติก่อนส่งคำขอ");
const id = await save({ navigate: false });
if (!id) return;
- const body = await call("submit", `/api/posts/${id}`, { method: "POST", body: JSON.stringify({ action: "submit" }) });
+ const body = await call("submit", `/api/posts/${id}`, { method: "POST", body: JSON.stringify({ action: "submit", assigneeId: selectedAssigneeId }) });
toast.show(body ? "ส่งให้ผู้อนุมัติแล้ว" : "บันทึกฉบับร่างแล้ว แต่ส่งขออนุมัติไม่สำเร็จ", body ? "ok" : "warn");
router.replace(`/posts/${id}`);
}
@@ -196,8 +206,15 @@ export function PostEditor({
async function act(action: string, extra: Record = {}) {
if (!post) return;
- if (dirty && canEdit && !(await save())) return;
- const body = await call(action, `/api/posts/${post.id}`, { method: "POST", body: JSON.stringify({ action, note: note || undefined, ...extra }) });
+ if (dirty && canEdit) {
+ if (!(await save())) return;
+ if (["approve", "reject", "publish", "schedule"].includes(action)) {
+ toast.show("บันทึกการแก้ไขแล้ว กรุณาส่งขออนุมัติใหม่", "warn");
+ router.refresh();
+ return;
+ }
+ }
+ const body = await call(action, `/api/posts/${post.id}`, { method: "POST", body: JSON.stringify({ action, note: note || undefined, ...(action === "submit" ? { assigneeId: selectedAssigneeId } : {}), ...extra }) });
if (body) {
setNote("");
toast.show(ACT_DONE[action] ?? "เรียบร้อย");
@@ -216,7 +233,7 @@ export function PostEditor({
? null
: (status === "DRAFT" || status === "FAILED" || status === "CANCELLED") && roleAtLeast(role, "EDITOR")
? { label: "ส่งขออนุมัติ", tone: "primary", run: () => act("submit") }
- : status === "PENDING_APPROVAL" && canApprove && !selfBlocked
+ : status === "PENDING_APPROVAL" && canDecide && !selfBlocked
? { label: "อนุมัติ", tone: "success", run: () => act("approve") }
: status === "APPROVED" && canApprove
? { label: "เผยแพร่ตอนนี้", tone: "success", run: () => act("publish") }
@@ -358,6 +375,17 @@ export function PostEditor({
{error && {error}}
+ {canEdit && (status === "DRAFT" || status === "FAILED" || status === "CANCELLED") && (
+
+
+
+ {eligibleApprovers.length === 0 &&
ให้ผู้จัดการเพจเพิ่มผู้อนุมัติอีกคนก่อนส่งคำขอ
}
+
+ )}
+
{canEdit && (
{/* On phones the save/submit pair lives in the action dock below. */}
@@ -409,10 +437,18 @@ export function PostEditor({
{status === "PENDING_APPROVAL" && (
<>
+ {approvalRequest?.status === "PENDING" &&
ส่งถึง {approvalRequest.assignee.name}
}
+ {canReassign &&
+
+
+
+
}
อนุมัติแล้ว {approvalsCount} / {requiredApprovals}
- {canApprove ? (
+ {canDecide ? (
selfBlocked ? (
คุณเป็นคนแก้โพสต์นี้ล่าสุด ต้องให้ผู้อนุมัติคนอื่นตรวจ
) : (
@@ -429,7 +465,7 @@ export function PostEditor({
>
)
) : (
-
รอผู้อนุมัติของเพจนี้ตรวจ
+
รอผู้อนุมัติที่ได้รับคำขอตรวจ
)}
>
)}
diff --git a/src/components/Shell.tsx b/src/components/Shell.tsx
index 77521d0..d467985 100644
--- a/src/components/Shell.tsx
+++ b/src/components/Shell.tsx
@@ -30,6 +30,7 @@ interface NavEntry {
const WORK: NavEntry[] = [
{ href: "/", label: "แผนคอนเทนต์", icon: "calendar", also: ["/calendar"] },
{ href: "/posts", label: "โพสต์ทั้งหมด", icon: "post", count: "pendingApprovals" },
+ { href: "/approvals", label: "รอฉันอนุมัติ", icon: "check", count: "pendingApprovals" },
{ href: "/inbox", label: "Inbox", icon: "inbox" },
{ href: "/auto-reply", label: "Auto-reply", icon: "bolt" },
{ href: "/insights", label: "Insights", icon: "chart" },
@@ -37,6 +38,7 @@ const WORK: NavEntry[] = [
];
const SETTINGS: NavEntry[] = [
{ href: "/account", label: "บัญชีของฉัน", icon: "users" },
+ { href: "/teams", label: "ทีมของฉัน", icon: "users" },
{ href: "/pages", label: "เพจที่เชื่อม", icon: "pages" },
{ href: "/profile", label: "โปรไฟล์ร้าน", icon: "store" },
{ href: "/users", label: "ผู้ใช้", icon: "users", superadmin: true },
diff --git a/src/components/TeamsManager.tsx b/src/components/TeamsManager.tsx
new file mode 100644
index 0000000..f070be5
--- /dev/null
+++ b/src/components/TeamsManager.tsx
@@ -0,0 +1,173 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
+import { withBase } from "@/lib/base-path";
+import { Icon } from "./Icon";
+import { EmptyState, Notice } from "./ui";
+
+type PageRole = "VIEWER" | "EDITOR" | "APPROVER" | "MANAGER";
+type TeamRole = "OWNER" | "ADMIN" | "MEMBER";
+type Team = { id: string; name: string; ownerId: string };
+type Detail = Team & {
+ members: { userId: string; role: TeamRole; user: { name: string; email: string; isActive: boolean } }[];
+ pages: { pageId: string; page: { name: string; members: { userId: string; role: PageRole }[] } }[];
+ invites: { id: string; email: string; expiresAt: string }[];
+};
+const ROLES: { value: PageRole; label: string }[] = [
+ { value: "VIEWER", label: "ดูอย่างเดียว" }, { value: "EDITOR", label: "ผู้เขียน" },
+ { value: "APPROVER", label: "ผู้อนุมัติ" }, { value: "MANAGER", label: "ผู้จัดการเพจ" },
+];
+
+async function request
(path: string, init?: RequestInit): Promise {
+ const res = await fetch(withBase(path), { ...init, headers: { "Content-Type": "application/json" }, cache: "no-store" });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(body.error ?? "ทำรายการไม่สำเร็จ");
+ return body as T;
+}
+
+export function TeamsManager({ currentUserId, superadmin, teams: initialTeams, pages }: { currentUserId: string; superadmin: boolean; teams: Team[]; pages: { id: string; name: string }[] }) {
+ const router = useRouter();
+ const [teams, setTeams] = useState(initialTeams);
+ const [selected, setSelected] = useState(initialTeams[0]?.id ?? "");
+ const [detail, setDetail] = useState(null);
+ const [name, setName] = useState("");
+ const [email, setEmail] = useState("");
+ const [selectedPages, setSelectedPages] = useState>({});
+ const [pageToAttach, setPageToAttach] = useState("");
+ const [inviteUrl, setInviteUrl] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [message, setMessage] = useState("");
+ const canManage = superadmin || detail?.ownerId === currentUserId || detail?.members.some((m) => m.userId === currentUserId && m.role === "ADMIN");
+
+ async function reload(id = selected) {
+ const [list, one] = await Promise.all([
+ request<{ teams: Team[] }>("/api/teams"),
+ id ? request<{ team: Detail }>(`/api/teams/${id}`) : Promise.resolve(null),
+ ]);
+ setTeams(list.teams);
+ setDetail(one?.team ?? null);
+ router.refresh();
+ }
+
+ useEffect(() => {
+ if (!selected) return;
+ let active = true;
+ request<{ team: Detail }>(`/api/teams/${selected}`).then((data) => { if (active) setDetail(data.team); }).catch((e) => { if (active) setError((e as Error).message); });
+ return () => { active = false; };
+ }, [selected]);
+
+ async function run(fn: () => Promise) {
+ setBusy(true); setError(""); setMessage("");
+ try { await fn(); } catch (e) { setError((e as Error).message); } finally { setBusy(false); }
+ }
+
+ async function createTeam(e: React.FormEvent) {
+ e.preventDefault();
+ await run(async () => {
+ const data = await request<{ team: Team }>("/api/teams", { method: "POST", body: JSON.stringify({ name }) });
+ setName(""); setSelected(data.team.id); await reload(data.team.id); setMessage("สร้างทีมแล้ว");
+ });
+ }
+
+ async function attachPage(e: React.FormEvent) {
+ e.preventDefault();
+ if (!selected || !pageToAttach) return;
+ await run(async () => {
+ await request(`/api/teams/${selected}/pages`, { method: "POST", body: JSON.stringify({ pageId: pageToAttach }) });
+ setPageToAttach(""); await reload(); setMessage("เพิ่มเพจเข้าทีมแล้ว");
+ });
+ }
+
+ async function invite(e: React.FormEvent) {
+ e.preventDefault();
+ if (!selected) return;
+ await run(async () => {
+ const pageRoles = Object.entries(selectedPages).map(([pageId, role]) => ({ pageId, role }));
+ const data = await request<{ url: string }>(`/api/teams/${selected}/invites`, { method: "POST", body: JSON.stringify({ email, pageRoles }) });
+ setInviteUrl(data.url); setEmail(""); setSelectedPages({}); await reload(); setMessage("สร้างคำเชิญแล้ว คัดลอกลิงก์ส่งให้ผู้รับ");
+ });
+ }
+
+ async function setRole(userId: string, pageId: string, pageRole: string) {
+ await run(async () => {
+ await request(`/api/teams/${selected}/members`, { method: "PUT", body: JSON.stringify({ userId, pageId, pageRole }) });
+ await reload(); setMessage("อัปเดตสิทธิ์แล้ว");
+ });
+ }
+
+ async function removeMember(userId: string, name: string) {
+ if (!window.confirm(`ถอด ${name} ออกจากทีมและทุกเพจในทีม?`)) return;
+ await run(async () => {
+ await request(`/api/teams/${selected}/members?userId=${encodeURIComponent(userId)}`, { method: "DELETE" });
+ await reload(); setMessage("ถอดสมาชิกแล้ว");
+ });
+ }
+
+ return
+
+
+ ทีม
+ {teams.length ? {teams.map((team) =>
+
+ )}
: }
+
+
+
+
+ {error &&
{error}}
+ {message &&
{message}}
+ {detail && <>
+
+ {detail.name}
{detail.members.length} คน · {detail.pages.length} เพจ
+
+
สมาชิกจะเห็นเฉพาะเพจที่ได้รับสิทธิ์ และรับคำขออนุมัติของเพจนั้นได้
+ {detail.pages.length === 0 ?
ยังไม่มีเพจในทีม เพิ่มเพจที่คุณเป็นผู้จัดการด้านล่าง
:
{detail.pages.map((p) => - {p.page.name}
)}
}
+ {(detail.ownerId === currentUserId || superadmin) &&
}
+
+
+ {canManage &&
}
+
+ สมาชิก
+ {detail.members.map((m) => -
+
{m.user.name}{m.user.email}{m.role === "OWNER" ? "เจ้าของ" : m.role === "ADMIN" ? "ผู้ดูแลทีม" : "สมาชิก"}
+ {canManage && m.role !== "OWNER" &&
+ {detail.pages.map((p) => )}
+ {detail.ownerId === currentUserId && }
+
+
}
+ )}
+
+ {canManage && detail.invites.length > 0 &&
คำเชิญที่รอตอบรับ
{detail.invites.map((i) => - {i.email}
)}
}
+ >}
+
+
;
+}
diff --git a/src/lib/ai/post-queue.ts b/src/lib/ai/post-queue.ts
index b876132..53a473b 100644
--- a/src/lib/ai/post-queue.ts
+++ b/src/lib/ai/post-queue.ts
@@ -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 };
diff --git a/src/lib/audit.ts b/src/lib/audit.ts
index 344dc71..d512b0b 100644
--- a/src/lib/audit.ts
+++ b/src/lib/audit.ts
@@ -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"
diff --git a/src/lib/auth/user.ts b/src/lib/auth/user.ts
index 529bd56..b66b5ab 100644
--- a/src/lib/auth/user.ts
+++ b/src/lib/auth/user.ts
@@ -30,16 +30,24 @@ export async function pageRoleOf(user: SessionUser, pageId: string): Promise {
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. */
diff --git a/src/lib/console.ts b/src/lib/console.ts
index 53d10f2..c8fefec 100644
--- a/src/lib/console.ts
+++ b/src/lib/console.ts
@@ -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 => {
});
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" } },
});
diff --git a/src/lib/posts/approvers.ts b/src/lib/posts/approvers.ts
new file mode 100644
index 0000000..824bfc5
--- /dev/null
+++ b/src/lib/posts/approvers.ts
@@ -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" })));
+}
diff --git a/src/lib/posts/workflow.ts b/src/lib/posts/workflow.ts
index 904b2da..c7d04c7 100644
--- a/src/lib/posts/workflow.ts
+++ b/src/lib/posts/workflow.ts
@@ -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 {
- if (post.status !== "DRAFT" && post.status !== "FAILED" && post.status !== "CANCELLED") {
+export async function submitForApproval(post: Post, user: SessionUser, assigneeId: string): Promise {
+ 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 {
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;
diff --git a/src/lib/teams/access.ts b/src/lib/teams/access.ts
new file mode 100644
index 0000000..e8ef704
--- /dev/null
+++ b/src/lib/teams/access.ts
@@ -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 };
+}
diff --git a/src/proxy.ts b/src/proxy.ts
index c53881f..83286cc 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -26,6 +26,7 @@ const CHANGE_PASSWORD_PATHS = [
// Static files under public/ that are safe to serve to anyone.
// /api/uploads/ = post images on disk; Meta's servers fetch these directly, no cookie.
const PUBLIC_PREFIXES = ["/_next/", "/logo/", "/icons/", "/api/uploads/"];
+const INVITE_PREFIXES = ["/join/", "/api/team-invites/"];
// Meta webhooks: it authenticates itself (hub.verify_token on GET,
// X-Hub-Signature-256 HMAC on POST), because Meta's servers have no session.
@@ -41,6 +42,7 @@ export async function proxy(request: NextRequest) {
if (
PUBLIC_PATHS.includes(pathname) ||
PUBLIC_PREFIXES.some((p) => pathname.startsWith(p)) ||
+ INVITE_PREFIXES.some((p) => pathname.startsWith(p)) ||
SELF_AUTH_PREFIXES.some((p) => pathname.startsWith(p))
) {
return NextResponse.next();