feat: add approvals workflow and unified member invitation management across projects, workspaces, and videos

This commit is contained in:
Yusuf İpek
2026-02-25 16:24:45 +03:00
parent 0ae1becc1b
commit a2b07b3e19
36 changed files with 3122 additions and 982 deletions
@@ -0,0 +1,93 @@
import { NextRequest } from 'next/server';
import { Prisma } from '@prisma/client';
import { auth, checkProjectAccess } from '@/lib/auth';
import { db } from '@/lib/db';
import { rateLimit } from '@/lib/rate-limit';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
type RouteParams = { params: Promise<{ requestId: string }> };
function isSerializableConflict(error: unknown): boolean {
return error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2034';
}
// POST /api/approvals/[requestId]/cancel
export async function POST(request: NextRequest, { params }: RouteParams) {
try {
const limited = await rateLimit(request, 'mutate');
if (limited) return limited;
const session = await auth();
if (!session?.user?.id) return apiErrors.unauthorized();
const { requestId } = await params;
const approvalRequest = await db.approvalRequest.findUnique({
where: { id: requestId },
include: {
version: {
include: {
video: {
include: {
project: { select: { id: true, ownerId: true, workspaceId: true, visibility: true } },
},
},
},
},
},
});
if (!approvalRequest) return apiErrors.notFound('Approval request');
const access = await checkProjectAccess(approvalRequest.version.video.project, session.user.id, { intent: 'manage' });
const canCancel = approvalRequest.requestedById === session.user.id || access.canEdit;
if (!canCancel) return apiErrors.forbidden('Access denied');
if (approvalRequest.status !== 'PENDING') {
return apiErrors.conflict('Only pending approval requests can be canceled');
}
const updated = await db.$transaction(async (tx) => {
const current = await tx.approvalRequest.findUnique({
where: { id: requestId },
select: { status: true },
});
if (!current) throw new Error('__NOT_FOUND__');
if (current.status !== 'PENDING') throw new Error('__NOT_PENDING__');
return tx.approvalRequest.update({
where: { id: requestId },
data: {
status: 'CANCELED',
canceledAt: new Date(),
canceledById: session.user.id,
},
include: {
requestedBy: { select: { id: true, name: true, email: true, image: true } },
canceledBy: { select: { id: true, name: true, email: true, image: true } },
decisions: {
orderBy: { createdAt: 'asc' },
include: { approver: { select: { id: true, name: true, email: true, image: true } } },
},
},
});
}, {
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
});
const response = successResponse({ request: updated });
return withCacheControl(response, 'private, no-store');
} catch (error) {
if (error instanceof Error) {
if (error.message === '__NOT_PENDING__') {
return apiErrors.conflict('Only pending approval requests can be canceled');
}
if (error.message === '__NOT_FOUND__') {
return apiErrors.notFound('Approval request');
}
}
if (isSerializableConflict(error)) {
return apiErrors.conflict('Request state changed. Please try again.');
}
console.error('Error canceling approval request:', error);
return apiErrors.internalError('Failed to cancel approval request');
}
}
@@ -0,0 +1,225 @@
import { NextRequest } from 'next/server';
import { Prisma } from '@prisma/client';
import { auth, checkProjectAccess } from '@/lib/auth';
import { db } from '@/lib/db';
import { notifyUsers } from '@/lib/notifications';
import { rateLimit } from '@/lib/rate-limit';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
type RouteParams = { params: Promise<{ requestId: string }> };
function isSerializableConflict(error: unknown): boolean {
return error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2034';
}
// POST /api/approvals/[requestId]/decision
export async function POST(request: NextRequest, { params }: RouteParams) {
try {
const limited = await rateLimit(request, 'mutate');
if (limited) return limited;
const session = await auth();
if (!session?.user?.id) return apiErrors.unauthorized();
const { requestId } = await params;
const body = await request.json().catch(() => ({}));
const decision = body.decision;
if (decision !== 'APPROVED' && decision !== 'REJECTED') {
return apiErrors.badRequest('Decision must be APPROVED or REJECTED');
}
const note = typeof body.note === 'string' ? body.note.trim() : '';
if (note.length > 2000) {
return apiErrors.badRequest('Note must be 2000 characters or fewer');
}
const approvalRequest = await db.approvalRequest.findUnique({
where: { id: requestId },
include: {
version: {
include: {
video: {
include: {
project: { select: { id: true, name: true, ownerId: true, workspaceId: true, visibility: true } },
},
},
},
},
decisions: {
where: { approverId: session.user.id },
select: { id: true, status: true },
},
},
});
if (!approvalRequest) return apiErrors.notFound('Approval request');
const access = await checkProjectAccess(approvalRequest.version.video.project, session.user.id);
if (!access.hasAccess) return apiErrors.forbidden('Access denied');
const myDecision = approvalRequest.decisions[0];
if (!myDecision) return apiErrors.forbidden('You are not an approver on this request');
if (approvalRequest.status !== 'PENDING') {
return apiErrors.conflict('This approval request is no longer pending');
}
if (myDecision.status !== 'PENDING') {
return apiErrors.conflict('You have already responded to this request');
}
const updated = await db.$transaction(async (tx) => {
const currentRequest = await tx.approvalRequest.findUnique({
where: { id: requestId },
include: {
decisions: {
orderBy: { createdAt: 'asc' },
include: {
approver: { select: { id: true, name: true, email: true, image: true } },
},
},
requestedBy: { select: { id: true, name: true, email: true, image: true } },
version: {
include: {
video: {
include: {
project: { select: { id: true, name: true } },
},
},
},
},
},
});
if (!currentRequest) {
throw new Error('__NOT_FOUND__');
}
if (currentRequest.status !== 'PENDING') {
throw new Error('__NOT_PENDING__');
}
const decisionRow = await tx.approvalDecision.findUnique({
where: { requestId_approverId: { requestId, approverId: session.user.id } },
select: { status: true },
});
if (!decisionRow) throw new Error('__NOT_APPROVER__');
if (decisionRow.status !== 'PENDING') throw new Error('__ALREADY_RESPONDED__');
await tx.approvalDecision.update({
where: { requestId_approverId: { requestId, approverId: session.user.id } },
data: {
status: decision,
note: note || null,
respondedAt: new Date(),
},
});
if (decision === 'REJECTED') {
await tx.approvalRequest.update({
where: { id: requestId },
data: {
status: 'REJECTED',
resolvedAt: new Date(),
},
});
} else {
const pendingCount = await tx.approvalDecision.count({
where: { requestId, status: 'PENDING' },
});
const rejectedCount = await tx.approvalDecision.count({
where: { requestId, status: 'REJECTED' },
});
if (pendingCount === 0 && rejectedCount === 0) {
await tx.approvalRequest.update({
where: { id: requestId },
data: {
status: 'APPROVED',
resolvedAt: new Date(),
},
});
}
}
return tx.approvalRequest.findUnique({
where: { id: requestId },
include: {
requestedBy: { select: { id: true, name: true, email: true, image: true } },
canceledBy: { select: { id: true, name: true, email: true, image: true } },
decisions: {
orderBy: { createdAt: 'asc' },
include: {
approver: { select: { id: true, name: true, email: true, image: true } },
},
},
version: {
include: {
video: {
include: {
project: { select: { id: true, name: true } },
},
},
},
},
},
});
}, {
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
});
if (!updated) return apiErrors.notFound('Approval request');
const actorName = session.user.name || 'A team member';
const versionLabel = updated.version.versionLabel || `Version ${updated.version.versionNumber}`;
const baseUrl = process.env.NEXTAUTH_URL || '';
const requestUrl = `${baseUrl}/projects/${updated.version.video.project.id}/videos/${updated.version.video.id}`;
notifyUsers([updated.requestedById], {
type: 'approval_action',
projectName: updated.version.video.project.name,
videoTitle: updated.version.video.title,
versionLabel,
actorName,
action: decision === 'APPROVED' ? 'approved' : 'rejected',
note: note || undefined,
url: requestUrl,
}).catch((error) => {
console.error('Approval action notification failed:', error);
});
if (updated.status === 'APPROVED') {
notifyUsers([updated.requestedById], {
type: 'approval_completed',
projectName: updated.version.video.project.name,
videoTitle: updated.version.video.title,
versionLabel,
approvedByCount: updated.decisions.filter((item) => item.status === 'APPROVED').length,
url: requestUrl,
}).catch((error) => {
console.error('Approval completed notification failed:', error);
});
} else if (updated.status === 'REJECTED') {
notifyUsers([updated.requestedById], {
type: 'approval_rejected',
projectName: updated.version.video.project.name,
videoTitle: updated.version.video.title,
versionLabel,
rejectedBy: actorName,
note: note || undefined,
url: requestUrl,
}).catch((error) => {
console.error('Approval rejected notification failed:', error);
});
}
const response = successResponse({ request: updated });
return withCacheControl(response, 'private, no-store');
} catch (error) {
if (error instanceof Error) {
if (error.message === '__NOT_PENDING__') return apiErrors.conflict('This approval request is no longer pending');
if (error.message === '__ALREADY_RESPONDED__') return apiErrors.conflict('You have already responded to this request');
if (error.message === '__NOT_APPROVER__') return apiErrors.forbidden('You are not an approver on this request');
if (error.message === '__NOT_FOUND__') return apiErrors.notFound('Approval request');
}
if (isSerializableConflict(error)) {
return apiErrors.conflict('Request state changed. Please try again.');
}
console.error('Error responding to approval request:', error);
return apiErrors.internalError('Failed to respond to approval request');
}
}
+54 -24
View File
@@ -1,6 +1,7 @@
import { NextRequest } from 'next/server';
import { db } from '@/lib/db';
import bcrypt from 'bcryptjs';
import { acceptInvitationTokenForUser, getValidInvitationByToken } from '@/lib/invitations';
import { checkRateLimit, getClientIp, rateLimitHeaders, RATE_LIMIT_CONFIGS } from '@/lib/rate-limit';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
@@ -16,27 +17,7 @@ export async function POST(request: NextRequest) {
}
const body = await request.json();
const { name, email, password, inviteCode } = body;
// Validate invite code using constant-time comparison to prevent timing attacks
const validInviteCode = process.env.INVITE_CODE;
if (!validInviteCode || !inviteCode) {
return apiErrors.forbidden('Invalid invite code');
}
// Constant-time comparison
const { timingSafeEqual } = await import('crypto');
const validBuffer = Buffer.from(validInviteCode);
const providedBuffer = Buffer.from(String(inviteCode));
// Ensure same length for comparison (prevents length-based timing leak)
const isValidLength = validBuffer.length === providedBuffer.length;
const compareBuffer = isValidLength ? providedBuffer : validBuffer;
const isValidCode = isValidLength && timingSafeEqual(validBuffer, compareBuffer);
if (!isValidCode) {
return apiErrors.forbidden('Invalid invite code');
}
const { name, email, password, inviteCode, invitationToken } = body;
// Validate required fields
if (!name || typeof name !== 'string' || name.trim().length < 2) {
@@ -46,20 +27,57 @@ export async function POST(request: NextRequest) {
if (!email || typeof email !== 'string') {
return apiErrors.badRequest('Email is required');
}
const normalizedEmail = email.toLowerCase().trim();
// Basic email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
if (!emailRegex.test(normalizedEmail)) {
return apiErrors.validationError('Invalid email format');
}
// Allow registration via a valid invitation token OR global invite code.
let invitationIsValid = false;
let validatedInvitationToken: string | null = null;
if (typeof invitationToken === 'string' && invitationToken.trim()) {
const normalizedToken = invitationToken.trim();
const invitation = await getValidInvitationByToken(normalizedToken);
if (invitation && invitation.email === normalizedEmail) {
invitationIsValid = true;
validatedInvitationToken = normalizedToken;
} else {
return apiErrors.forbidden('Invalid or expired invitation token');
}
}
if (!invitationIsValid) {
// Validate invite code using constant-time comparison to prevent timing attacks
const validInviteCode = process.env.INVITE_CODE;
if (!validInviteCode || !inviteCode) {
return apiErrors.forbidden('Invalid invite code');
}
// Constant-time comparison
const { timingSafeEqual } = await import('crypto');
const validBuffer = Buffer.from(validInviteCode);
const providedBuffer = Buffer.from(String(inviteCode));
// Ensure same length for comparison (prevents length-based timing leak)
const isValidLength = validBuffer.length === providedBuffer.length;
const compareBuffer = isValidLength ? providedBuffer : validBuffer;
const isValidCode = isValidLength && timingSafeEqual(validBuffer, compareBuffer);
if (!isValidCode) {
return apiErrors.forbidden('Invalid invite code');
}
}
if (!password || typeof password !== 'string' || password.length < 8) {
return apiErrors.badRequest('Password must be at least 8 characters');
}
// Check if email already exists
const existingUser = await db.user.findUnique({
where: { email: email.toLowerCase() },
where: { email: normalizedEmail },
});
if (existingUser) {
@@ -73,7 +91,7 @@ export async function POST(request: NextRequest) {
const user = await db.user.create({
data: {
name: name.trim(),
email: email.toLowerCase(),
email: normalizedEmail,
password: hashedPassword,
},
select: {
@@ -84,6 +102,18 @@ export async function POST(request: NextRequest) {
},
});
if (validatedInvitationToken) {
const result = await acceptInvitationTokenForUser({
token: validatedInvitationToken,
userId: user.id,
email: normalizedEmail,
});
if (result !== 'accepted') {
await db.user.delete({ where: { id: user.id } });
return apiErrors.conflict('Invitation could not be accepted. Please request a new invitation.');
}
}
const response = successResponse(
{ message: 'Account created successfully', user },
201
@@ -0,0 +1,34 @@
import { NextRequest } from 'next/server';
import { auth, checkProjectAccess } from '@/lib/auth';
import { db } from '@/lib/db';
import { getApprovalCandidatesForProject } from '@/lib/approval-workflow';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
type RouteParams = { params: Promise<{ projectId: string }> };
// GET /api/projects/[projectId]/approval-candidates
export async function GET(_request: NextRequest, { params }: RouteParams) {
try {
const session = await auth();
if (!session?.user?.id) return apiErrors.unauthorized();
const { projectId } = await params;
const project = await db.project.findUnique({
where: { id: projectId },
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
});
if (!project) return apiErrors.notFound('Project');
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
if (!access.canEdit) return apiErrors.forbidden('Access denied');
const candidates = await getApprovalCandidatesForProject(projectId);
if (!candidates) return apiErrors.notFound('Project');
const response = successResponse({ candidates });
return withCacheControl(response, 'private, no-store');
} catch (error) {
console.error('Error fetching approval candidates:', error);
return apiErrors.internalError('Failed to fetch approval candidates');
}
}
@@ -0,0 +1,70 @@
import { NextRequest } from 'next/server';
import { InvitationStatus, ProjectMemberRole } from '@prisma/client';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { rateLimit } from '@/lib/rate-limit';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
type RouteParams = { params: Promise<{ projectId: string; invitationId: string }> };
// DELETE /api/projects/[projectId]/members/invitations/[invitationId] - Cancel a pending invitation
export async function DELETE(request: NextRequest, { params }: RouteParams) {
try {
const limited = await rateLimit(request, 'manage-member');
if (limited) return limited;
const session = await auth();
const { projectId, invitationId } = await params;
if (!session?.user?.id) {
return apiErrors.unauthorized();
}
const project = await db.project.findUnique({
where: { id: projectId },
include: { members: { where: { userId: session.user.id } } },
});
if (!project) {
return apiErrors.notFound('Project');
}
const isOwner = project.ownerId === session.user.id;
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
if (!isOwner && !isAdmin) {
return apiErrors.forbidden('Only project owners and admins can cancel invitations');
}
const invitation = await db.invitation.findFirst({
where: {
id: invitationId,
projectId,
scope: 'PROJECT',
},
select: {
id: true,
status: true,
},
});
if (!invitation) {
return apiErrors.notFound('Invitation');
}
if (invitation.status !== InvitationStatus.PENDING) {
return apiErrors.conflict('Only pending invitations can be canceled');
}
await db.invitation.update({
where: { id: invitation.id },
data: { status: InvitationStatus.CANCELED },
});
const response = successResponse({ message: 'Invitation canceled' });
return withCacheControl(response, 'private, no-store');
} catch (error) {
console.error('Error canceling project invitation:', error);
return apiErrors.internalError('Failed to cancel invitation');
}
}
+75 -39
View File
@@ -1,8 +1,9 @@
import { NextRequest } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { ProjectMemberRole } from '@prisma/client';
import { InvitationRole, ProjectMemberRole } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
import { buildInvitationUrl, createOrRefreshInvitation, sendInvitationEmail } from '@/lib/invitations';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
type RouteParams = { params: Promise<{ projectId: string }> };
@@ -30,26 +31,51 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
const isOwner = project.ownerId === session.user.id;
const isMember = project.members.length > 0;
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
if (!isOwner && !isMember) {
return apiErrors.forbidden('Access denied');
}
const members = await db.projectMember.findMany({
where: { projectId },
include: {
user: { select: { id: true, name: true, email: true, image: true } },
},
orderBy: { createdAt: 'asc' },
});
const now = new Date();
const canViewPendingInvitations = isOwner || isAdmin;
const [members, owner, pendingInvitations] = await Promise.all([
db.projectMember.findMany({
where: { projectId },
include: {
user: { select: { id: true, name: true, email: true, image: true } },
},
orderBy: { createdAt: 'asc' },
}),
db.user.findUnique({
where: { id: project.ownerId },
select: { id: true, name: true, email: true, image: true },
}),
canViewPendingInvitations
? db.invitation.findMany({
where: {
projectId,
scope: 'PROJECT',
status: 'PENDING',
expiresAt: { gt: now },
},
select: {
id: true,
email: true,
role: true,
createdAt: true,
expiresAt: true,
invitedBy: {
select: { id: true, name: true, email: true },
},
},
orderBy: { createdAt: 'desc' },
})
: Promise.resolve([]),
]);
const owner = await db.user.findUnique({
where: { id: project.ownerId },
select: { id: true, name: true, email: true, image: true },
});
const response = successResponse({ members, owner });
return withCacheControl(response, 'private, max-age=60, stale-while-revalidate=120');
const response = successResponse({ members, owner, pendingInvitations });
return withCacheControl(response, 'private, no-store');
} catch (error) {
console.error('Error fetching project members:', error);
return apiErrors.internalError('Failed to fetch members');
@@ -93,45 +119,55 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
return apiErrors.badRequest('Email is required');
}
const normalizedEmail = email.toLowerCase().trim();
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(normalizedEmail)) {
return apiErrors.validationError('Invalid email format');
}
// Validate role
const validRoles = ['ADMIN', 'COMMENTATOR'];
const memberRole = validRoles.includes(role) ? role : 'COMMENTATOR';
// Find user by email
// If this email belongs to an existing user, validate owner/member conflicts.
const userToInvite = await db.user.findUnique({
where: { email: email.toLowerCase().trim() },
where: { email: normalizedEmail },
select: { id: true },
});
if (!userToInvite) {
const response = successResponse({ message: 'If the user exists, an invitation has been sent.' });
return withCacheControl(response, 'private, no-store');
}
if (userToInvite.id === project.ownerId) {
if (userToInvite?.id === project.ownerId) {
return apiErrors.badRequest('Cannot invite the project owner as a member');
}
// Check if already a member
const existingMember = await db.projectMember.findUnique({
where: { projectId_userId: { projectId, userId: userToInvite.id } },
});
if (userToInvite) {
const existingMember = await db.projectMember.findUnique({
where: { projectId_userId: { projectId, userId: userToInvite.id } },
});
if (existingMember) {
return apiErrors.conflict('User is already a member of this project');
if (existingMember) {
return apiErrors.conflict('User is already a member of this project');
}
}
const member = await db.projectMember.create({
data: {
projectId,
userId: userToInvite.id,
role: memberRole as ProjectMemberRole,
},
include: {
user: { select: { id: true, name: true, email: true, image: true } },
},
const invitation = await createOrRefreshInvitation({
email: normalizedEmail,
scope: 'PROJECT',
role: memberRole as InvitationRole,
invitedById: session.user.id,
projectId,
});
const response = successResponse(member, 201);
const invitationUrl = buildInvitationUrl(invitation.token, normalizedEmail);
void sendInvitationEmail({
to: normalizedEmail,
inviterName: session.user.name || 'A team member',
role: invitation.role,
scope: invitation.scope,
targetName: project.name,
invitationUrl,
});
const response = successResponse({ message: 'Invitation email sent.' });
return withCacheControl(response, 'private, no-store');
} catch (error) {
console.error('Error inviting project member:', error);
@@ -125,6 +125,7 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
canDownload: access.hasAccess,
canManageTags: access.canEdit,
canResolveComments: access.canEdit,
canRequestApproval: access.canEdit,
});
return withCacheControl(response, 'private, no-cache');
+4
View File
@@ -29,6 +29,7 @@ export async function GET() {
onNewVersion: true,
onNewComment: true,
onNewReply: true,
onApprovalEvents: true,
timezone: 'UTC',
}
);
@@ -61,6 +62,7 @@ export async function PUT(request: NextRequest) {
onNewVersion,
onNewComment,
onNewReply,
onApprovalEvents,
timezone,
} = body;
@@ -81,6 +83,7 @@ export async function PUT(request: NextRequest) {
onNewVersion: onNewVersion ?? true,
onNewComment: onNewComment ?? true,
onNewReply: onNewReply ?? true,
onApprovalEvents: onApprovalEvents ?? true,
timezone: timezone || 'UTC',
},
update: {
@@ -92,6 +95,7 @@ export async function PUT(request: NextRequest) {
onNewVersion: onNewVersion ?? true,
onNewComment: onNewComment ?? true,
onNewReply: onNewReply ?? true,
onApprovalEvents: onApprovalEvents ?? true,
timezone: timezone || 'UTC',
},
});
@@ -0,0 +1,183 @@
import { NextRequest } from 'next/server';
import { Prisma } from '@prisma/client';
import { auth, checkProjectAccess } from '@/lib/auth';
import { db } from '@/lib/db';
import { getApprovalCandidatesForProject } from '@/lib/approval-workflow';
import { notifyUsers } from '@/lib/notifications';
import { rateLimit } from '@/lib/rate-limit';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
type RouteParams = { params: Promise<{ versionId: string }> };
function isSerializableConflict(error: unknown): boolean {
return error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2034';
}
// GET /api/versions/[versionId]/approvals
export async function GET(_request: NextRequest, { params }: RouteParams) {
try {
const session = await auth();
if (!session?.user?.id) return apiErrors.unauthorized();
const { versionId } = await params;
const version = await db.videoVersion.findUnique({
where: { id: versionId },
include: {
video: {
include: {
project: { select: { id: true, ownerId: true, workspaceId: true, visibility: true } },
},
},
},
});
if (!version) return apiErrors.notFound('Version');
const access = await checkProjectAccess(version.video.project, session.user.id);
const hasMembership = access.isOwner || access.isProjectMember || access.isWorkspaceMember;
if (!hasMembership) return apiErrors.forbidden('Access denied');
const requests = await db.approvalRequest.findMany({
where: { versionId },
orderBy: { createdAt: 'desc' },
include: {
requestedBy: { select: { id: true, name: true, email: true, image: true } },
canceledBy: { select: { id: true, name: true, email: true, image: true } },
decisions: {
orderBy: { createdAt: 'asc' },
include: {
approver: { select: { id: true, name: true, email: true, image: true } },
},
},
},
});
const response = successResponse({ requests });
return withCacheControl(response, 'private, no-store');
} catch (error) {
console.error('Error fetching approvals:', error);
return apiErrors.internalError('Failed to fetch approvals');
}
}
// POST /api/versions/[versionId]/approvals
export async function POST(request: NextRequest, { params }: RouteParams) {
try {
const limited = await rateLimit(request, 'mutate');
if (limited) return limited;
const session = await auth();
if (!session?.user?.id) return apiErrors.unauthorized();
const { versionId } = await params;
const version = await db.videoVersion.findUnique({
where: { id: versionId },
include: {
video: {
include: {
project: { select: { id: true, name: true, ownerId: true, workspaceId: true, visibility: true } },
},
},
},
});
if (!version) return apiErrors.notFound('Version');
const access = await checkProjectAccess(version.video.project, session.user.id, { intent: 'manage' });
if (!access.canEdit) return apiErrors.forbidden('Access denied');
const body = await request.json().catch(() => ({})) as { approverIds?: unknown; message?: unknown };
const message = typeof body.message === 'string' ? body.message.trim() : '';
if (message.length > 2000) {
return apiErrors.badRequest('Message must be 2000 characters or fewer');
}
const rawApproverIds = Array.isArray(body.approverIds) ? body.approverIds : [];
const approverIds = Array.from(new Set(
rawApproverIds
.filter((approverId): approverId is string => typeof approverId === 'string' && approverId.trim().length > 0)
.map((approverId) => approverId.trim())
));
if (approverIds.length === 0) {
return apiErrors.badRequest('At least one approver is required');
}
if (approverIds.includes(session.user.id)) {
return apiErrors.badRequest('Requester cannot be an approver');
}
const candidates = await getApprovalCandidatesForProject(version.video.project.id);
if (!candidates) return apiErrors.notFound('Project');
const candidateIds = new Set(candidates.map((candidate) => candidate.id));
if (approverIds.some((id) => !candidateIds.has(id))) {
return apiErrors.badRequest('One or more approvers are not eligible for this project');
}
const created = await db.$transaction(async (tx) => {
const existingPending = await tx.approvalRequest.findFirst({
where: { versionId, status: 'PENDING' },
select: { id: true },
});
if (existingPending) {
throw new Error('__PENDING_REQUEST_EXISTS__');
}
return tx.approvalRequest.create({
data: {
versionId,
requestedById: session.user.id,
message: message || null,
decisions: {
createMany: {
data: approverIds.map((approverId) => ({
approverId,
status: 'PENDING',
})),
},
},
},
include: {
requestedBy: { select: { id: true, name: true, email: true, image: true } },
canceledBy: { select: { id: true, name: true, email: true, image: true } },
decisions: {
orderBy: { createdAt: 'asc' },
include: {
approver: { select: { id: true, name: true, email: true, image: true } },
},
},
},
});
}, {
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
});
const requesterName = session.user.name || 'A team member';
const versionLabel = version.versionLabel || `Version ${version.versionNumber}`;
const baseUrl = process.env.NEXTAUTH_URL || '';
const requestUrl = `${baseUrl}/projects/${version.video.project.id}/videos/${version.video.id}`;
notifyUsers(approverIds, {
type: 'approval_requested',
projectName: version.video.project.name,
videoTitle: version.video.title,
versionLabel,
requestedBy: requesterName,
message: message || undefined,
url: requestUrl,
}).catch((error) => {
console.error('Approval request notification failed:', error);
});
const response = successResponse({ request: created }, 201);
return withCacheControl(response, 'private, no-store');
} catch (error) {
if (error instanceof Error && error.message === '__PENDING_REQUEST_EXISTS__') {
return apiErrors.conflict('An approval request is already pending for this version');
}
if (isSerializableConflict(error)) {
return apiErrors.conflict('Request state changed. Please try again.');
}
console.error('Error creating approval request:', error);
return apiErrors.internalError('Failed to create approval request');
}
}
@@ -0,0 +1,70 @@
import { NextRequest } from 'next/server';
import { InvitationStatus, WorkspaceMemberRole } from '@prisma/client';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { rateLimit } from '@/lib/rate-limit';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
type RouteParams = { params: Promise<{ workspaceId: string; invitationId: string }> };
// DELETE /api/workspaces/[workspaceId]/members/invitations/[invitationId] - Cancel a pending invitation
export async function DELETE(request: NextRequest, { params }: RouteParams) {
try {
const limited = await rateLimit(request, 'manage-member');
if (limited) return limited;
const session = await auth();
const { workspaceId, invitationId } = await params;
if (!session?.user?.id) {
return apiErrors.unauthorized();
}
const workspace = await db.workspace.findUnique({
where: { id: workspaceId },
include: { members: { where: { userId: session.user.id } } },
});
if (!workspace) {
return apiErrors.notFound('Workspace');
}
const isOwner = workspace.ownerId === session.user.id;
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
if (!isOwner && !isAdmin) {
return apiErrors.forbidden('Only workspace owners and admins can cancel invitations');
}
const invitation = await db.invitation.findFirst({
where: {
id: invitationId,
workspaceId,
scope: 'WORKSPACE',
},
select: {
id: true,
status: true,
},
});
if (!invitation) {
return apiErrors.notFound('Invitation');
}
if (invitation.status !== InvitationStatus.PENDING) {
return apiErrors.conflict('Only pending invitations can be canceled');
}
await db.invitation.update({
where: { id: invitation.id },
data: { status: InvitationStatus.CANCELED },
});
const response = successResponse({ message: 'Invitation canceled' });
return withCacheControl(response, 'private, no-store');
} catch (error) {
console.error('Error canceling workspace invitation:', error);
return apiErrors.internalError('Failed to cancel invitation');
}
}
@@ -1,8 +1,9 @@
import { NextRequest } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { WorkspaceMemberRole } from '@prisma/client';
import { InvitationRole, WorkspaceMemberRole } from '@prisma/client';
import { rateLimit } from '@/lib/rate-limit';
import { buildInvitationUrl, createOrRefreshInvitation, sendInvitationEmail } from '@/lib/invitations';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
type RouteParams = { params: Promise<{ workspaceId: string }> };
@@ -54,12 +55,15 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
const isOwner = workspace.ownerId === session.user.id;
const isMember = workspace.members.length > 0;
const isAdmin = workspace.members[0]?.role === WorkspaceMemberRole.ADMIN;
if (!isOwner && !isMember) {
return apiErrors.forbidden('Access denied');
}
const [members, total] = await Promise.all([
const now = new Date();
const canViewPendingInvitations = isOwner || isAdmin;
const [members, total, pendingInvitations] = await Promise.all([
db.workspaceMember.findMany({
where: { workspaceId },
include: {
@@ -72,6 +76,27 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
db.workspaceMember.count({
where: { workspaceId },
}),
canViewPendingInvitations
? db.invitation.findMany({
where: {
workspaceId,
scope: 'WORKSPACE',
status: 'PENDING',
expiresAt: { gt: now },
},
select: {
id: true,
email: true,
role: true,
createdAt: true,
expiresAt: true,
invitedBy: {
select: { id: true, name: true, email: true },
},
},
orderBy: { createdAt: 'desc' },
})
: Promise.resolve([]),
]);
// Include the owner as well
@@ -81,7 +106,7 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
});
const response = successResponse(
{ members, owner },
{ members, owner, pendingInvitations },
200,
{
page,
@@ -90,7 +115,7 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
totalPages: Math.ceil(total / limit),
}
);
return withCacheControl(response, 'private, max-age=60, stale-while-revalidate=120');
return withCacheControl(response, 'private, no-store');
} catch (error) {
console.error('Error fetching workspace members:', error);
return apiErrors.internalError('Failed to fetch members');
@@ -134,45 +159,55 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
return apiErrors.badRequest('Email is required');
}
const normalizedEmail = email.toLowerCase().trim();
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(normalizedEmail)) {
return apiErrors.validationError('Invalid email format');
}
// Validate role
const validRoles = ['ADMIN', 'COMMENTATOR'];
const memberRole = validRoles.includes(role) ? role : 'COMMENTATOR';
// Find user by email
// If this email belongs to an existing user, validate owner/member conflicts.
const userToInvite = await db.user.findUnique({
where: { email: email.toLowerCase().trim() },
where: { email: normalizedEmail },
select: { id: true },
});
if (!userToInvite) {
const response = successResponse({ message: 'If the user exists, an invitation has been sent.' });
return withCacheControl(response, 'private, no-store');
}
if (userToInvite.id === workspace.ownerId) {
if (userToInvite?.id === workspace.ownerId) {
return apiErrors.badRequest('Cannot invite the workspace owner as a member');
}
// Check if already a member
const existingMember = await db.workspaceMember.findUnique({
where: { workspaceId_userId: { workspaceId, userId: userToInvite.id } },
});
if (userToInvite) {
const existingMember = await db.workspaceMember.findUnique({
where: { workspaceId_userId: { workspaceId, userId: userToInvite.id } },
});
if (existingMember) {
return apiErrors.conflict('User is already a member of this workspace');
if (existingMember) {
return apiErrors.conflict('User is already a member of this workspace');
}
}
const member = await db.workspaceMember.create({
data: {
workspaceId,
userId: userToInvite.id,
role: memberRole as WorkspaceMemberRole,
},
include: {
user: { select: { id: true, name: true, email: true, image: true } },
},
const invitation = await createOrRefreshInvitation({
email: normalizedEmail,
scope: 'WORKSPACE',
role: memberRole as InvitationRole,
invitedById: session.user.id,
workspaceId,
});
const response = successResponse(member, 201);
const invitationUrl = buildInvitationUrl(invitation.token, normalizedEmail);
void sendInvitationEmail({
to: normalizedEmail,
inviterName: session.user.name || 'A team member',
role: invitation.role,
scope: invitation.scope,
targetName: workspace.name,
invitationUrl,
});
const response = successResponse({ message: 'Invitation email sent.' });
return withCacheControl(response, 'private, no-store');
} catch (error) {
console.error('Error inviting workspace member:', error);
+17
View File
@@ -3,6 +3,7 @@ import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { rateLimit } from '@/lib/rate-limit';
import { cleanupWorkspaceMediaFiles } from '@/lib/r2-cleanup';
import { cleanupBunnyStreamVideos } from '@/lib/bunny-stream-cleanup';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
type RouteParams = { params: Promise<{ workspaceId: string }> };
@@ -164,6 +165,22 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
return apiErrors.forbidden('Only the workspace owner can delete it');
}
// Delete Bunny provider videos first to avoid orphaned external assets.
const workspaceVersionRefs = await db.videoVersion.findMany({
where: {
video: {
project: {
workspaceId,
},
},
},
select: {
providerId: true,
videoId: true,
},
});
await cleanupBunnyStreamVideos(workspaceVersionRefs);
// Clean up voice files from R2 before cascade delete removes comment rows
await cleanupWorkspaceMediaFiles(workspaceId);