Add self-service teams and assigned post approvals
This commit is contained in:
@@ -27,7 +27,11 @@ npm run dev # http://localhost:3000
|
|||||||
|
|
||||||
ผู้ใช้ที่สร้างจาก CLI หรือหน้า `/users` ต้องเปลี่ยนรหัสผ่านตอนเข้าครั้งแรก
|
ผู้ใช้ที่สร้างจาก CLI หรือหน้า `/users` ต้องเปลี่ยนรหัสผ่านตอนเข้าครั้งแรก
|
||||||
|
|
||||||
**เข้าสู่ระบบด้วย Google / Facebook** (ไม่บังคับ) — ใช้ได้กับบัญชีที่มีอยู่แล้วเท่านั้น (ไม่มีสมัครเอง): แอดมินสร้างผู้ใช้ด้วยอีเมลเดียวกับบัญชี Google/Facebook ของคนนั้น → ครั้งแรกที่กดปุ่ม ระบบผูกบัญชีให้จากอีเมลที่ยืนยันแล้ว → ครั้งต่อไปจำจาก ID ของ provider. เข้าด้วยวิธีนี้ไม่ต้องเปลี่ยนรหัสผ่านชั่วคราว (แต่ถ้าเข้าด้วยรหัสผ่านยังต้องเปลี่ยน)
|
**เข้าสู่ระบบด้วย Google / Facebook** (ไม่บังคับ) — ใช้ได้กับบัญชีที่มีอยู่แล้วเท่านั้น: แอดมินสร้างผู้ใช้ด้วยอีเมลเดียวกับบัญชี Google/Facebook ของคนนั้น → ครั้งแรกที่กดปุ่ม ระบบผูกบัญชีให้จากอีเมลที่ยืนยันแล้ว → ครั้งต่อไปจำจาก ID ของ provider. เข้าด้วยวิธีนี้ไม่ต้องเปลี่ยนรหัสผ่านชั่วคราว (แต่ถ้าเข้าด้วยรหัสผ่านยังต้องเปลี่ยน)
|
||||||
|
|
||||||
|
**ทีมและคำเชิญ** — ผู้ใช้ล็อกอินแล้วสร้างทีมที่ `/teams` ได้ เจ้าของทีมเพิ่มเพจที่ตนเป็น `MANAGER`, เชิญสมาชิกด้วยอีเมลและคัดลอกลิงก์ไปส่ง ผู้รับที่มีบัญชีแล้วต้องล็อกอินด้วยอีเมลนั้น ส่วนผู้รับใหม่ตั้งชื่อ/รหัสผ่านจากลิงก์คำเชิญ ลิงก์ใช้ครั้งเดียวและหมดอายุใน 7 วัน การรับคำเชิญให้สิทธิ์เฉพาะเพจที่ระบุในคำเชิญ; ทีมไม่มีบริการส่งอีเมลอัตโนมัติ
|
||||||
|
|
||||||
|
**คำขออนุมัติ** — ผู้เขียนเลือกผู้อนุมัติของเพจก่อนส่งงาน ผู้รับเห็นงานที่ `/approvals`; ผู้ส่งติดตามและเปลี่ยนผู้รับได้ ผู้สร้างหรือผู้แก้ล่าสุดอนุมัติงานตัวเองไม่ได้ แก้เนื้อหาแล้วคำขอเดิมหมดผลและโพสต์กลับเป็นฉบับร่าง
|
||||||
|
|
||||||
## Env
|
## Env
|
||||||
|
|
||||||
|
|||||||
@@ -136,7 +136,15 @@ model PostInsightSnapshot { postId, date @db.Date, impressions, engaged, reactio
|
|||||||
- `MEMBER` เชื่อม Facebook ของตนและเลือกเพจที่บัญชีนั้นมีงาน `MANAGE` หรือสิทธิ์จัดการเต็มรูปแบบ เมื่อเชื่อมจะได้ `PageMember: MANAGER` ของเพจนั้น; เพจที่เชื่อมอยู่แล้วเพิ่มสิทธิ์ให้ผู้เชื่อมโดยไม่เขียนทับ token เดิม
|
- `MEMBER` เชื่อม Facebook ของตนและเลือกเพจที่บัญชีนั้นมีงาน `MANAGE` หรือสิทธิ์จัดการเต็มรูปแบบ เมื่อเชื่อมจะได้ `PageMember: MANAGER` ของเพจนั้น; เพจที่เชื่อมอยู่แล้วเพิ่มสิทธิ์ให้ผู้เชื่อมโดยไม่เขียนทับ token เดิม
|
||||||
- `SUPERADMIN` เข้าได้ทุกเพจ + เชื่อม/ถอดเพจ + จัดการผู้ใช้
|
- `SUPERADMIN` เข้าได้ทุกเพจ + เชื่อม/ถอดเพจ + จัดการผู้ใช้
|
||||||
- **Separation of duty**: คนที่แก้ล่าสุดอนุมัติโพสต์ตัวเองไม่ได้ (ยกเว้น SUPERADMIN และต้องบันทึกใน AuditLog ว่าอนุมัติงานตัวเอง)
|
- **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 แล้ว
|
- เช็กสิทธิ์ใน route handler ทุกตัวด้วย `requirePageRole(session, pageId, minRole)` — proxy เช็กแค่ว่า login แล้ว
|
||||||
|
|
||||||
## Flow โพสต์
|
## Flow โพสต์
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -18,6 +18,25 @@ enum PageRole {
|
|||||||
MANAGER // + manage page members
|
MANAGER // + manage page members
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum TeamRole {
|
||||||
|
OWNER
|
||||||
|
ADMIN
|
||||||
|
MEMBER
|
||||||
|
}
|
||||||
|
|
||||||
|
enum TeamInviteStatus {
|
||||||
|
PENDING
|
||||||
|
ACCEPTED
|
||||||
|
REVOKED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum ApprovalRequestStatus {
|
||||||
|
PENDING
|
||||||
|
APPROVED
|
||||||
|
REJECTED
|
||||||
|
CANCELLED
|
||||||
|
}
|
||||||
|
|
||||||
enum PageStatus {
|
enum PageStatus {
|
||||||
ACTIVE
|
ACTIVE
|
||||||
TOKEN_INVALID
|
TOKEN_INVALID
|
||||||
@@ -67,6 +86,11 @@ model User {
|
|||||||
analyses PageAnalysis[]
|
analyses PageAnalysis[]
|
||||||
identities UserIdentity[]
|
identities UserIdentity[]
|
||||||
postGenerationJobs PostGenerationJob[]
|
postGenerationJobs PostGenerationJob[]
|
||||||
|
ownedTeams Team[] @relation("TeamOwner")
|
||||||
|
teamMemberships TeamMember[]
|
||||||
|
teamInvitesSent TeamInvite[] @relation("TeamInviteSender")
|
||||||
|
approvalAssignments ApprovalRequest[] @relation("ApprovalAssignee")
|
||||||
|
approvalRequestsSent ApprovalRequest[] @relation("ApprovalRequester")
|
||||||
|
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
@@ -143,6 +167,7 @@ model Page {
|
|||||||
profile PageProfile?
|
profile PageProfile?
|
||||||
aiUsage AiUsage[]
|
aiUsage AiUsage[]
|
||||||
generationJobs PostGenerationJob[]
|
generationJobs PostGenerationJob[]
|
||||||
|
teamPage TeamPage?
|
||||||
|
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
@@ -201,6 +226,7 @@ model Post {
|
|||||||
insights PostInsightSnapshot[]
|
insights PostInsightSnapshot[]
|
||||||
auditLogs AuditLog[]
|
auditLogs AuditLog[]
|
||||||
generationJob PostGenerationJob?
|
generationJob PostGenerationJob?
|
||||||
|
approvalRequest ApprovalRequest?
|
||||||
|
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
@@ -209,6 +235,78 @@ model Post {
|
|||||||
@@index([status, scheduledPublishAt])
|
@@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
|
// One approver's vote. Rows are deleted whenever the content changes or the
|
||||||
// post is rejected, which restarts the approval round.
|
// post is rejected, which restarts the approval round.
|
||||||
model PostApproval {
|
model PostApproval {
|
||||||
|
|||||||
@@ -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>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
@@ -1,12 +1,16 @@
|
|||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { getConsoleContext, scopedPageIds } from "@/lib/console";
|
import { getConsoleContext, scopedPageIds } from "@/lib/console";
|
||||||
import { Shell } from "@/components/Shell";
|
import { Shell } from "@/components/Shell";
|
||||||
|
import { roleAtLeast } from "@/lib/auth/roles";
|
||||||
|
|
||||||
export default async function ConsoleLayout({ children }: { children: React.ReactNode }) {
|
export default async function ConsoleLayout({ children }: { children: React.ReactNode }) {
|
||||||
const ctx = await getConsoleContext();
|
const ctx = await getConsoleContext();
|
||||||
const pendingApprovals = await prisma.post.count({
|
const assignedCount = await prisma.approvalRequest.count({
|
||||||
where: { pageId: { in: scopedPageIds(ctx) }, status: "PENDING_APPROVAL" },
|
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 (
|
return (
|
||||||
<Shell
|
<Shell
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { notFound } from "next/navigation";
|
|||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { getConsoleContext } from "@/lib/console";
|
import { getConsoleContext } from "@/lib/console";
|
||||||
import { REQUIRED_APPROVALS } from "@/lib/posts/workflow";
|
import { REQUIRED_APPROVALS } from "@/lib/posts/workflow";
|
||||||
|
import { approversForPages } from "@/lib/posts/approvers";
|
||||||
import { PostEditor } from "@/components/PostEditor";
|
import { PostEditor } from "@/components/PostEditor";
|
||||||
import { PageTitle } from "@/components/ui";
|
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);
|
const page = post && ctx.pages.find((p) => p.id === post.pageId);
|
||||||
if (!post || !page) notFound();
|
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.postApproval.count({ where: { postId: id } }),
|
||||||
prisma.auditLog.findMany({ where: { postId: id }, orderBy: { createdAt: "desc" }, take: 30 }),
|
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 (
|
return (
|
||||||
@@ -48,6 +51,8 @@ export default async function PostPage(props: PageProps<"/posts/[id]">) {
|
|||||||
note: (l.detail as { note?: string } | null)?.note ?? null,
|
note: (l.detail as { note?: string } | null)?.note ?? null,
|
||||||
}))}
|
}))}
|
||||||
approvalsCount={approvalsCount}
|
approvalsCount={approvalsCount}
|
||||||
|
approvers={approvers}
|
||||||
|
approvalRequest={approvalRequest}
|
||||||
requiredApprovals={REQUIRED_APPROVALS}
|
requiredApprovals={REQUIRED_APPROVALS}
|
||||||
currentUserId={ctx.user.id}
|
currentUserId={ctx.user.id}
|
||||||
superadmin={ctx.user.globalRole === "SUPERADMIN"}
|
superadmin={ctx.user.globalRole === "SUPERADMIN"}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { PostEditor } from "@/components/PostEditor";
|
|||||||
import { EmptyState, PageTitle } from "@/components/ui";
|
import { EmptyState, PageTitle } from "@/components/ui";
|
||||||
import { isDayKey } from "@/lib/board";
|
import { isDayKey } from "@/lib/board";
|
||||||
import type { AnalysisReport } from "@/lib/analysis/types";
|
import type { AnalysisReport } from "@/lib/analysis/types";
|
||||||
|
import { approversForPages } from "@/lib/posts/approvers";
|
||||||
|
|
||||||
export default async function NewPostPage(props: PageProps<"/posts/new">) {
|
export default async function NewPostPage(props: PageProps<"/posts/new">) {
|
||||||
const sp = await props.searchParams;
|
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.
|
// 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 firstId = ideaPageId ?? ctx.selected?.id ?? null;
|
||||||
const ordered = firstId ? [...editable.filter((p) => p.id === firstId), ...editable.filter((p) => p.id !== firstId)] : editable;
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -53,6 +55,7 @@ export default async function NewPostPage(props: PageProps<"/posts/new">) {
|
|||||||
initialDraft={initialDraft}
|
initialDraft={initialDraft}
|
||||||
pages={ordered.map(({ id, name, pictureUrl, igUsername, role }) => ({ id, name, pictureUrl, igUsername, role }))}
|
pages={ordered.map(({ id, name, pictureUrl, igUsername, role }) => ({ id, name, pictureUrl, igUsername, role }))}
|
||||||
post={null}
|
post={null}
|
||||||
|
approvers={approvers}
|
||||||
currentUserId={ctx.user.id}
|
currentUserId={ctx.user.id}
|
||||||
superadmin={ctx.user.globalRole === "SUPERADMIN"}
|
superadmin={ctx.user.globalRole === "SUPERADMIN"}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -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 }))} />
|
||||||
|
</>;
|
||||||
|
}
|
||||||
@@ -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 } });
|
const target = await prisma.user.findUnique({ where: { id: userId }, select: { id: true, isActive: true } });
|
||||||
if (!target?.isActive) return NextResponse.json({ error: "ไม่พบผู้ใช้" }, { status: 404 });
|
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({
|
await prisma.pageMember.upsert({
|
||||||
where: { userId_pageId: { userId, pageId: id } },
|
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") ?? "";
|
const userId = new URL(req.url).searchParams.get("userId") ?? "";
|
||||||
if (userId === auth.user.id) return NextResponse.json({ error: "ถอดสิทธิ์ตัวเองไม่ได้" }, { status: 400 });
|
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 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 } });
|
await audit({ action: "PAGE_MEMBER_REMOVED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId: id, detail: { userId } });
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
|
|||||||
@@ -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 } });
|
const prior = await prisma.page.findUnique({ where: { fbPageId }, select: { id: true, status: true, webhookSubscribedAt: true } });
|
||||||
if (prior && auth.user.globalRole !== "SUPERADMIN") {
|
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";
|
const refreshToken = prior.status !== "ACTIVE";
|
||||||
if (refreshToken) {
|
if (refreshToken) {
|
||||||
await prisma.page.update({
|
await prisma.page.update({
|
||||||
|
|||||||
@@ -19,11 +19,12 @@ export async function GET(_req: Request, ctx: RouteContext<"/api/posts/[id]">) {
|
|||||||
const auth = await requirePageAction(post.pageId, "view");
|
const auth = await requirePageAction(post.pageId, "view");
|
||||||
if (!auth.ok) return auth.response;
|
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.postApproval.findMany({ where: { postId: id }, orderBy: { createdAt: "asc" } }),
|
||||||
prisma.auditLog.findMany({ where: { postId: id }, orderBy: { createdAt: "desc" }, take: 50 }),
|
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]">) {
|
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);
|
updated = await planPost(post, auth.user, body.plannedAt ? new Date(str(body.plannedAt)) : null);
|
||||||
break;
|
break;
|
||||||
case "submit":
|
case "submit":
|
||||||
updated = await submitForApproval(post, auth.user);
|
updated = await submitForApproval(post, auth.user, str(body.assigneeId));
|
||||||
break;
|
break;
|
||||||
case "approve":
|
case "approve":
|
||||||
updated = await approvePost(post, auth.user, note);
|
updated = await approvePost(post, auth.user, note);
|
||||||
|
|||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import crypto from "node:crypto";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import type { PageRole } from "@prisma/client";
|
||||||
|
import { appUrl } from "@/lib/base-path";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { actorLabel, pageRoleOf } from "@/lib/auth/user";
|
||||||
|
import { PAGE_ROLES, roleAtLeast } from "@/lib/auth/roles";
|
||||||
|
import { requireTeamManager } from "@/lib/teams/access";
|
||||||
|
import { audit } from "@/lib/audit";
|
||||||
|
import { readJson, str } from "@/lib/http";
|
||||||
|
|
||||||
|
export async function POST(req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await ctx.params;
|
||||||
|
const auth = await requireTeamManager(id);
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
const body = await readJson(req);
|
||||||
|
const email = str(body.email).trim().toLowerCase();
|
||||||
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return NextResponse.json({ error: "กรอกอีเมลให้ถูกต้อง" }, { status: 400 });
|
||||||
|
if (email === auth.user.email.toLowerCase()) return NextResponse.json({ error: "คุณอยู่ในทีมนี้แล้ว" }, { status: 400 });
|
||||||
|
const existingUser = await prisma.user.findUnique({ where: { email }, select: { id: true } });
|
||||||
|
if (existingUser && await prisma.teamMember.findUnique({ where: { teamId_userId: { teamId: id, userId: existingUser.id } } })) {
|
||||||
|
return NextResponse.json({ error: "ผู้ใช้นี้อยู่ในทีมแล้ว" }, { status: 409 });
|
||||||
|
}
|
||||||
|
const rawRoles = Array.isArray(body.pageRoles) ? body.pageRoles : [];
|
||||||
|
const pageRoles: { pageId: string; role: PageRole }[] = [];
|
||||||
|
for (const row of rawRoles) {
|
||||||
|
const pageId = str(row?.pageId);
|
||||||
|
const role = str(row?.role) as PageRole;
|
||||||
|
if (!pageId || !PAGE_ROLES.includes(role) || pageRoles.some((x) => x.pageId === pageId)) return NextResponse.json({ error: "สิทธิ์เพจไม่ถูกต้อง" }, { status: 400 });
|
||||||
|
const teamPage = await prisma.teamPage.findUnique({ where: { pageId }, select: { teamId: true } });
|
||||||
|
const inviterRole = await pageRoleOf(auth.user, pageId);
|
||||||
|
if (teamPage?.teamId !== id || !roleAtLeast(inviterRole, "MANAGER")) return NextResponse.json({ error: "คุณไม่มีสิทธิ์ให้คนอื่นเข้าถึงเพจนี้" }, { status: 403 });
|
||||||
|
pageRoles.push({ pageId, role });
|
||||||
|
}
|
||||||
|
const token = crypto.randomBytes(32).toString("base64url");
|
||||||
|
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
|
||||||
|
const invite = await prisma.$transaction(async (tx) => {
|
||||||
|
await tx.teamInvite.updateMany({ where: { teamId: id, email, status: "PENDING" }, data: { status: "REVOKED" } });
|
||||||
|
const created = await tx.teamInvite.create({ data: { teamId: id, email, tokenHash, invitedById: auth.user.id, pageRoles, expiresAt: new Date(Date.now() + 7 * 86400000) } });
|
||||||
|
await audit({ action: "TEAM_INVITE_CREATED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { teamId: id, inviteId: created.id, email, pageRoles } }, tx);
|
||||||
|
return created;
|
||||||
|
});
|
||||||
|
return NextResponse.json({ invite: { id: invite.id, email, expiresAt: invite.expiresAt }, url: `${appUrl(new URL(req.url).origin)}/join/${token}` }, { status: 201 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await ctx.params;
|
||||||
|
const auth = await requireTeamManager(id);
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
const inviteId = new URL(req.url).searchParams.get("inviteId") ?? "";
|
||||||
|
const changed = await prisma.teamInvite.updateMany({ where: { id: inviteId, teamId: id, status: "PENDING" }, data: { status: "REVOKED" } });
|
||||||
|
if (!changed.count) return NextResponse.json({ error: "ไม่พบคำเชิญ" }, { status: 404 });
|
||||||
|
await audit({ action: "TEAM_INVITE_REVOKED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { teamId: id, inviteId } });
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import type { PageRole } from "@prisma/client";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { actorLabel, pageRoleOf } from "@/lib/auth/user";
|
||||||
|
import { PAGE_ROLES } from "@/lib/auth/roles";
|
||||||
|
import { requireTeamManager } from "@/lib/teams/access";
|
||||||
|
import { audit } from "@/lib/audit";
|
||||||
|
import { readJson, str } from "@/lib/http";
|
||||||
|
|
||||||
|
export async function PUT(req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await ctx.params;
|
||||||
|
const auth = await requireTeamManager(id);
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
const body = await readJson(req);
|
||||||
|
const userId = str(body.userId);
|
||||||
|
const member = await prisma.teamMember.findUnique({ where: { teamId_userId: { teamId: id, userId } } });
|
||||||
|
if (!member) return NextResponse.json({ error: "ไม่พบสมาชิกทีม" }, { status: 404 });
|
||||||
|
const teamRole = str(body.teamRole);
|
||||||
|
if (teamRole) {
|
||||||
|
if (auth.user.id !== auth.team.ownerId || member.role === "OWNER" || !["ADMIN", "MEMBER"].includes(teamRole)) return NextResponse.json({ error: "เฉพาะเจ้าของทีมที่เปลี่ยนผู้ดูแลทีมได้" }, { status: 403 });
|
||||||
|
await prisma.teamMember.update({ where: { id: member.id }, data: { role: teamRole as "ADMIN" | "MEMBER" } });
|
||||||
|
await audit({ action: "TEAM_MEMBER_ROLE_SET", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { teamId: id, userId, teamRole } });
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
|
const pageId = str(body.pageId);
|
||||||
|
const role = str(body.pageRole) as PageRole;
|
||||||
|
const attached = await prisma.teamPage.findUnique({ where: { pageId }, select: { teamId: true } });
|
||||||
|
if (attached?.teamId !== id || await pageRoleOf(auth.user, pageId) !== "MANAGER") return NextResponse.json({ error: "ไม่มีสิทธิ์จัดการสมาชิกของเพจนี้" }, { status: 403 });
|
||||||
|
if (member.role === "OWNER") return NextResponse.json({ error: "เปลี่ยนสิทธิ์เจ้าของทีมในเพจนี้ไม่ได้" }, { status: 403 });
|
||||||
|
if (role && !PAGE_ROLES.includes(role)) return NextResponse.json({ error: "สิทธิ์ไม่ถูกต้อง" }, { status: 400 });
|
||||||
|
await prisma.$transaction(async (tx) => {
|
||||||
|
if (role) await tx.pageMember.upsert({ where: { userId_pageId: { userId, pageId } }, create: { userId, pageId, role }, update: { role } });
|
||||||
|
else await tx.pageMember.deleteMany({ where: { userId, pageId } });
|
||||||
|
await audit({ action: role ? "PAGE_MEMBER_SET" : "PAGE_MEMBER_REMOVED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, detail: { teamId: id, userId, role: role || null } }, tx);
|
||||||
|
});
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await ctx.params;
|
||||||
|
const auth = await requireTeamManager(id);
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
const userId = new URL(req.url).searchParams.get("userId") ?? "";
|
||||||
|
const member = await prisma.teamMember.findUnique({ where: { teamId_userId: { teamId: id, userId } } });
|
||||||
|
if (!member) return NextResponse.json({ error: "ไม่พบสมาชิกทีม" }, { status: 404 });
|
||||||
|
if (member.role === "OWNER" || userId === auth.user.id || (member.role === "ADMIN" && auth.team.ownerId !== auth.user.id)) return NextResponse.json({ error: "ไม่มีสิทธิ์ถอดสมาชิกนี้" }, { status: 403 });
|
||||||
|
await prisma.$transaction(async (tx) => {
|
||||||
|
const pages = await tx.teamPage.findMany({ where: { teamId: id }, select: { pageId: true } });
|
||||||
|
await tx.pageMember.deleteMany({ where: { userId, pageId: { in: pages.map((p) => p.pageId) } } });
|
||||||
|
await tx.teamMember.delete({ where: { id: member.id } });
|
||||||
|
await audit({ action: "TEAM_MEMBER_REMOVED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { teamId: id, userId } }, tx);
|
||||||
|
});
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { actorLabel, pageRoleOf } from "@/lib/auth/user";
|
||||||
|
import { requireTeamManager } from "@/lib/teams/access";
|
||||||
|
import { audit } from "@/lib/audit";
|
||||||
|
import { readJson, str } from "@/lib/http";
|
||||||
|
|
||||||
|
export async function POST(req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await ctx.params;
|
||||||
|
const auth = await requireTeamManager(id);
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
if (auth.team.ownerId !== auth.user.id && auth.user.globalRole !== "SUPERADMIN") return NextResponse.json({ error: "เฉพาะเจ้าของทีมที่เพิ่มเพจเข้าทีมได้" }, { status: 403 });
|
||||||
|
const pageId = str((await readJson(req)).pageId);
|
||||||
|
if (await pageRoleOf(auth.user, pageId) !== "MANAGER") return NextResponse.json({ error: "ต้องเป็นผู้จัดการเพจนี้ก่อนเพิ่มเข้าทีม" }, { status: 403 });
|
||||||
|
const existing = await prisma.teamPage.findUnique({ where: { pageId } });
|
||||||
|
if (existing) return NextResponse.json({ error: existing.teamId === id ? "เพจอยู่ในทีมนี้แล้ว" : "เพจนี้อยู่ในทีมอื่นแล้ว" }, { status: 409 });
|
||||||
|
const pageMembers = await prisma.pageMember.findMany({ where: { pageId }, select: { userId: true } });
|
||||||
|
const teamMembers = await prisma.teamMember.findMany({ where: { teamId: id }, select: { userId: true } });
|
||||||
|
const members = new Set(teamMembers.map((m) => m.userId));
|
||||||
|
if (pageMembers.some((m) => !members.has(m.userId))) return NextResponse.json({ error: "เพจนี้ยังมีผู้ใช้ที่ไม่ได้อยู่ในทีม ให้เชิญเข้าทีมก่อน" }, { status: 409 });
|
||||||
|
await prisma.$transaction(async (tx) => {
|
||||||
|
await tx.teamPage.create({ data: { teamId: id, pageId } });
|
||||||
|
await audit({ action: "TEAM_PAGE_ADDED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, detail: { teamId: id } }, tx);
|
||||||
|
});
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { requireUser } from "@/lib/auth/user";
|
||||||
|
|
||||||
|
export async function GET(_req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await ctx.params;
|
||||||
|
const auth = await requireUser();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
const team = await prisma.team.findFirst({
|
||||||
|
where: { id, ...(auth.user.globalRole === "SUPERADMIN" ? {} : { members: { some: { userId: auth.user.id } } }) },
|
||||||
|
select: {
|
||||||
|
id: true, name: true, ownerId: true,
|
||||||
|
members: { select: { userId: true, role: true, user: { select: { name: true, email: true, isActive: true } } }, orderBy: { createdAt: "asc" } },
|
||||||
|
pages: {
|
||||||
|
select: {
|
||||||
|
pageId: true,
|
||||||
|
page: { select: { name: true, pictureUrl: true, members: { select: { userId: true, role: true } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
invites: { where: { status: "PENDING" }, select: { id: true, email: true, expiresAt: true, pageRoles: true }, orderBy: { createdAt: "desc" } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!team) return NextResponse.json({ error: "ไม่พบทีม" }, { status: 404 });
|
||||||
|
return NextResponse.json({ team });
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { actorLabel, requireUser } from "@/lib/auth/user";
|
||||||
|
import { audit } from "@/lib/audit";
|
||||||
|
import { readJson, str } from "@/lib/http";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const auth = await requireUser();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
const teams = await prisma.team.findMany({
|
||||||
|
where: auth.user.globalRole === "SUPERADMIN" ? undefined : { members: { some: { userId: auth.user.id } } },
|
||||||
|
select: { id: true, name: true, ownerId: true, members: { select: { userId: true, role: true, user: { select: { name: true, email: true } } } }, pages: { select: { pageId: true, page: { select: { name: true } } } } },
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
});
|
||||||
|
return NextResponse.json({ teams });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
const auth = await requireUser();
|
||||||
|
if (!auth.ok) return auth.response;
|
||||||
|
const body = await readJson(req);
|
||||||
|
const name = str(body.name).trim();
|
||||||
|
if (name.length < 2 || name.length > 80) return NextResponse.json({ error: "ชื่อทีมต้องยาว 2–80 ตัวอักษร" }, { status: 400 });
|
||||||
|
const team = await prisma.$transaction(async (tx) => {
|
||||||
|
const created = await tx.team.create({ data: { name, ownerId: auth.user.id, members: { create: { userId: auth.user.id, role: "OWNER" } } } });
|
||||||
|
await audit({ action: "TEAM_CREATED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), detail: { teamId: created.id, name } }, tx);
|
||||||
|
return created;
|
||||||
|
});
|
||||||
|
return NextResponse.json({ team }, { status: 201 });
|
||||||
|
}
|
||||||
@@ -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>;
|
||||||
|
}
|
||||||
@@ -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<Info | null>(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 <div className="max-w-lg mx-auto">
|
||||||
|
<div className="flex items-center gap-3 mb-8"><span className="w-10 h-10 bg-blue rounded-xl text-white grid place-items-center"><Icon name="users" size={22} /></span><span className="font-bold text-lg">คำเชิญเข้าทีม</span></div>
|
||||||
|
<section className="card"><div className="card-head"><h1 className="text-xl font-bold">ร่วมงานกับทีม</h1></div><div className="card-body flex flex-col gap-4">
|
||||||
|
{loading && <p className="text-ink-3">กำลังตรวจคำเชิญ…</p>}
|
||||||
|
{error && <Notice tone="red">{error}</Notice>}
|
||||||
|
{info && <>
|
||||||
|
<p>ทีม <strong>{info.team}</strong> เชิญ <strong>{info.email}</strong> เข้าร่วม</p>
|
||||||
|
<form onSubmit={accept} className="flex flex-col gap-3">
|
||||||
|
{info.existingAccount ? <p className="text-ink-2 text-[13px]">หากมีบัญชีอยู่แล้ว ให้เข้าสู่ระบบด้วยอีเมลนี้ก่อนกดรับคำเชิญ</p> : <>
|
||||||
|
<label htmlFor="join-name" className="field"><span>ชื่อที่แสดง *</span><input id="join-name" className="input" value={name} onChange={(e) => setName(e.target.value)} required aria-required="true" maxLength={100} autoComplete="name" /></label>
|
||||||
|
<label htmlFor="join-password" className="field"><span>รหัสผ่านใหม่ *</span><span className="text-ink-3 text-[12px]">ใช้อย่างน้อย 10 ตัวอักษร</span><input id="join-password" type="password" className="input" value={password} onChange={(e) => setPassword(e.target.value)} required aria-required="true" minLength={10} autoComplete="new-password" /></label>
|
||||||
|
</>}
|
||||||
|
<button type="submit" className="btn btn-primary" disabled={busy}>{busy ? "กำลังรับคำเชิญ…" : "รับคำเชิญ"}</button>
|
||||||
|
</form>
|
||||||
|
{info.existingAccount && <Link className="text-blue underline text-[13px]" href={`/login?from=${encodeURIComponent(`/join/${token}`)}`}>เข้าสู่ระบบด้วยอีเมลที่ได้รับคำเชิญ</Link>}
|
||||||
|
</>}
|
||||||
|
</div></section>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
@@ -86,6 +86,8 @@ export function PostEditor({
|
|||||||
log = [],
|
log = [],
|
||||||
approvalsCount = 0,
|
approvalsCount = 0,
|
||||||
requiredApprovals = 1,
|
requiredApprovals = 1,
|
||||||
|
approvers = [],
|
||||||
|
approvalRequest = null,
|
||||||
currentUserId,
|
currentUserId,
|
||||||
superadmin,
|
superadmin,
|
||||||
initialDay,
|
initialDay,
|
||||||
@@ -96,6 +98,8 @@ export function PostEditor({
|
|||||||
log?: EditorLogEntry[];
|
log?: EditorLogEntry[];
|
||||||
approvalsCount?: number;
|
approvalsCount?: number;
|
||||||
requiredApprovals?: 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;
|
currentUserId: string;
|
||||||
superadmin: boolean;
|
superadmin: boolean;
|
||||||
initialDay?: string;
|
initialDay?: string;
|
||||||
@@ -113,16 +117,21 @@ export function PostEditor({
|
|||||||
const [targets, setTargets] = useState<Target[]>(post?.targets ?? ["FACEBOOK"]);
|
const [targets, setTargets] = useState<Target[]>(post?.targets ?? ["FACEBOOK"]);
|
||||||
const [scheduleAt, setScheduleAt] = useState(() => toBangkokInput(new Date(Date.now() + 60 * 60 * 1000)));
|
const [scheduleAt, setScheduleAt] = useState(() => toBangkokInput(new Date(Date.now() + 60 * 60 * 1000)));
|
||||||
const [note, setNote] = useState("");
|
const [note, setNote] = useState("");
|
||||||
|
const [assigneeId, setAssigneeId] = useState(approvalRequest?.assigneeId ?? "");
|
||||||
const [plannedDay, setPlannedDay] = useState(initialDay ?? "");
|
const [plannedDay, setPlannedDay] = useState(initialDay ?? "");
|
||||||
const [busy, setBusy] = useState<string | null>(null);
|
const [busy, setBusy] = useState<string | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const page = pages.find((p) => p.id === pageId) ?? 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 role = page?.role ?? null;
|
||||||
const status: PostStatus = post?.status ?? "DRAFT";
|
const status: PostStatus = post?.status ?? "DRAFT";
|
||||||
const editable = !post || EDITABLE.includes(status);
|
const editable = !post || EDITABLE.includes(status);
|
||||||
const canEdit = roleAtLeast(role, "EDITOR") && editable;
|
const canEdit = roleAtLeast(role, "EDITOR") && editable;
|
||||||
const canApprove = roleAtLeast(role, "APPROVER");
|
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 ownWork = post && (post.lastEditedById === currentUserId || post.createdById === currentUserId);
|
||||||
const selfBlocked = Boolean(ownWork && !superadmin);
|
const selfBlocked = Boolean(ownWork && !superadmin);
|
||||||
const dirty =
|
const dirty =
|
||||||
@@ -178,9 +187,10 @@ export function PostEditor({
|
|||||||
|
|
||||||
/** New post: create and submit in one tap. */
|
/** New post: create and submit in one tap. */
|
||||||
async function saveAndSubmit() {
|
async function saveAndSubmit() {
|
||||||
|
if (!selectedAssigneeId) return setError("เลือกผู้อนุมัติก่อนส่งคำขอ");
|
||||||
const id = await save({ navigate: false });
|
const id = await save({ navigate: false });
|
||||||
if (!id) return;
|
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");
|
toast.show(body ? "ส่งให้ผู้อนุมัติแล้ว" : "บันทึกฉบับร่างแล้ว แต่ส่งขออนุมัติไม่สำเร็จ", body ? "ok" : "warn");
|
||||||
router.replace(`/posts/${id}`);
|
router.replace(`/posts/${id}`);
|
||||||
}
|
}
|
||||||
@@ -196,8 +206,15 @@ export function PostEditor({
|
|||||||
|
|
||||||
async function act(action: string, extra: Record<string, unknown> = {}) {
|
async function act(action: string, extra: Record<string, unknown> = {}) {
|
||||||
if (!post) return;
|
if (!post) return;
|
||||||
if (dirty && canEdit && !(await save())) return;
|
if (dirty && canEdit) {
|
||||||
const body = await call(action, `/api/posts/${post.id}`, { method: "POST", body: JSON.stringify({ action, note: note || undefined, ...extra }) });
|
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) {
|
if (body) {
|
||||||
setNote("");
|
setNote("");
|
||||||
toast.show(ACT_DONE[action] ?? "เรียบร้อย");
|
toast.show(ACT_DONE[action] ?? "เรียบร้อย");
|
||||||
@@ -216,7 +233,7 @@ export function PostEditor({
|
|||||||
? null
|
? null
|
||||||
: (status === "DRAFT" || status === "FAILED" || status === "CANCELLED") && roleAtLeast(role, "EDITOR")
|
: (status === "DRAFT" || status === "FAILED" || status === "CANCELLED") && roleAtLeast(role, "EDITOR")
|
||||||
? { label: "ส่งขออนุมัติ", tone: "primary", run: () => act("submit") }
|
? { label: "ส่งขออนุมัติ", tone: "primary", run: () => act("submit") }
|
||||||
: status === "PENDING_APPROVAL" && canApprove && !selfBlocked
|
: status === "PENDING_APPROVAL" && canDecide && !selfBlocked
|
||||||
? { label: "อนุมัติ", tone: "success", run: () => act("approve") }
|
? { label: "อนุมัติ", tone: "success", run: () => act("approve") }
|
||||||
: status === "APPROVED" && canApprove
|
: status === "APPROVED" && canApprove
|
||||||
? { label: "เผยแพร่ตอนนี้", tone: "success", run: () => act("publish") }
|
? { label: "เผยแพร่ตอนนี้", tone: "success", run: () => act("publish") }
|
||||||
@@ -358,6 +375,17 @@ export function PostEditor({
|
|||||||
|
|
||||||
{error && <Notice tone="red">{error}</Notice>}
|
{error && <Notice tone="red">{error}</Notice>}
|
||||||
|
|
||||||
|
{canEdit && (status === "DRAFT" || status === "FAILED" || status === "CANCELLED") && (
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor="post-approver">ผู้อนุมัติ *</label>
|
||||||
|
<select id="post-approver" className="input" value={selectedAssigneeId} onChange={(e) => setAssigneeId(e.target.value)} aria-required="true">
|
||||||
|
{eligibleApprovers.length === 0 && <option value="">ยังไม่มีผู้อนุมัติในเพจนี้</option>}
|
||||||
|
{eligibleApprovers.map((person) => <option key={person.id} value={person.id}>{person.name} ({person.email})</option>)}
|
||||||
|
</select>
|
||||||
|
{eligibleApprovers.length === 0 && <p className="text-ink-3 text-[13px]">ให้ผู้จัดการเพจเพิ่มผู้อนุมัติอีกคนก่อนส่งคำขอ</p>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<div className="flex flex-wrap gap-2 pt-1">
|
<div className="flex flex-wrap gap-2 pt-1">
|
||||||
{/* On phones the save/submit pair lives in the action dock below. */}
|
{/* On phones the save/submit pair lives in the action dock below. */}
|
||||||
@@ -409,10 +437,18 @@ export function PostEditor({
|
|||||||
|
|
||||||
{status === "PENDING_APPROVAL" && (
|
{status === "PENDING_APPROVAL" && (
|
||||||
<>
|
<>
|
||||||
|
{approvalRequest?.status === "PENDING" && <p className="text-ink-2 text-[13px]">ส่งถึง {approvalRequest.assignee.name}</p>}
|
||||||
|
{canReassign && <div className="flex flex-col gap-2">
|
||||||
|
<label htmlFor="reassign-approver" className="text-[13px] font-medium">เปลี่ยนผู้อนุมัติ</label>
|
||||||
|
<select id="reassign-approver" className="input" value={selectedAssigneeId} onChange={(e) => setAssigneeId(e.target.value)}>
|
||||||
|
{eligibleApprovers.map((person) => <option key={person.id} value={person.id}>{person.name} ({person.email})</option>)}
|
||||||
|
</select>
|
||||||
|
<button type="button" className="btn btn-ghost self-start" disabled={Boolean(busy) || !selectedAssigneeId || selectedAssigneeId === approvalRequest?.assigneeId} onClick={() => act("submit")}>ส่งให้ผู้อนุมัติคนใหม่</button>
|
||||||
|
</div>}
|
||||||
<p className="text-ink-2">
|
<p className="text-ink-2">
|
||||||
อนุมัติแล้ว <b className="num">{approvalsCount}</b> / {requiredApprovals}
|
อนุมัติแล้ว <b className="num">{approvalsCount}</b> / {requiredApprovals}
|
||||||
</p>
|
</p>
|
||||||
{canApprove ? (
|
{canDecide ? (
|
||||||
selfBlocked ? (
|
selfBlocked ? (
|
||||||
<Notice tone="amber">คุณเป็นคนแก้โพสต์นี้ล่าสุด ต้องให้ผู้อนุมัติคนอื่นตรวจ</Notice>
|
<Notice tone="amber">คุณเป็นคนแก้โพสต์นี้ล่าสุด ต้องให้ผู้อนุมัติคนอื่นตรวจ</Notice>
|
||||||
) : (
|
) : (
|
||||||
@@ -429,7 +465,7 @@ export function PostEditor({
|
|||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
) : (
|
) : (
|
||||||
<p className="text-ink-3 text-[13px]">รอผู้อนุมัติของเพจนี้ตรวจ</p>
|
<p className="text-ink-3 text-[13px]">รอผู้อนุมัติที่ได้รับคำขอตรวจ</p>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ interface NavEntry {
|
|||||||
const WORK: NavEntry[] = [
|
const WORK: NavEntry[] = [
|
||||||
{ href: "/", label: "แผนคอนเทนต์", icon: "calendar", also: ["/calendar"] },
|
{ href: "/", label: "แผนคอนเทนต์", icon: "calendar", also: ["/calendar"] },
|
||||||
{ href: "/posts", label: "โพสต์ทั้งหมด", icon: "post", count: "pendingApprovals" },
|
{ href: "/posts", label: "โพสต์ทั้งหมด", icon: "post", count: "pendingApprovals" },
|
||||||
|
{ href: "/approvals", label: "รอฉันอนุมัติ", icon: "check", count: "pendingApprovals" },
|
||||||
{ href: "/inbox", label: "Inbox", icon: "inbox" },
|
{ href: "/inbox", label: "Inbox", icon: "inbox" },
|
||||||
{ href: "/auto-reply", label: "Auto-reply", icon: "bolt" },
|
{ href: "/auto-reply", label: "Auto-reply", icon: "bolt" },
|
||||||
{ href: "/insights", label: "Insights", icon: "chart" },
|
{ href: "/insights", label: "Insights", icon: "chart" },
|
||||||
@@ -37,6 +38,7 @@ const WORK: NavEntry[] = [
|
|||||||
];
|
];
|
||||||
const SETTINGS: NavEntry[] = [
|
const SETTINGS: NavEntry[] = [
|
||||||
{ href: "/account", label: "บัญชีของฉัน", icon: "users" },
|
{ href: "/account", label: "บัญชีของฉัน", icon: "users" },
|
||||||
|
{ href: "/teams", label: "ทีมของฉัน", icon: "users" },
|
||||||
{ href: "/pages", label: "เพจที่เชื่อม", icon: "pages" },
|
{ href: "/pages", label: "เพจที่เชื่อม", icon: "pages" },
|
||||||
{ href: "/profile", label: "โปรไฟล์ร้าน", icon: "store" },
|
{ href: "/profile", label: "โปรไฟล์ร้าน", icon: "store" },
|
||||||
{ href: "/users", label: "ผู้ใช้", icon: "users", superadmin: true },
|
{ href: "/users", label: "ผู้ใช้", icon: "users", superadmin: true },
|
||||||
|
|||||||
@@ -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<T>(path: string, init?: RequestInit): Promise<T> {
|
||||||
|
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<Detail | null>(null);
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [selectedPages, setSelectedPages] = useState<Record<string, PageRole>>({});
|
||||||
|
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<void>) {
|
||||||
|
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 <div className="grid gap-5 xl:grid-cols-[300px_minmax(0,1fr)] items-start">
|
||||||
|
<div className="flex flex-col gap-5">
|
||||||
|
<section className="card">
|
||||||
|
<div className="card-head"><h2>ทีม</h2></div>
|
||||||
|
{teams.length ? <div className="card-body flex flex-col gap-2">{teams.map((team) =>
|
||||||
|
<button key={team.id} type="button" className={`btn justify-start ${selected === team.id ? "btn-primary" : "btn-ghost"}`} onClick={() => { setSelected(team.id); setDetail(null); setInviteUrl(""); setSelectedPages({}); setPageToAttach(""); setEmail(""); }}>{team.name}</button>
|
||||||
|
)}</div> : <EmptyState icon="users" title="ยังไม่มีทีม" hint="ตั้งชื่อทีมเพื่อเริ่มชวนคนทำงานร่วมกัน" />}
|
||||||
|
</section>
|
||||||
|
<section className="card">
|
||||||
|
<div className="card-head"><h2>สร้างทีมใหม่</h2></div>
|
||||||
|
<form className="card-body flex flex-col gap-3" onSubmit={createTeam}>
|
||||||
|
<label htmlFor="team-name" className="field"><span>ชื่อทีม *</span><span className="text-ink-3 text-[12px]">2–80 ตัวอักษร</span><input id="team-name" className="input" value={name} onChange={(e) => setName(e.target.value)} required aria-required="true" /></label>
|
||||||
|
<button type="submit" className="btn btn-primary" disabled={busy}><Icon name="plus" size={16} /> สร้างทีม</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-5">
|
||||||
|
{error && <Notice tone="red">{error}</Notice>}
|
||||||
|
{message && <Notice tone="blue">{message}</Notice>}
|
||||||
|
{detail && <>
|
||||||
|
<section className="card">
|
||||||
|
<div className="card-head"><h2>{detail.name}</h2><span className="ml-auto text-ink-3 text-[13px]">{detail.members.length} คน · {detail.pages.length} เพจ</span></div>
|
||||||
|
<div className="card-body flex flex-col gap-3">
|
||||||
|
<p className="text-ink-2 text-[13px]">สมาชิกจะเห็นเฉพาะเพจที่ได้รับสิทธิ์ และรับคำขออนุมัติของเพจนั้นได้</p>
|
||||||
|
{detail.pages.length === 0 ? <p className="text-ink-3 text-[13px]">ยังไม่มีเพจในทีม เพิ่มเพจที่คุณเป็นผู้จัดการด้านล่าง</p> : <ul className="flex flex-wrap gap-2">{detail.pages.map((p) => <li key={p.pageId} className="pill pill-blue">{p.page.name}</li>)}</ul>}
|
||||||
|
{(detail.ownerId === currentUserId || superadmin) && <form className="flex flex-col sm:flex-row gap-2" onSubmit={attachPage}>
|
||||||
|
<label htmlFor="team-page" className="sr-only">เพจที่จะเพิ่มเข้าทีม</label>
|
||||||
|
<select id="team-page" className="input flex-1" value={pageToAttach} onChange={(e) => setPageToAttach(e.target.value)} required>
|
||||||
|
<option value="">เลือกเพจที่จะเพิ่ม</option>
|
||||||
|
{pages.filter((p) => !detail.pages.some((x) => x.pageId === p.id)).map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
|
||||||
|
</select>
|
||||||
|
<button type="submit" className="btn btn-primary" disabled={busy}>เพิ่มเพจ</button>
|
||||||
|
</form>}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{canManage && <section className="card">
|
||||||
|
<div className="card-head"><h2>เชิญสมาชิก</h2></div>
|
||||||
|
<form className="card-body flex flex-col gap-3" onSubmit={invite}>
|
||||||
|
<label htmlFor="team-invite-email" className="field"><span>อีเมลผู้รับ *</span><input id="team-invite-email" type="email" inputMode="email" autoComplete="email" className="input" value={email} onChange={(e) => setEmail(e.target.value)} required aria-required="true" /></label>
|
||||||
|
<fieldset className="flex flex-col gap-2"><legend className="font-medium mb-2">ให้สิทธิ์ในเพจ</legend>
|
||||||
|
{detail.pages.length === 0 && <p className="text-ink-3 text-[13px]">เชิญเข้าทีมก่อน แล้วค่อยเพิ่มสิทธิ์รายเพจได้</p>}
|
||||||
|
{detail.pages.map((p) => <div key={p.pageId} className="flex flex-col sm:flex-row sm:items-center gap-2">
|
||||||
|
<label className="flex items-center gap-2 flex-1"><input type="checkbox" checked={p.pageId in selectedPages} onChange={(e) => setSelectedPages((cur) => { const next = { ...cur }; if (e.target.checked) next[p.pageId] = "EDITOR"; else delete next[p.pageId]; return next; })} />{p.page.name}</label>
|
||||||
|
{p.pageId in selectedPages && <select className="input" aria-label={`สิทธิ์ในเพจ ${p.page.name}`} value={selectedPages[p.pageId]} onChange={(e) => setSelectedPages((cur) => ({ ...cur, [p.pageId]: e.target.value as PageRole }))}>{ROLES.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}</select>}
|
||||||
|
</div>)}
|
||||||
|
</fieldset>
|
||||||
|
<button type="submit" className="btn btn-primary self-start" disabled={busy}><Icon name="link" size={16} /> สร้างลิงก์คำเชิญ</button>
|
||||||
|
{inviteUrl && <div className="flex flex-col sm:flex-row gap-2"><input className="input flex-1" readOnly value={inviteUrl} aria-label="ลิงก์คำเชิญ" /><button type="button" className="btn btn-ghost" onClick={() => navigator.clipboard.writeText(inviteUrl).then(() => setMessage("คัดลอกลิงก์แล้ว")).catch(() => setError("คัดลอกไม่ได้ กรุณาคัดลอกจากช่องลิงก์"))}>คัดลอก</button></div>}
|
||||||
|
</form>
|
||||||
|
</section>}
|
||||||
|
<section className="card">
|
||||||
|
<div className="card-head"><h2>สมาชิก</h2></div>
|
||||||
|
<ul>{detail.members.map((m) => <li key={m.userId} className="px-[18px] py-3 border-b border-line-2 last:border-0 flex flex-col gap-2">
|
||||||
|
<div className="flex items-center gap-2"><span className="font-medium">{m.user.name}</span><span className="text-ink-3 text-[12px]">{m.user.email}</span><span className="pill pill-blue ml-auto">{m.role === "OWNER" ? "เจ้าของ" : m.role === "ADMIN" ? "ผู้ดูแลทีม" : "สมาชิก"}</span></div>
|
||||||
|
{canManage && m.role !== "OWNER" && <div className="flex flex-wrap items-center gap-2">
|
||||||
|
{detail.pages.map((p) => <label key={p.pageId} className="flex items-center gap-1 text-[12px]">{p.page.name}<select className="input" value={p.page.members.find((x) => x.userId === m.userId)?.role ?? ""} onChange={(e) => setRole(m.userId, p.pageId, e.target.value)} disabled={busy}><option value="">ไม่ให้สิทธิ์</option>{ROLES.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}</select></label>)}
|
||||||
|
{detail.ownerId === currentUserId && <select className="input" aria-label={`สิทธิ์ในทีมของ ${m.user.name}`} value={m.role} disabled={busy} onChange={(e) => run(async () => { await request(`/api/teams/${selected}/members`, { method: "PUT", body: JSON.stringify({ userId: m.userId, teamRole: e.target.value }) }); await reload(); })}><option value="MEMBER">สมาชิก</option><option value="ADMIN">ผู้ดูแลทีม</option></select>}
|
||||||
|
<button type="button" className="btn btn-ghost btn-sm text-danger" disabled={busy} onClick={() => removeMember(m.userId, m.user.name)}>ถอดออก</button>
|
||||||
|
</div>}
|
||||||
|
</li>)}</ul>
|
||||||
|
</section>
|
||||||
|
{canManage && detail.invites.length > 0 && <section className="card"><div className="card-head"><h2>คำเชิญที่รอตอบรับ</h2></div><ul>{detail.invites.map((i) => <li key={i.id} className="px-[18px] py-3 flex items-center gap-2 border-b border-line-2 last:border-0"><span className="flex-1">{i.email}</span><button type="button" className="btn btn-ghost btn-sm" disabled={busy} onClick={() => run(async () => { await request(`/api/teams/${selected}/invites?inviteId=${i.id}`, { method: "DELETE" }); await reload(); })}>ยกเลิก</button></li>)}</ul></section>}
|
||||||
|
</>}
|
||||||
|
</div>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
@@ -53,9 +53,10 @@ export async function claimPostJob() {
|
|||||||
|
|
||||||
async function assertJobAccess(pageId: string, userId: string) {
|
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 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 } });
|
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("ผู้สั่งงานไม่มีสิทธิ์สร้างโพสต์ในเพจนี้แล้ว");
|
throw new UserFacingError("ผู้สั่งงานไม่มีสิทธิ์สร้างโพสต์ในเพจนี้แล้ว");
|
||||||
}
|
}
|
||||||
return { user, page };
|
return { user, page };
|
||||||
|
|||||||
@@ -12,6 +12,13 @@ export type AuditAction =
|
|||||||
| "PAGE_TOKEN_INVALID"
|
| "PAGE_TOKEN_INVALID"
|
||||||
| "PAGE_MEMBER_SET"
|
| "PAGE_MEMBER_SET"
|
||||||
| "PAGE_MEMBER_REMOVED"
|
| "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_ANALYSIS_REQUESTED"
|
||||||
| "PAGE_PROFILE_SAVED"
|
| "PAGE_PROFILE_SAVED"
|
||||||
| "POST_CREATED"
|
| "POST_CREATED"
|
||||||
|
|||||||
+11
-3
@@ -30,16 +30,24 @@ export async function pageRoleOf(user: SessionUser, pageId: string): Promise<Pag
|
|||||||
if (isSuperadmin(user)) return "MANAGER";
|
if (isSuperadmin(user)) return "MANAGER";
|
||||||
const m = await prisma.pageMember.findUnique({
|
const m = await prisma.pageMember.findUnique({
|
||||||
where: { userId_pageId: { userId: user.id, pageId } },
|
where: { userId_pageId: { userId: user.id, pageId } },
|
||||||
select: { role: true },
|
select: { role: true, page: { select: { teamPage: { select: { teamId: true } } } } },
|
||||||
});
|
});
|
||||||
|
if (m?.page.teamPage) {
|
||||||
|
const inTeam = await prisma.teamMember.findUnique({ where: { teamId_userId: { teamId: m.page.teamPage.teamId, userId: user.id } }, select: { id: true } });
|
||||||
|
if (!inTeam) return null;
|
||||||
|
}
|
||||||
return m?.role ?? null;
|
return m?.role ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Page ids the user can see (null = all pages, for SUPERADMIN). */
|
/** Page ids the user can see (null = all pages, for SUPERADMIN). */
|
||||||
export async function accessiblePageIds(user: SessionUser): Promise<string[] | null> {
|
export async function accessiblePageIds(user: SessionUser): Promise<string[] | null> {
|
||||||
if (isSuperadmin(user)) return null;
|
if (isSuperadmin(user)) return null;
|
||||||
const rows = await prisma.pageMember.findMany({ where: { userId: user.id }, select: { pageId: true } });
|
const [rows, teams] = await Promise.all([
|
||||||
return rows.map((r) => r.pageId);
|
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. */
|
/** Prisma `where` fragment restricting to pages the user can see. */
|
||||||
|
|||||||
+3
-2
@@ -3,7 +3,7 @@ import { cookies } from "next/headers";
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import type { PageRole } from "@prisma/client";
|
import type { PageRole } from "@prisma/client";
|
||||||
import { prisma } from "@/lib/db";
|
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";
|
export const SELECTED_PAGE_COOKIE = "pm_page";
|
||||||
|
|
||||||
@@ -39,8 +39,9 @@ export const getConsoleContext = cache(async (): Promise<ConsoleContext> => {
|
|||||||
});
|
});
|
||||||
pages = rows.map((p) => ({ ...p, role: "MANAGER" as const }));
|
pages = rows.map((p) => ({ ...p, role: "MANAGER" as const }));
|
||||||
} else {
|
} else {
|
||||||
|
const ids = await accessiblePageIds(user);
|
||||||
const rows = await prisma.pageMember.findMany({
|
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 } } },
|
select: { role: true, page: { select: { id: true, fbPageId: true, name: true, pictureUrl: true, igUsername: true, status: true } } },
|
||||||
orderBy: { page: { name: "asc" } },
|
orderBy: { page: { name: "asc" } },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { roleAtLeast } from "@/lib/auth/roles";
|
||||||
|
|
||||||
|
export async function approversForPages(pageIds: string[]) {
|
||||||
|
if (!pageIds.length) return [];
|
||||||
|
const [pages, users] = await Promise.all([
|
||||||
|
prisma.page.findMany({ where: { id: { in: pageIds } }, select: { id: true, teamPage: { select: { teamId: true } } } }),
|
||||||
|
prisma.user.findMany({
|
||||||
|
where: { isActive: true, OR: [{ globalRole: "SUPERADMIN" }, { memberships: { some: { pageId: { in: pageIds }, role: { in: ["APPROVER", "MANAGER"] } } } }] },
|
||||||
|
select: { id: true, name: true, email: true, globalRole: true, memberships: { where: { pageId: { in: pageIds } }, select: { pageId: true, role: true } }, teamMemberships: { select: { teamId: true } } },
|
||||||
|
orderBy: { name: "asc" },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
return pages.flatMap((page) => users.filter((user) =>
|
||||||
|
user.globalRole === "SUPERADMIN" ||
|
||||||
|
((!page.teamPage || user.teamMemberships.some((m) => m.teamId === page.teamPage!.teamId)) && user.memberships.some((m) => m.pageId === page.id && roleAtLeast(m.role, "APPROVER")))
|
||||||
|
).map((user) => ({ pageId: page.id, id: user.id, name: user.name, email: user.email, superadmin: user.globalRole === "SUPERADMIN" })));
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import type { Post, PostStatus } from "@prisma/client";
|
import type { Post, PostStatus } from "@prisma/client";
|
||||||
import { prisma } from "@/lib/db";
|
import { prisma } from "@/lib/db";
|
||||||
import { audit, SYSTEM_ACTOR } from "@/lib/audit";
|
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 { getPageCredentials } from "@/lib/facebook/tokens";
|
||||||
import { cancelScheduledFacebookPost, publishToFacebook, scheduleTimeProblem } from "@/lib/facebook/posts";
|
import { cancelScheduledFacebookPost, publishToFacebook, scheduleTimeProblem } from "@/lib/facebook/posts";
|
||||||
import { publishToInstagram } from "@/lib/instagram/posts";
|
import { publishToInstagram } from "@/lib/instagram/posts";
|
||||||
@@ -55,12 +56,15 @@ export async function editPost(post: Post, user: SessionUser, next: PostContent,
|
|||||||
...(newlyAiAssisted ? { aiAssisted: true } : {}),
|
...(newlyAiAssisted ? { aiAssisted: true } : {}),
|
||||||
};
|
};
|
||||||
return prisma.$transaction(async (tx) => {
|
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({
|
const updated = await tx.post.update({
|
||||||
where: { id: post.id },
|
where: { id: post.id },
|
||||||
data: {
|
data: {
|
||||||
...next,
|
...next,
|
||||||
status: voidsApproval ? "PENDING_APPROVAL" : backToDraft ? "DRAFT" : post.status,
|
status: voidsApproval || backToDraft ? "DRAFT" : post.status,
|
||||||
...(backToDraft ? { lastError: null } : {}),
|
...(backToDraft ? { lastError: null } : {}),
|
||||||
...(newlyAiAssisted ? { aiAssisted: true } : {}),
|
...(newlyAiAssisted ? { aiAssisted: true } : {}),
|
||||||
lastEditedById: user.id,
|
lastEditedById: user.id,
|
||||||
@@ -82,14 +86,33 @@ export async function editPost(post: Post, user: SessionUser, next: PostContent,
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function submitForApproval(post: Post, user: SessionUser): Promise<Post> {
|
export async function submitForApproval(post: Post, user: SessionUser, assigneeId: string): Promise<Post> {
|
||||||
if (post.status !== "DRAFT" && post.status !== "FAILED" && post.status !== "CANCELLED") {
|
if (post.status !== "DRAFT" && post.status !== "FAILED" && post.status !== "CANCELLED" && post.status !== "PENDING_APPROVAL") {
|
||||||
throw new UserFacingError("ส่งขออนุมัติได้เฉพาะโพสต์ที่เป็นฉบับร่าง");
|
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) => {
|
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 } });
|
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 tx.approvalRequest.upsert({
|
||||||
await audit({ action: "POST_SUBMITTED", actorId: user.id, actorLabel: actorLabel(user), pageId: post.pageId, postId: post.id }, tx);
|
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;
|
return updated;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -103,6 +126,8 @@ export function selfApprovalBlockReason(post: Post, user: SessionUser): string |
|
|||||||
|
|
||||||
export async function approvePost(post: Post, user: SessionUser, note: string | null): Promise<Post> {
|
export async function approvePost(post: Post, user: SessionUser, note: string | null): Promise<Post> {
|
||||||
if (post.status !== "PENDING_APPROVAL") throw new UserFacingError("โพสต์นี้ไม่ได้อยู่ในสถานะรออนุมัติ");
|
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);
|
const block = selfApprovalBlockReason(post, user);
|
||||||
if (block) throw new UserFacingError(block);
|
if (block) throw new UserFacingError(block);
|
||||||
const ownWork = post.lastEditedById === user.id || post.createdById === user.id;
|
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 votes = await tx.postApproval.count({ where: { postId: post.id } });
|
||||||
const done = votes >= REQUIRED_APPROVALS;
|
const done = votes >= REQUIRED_APPROVALS;
|
||||||
const updated = done ? await tx.post.update({ where: { id: post.id }, data: { status: "APPROVED" } }) : post;
|
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(
|
await audit(
|
||||||
{
|
{
|
||||||
action: "POST_APPROVED",
|
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") {
|
if (post.status !== "PENDING_APPROVAL" && post.status !== "APPROVED") {
|
||||||
throw new UserFacingError("ตีกลับได้เฉพาะโพสต์ที่รออนุมัติหรืออนุมัติแล้ว");
|
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) => {
|
return prisma.$transaction(async (tx) => {
|
||||||
await tx.postApproval.deleteMany({ where: { postId: post.id } });
|
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 } });
|
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);
|
await audit({ action: "POST_REJECTED", actorId: user.id, actorLabel: actorLabel(user), pageId: post.pageId, postId: post.id, detail: { note } }, tx);
|
||||||
return updated;
|
return updated;
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/db";
|
||||||
|
import { requireUser } from "@/lib/auth/user";
|
||||||
|
|
||||||
|
export async function requireTeamManager(teamId: string) {
|
||||||
|
const auth = await requireUser();
|
||||||
|
if (!auth.ok) return auth;
|
||||||
|
const member = await prisma.teamMember.findUnique({
|
||||||
|
where: { teamId_userId: { teamId, userId: auth.user.id } },
|
||||||
|
select: { role: true },
|
||||||
|
});
|
||||||
|
if (auth.user.globalRole !== "SUPERADMIN" && member?.role !== "OWNER" && member?.role !== "ADMIN") {
|
||||||
|
return { ok: false as const, response: NextResponse.json({ error: "ไม่มีสิทธิ์จัดการทีมนี้" }, { status: 404 }) };
|
||||||
|
}
|
||||||
|
const team = await prisma.team.findUnique({ where: { id: teamId }, select: { id: true, ownerId: true } });
|
||||||
|
if (!team) return { ok: false as const, response: NextResponse.json({ error: "ไม่พบทีม" }, { status: 404 }) };
|
||||||
|
return { ok: true as const, user: auth.user, team, member };
|
||||||
|
}
|
||||||
@@ -26,6 +26,7 @@ const CHANGE_PASSWORD_PATHS = [
|
|||||||
// Static files under public/ that are safe to serve to anyone.
|
// 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.
|
// /api/uploads/ = post images on disk; Meta's servers fetch these directly, no cookie.
|
||||||
const PUBLIC_PREFIXES = ["/_next/", "/logo/", "/icons/", "/api/uploads/"];
|
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,
|
// Meta webhooks: it authenticates itself (hub.verify_token on GET,
|
||||||
// X-Hub-Signature-256 HMAC on POST), because Meta's servers have no session.
|
// 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 (
|
if (
|
||||||
PUBLIC_PATHS.includes(pathname) ||
|
PUBLIC_PATHS.includes(pathname) ||
|
||||||
PUBLIC_PREFIXES.some((p) => pathname.startsWith(p)) ||
|
PUBLIC_PREFIXES.some((p) => pathname.startsWith(p)) ||
|
||||||
|
INVITE_PREFIXES.some((p) => pathname.startsWith(p)) ||
|
||||||
SELF_AUTH_PREFIXES.some((p) => pathname.startsWith(p))
|
SELF_AUTH_PREFIXES.some((p) => pathname.startsWith(p))
|
||||||
) {
|
) {
|
||||||
return NextResponse.next();
|
return NextResponse.next();
|
||||||
|
|||||||
Reference in New Issue
Block a user