Round 14: Self-Assessment, Learning Goals, Portfolio, Homework, Announcements

This commit is contained in:
Mustafa Cetin committed 2026-07-29 10:53:22 +00:00
1 parent d325984786
commit 50c2d13d90
22 files changed
+5232 -2

No files matched your search

+144
View File
@@ -0,0 +1,144 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
const priorityEnum = z.enum(['low', 'normal', 'high', 'urgent']);
const targetAudienceEnum = z.enum(['all', 'teachers', 'students', 'parents', 'class']);
const updateAnnouncementSchema = z.object({
title: z.string().min(1).max(200).optional(),
content: z.string().min(1).max(10000).optional(),
priority: priorityEnum.optional(),
targetAudience: targetAudienceEnum.optional(),
classGroupId: z.string().optional().nullable(),
isPinned: z.boolean().optional(),
expiresAt: z.string().optional().nullable(),
});
function isTeacherOrAdmin(role: string | undefined): boolean {
return role === 'TEACHER' || role === 'SCHOOL_ADMIN' || role === 'SUPER_ADMIN';
}
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
const announcement = await db.announcement.findUnique({
where: { id, deletedAt: null },
include: {
author: { select: { id: true, firstName: true, lastName: true } },
classGroup: { select: { id: true, name: true } },
},
});
if (!announcement) {
return NextResponse.json({ error: 'Announcement not found' }, { status: 404 });
}
return NextResponse.json(announcement);
} catch (error) {
console.error('Announcement GET [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function PUT(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
if (!isTeacherOrAdmin(session.user?.role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const { id } = await params;
const body = await request.json();
const parsed = updateAnnouncementSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Validation failed', details: parsed.error.issues },
{ status: 400 }
);
}
const existing = await db.announcement.findUnique({ where: { id, deletedAt: null } });
if (!existing) {
return NextResponse.json({ error: 'Announcement not found' }, { status: 404 });
}
// Only the author or admins can edit
if (session.user?.role === 'TEACHER' && existing.authorId !== session.userId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const updateData: Record<string, unknown> = {};
if (parsed.data.title !== undefined) updateData.title = parsed.data.title;
if (parsed.data.content !== undefined) updateData.content = parsed.data.content;
if (parsed.data.priority !== undefined) updateData.priority = parsed.data.priority;
if (parsed.data.targetAudience !== undefined) updateData.targetAudience = parsed.data.targetAudience;
if (parsed.data.classGroupId !== undefined) updateData.classGroupId = parsed.data.classGroupId || null;
if (parsed.data.isPinned !== undefined) updateData.isPinned = parsed.data.isPinned;
if (parsed.data.expiresAt !== undefined) updateData.expiresAt = parsed.data.expiresAt ? new Date(parsed.data.expiresAt) : null;
const announcement = await db.announcement.update({
where: { id },
data: updateData,
include: {
author: { select: { id: true, firstName: true, lastName: true } },
classGroup: { select: { id: true, name: true } },
},
});
return NextResponse.json(announcement);
} catch (error) {
console.error('Announcement PUT [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function DELETE(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
if (!isTeacherOrAdmin(session.user?.role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const { id } = await params;
const existing = await db.announcement.findUnique({ where: { id, deletedAt: null } });
if (!existing) {
return NextResponse.json({ error: 'Announcement not found' }, { status: 404 });
}
if (session.user?.role === 'TEACHER' && existing.authorId !== session.userId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
await db.announcement.update({
where: { id },
data: { deletedAt: new Date() },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('Announcement DELETE [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+157
View File
@@ -0,0 +1,157 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
const priorityEnum = z.enum(['low', 'normal', 'high', 'urgent']);
const targetAudienceEnum = z.enum(['all', 'teachers', 'students', 'parents', 'class']);
const createAnnouncementSchema = z.object({
schoolId: z.string().min(1),
title: z.string().min(1).max(200),
content: z.string().min(1).max(10000),
priority: priorityEnum.optional().default('normal'),
targetAudience: targetAudienceEnum.optional().default('all'),
classGroupId: z.string().optional().nullable(),
isPinned: z.boolean().optional().default(false),
expiresAt: z.string().optional().nullable(),
});
function isTeacherOrAdmin(role: string | undefined): boolean {
return role === 'TEACHER' || role === 'SCHOOL_ADMIN' || role === 'SUPER_ADMIN';
}
export async function GET(request: Request) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const schoolIdParam = searchParams.get('schoolId');
const priority = searchParams.get('priority');
const targetAudience = searchParams.get('targetAudience');
const classGroupId = searchParams.get('classGroupId');
const isPinned = searchParams.get('isPinned');
const limit = parseInt(searchParams.get('limit') || '50', 10);
let schoolId: string | undefined;
if (session.user?.role === 'SCHOOL_ADMIN') {
schoolId = session.user.schoolId ?? undefined;
} else {
schoolId = schoolIdParam ?? session.user?.schoolId ?? undefined;
}
if (!schoolId) {
return NextResponse.json([]);
}
const where: Record<string, unknown> = {
schoolId,
deletedAt: null,
OR: [
{ expiresAt: null },
{ expiresAt: { gt: new Date() } },
],
};
if (priority && priority !== 'all') where.priority = priority;
if (targetAudience && targetAudience !== 'all') where.targetAudience = targetAudience;
if (classGroupId && classGroupId !== 'all') where.classGroupId = classGroupId;
if (isPinned === 'true') where.isPinned = true;
// Filter by role-based target audience
if (session.user?.role === 'STUDENT') {
where.OR = [
{ targetAudience: 'all' },
{ targetAudience: 'students' },
];
} else if (session.user?.role === 'PARENT') {
where.OR = [
{ targetAudience: 'all' },
{ targetAudience: 'parents' },
];
}
const announcements = await db.announcement.findMany({
where,
orderBy: [
{ isPinned: 'desc' },
{ createdAt: 'desc' },
],
take: limit,
include: {
author: { select: { id: true, firstName: true, lastName: true } },
classGroup: { select: { id: true, name: true } },
},
});
return NextResponse.json(announcements);
} catch (error) {
console.error('Announcements GET error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: Request) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
if (!isTeacherOrAdmin(session.user?.role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const body = await request.json();
const parsed = createAnnouncementSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Validation failed', details: parsed.error.issues },
{ status: 400 }
);
}
const { schoolId, classGroupId, expiresAt, ...rest } = parsed.data;
// Verify school
const school = await db.school.findUnique({ where: { id: schoolId } });
if (!school) {
return NextResponse.json({ error: 'School not found' }, { status: 404 });
}
if (session.user?.role === 'SCHOOL_ADMIN' && session.user.schoolId && school.id !== session.user.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
// Verify classGroup if provided
if (classGroupId) {
const cg = await db.classGroup.findUnique({ where: { id: classGroupId } });
if (!cg || cg.schoolId !== schoolId) {
return NextResponse.json({ error: 'Class group not found in this school' }, { status: 404 });
}
}
const announcement = await db.announcement.create({
data: {
schoolId,
authorId: session.userId,
title: rest.title,
content: rest.content,
priority: rest.priority,
targetAudience: rest.targetAudience,
classGroupId: classGroupId || null,
isPinned: rest.isPinned,
expiresAt: expiresAt ? new Date(expiresAt) : null,
},
include: {
author: { select: { id: true, firstName: true, lastName: true } },
classGroup: { select: { id: true, name: true } },
},
});
return NextResponse.json(announcement, { status: 201 });
} catch (error) {
console.error('Announcements POST error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+160
View File
@@ -0,0 +1,160 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
const homeworkTypeEnum = z.enum(['assignment', 'reading', 'project', 'practice', 'research']);
const updateHomeworkSchema = z.object({
title: z.string().min(1).max(200).optional(),
description: z.string().max(5000).optional().nullable(),
dueDate: z.string().min(1).optional(),
homeworkType: homeworkTypeEnum.optional(),
maxPoints: z.number().min(0).optional().nullable(),
attachments: z.array(z.string()).optional().nullable(),
isPublished: z.boolean().optional(),
subjectId: z.string().optional().nullable(),
classGroupId: z.string().optional(),
});
function isTeacherOrAdmin(role: string | undefined): boolean {
return role === 'TEACHER' || role === 'SCHOOL_ADMIN' || role === 'SUPER_ADMIN';
}
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
const homework = await db.homework.findUnique({
where: { id, deletedAt: null },
include: {
classGroup: { select: { id: true, name: true, gradeLevel: true } },
subject: { select: { id: true, name: true } },
teacher: { select: { id: true, firstName: true, lastName: true } },
submissions: {
include: {
student: { select: { id: true, firstName: true, lastName: true } },
},
orderBy: { createdAt: 'desc' },
},
},
});
if (!homework) {
return NextResponse.json({ error: 'Homework not found' }, { status: 404 });
}
// Students can only see published homework
if (session.user?.role === 'STUDENT' && !homework.isPublished) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
return NextResponse.json(homework);
} catch (error) {
console.error('Homework GET [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function PUT(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
if (!isTeacherOrAdmin(session.user?.role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const { id } = await params;
const body = await request.json();
const parsed = updateHomeworkSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Validation failed', details: parsed.error.issues },
{ status: 400 }
);
}
const existing = await db.homework.findUnique({ where: { id, deletedAt: null } });
if (!existing) {
return NextResponse.json({ error: 'Homework not found' }, { status: 404 });
}
// Only the teacher who created it or admins can edit
if (session.user?.role === 'TEACHER' && existing.teacherId !== session.userId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const updateData: Record<string, unknown> = {};
if (parsed.data.title !== undefined) updateData.title = parsed.data.title;
if (parsed.data.description !== undefined) updateData.description = parsed.data.description;
if (parsed.data.dueDate !== undefined) updateData.dueDate = new Date(parsed.data.dueDate);
if (parsed.data.homeworkType !== undefined) updateData.homeworkType = parsed.data.homeworkType;
if (parsed.data.maxPoints !== undefined) updateData.maxPoints = parsed.data.maxPoints;
if (parsed.data.attachments !== undefined) updateData.attachments = parsed.data.attachments ? JSON.stringify(parsed.data.attachments) : null;
if (parsed.data.isPublished !== undefined) updateData.isPublished = parsed.data.isPublished;
if (parsed.data.subjectId !== undefined) updateData.subjectId = parsed.data.subjectId || null;
if (parsed.data.classGroupId !== undefined) updateData.classGroupId = parsed.data.classGroupId;
const homework = await db.homework.update({
where: { id },
data: updateData,
include: {
classGroup: { select: { id: true, name: true, gradeLevel: true } },
subject: { select: { id: true, name: true } },
teacher: { select: { id: true, firstName: true, lastName: true } },
},
});
return NextResponse.json(homework);
} catch (error) {
console.error('Homework PUT [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function DELETE(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
if (!isTeacherOrAdmin(session.user?.role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const { id } = await params;
const existing = await db.homework.findUnique({ where: { id, deletedAt: null } });
if (!existing) {
return NextResponse.json({ error: 'Homework not found' }, { status: 404 });
}
if (session.user?.role === 'TEACHER' && existing.teacherId !== session.userId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
await db.homework.update({
where: { id },
data: { deletedAt: new Date() },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('Homework DELETE [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
@@ -0,0 +1,103 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
const gradeSchema = z.object({
score: z.number().min(0).optional().nullable(),
feedback: z.string().max(5000).optional().nullable(),
status: z.enum(['graded', 'submitted', 'late', 'pending']).optional(),
});
function isTeacherOrAdmin(role: string | undefined): boolean {
return role === 'TEACHER' || role === 'SCHOOL_ADMIN' || role === 'SUPER_ADMIN';
}
export async function PUT(
request: Request,
{ params }: { params: Promise<{ id: string; submissionId: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
if (!isTeacherOrAdmin(session.user?.role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const { submissionId } = await params;
const body = await request.json();
const parsed = gradeSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Validation failed', details: parsed.error.issues },
{ status: 400 }
);
}
const existing = await db.homeworkSubmission.findUnique({
where: { id: submissionId, deletedAt: null },
});
if (!existing) {
return NextResponse.json({ error: 'Submission not found' }, { status: 404 });
}
const updateData: Record<string, unknown> = {};
if (parsed.data.score !== undefined) {
updateData.score = parsed.data.score;
updateData.gradedAt = new Date();
if (!parsed.data.status) updateData.status = 'graded';
}
if (parsed.data.feedback !== undefined) updateData.feedback = parsed.data.feedback;
if (parsed.data.status !== undefined) updateData.status = parsed.data.status;
const submission = await db.homeworkSubmission.update({
where: { id: submissionId },
data: updateData,
include: {
student: { select: { id: true, firstName: true, lastName: true } },
homework: { select: { id: true, title: true, maxPoints: true } },
},
});
return NextResponse.json(submission);
} catch (error) {
console.error('HomeworkSubmission PUT error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function DELETE(
_request: Request,
{ params }: { params: Promise<{ id: string; submissionId: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
if (!isTeacherOrAdmin(session.user?.role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const { submissionId } = await params;
const existing = await db.homeworkSubmission.findUnique({
where: { id: submissionId, deletedAt: null },
});
if (!existing) {
return NextResponse.json({ error: 'Submission not found' }, { status: 404 });
}
await db.homeworkSubmission.update({
where: { id: submissionId },
data: { deletedAt: new Date() },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('HomeworkSubmission DELETE error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
@@ -0,0 +1,170 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
const submitSchema = z.object({
content: z.string().max(10000).optional().nullable(),
attachments: z.array(z.string()).optional().nullable(),
status: z.enum(['submitted', 'late']).optional().default('submitted'),
});
function isTeacherOrAdmin(role: string | undefined): boolean {
return role === 'TEACHER' || role === 'SCHOOL_ADMIN' || role === 'SUPER_ADMIN';
}
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
const { searchParams } = new URL(request.url);
const status = searchParams.get('status');
const where: Record<string, unknown> = { homeworkId: id, deletedAt: null };
if (status && status !== 'all') where.status = status;
const submissions = await db.homeworkSubmission.findMany({
where,
include: {
student: { select: { id: true, firstName: true, lastName: true } },
homework: { select: { id: true, title: true, maxPoints: true } },
},
orderBy: { createdAt: 'desc' },
});
return NextResponse.json(submissions);
} catch (error) {
console.error('HomeworkSubmissions GET error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
// Verify homework exists and is published
const homework = await db.homework.findUnique({
where: { id, deletedAt: null },
});
if (!homework) {
return NextResponse.json({ error: 'Homework not found' }, { status: 404 });
}
const body = await request.json();
const parsed = submitSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Validation failed', details: parsed.error.issues },
{ status: 400 }
);
}
// For students, we need to find the student record
let studentId: string | undefined;
if (session.user?.role === 'STUDENT') {
// Student users need to find their student record via enrollment
const student = await db.student.findFirst({
where: {
schoolId: homework.schoolId,
deletedAt: null,
enrollments: {
some: { classGroupId: homework.classGroupId },
},
},
});
if (!student) {
return NextResponse.json({ error: 'Student not found in this class' }, { status: 404 });
}
studentId = student.id;
} else if (isTeacherOrAdmin(session.user?.role)) {
// Teachers can submit on behalf of a student
studentId = body.studentId;
if (!studentId) {
return NextResponse.json({ error: 'studentId is required' }, { status: 400 });
}
}
if (!studentId) {
return NextResponse.json({ error: 'Cannot determine student' }, { status: 400 });
}
// Check for existing submission
const existing = await db.homeworkSubmission.findUnique({
where: { homeworkId_studentId: { homeworkId: id, studentId } },
});
if (existing && existing.deletedAt === null) {
// Update existing submission
const isLate = new Date() > homework.dueDate;
const submission = await db.homeworkSubmission.update({
where: { id: existing.id },
data: {
content: parsed.data.content ?? null,
attachments: parsed.data.attachments ? JSON.stringify(parsed.data.attachments) : null,
status: isLate ? 'late' : (parsed.data.status ?? 'submitted'),
submittedAt: new Date(),
},
include: {
student: { select: { id: true, firstName: true, lastName: true } },
},
});
return NextResponse.json(submission);
}
// If there's a soft-deleted submission, restore it
if (existing && existing.deletedAt !== null) {
const isLate = new Date() > homework.dueDate;
const submission = await db.homeworkSubmission.update({
where: { id: existing.id },
data: {
content: parsed.data.content ?? null,
attachments: parsed.data.attachments ? JSON.stringify(parsed.data.attachments) : null,
status: isLate ? 'late' : (parsed.data.status ?? 'submitted'),
submittedAt: new Date(),
deletedAt: null,
},
include: {
student: { select: { id: true, firstName: true, lastName: true } },
},
});
return NextResponse.json(submission);
}
// Create new submission
const isLate = new Date() > homework.dueDate;
const submission = await db.homeworkSubmission.create({
data: {
homeworkId: id,
studentId,
content: parsed.data.content ?? null,
attachments: parsed.data.attachments ? JSON.stringify(parsed.data.attachments) : null,
status: isLate ? 'late' : (parsed.data.status ?? 'submitted'),
submittedAt: new Date(),
},
include: {
student: { select: { id: true, firstName: true, lastName: true } },
},
});
return NextResponse.json(submission, { status: 201 });
} catch (error) {
console.error('HomeworkSubmission POST error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+160
View File
@@ -0,0 +1,160 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
const homeworkTypeEnum = z.enum(['assignment', 'reading', 'project', 'practice', 'research']);
const createHomeworkSchema = z.object({
schoolId: z.string().min(1),
classGroupId: z.string().min(1),
subjectId: z.string().optional().nullable(),
title: z.string().min(1).max(200),
description: z.string().max(5000).optional().nullable(),
dueDate: z.string().min(1),
homeworkType: homeworkTypeEnum.optional().default('assignment'),
maxPoints: z.number().min(0).optional().nullable(),
attachments: z.array(z.string()).optional().nullable(),
isPublished: z.boolean().optional().default(true),
});
function isTeacherOrAdmin(role: string | undefined): boolean {
return role === 'TEACHER' || role === 'SCHOOL_ADMIN' || role === 'SUPER_ADMIN';
}
export async function GET(request: Request) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const schoolIdParam = searchParams.get('schoolId');
const classGroupId = searchParams.get('classGroupId');
const subjectId = searchParams.get('subjectId');
const teacherId = searchParams.get('teacherId');
const homeworkType = searchParams.get('homeworkType');
const isPublished = searchParams.get('isPublished');
const dueDateFrom = searchParams.get('dueDateFrom');
const dueDateTo = searchParams.get('dueDateTo');
let schoolId: string | undefined;
if (session.user?.role === 'SCHOOL_ADMIN') {
schoolId = session.user.schoolId ?? undefined;
} else {
schoolId = schoolIdParam ?? session.user?.schoolId ?? undefined;
}
if (!schoolId) {
return NextResponse.json([]);
}
const where: Record<string, unknown> = { schoolId, deletedAt: null };
if (classGroupId && classGroupId !== 'all') where.classGroupId = classGroupId;
if (subjectId && subjectId !== 'all') where.subjectId = subjectId;
if (teacherId) where.teacherId = teacherId;
if (homeworkType && homeworkType !== 'all') where.homeworkType = homeworkType;
if (isPublished === 'true') where.isPublished = true;
if (isPublished === 'false') where.isPublished = false;
if (dueDateFrom || dueDateTo) {
const dateFilter: Record<string, unknown> = {};
if (dueDateFrom) dateFilter.gte = new Date(dueDateFrom);
if (dueDateTo) dateFilter.lte = new Date(dueDateTo);
where.dueDate = dateFilter;
}
// For students, only show published homework
if (session.user?.role === 'STUDENT') {
where.isPublished = true;
}
const homeworks = await db.homework.findMany({
where,
orderBy: { dueDate: 'asc' },
include: {
classGroup: { select: { id: true, name: true, gradeLevel: true } },
subject: { select: { id: true, name: true } },
teacher: { select: { id: true, firstName: true, lastName: true } },
_count: { select: { submissions: true } },
},
});
return NextResponse.json(homeworks);
} catch (error) {
console.error('Homework GET error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: Request) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
if (!isTeacherOrAdmin(session.user?.role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const body = await request.json();
const parsed = createHomeworkSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Validation failed', details: parsed.error.issues },
{ status: 400 }
);
}
const { schoolId, classGroupId, subjectId, dueDate, attachments, ...rest } = parsed.data;
// Verify school
const school = await db.school.findUnique({ where: { id: schoolId } });
if (!school) {
return NextResponse.json({ error: 'School not found' }, { status: 404 });
}
if (session.user?.role === 'SCHOOL_ADMIN' && session.user.schoolId && school.id !== session.user.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
// Verify classGroup
const classGroup = await db.classGroup.findUnique({ where: { id: classGroupId } });
if (!classGroup || classGroup.schoolId !== schoolId) {
return NextResponse.json({ error: 'Class group not found in this school' }, { status: 404 });
}
// Verify subject if provided
if (subjectId) {
const subject = await db.subject.findUnique({ where: { id: subjectId } });
if (!subject) {
return NextResponse.json({ error: 'Subject not found' }, { status: 404 });
}
}
const homework = await db.homework.create({
data: {
schoolId,
classGroupId,
subjectId: subjectId || null,
teacherId: session.userId,
title: rest.title,
description: rest.description ?? null,
dueDate: new Date(dueDate),
homeworkType: rest.homeworkType,
maxPoints: rest.maxPoints ?? null,
attachments: attachments ? JSON.stringify(attachments) : null,
isPublished: rest.isPublished,
},
include: {
classGroup: { select: { id: true, name: true, gradeLevel: true } },
subject: { select: { id: true, name: true } },
teacher: { select: { id: true, firstName: true, lastName: true } },
},
});
return NextResponse.json(homework, { status: 201 });
} catch (error) {
console.error('Homework POST error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+147
View File
@@ -0,0 +1,147 @@
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
const goal = await db.learningGoal.findFirst({
where: { id, deletedAt: null },
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
selfAssessments: {
where: { deletedAt: null },
select: { id: true, selfLevel: true, confidence: true, createdAt: true },
orderBy: { createdAt: 'desc' },
take: 5,
},
},
});
if (!goal) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== goal.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
return NextResponse.json(goal);
} catch (error) {
console.error('LearningGoal GET [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function PUT(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
const existing = await db.learningGoal.findFirst({
where: { id, deletedAt: null },
});
if (!existing) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== existing.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const body = await request.json();
const {
title,
description,
competencyId,
targetLevel,
currentLevel,
deadline,
status,
progress,
} = body;
const updated = await db.learningGoal.update({
where: { id },
data: {
...(title !== undefined && { title }),
...(description !== undefined && { description }),
...(competencyId !== undefined && { competencyId: competencyId || null }),
...(targetLevel !== undefined && { targetLevel }),
...(currentLevel !== undefined && { currentLevel }),
...(deadline !== undefined && { deadline: deadline ? new Date(deadline) : null }),
...(status !== undefined && { status }),
...(progress !== undefined && { progress }),
},
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
},
});
return NextResponse.json(updated);
} catch (error) {
console.error('LearningGoal PUT [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
const existing = await db.learningGoal.findFirst({
where: { id, deletedAt: null },
});
if (!existing) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== existing.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
// Soft delete
await db.learningGoal.update({
where: { id },
data: { deletedAt: new Date() },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('LearningGoal DELETE [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+123
View File
@@ -0,0 +1,123 @@
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
export async function GET(request: Request) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const schoolId = searchParams.get('schoolId');
const studentId = searchParams.get('studentId');
const competencyId = searchParams.get('competencyId');
const status = searchParams.get('status');
if (!schoolId) {
return NextResponse.json({ error: 'schoolId is required' }, { status: 400 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const where: Record<string, unknown> = {
schoolId,
deletedAt: null,
};
if (studentId) where.studentId = studentId;
if (competencyId) where.competencyId = competencyId;
if (status) where.status = status;
const goals = await db.learningGoal.findMany({
where,
orderBy: { createdAt: 'desc' },
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
selfAssessments: {
where: { deletedAt: null },
select: { id: true, selfLevel: true, confidence: true, createdAt: true },
orderBy: { createdAt: 'desc' },
take: 5,
},
},
});
return NextResponse.json(goals);
} catch (error) {
console.error('LearningGoal GET error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: Request) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const body = await request.json();
const {
schoolId,
studentId,
competencyId,
title,
description,
targetLevel,
currentLevel,
deadline,
status,
progress,
isDemo,
} = body;
if (!schoolId || !studentId || !title) {
return NextResponse.json(
{ error: 'schoolId, studentId, and title are required' },
{ status: 400 }
);
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const goal = await db.learningGoal.create({
data: {
schoolId,
studentId,
competencyId: competencyId || null,
title,
description: description || null,
targetLevel: targetLevel || null,
currentLevel: currentLevel || null,
deadline: deadline ? new Date(deadline) : null,
status: status || 'active',
progress: progress || 0,
isDemo: isDemo ?? false,
},
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
},
});
return NextResponse.json(goal, { status: 201 });
} catch (error) {
console.error('LearningGoal POST error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+145
View File
@@ -0,0 +1,145 @@
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
const entry = await db.portfolioEntry.findFirst({
where: { id, deletedAt: null },
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
},
});
if (!entry) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== entry.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
return NextResponse.json(entry);
} catch (error) {
console.error('PortfolioEntry GET [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function PUT(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
const existing = await db.portfolioEntry.findFirst({
where: { id, deletedAt: null },
});
if (!existing) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== existing.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const body = await request.json();
const {
title,
description,
entryType,
competencyId,
content,
mediaUrls,
notebookPageId,
drawingId,
isPublic,
tags,
} = body;
const updated = await db.portfolioEntry.update({
where: { id },
data: {
...(title !== undefined && { title }),
...(description !== undefined && { description }),
...(entryType !== undefined && { entryType }),
...(competencyId !== undefined && { competencyId: competencyId || null }),
...(content !== undefined && { content }),
...(mediaUrls !== undefined && { mediaUrls: mediaUrls ? JSON.stringify(mediaUrls) : null }),
...(notebookPageId !== undefined && { notebookPageId: notebookPageId || null }),
...(drawingId !== undefined && { drawingId: drawingId || null }),
...(isPublic !== undefined && { isPublic }),
...(tags !== undefined && { tags: tags ? JSON.stringify(tags) : null }),
},
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
},
});
return NextResponse.json(updated);
} catch (error) {
console.error('PortfolioEntry PUT [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
const existing = await db.portfolioEntry.findFirst({
where: { id, deletedAt: null },
});
if (!existing) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== existing.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
// Soft delete
await db.portfolioEntry.update({
where: { id },
data: { deletedAt: new Date() },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('PortfolioEntry DELETE [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+123
View File
@@ -0,0 +1,123 @@
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
export async function GET(request: Request) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const schoolId = searchParams.get('schoolId');
const studentId = searchParams.get('studentId');
const entryType = searchParams.get('entryType');
const competencyId = searchParams.get('competencyId');
const isPublic = searchParams.get('isPublic');
if (!schoolId) {
return NextResponse.json({ error: 'schoolId is required' }, { status: 400 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const where: Record<string, unknown> = {
schoolId,
deletedAt: null,
};
if (studentId) where.studentId = studentId;
if (entryType) where.entryType = entryType;
if (competencyId) where.competencyId = competencyId;
if (isPublic !== null && isPublic !== undefined) where.isPublic = isPublic === 'true';
const entries = await db.portfolioEntry.findMany({
where,
orderBy: { createdAt: 'desc' },
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
},
});
return NextResponse.json(entries);
} catch (error) {
console.error('PortfolioEntry GET error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: Request) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const body = await request.json();
const {
schoolId,
studentId,
title,
description,
entryType,
competencyId,
content,
mediaUrls,
notebookPageId,
drawingId,
isPublic,
tags,
isDemo,
} = body;
if (!schoolId || !studentId || !title || !entryType) {
return NextResponse.json(
{ error: 'schoolId, studentId, title, and entryType are required' },
{ status: 400 }
);
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const entry = await db.portfolioEntry.create({
data: {
schoolId,
studentId,
title,
description: description || null,
entryType,
competencyId: competencyId || null,
content: content || null,
mediaUrls: mediaUrls ? JSON.stringify(mediaUrls) : null,
notebookPageId: notebookPageId || null,
drawingId: drawingId || null,
isPublic: isPublic ?? false,
tags: tags ? JSON.stringify(tags) : null,
isDemo: isDemo ?? false,
},
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
},
});
return NextResponse.json(entry, { status: 201 });
} catch (error) {
console.error('PortfolioEntry POST error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+149
View File
@@ -0,0 +1,149 @@
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
const assessment = await db.selfAssessment.findFirst({
where: { id, deletedAt: null },
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
classGroup: {
select: { id: true, name: true },
},
goal: {
select: { id: true, title: true, status: true },
},
},
});
if (!assessment) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== assessment.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
return NextResponse.json(assessment);
} catch (error) {
console.error('SelfAssessment GET [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function PUT(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
const existing = await db.selfAssessment.findFirst({
where: { id, deletedAt: null },
});
if (!existing) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== existing.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const body = await request.json();
const {
selfLevel,
confidence,
reflection,
evidence,
goalId,
classGroupId,
} = body;
const updated = await db.selfAssessment.update({
where: { id },
data: {
...(selfLevel !== undefined && { selfLevel }),
...(confidence !== undefined && { confidence: confidence || null }),
...(reflection !== undefined && { reflection }),
...(evidence !== undefined && { evidence }),
...(goalId !== undefined && { goalId: goalId || null }),
...(classGroupId !== undefined && { classGroupId: classGroupId || null }),
},
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
classGroup: {
select: { id: true, name: true },
},
goal: {
select: { id: true, title: true, status: true },
},
},
});
return NextResponse.json(updated);
} catch (error) {
console.error('SelfAssessment PUT [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { id } = await params;
const existing = await db.selfAssessment.findFirst({
where: { id, deletedAt: null },
});
if (!existing) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== existing.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
// Soft delete
await db.selfAssessment.update({
where: { id },
data: { deletedAt: new Date() },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('SelfAssessment DELETE [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+134
View File
@@ -0,0 +1,134 @@
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
export async function GET(request: Request) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const schoolId = searchParams.get('schoolId');
const studentId = searchParams.get('studentId');
const competencyId = searchParams.get('competencyId');
const classGroupId = searchParams.get('classGroupId');
if (!schoolId) {
return NextResponse.json({ error: 'schoolId is required' }, { status: 400 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const where: Record<string, unknown> = {
schoolId,
deletedAt: null,
};
if (studentId) where.studentId = studentId;
if (competencyId) where.competencyId = competencyId;
if (classGroupId) where.classGroupId = classGroupId;
const assessments = await db.selfAssessment.findMany({
where,
orderBy: { createdAt: 'desc' },
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
classGroup: {
select: { id: true, name: true },
},
goal: {
select: { id: true, title: true, status: true },
},
},
});
return NextResponse.json(assessments);
} catch (error) {
console.error('SelfAssessment GET error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: Request) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
const body = await request.json();
const {
schoolId,
studentId,
competencyId,
classGroupId,
selfLevel,
confidence,
reflection,
evidence,
goalId,
isDemo,
} = body;
if (!schoolId || !studentId || !competencyId || selfLevel === undefined) {
return NextResponse.json(
{ error: 'schoolId, studentId, competencyId, and selfLevel are required' },
{ status: 400 }
);
}
if (selfLevel < 1 || selfLevel > 6) {
return NextResponse.json(
{ error: 'selfLevel must be between 1 and 6' },
{ status: 400 }
);
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const assessment = await db.selfAssessment.create({
data: {
schoolId,
studentId,
competencyId,
classGroupId: classGroupId || null,
selfLevel,
confidence: confidence || null,
reflection: reflection || null,
evidence: evidence || null,
goalId: goalId || null,
isDemo: isDemo ?? false,
},
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
classGroup: {
select: { id: true, name: true },
},
goal: {
select: { id: true, title: true, status: true },
},
},
});
return NextResponse.json(assessment, { status: 201 });
} catch (error) {
console.error('SelfAssessment POST error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}