130 lines
4.0 KiB
TypeScript
130 lines
4.0 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { getServerSession } from "next-auth/next";
|
|
import { authOptions } from "@/app/api/auth/options";
|
|
import { prisma } from "@/lib/prisma";
|
|
|
|
/**
|
|
* Check if a user exists in the database
|
|
*/
|
|
async function userExists(userId: string): Promise<boolean> {
|
|
try {
|
|
const user = await prisma.user.findUnique({
|
|
where: { id: userId },
|
|
select: { id: true }
|
|
});
|
|
return !!user;
|
|
} catch (error) {
|
|
console.error(`Error checking if user exists:`, error);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// GET - Retrieve all announcements (with role filtering)
|
|
export async function GET(req: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
|
|
if (!session) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
// Get user role from session
|
|
const userRole = session.user.role || [];
|
|
const roles = Array.isArray(userRole) ? userRole : [userRole];
|
|
|
|
// Query announcements based on role
|
|
const announcements = await prisma.announcement.findMany({
|
|
where: {
|
|
OR: [
|
|
{ targetRoles: { has: "all" } },
|
|
{ targetRoles: { hasSome: roles } }
|
|
]
|
|
},
|
|
orderBy: {
|
|
createdAt: "desc"
|
|
},
|
|
include: {
|
|
author: {
|
|
select: {
|
|
id: true,
|
|
email: true
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
return NextResponse.json(announcements);
|
|
} catch (error) {
|
|
console.error("Error fetching announcements:", error);
|
|
return NextResponse.json({ error: "Failed to fetch announcements" }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
// POST - Create a new announcement
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
|
|
if (!session) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
// Check if user has admin, entrepreneurship, or communication role
|
|
const userRole = session.user.role || [];
|
|
const roles = Array.isArray(userRole) ? userRole : [userRole];
|
|
const hasAdminAccess = roles.some(role =>
|
|
["admin", "entrepreneurship", "communication"].includes(role)
|
|
);
|
|
|
|
if (!hasAdminAccess) {
|
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
}
|
|
|
|
// Parse request body
|
|
const { title, content, targetRoles } = await req.json();
|
|
|
|
// Validate request body
|
|
if (!title || !content || !targetRoles || !targetRoles.length) {
|
|
return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
|
|
}
|
|
|
|
// Verify user exists in database (using session user id)
|
|
console.log("Verifying user ID:", session.user.id);
|
|
|
|
const userExistsInDB = await userExists(session.user.id);
|
|
|
|
if (!userExistsInDB) {
|
|
console.error("User not found in database:", session.user.id);
|
|
return NextResponse.json({
|
|
error: "User not found",
|
|
details: `The user ID from your session (${session.user.id}) doesn't exist in the database. This may be due to a session/database mismatch or the user hasn't been synced to the application database.`
|
|
}, { status: 400 });
|
|
}
|
|
|
|
// Create new announcement
|
|
const announcement = await prisma.announcement.create({
|
|
data: {
|
|
title,
|
|
content,
|
|
targetRoles,
|
|
authorId: session.user.id
|
|
}
|
|
});
|
|
|
|
return NextResponse.json(announcement, { status: 201 });
|
|
} catch (error) {
|
|
console.error("Error creating announcement:", error);
|
|
// Return more detailed error information
|
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
// Use a type guard to safely access the 'code' property
|
|
const errorCode = typeof error === 'object' && error !== null && 'code' in error
|
|
? (error as { code: unknown }).code?.toString() || "UNKNOWN"
|
|
: "UNKNOWN";
|
|
|
|
return NextResponse.json({
|
|
error: "Failed to create announcement",
|
|
details: errorMessage,
|
|
code: errorCode
|
|
}, { status: 500 });
|
|
}
|
|
}
|