Round 16: Peer Assessment, Emergency Contacts, School Events, School Branding, Email Templates, Performance, Styling Polish, Onboarding 24 Steps

This commit is contained in:
Mustafa Cetin committed 2026-07-29 11:45:24 +00:00
1 parent d45ba030f5
commit 6174f127f9
30 files changed
+4835 -142

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
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') ?? session.user?.schoolId;
const status = searchParams.get('status');
const limit = parseInt(searchParams.get('limit') || '50', 10);
if (!schoolId) {
return NextResponse.json({ error: 'School ID required' }, { status: 400 });
}
const where: Record<string, unknown> = { schoolId };
if (status) where.status = status;
const logs = await db.emailLog.findMany({
where,
orderBy: { createdAt: 'desc' },
take: limit,
});
const counts = {
total: await db.emailLog.count({ where: { schoolId } }),
sent: await db.emailLog.count({ where: { schoolId, status: 'sent' } }),
failed: await db.emailLog.count({ where: { schoolId, status: 'failed' } }),
pending: await db.emailLog.count({ where: { schoolId, status: 'pending' } }),
bounced: await db.emailLog.count({ where: { schoolId, status: 'bounced' } }),
};
return NextResponse.json({ logs, counts });
} catch (error) {
console.error('EmailLogs GET error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+107
View File
@@ -0,0 +1,107 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
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 template = await db.emailTemplate.findUnique({
where: { id, deletedAt: null },
});
if (!template) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json(template);
} catch (error) {
console.error('EmailTemplate GET error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
const updateTemplateSchema = z.object({
name: z.string().min(1).optional(),
subject: z.string().min(1).optional(),
body: z.string().min(1).optional(),
isDefault: z.boolean().optional(),
});
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 (
session.user?.role !== 'SUPER_ADMIN' &&
session.user?.role !== 'SCHOOL_ADMIN'
) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const { id } = await params;
const body = await request.json();
const parsed = updateTemplateSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Validation failed', details: parsed.error.issues },
{ status: 400 }
);
}
const template = await db.emailTemplate.update({
where: { id },
data: parsed.data,
});
return NextResponse.json(template);
} catch (error) {
console.error('EmailTemplate PUT 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 (
session.user?.role !== 'SUPER_ADMIN' &&
session.user?.role !== 'SCHOOL_ADMIN'
) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const { id } = await params;
// Soft delete
await db.emailTemplate.update({
where: { id },
data: { deletedAt: new Date() },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('EmailTemplate DELETE error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+75
View File
@@ -0,0 +1,75 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
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') ?? session.user?.schoolId;
if (!schoolId) {
return NextResponse.json({ error: 'School ID required' }, { status: 400 });
}
const templates = await db.emailTemplate.findMany({
where: {
schoolId,
deletedAt: null,
},
orderBy: { createdAt: 'desc' },
});
return NextResponse.json(templates);
} catch (error) {
console.error('EmailTemplates GET error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
const createTemplateSchema = z.object({
schoolId: z.string().min(1),
name: z.string().min(1),
subject: z.string().min(1),
body: z.string().min(1),
isDefault: z.boolean().default(false),
});
export async function POST(request: Request) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
if (
session.user?.role !== 'SUPER_ADMIN' &&
session.user?.role !== 'SCHOOL_ADMIN'
) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const body = await request.json();
const parsed = createTemplateSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Validation failed', details: parsed.error.issues },
{ status: 400 }
);
}
const template = await db.emailTemplate.create({
data: parsed.data,
});
return NextResponse.json(template, { status: 201 });
} catch (error) {
console.error('EmailTemplates POST error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+95
View File
@@ -0,0 +1,95 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
const sendSchema = z.object({
templateId: z.string().optional(),
schoolId: z.string().min(1),
recipientEmail: z.string().email(),
recipientName: z.string().optional(),
subject: z.string().min(1),
body: z.string().min(1),
isTest: z.boolean().default(false),
});
export async function POST(request: Request) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
}
if (
session.user?.role !== 'SUPER_ADMIN' &&
session.user?.role !== 'SCHOOL_ADMIN'
) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const body = await request.json();
const parsed = sendSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Validation failed', details: parsed.error.issues },
{ status: 400 }
);
}
// Replace template variables with sample data
const replaceVariables = (text: string, vars: Record<string, string>) => {
let result = text;
for (const [key, value] of Object.entries(vars)) {
result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), value);
}
return result;
};
const sampleVars: Record<string, string> = {
studentName: parsed.data.recipientName || 'Max Mustermann',
className: 'Klasse 5a',
teacherName: `${session.user?.firstName || 'Frau'} ${session.user?.lastName || 'Muster'}`,
date: new Date().toLocaleDateString('de-DE'),
score: '85%',
schoolName: 'CompetenceTrack Schule',
subjectName: 'Mathematik',
behaviorDescription: 'Beschreibung des Vorfalls',
behaviorCategory: 'Störung',
attendanceStatus: 'Fehlend',
email: parsed.data.recipientEmail,
competencyProgress: 'Alle Kompetenzen auf dem erwarteten Niveau',
};
const processedSubject = replaceVariables(parsed.data.subject, sampleVars);
const processedBody = replaceVariables(parsed.data.body, sampleVars);
// Create email log entry
const emailLog = await db.emailLog.create({
data: {
schoolId: parsed.data.schoolId,
templateId: parsed.data.templateId || null,
recipientEmail: parsed.data.recipientEmail,
recipientName: parsed.data.recipientName || null,
subject: processedSubject,
body: processedBody,
status: 'sent',
sentAt: new Date(),
},
});
// In production, this would use an actual email sending service
// For now, we log the email as "sent" and return success
console.log(`[Email] ${parsed.data.isTest ? '[TEST] ' : ''}To: ${parsed.data.recipientEmail}, Subject: ${processedSubject}`);
return NextResponse.json({
success: true,
logId: emailLog.id,
message: parsed.data.isTest
? 'Test email logged successfully'
: 'Email logged successfully',
});
} catch (error) {
console.error('Email send error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
@@ -0,0 +1,137 @@
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 contact = await db.emergencyContact.findFirst({
where: { id, deletedAt: null },
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
},
});
if (!contact) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== contact.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
return NextResponse.json(contact);
} catch (error) {
console.error('EmergencyContact 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.emergencyContact.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 {
name,
relationship,
phone,
phoneAlt,
email,
address,
isPrimary,
priority,
notes,
} = body;
const updated = await db.emergencyContact.update({
where: { id },
data: {
...(name !== undefined && { name }),
...(relationship !== undefined && { relationship }),
...(phone !== undefined && { phone }),
...(phoneAlt !== undefined && { phoneAlt: phoneAlt || null }),
...(email !== undefined && { email: email || null }),
...(address !== undefined && { address: address || null }),
...(isPrimary !== undefined && { isPrimary }),
...(priority !== undefined && { priority }),
...(notes !== undefined && { notes }),
},
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
},
});
return NextResponse.json(updated);
} catch (error) {
console.error('EmergencyContact 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.emergencyContact.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.emergencyContact.update({
where: { id },
data: { deletedAt: new Date() },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('EmergencyContact DELETE [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+109
View File
@@ -0,0 +1,109 @@
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');
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;
const contacts = await db.emergencyContact.findMany({
where,
orderBy: [{ isPrimary: 'desc' }, { priority: 'asc' }],
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
},
});
return NextResponse.json(contacts);
} catch (error) {
console.error('EmergencyContact 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,
name,
relationship,
phone,
phoneAlt,
email,
address,
isPrimary,
priority,
notes,
isDemo,
} = body;
if (!schoolId || !studentId || !name || !relationship || !phone) {
return NextResponse.json(
{ error: 'schoolId, studentId, name, relationship, and phone are required' },
{ status: 400 }
);
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const contact = await db.emergencyContact.create({
data: {
schoolId,
studentId,
name,
relationship,
phone,
phoneAlt: phoneAlt || null,
email: email || null,
address: address || null,
isPrimary: isPrimary ?? false,
priority: priority ?? 1,
notes: notes || null,
isDemo: isDemo ?? false,
},
include: {
student: {
select: { id: true, firstName: true, lastName: true },
},
},
});
return NextResponse.json(contact, { status: 201 });
} catch (error) {
console.error('EmergencyContact POST error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+161
View File
@@ -0,0 +1,161 @@
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.peerAssessment.findFirst({
where: { id, deletedAt: null },
include: {
assessor: {
select: { id: true, firstName: true, lastName: true },
},
assessed: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
classGroup: {
select: { id: true, name: true },
},
rubric: {
select: { id: true, title: 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('PeerAssessment 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.peerAssessment.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 {
level,
comment,
assessmentType,
competencyId,
classGroupId,
rubricId,
isAnonymous,
} = body;
if (level !== undefined && level !== null && (level < 1 || level > 6)) {
return NextResponse.json({ error: 'level must be between 1 and 6' }, { status: 400 });
}
const updated = await db.peerAssessment.update({
where: { id },
data: {
...(level !== undefined && { level: level ?? null }),
...(comment !== undefined && { comment }),
...(assessmentType !== undefined && { assessmentType }),
...(competencyId !== undefined && { competencyId: competencyId || null }),
...(classGroupId !== undefined && { classGroupId: classGroupId || null }),
...(rubricId !== undefined && { rubricId: rubricId || null }),
...(isAnonymous !== undefined && { isAnonymous }),
},
include: {
assessor: {
select: { id: true, firstName: true, lastName: true },
},
assessed: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
classGroup: {
select: { id: true, name: true },
},
rubric: {
select: { id: true, title: true },
},
},
});
return NextResponse.json(updated);
} catch (error) {
console.error('PeerAssessment 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.peerAssessment.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.peerAssessment.update({
where: { id },
data: { deletedAt: new Date() },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('PeerAssessment DELETE [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+146
View File
@@ -0,0 +1,146 @@
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 assessedId = searchParams.get('assessedId');
const assessorId = searchParams.get('assessorId');
const competencyId = searchParams.get('competencyId');
const classGroupId = searchParams.get('classGroupId');
const assessmentType = searchParams.get('assessmentType');
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 (assessedId) where.assessedId = assessedId;
if (assessorId) where.assessorId = assessorId;
if (competencyId) where.competencyId = competencyId;
if (classGroupId) where.classGroupId = classGroupId;
if (assessmentType) where.assessmentType = assessmentType;
const assessments = await db.peerAssessment.findMany({
where,
orderBy: { createdAt: 'desc' },
include: {
assessor: {
select: { id: true, firstName: true, lastName: true },
},
assessed: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
classGroup: {
select: { id: true, name: true },
},
rubric: {
select: { id: true, title: true },
},
},
});
return NextResponse.json(assessments);
} catch (error) {
console.error('PeerAssessment 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,
assessorId,
assessedId,
competencyId,
classGroupId,
assessmentType,
level,
comment,
rubricId,
isAnonymous,
isDemo,
} = body;
if (!schoolId || !assessorId || !assessedId || !assessmentType) {
return NextResponse.json(
{ error: 'schoolId, assessorId, assessedId, and assessmentType are required' },
{ status: 400 }
);
}
if (level !== undefined && level !== null && (level < 1 || level > 6)) {
return NextResponse.json(
{ error: 'level 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.peerAssessment.create({
data: {
schoolId,
assessorId,
assessedId,
competencyId: competencyId || null,
classGroupId: classGroupId || null,
assessmentType,
level: level ?? null,
comment: comment || null,
rubricId: rubricId || null,
isAnonymous: isAnonymous ?? false,
isDemo: isDemo ?? false,
},
include: {
assessor: {
select: { id: true, firstName: true, lastName: true },
},
assessed: {
select: { id: true, firstName: true, lastName: true },
},
competency: {
select: { id: true, code: true, title: true },
},
classGroup: {
select: { id: true, name: true },
},
rubric: {
select: { id: true, title: true },
},
},
});
return NextResponse.json(assessment, { status: 201 });
} catch (error) {
console.error('PeerAssessment POST error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
@@ -0,0 +1,113 @@
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getSession } from '@/lib/auth';
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;
const event = await db.schoolEvent.findFirst({
where: { id, deletedAt: null },
});
if (!event) {
return NextResponse.json({ error: 'Event not found' }, { status: 404 });
}
if (!event.requiresRegistration) {
return NextResponse.json({ error: 'Event does not require registration' }, { status: 400 });
}
const body = await request.json();
const { userId, notes } = body;
if (!userId) {
return NextResponse.json({ error: 'userId is required' }, { status: 400 });
}
// Check if already registered
const existing = await db.eventRegistration.findUnique({
where: { eventId_userId: { eventId: id, userId } },
});
if (existing) {
if (existing.status === 'cancelled') {
// Re-register
const updated = await db.eventRegistration.update({
where: { id: existing.id },
data: { status: 'registered', notes: notes || null },
});
return NextResponse.json(updated);
}
return NextResponse.json({ error: 'Already registered' }, { status: 409 });
}
// Check max participants
if (event.maxParticipants) {
const count = await db.eventRegistration.count({
where: { eventId: id, status: 'registered' },
});
if (count >= event.maxParticipants) {
return NextResponse.json({ error: 'Event is full' }, { status: 400 });
}
}
const registration = await db.eventRegistration.create({
data: {
eventId: id,
userId,
notes: notes || null,
},
});
return NextResponse.json(registration, { status: 201 });
} catch (error) {
console.error('EventRegistration POST 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 body = await request.json();
const { userId, status } = body;
if (!userId || !status) {
return NextResponse.json({ error: 'userId and status are required' }, { status: 400 });
}
const registration = await db.eventRegistration.findUnique({
where: { eventId_userId: { eventId: id, userId } },
});
if (!registration) {
return NextResponse.json({ error: 'Registration not found' }, { status: 404 });
}
const updated = await db.eventRegistration.update({
where: { id: registration.id },
data: { status },
});
return NextResponse.json(updated);
} catch (error) {
console.error('EventRegistration PUT error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+165
View File
@@ -0,0 +1,165 @@
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 event = await db.schoolEvent.findFirst({
where: { id, deletedAt: null },
include: {
organizer: {
select: { id: true, firstName: true, lastName: true },
},
classGroup: {
select: { id: true, name: true },
},
registrations: {
include: {
user: {
select: { id: true, firstName: true, lastName: true },
},
},
},
},
});
if (!event) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== event.schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
return NextResponse.json(event);
} catch (error) {
console.error('SchoolEvent 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.schoolEvent.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,
eventType,
startDate,
endDate,
location,
organizerId,
classGroupId,
isAllSchool,
isPublic,
requiresRegistration,
maxParticipants,
notes,
} = body;
const updated = await db.schoolEvent.update({
where: { id },
data: {
...(title !== undefined && { title }),
...(description !== undefined && { description }),
...(eventType !== undefined && { eventType }),
...(startDate !== undefined && { startDate: new Date(startDate) }),
...(endDate !== undefined && { endDate: endDate ? new Date(endDate) : null }),
...(location !== undefined && { location }),
...(organizerId !== undefined && { organizerId: organizerId || null }),
...(classGroupId !== undefined && { classGroupId: classGroupId || null }),
...(isAllSchool !== undefined && { isAllSchool }),
...(isPublic !== undefined && { isPublic }),
...(requiresRegistration !== undefined && { requiresRegistration }),
...(maxParticipants !== undefined && { maxParticipants: maxParticipants || null }),
...(notes !== undefined && { notes }),
},
include: {
organizer: {
select: { id: true, firstName: true, lastName: true },
},
classGroup: {
select: { id: true, name: true },
},
registrations: {
include: {
user: {
select: { id: true, firstName: true, lastName: true },
},
},
},
},
});
return NextResponse.json(updated);
} catch (error) {
console.error('SchoolEvent 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.schoolEvent.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.schoolEvent.update({
where: { id },
data: { deletedAt: new Date() },
});
return NextResponse.json({ success: true });
} catch (error) {
console.error('SchoolEvent DELETE [id] error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+142
View File
@@ -0,0 +1,142 @@
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 eventType = searchParams.get('eventType');
const classGroupId = searchParams.get('classGroupId');
const upcoming = searchParams.get('upcoming');
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 (eventType) where.eventType = eventType;
if (classGroupId) where.classGroupId = classGroupId;
if (upcoming === 'true') {
where.startDate = { gte: new Date() };
}
const events = await db.schoolEvent.findMany({
where,
orderBy: { startDate: 'asc' },
include: {
organizer: {
select: { id: true, firstName: true, lastName: true },
},
classGroup: {
select: { id: true, name: true },
},
registrations: {
include: {
user: {
select: { id: true, firstName: true, lastName: true },
},
},
},
},
});
return NextResponse.json(events);
} catch (error) {
console.error('SchoolEvent 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,
title,
description,
eventType,
startDate,
endDate,
location,
organizerId,
classGroupId,
isAllSchool,
isPublic,
requiresRegistration,
maxParticipants,
notes,
isDemo,
} = body;
if (!schoolId || !title || !eventType || !startDate) {
return NextResponse.json(
{ error: 'schoolId, title, eventType, and startDate are required' },
{ status: 400 }
);
}
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== schoolId) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const event = await db.schoolEvent.create({
data: {
schoolId,
title,
description: description || null,
eventType,
startDate: new Date(startDate),
endDate: endDate ? new Date(endDate) : null,
location: location || null,
organizerId: organizerId || null,
classGroupId: classGroupId || null,
isAllSchool: isAllSchool ?? true,
isPublic: isPublic ?? true,
requiresRegistration: requiresRegistration ?? false,
maxParticipants: maxParticipants || null,
notes: notes || null,
isDemo: isDemo ?? false,
},
include: {
organizer: {
select: { id: true, firstName: true, lastName: true },
},
classGroup: {
select: { id: true, name: true },
},
registrations: {
include: {
user: {
select: { id: true, firstName: true, lastName: true },
},
},
},
},
});
return NextResponse.json(event, { status: 201 });
} catch (error) {
console.error('SchoolEvent POST error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+67
View File
@@ -8,6 +8,18 @@ const createSchoolSchema = z.object({
schoolType: z.enum(['ELEMENTARY', 'MIDDLE', 'GYMNASIUM', 'OTHER']),
country: z.string().default('DE'),
timezone: z.string().default('Europe/Berlin'),
// Branding fields
logoUrl: z.string().optional(),
primaryColor: z.string().optional(),
secondaryColor: z.string().optional(),
accentColor: z.string().optional(),
fontFamily: z.string().optional(),
customCss: z.string().optional(),
motto: z.string().optional(),
websiteUrl: z.string().optional(),
emailDomain: z.string().optional(),
address: z.string().optional(),
phone: z.string().optional(),
});
export async function GET(request: Request) {
@@ -19,6 +31,7 @@ export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const schoolType = searchParams.get('schoolType');
const includeBranding = searchParams.get('includeBranding') === 'true';
const where: Record<string, unknown> = {};
if (schoolType) where.schoolType = schoolType;
@@ -39,6 +52,7 @@ export async function GET(request: Request) {
students: { where: { deletedAt: null } },
},
},
...(includeBranding ? {} : {}),
},
});
@@ -79,6 +93,47 @@ export async function POST(request: Request) {
data: parsed.data,
});
// Seed default email templates for the new school
const defaultTemplates = [
{
schoolId: school.id,
name: 'weekly_report',
subject: 'Wochenbericht {{studentName}}',
body: '<h1>Wochenbericht für {{studentName}}</h1><p>Klasse: {{className}}</p><p>Lehrkraft: {{teacherName}}</p><p>Datum: {{date}}</p><h2>Kompetenzfortschritt</h2><p>{{competencyProgress}}</p><p>Mit freundlichen Grüßen,<br>{{schoolName}}</p>',
isDefault: true,
},
{
schoolId: school.id,
name: 'assessment_reminder',
subject: 'Bewertung am {{date}}',
body: '<h1>Bewertungserinnerung</h1><p>Hallo {{teacherName}},</p><p>am {{date}} steht eine Bewertung an für {{className}}.</p><p>Betreff: {{subjectName}}</p><p>Mit freundlichen Grüßen,<br>{{schoolName}}</p>',
isDefault: true,
},
{
schoolId: school.id,
name: 'behavior_alert',
subject: 'Verhaltensnotice für {{studentName}}',
body: '<h1>Verhaltensnotice</h1><p>Schüler/in: {{studentName}}</p><p>Klasse: {{className}}</p><p>Datum: {{date}}</p><p>Vorfall: {{behaviorDescription}}</p><p>Kategorie: {{behaviorCategory}}</p><p>Mit freundlichen Grüßen,<br>{{schoolName}}</p>',
isDefault: true,
},
{
schoolId: school.id,
name: 'attendance_notice',
subject: 'Anwesenheits-Notice',
body: '<h1>Anwesenheitsnotice</h1><p>Schüler/in: {{studentName}}</p><p>Klasse: {{className}}</p><p>Datum: {{date}}</p><p>Status: {{attendanceStatus}}</p><p>Mit freundlichen Grüßen,<br>{{schoolName}}</p>',
isDefault: true,
},
{
schoolId: school.id,
name: 'welcome',
subject: 'Willkommen bei CompetenceTrack',
body: '<h1>Willkommen bei CompetenceTrack!</h1><p>Hallo {{studentName}},</p><p>du wurdest für die Schule {{schoolName}} registriert.</p><p>Deine Zugangsdaten:</p><p>E-Mail: {{email}}</p><p>Bitte melde dich an und ändere dein Passwort.</p><p>Mit freundlichen Grüßen,<br>{{schoolName}}</p>',
isDefault: true,
},
];
await db.emailTemplate.createMany({ data: defaultTemplates });
return NextResponse.json(school, { status: 201 });
} catch (error) {
console.error('Schools POST error:', error);
@@ -95,6 +150,18 @@ const updateSchoolSchema = z.object({
schoolType: z.enum(['ELEMENTARY', 'MIDDLE', 'GYMNASIUM', 'OTHER']).optional(),
country: z.string().optional(),
timezone: z.string().optional(),
// Branding fields
logoUrl: z.string().nullable().optional(),
primaryColor: z.string().nullable().optional(),
secondaryColor: z.string().nullable().optional(),
accentColor: z.string().nullable().optional(),
fontFamily: z.string().nullable().optional(),
customCss: z.string().nullable().optional(),
motto: z.string().nullable().optional(),
websiteUrl: z.string().nullable().optional(),
emailDomain: z.string().nullable().optional(),
address: z.string().nullable().optional(),
phone: z.string().nullable().optional(),
});
export async function PUT(request: Request) {