Round 13: PWA Offline Mode, Rate Limiting, Behavior Analytics, Interventions, Audit Logging
This commit is contained in:
1 parent
ceea8fb591
commit
ff4dd670d4
33 files changed
+6327
-509
No files matched your search
@@ -12,8 +12,13 @@ export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const schoolId = searchParams.get('schoolId');
|
||||
const action = searchParams.get('action');
|
||||
const entityType = searchParams.get('entityType');
|
||||
const userId = searchParams.get('userId');
|
||||
const startDate = searchParams.get('startDate');
|
||||
const endDate = searchParams.get('endDate');
|
||||
const page = parseInt(searchParams.get('page') || '1', 10);
|
||||
const pageSize = parseInt(searchParams.get('pageSize') || '50', 10);
|
||||
const exportCsv = searchParams.get('export') === 'csv';
|
||||
|
||||
const where: Record<string, unknown> = {};
|
||||
|
||||
@@ -25,6 +30,8 @@ export async function GET(request: Request) {
|
||||
}
|
||||
|
||||
if (action) where.action = action;
|
||||
if (entityType) where.entityType = entityType;
|
||||
if (userId) where.userId = userId;
|
||||
|
||||
if (startDate || endDate) {
|
||||
where.timestamp = {
|
||||
@@ -33,10 +40,52 @@ export async function GET(request: Request) {
|
||||
};
|
||||
}
|
||||
|
||||
// CSV export
|
||||
if (exportCsv) {
|
||||
const entries = await db.auditLog.findMany({
|
||||
where,
|
||||
orderBy: { timestamp: 'desc' },
|
||||
take: 10000,
|
||||
include: {
|
||||
user: {
|
||||
select: { id: true, firstName: true, lastName: true, email: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const header = 'Timestamp,User,Action,Entity Type,Entity ID,Changes,IP Address,User Agent,Metadata';
|
||||
const rows = entries.map((e) => {
|
||||
const userName = e.user ? `${e.user.firstName} ${e.user.lastName}` : 'System';
|
||||
const escape = (s: string | null) => (s ? `"${s.replace(/"/g, '""')}"` : '""');
|
||||
return [
|
||||
new Date(e.timestamp).toISOString(),
|
||||
escape(userName),
|
||||
escape(e.action),
|
||||
escape(e.entityType),
|
||||
escape(e.entityId),
|
||||
escape(e.changes),
|
||||
escape(e.ipAddress),
|
||||
escape(e.userAgent),
|
||||
escape(e.metadata),
|
||||
].join(',');
|
||||
});
|
||||
|
||||
const csv = [header, ...rows].join('\n');
|
||||
return new Response(csv, {
|
||||
headers: {
|
||||
'Content-Type': 'text/csv; charset=utf-8',
|
||||
'Content-Disposition': 'attachment; filename="audit-log.csv"',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Regular paginated response
|
||||
const total = await db.auditLog.count({ where });
|
||||
const entries = await db.auditLog.findMany({
|
||||
where,
|
||||
orderBy: { timestamp: 'desc' },
|
||||
take: 200,
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
include: {
|
||||
user: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
@@ -44,7 +93,15 @@ export async function GET(request: Request) {
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(entries);
|
||||
return NextResponse.json({
|
||||
entries,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalPages: Math.ceil(total / pageSize),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('AuditLog GET error:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
getSession,
|
||||
clearSession,
|
||||
} from '@/lib/auth';
|
||||
import { withRateLimit, checkRateLimit, getRateLimitKey, getRateLimitHeaders, createRateLimitResponse } from '@/lib/rate-limit';
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email(),
|
||||
@@ -23,7 +24,7 @@ const registerSchema = z.object({
|
||||
role: z.enum(['TEACHER', 'SCHOOL_ADMIN', 'SUPER_ADMIN']).default('TEACHER'),
|
||||
});
|
||||
|
||||
export async function POST(request: Request) {
|
||||
export const POST = withRateLimit(async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { action } = body;
|
||||
@@ -138,15 +139,33 @@ export async function POST(request: Request) {
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}, 'auth');
|
||||
|
||||
export async function GET(request: Request) {
|
||||
// Apply rate limit for auth check endpoint
|
||||
const key = getRateLimitKey(request);
|
||||
const result = checkRateLimit(key, 60, 60 * 1000); // 60 per minute for GET
|
||||
|
||||
if (!result.allowed) {
|
||||
const rateLimitResponse = createRateLimitResponse(result);
|
||||
return NextResponse.json(rateLimitResponse.body, {
|
||||
status: rateLimitResponse.status,
|
||||
headers: rateLimitResponse.headers,
|
||||
});
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session || !session.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
return NextResponse.json(session.user);
|
||||
|
||||
const response = NextResponse.json(session.user);
|
||||
const rateLimitHeaders = getRateLimitHeaders(result);
|
||||
for (const [headerKey, headerValue] of rateLimitHeaders.entries()) {
|
||||
response.headers.set(headerKey, headerValue);
|
||||
}
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error('Auth me error:', error);
|
||||
return NextResponse.json(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { withRateLimit } from '@/lib/rate-limit';
|
||||
|
||||
// GET /api/backup — List backups for a school
|
||||
export async function GET(req: NextRequest) {
|
||||
@@ -21,7 +22,7 @@ export async function GET(req: NextRequest) {
|
||||
}
|
||||
|
||||
// POST /api/backup — Create a new backup or restore from backup
|
||||
export async function POST(req: NextRequest) {
|
||||
export const POST = withRateLimit(async function POST(req: NextRequest) {
|
||||
try {
|
||||
const body = await req.json();
|
||||
const { schoolId, action, backupId, notes } = body;
|
||||
@@ -139,7 +140,7 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
return NextResponse.json({ error: 'Failed to create backup' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
}, 'heavy');
|
||||
|
||||
// DELETE /api/backup — Delete a backup
|
||||
export async function DELETE(req: NextRequest) {
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
import { logAudit, extractClientInfo } from '@/lib/audit';
|
||||
|
||||
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 intervention = await db.behaviorIntervention.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
include: {
|
||||
student: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
incident: {
|
||||
select: { id: true, description: true, date: true, severity: true },
|
||||
},
|
||||
assignedUser: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!intervention) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// If not super admin, restrict to user's school
|
||||
if (session.user?.role !== 'SUPER_ADMIN' && session.user?.schoolId !== intervention.schoolId) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
|
||||
return NextResponse.json(intervention);
|
||||
} catch (error) {
|
||||
console.error('BehaviorIntervention 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.behaviorIntervention.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 {
|
||||
type,
|
||||
description,
|
||||
status: interventionStatus,
|
||||
assignedTo,
|
||||
startDate,
|
||||
endDate,
|
||||
outcome,
|
||||
incidentId,
|
||||
} = body;
|
||||
|
||||
const updated = await db.behaviorIntervention.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(type !== undefined && { type }),
|
||||
...(description !== undefined && { description }),
|
||||
...(interventionStatus !== undefined && { status: interventionStatus }),
|
||||
...(assignedTo !== undefined && { assignedTo: assignedTo || null }),
|
||||
...(startDate !== undefined && { startDate: startDate ? new Date(startDate) : null }),
|
||||
...(endDate !== undefined && { endDate: endDate ? new Date(endDate) : null }),
|
||||
...(outcome !== undefined && { outcome }),
|
||||
...(incidentId !== undefined && { incidentId: incidentId || null }),
|
||||
},
|
||||
include: {
|
||||
student: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
incident: {
|
||||
select: { id: true, description: true, date: true, severity: true },
|
||||
},
|
||||
assignedUser: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Audit log
|
||||
const clientInfo = extractClientInfo(request);
|
||||
await logAudit({
|
||||
userId: session.user?.id,
|
||||
schoolId: existing.schoolId,
|
||||
action: 'UPDATE',
|
||||
entityType: 'BehaviorIntervention',
|
||||
entityId: id,
|
||||
changes: { before: existing, after: updated },
|
||||
...clientInfo,
|
||||
});
|
||||
|
||||
return NextResponse.json(updated);
|
||||
} catch (error) {
|
||||
console.error('BehaviorIntervention 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.behaviorIntervention.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.behaviorIntervention.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date() },
|
||||
});
|
||||
|
||||
// Audit log
|
||||
const clientInfo = extractClientInfo(request);
|
||||
await logAudit({
|
||||
userId: session.user?.id,
|
||||
schoolId: existing.schoolId,
|
||||
action: 'DELETE',
|
||||
entityType: 'BehaviorIntervention',
|
||||
entityId: id,
|
||||
changes: { before: existing },
|
||||
...clientInfo,
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('BehaviorIntervention DELETE [id] error:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
import { logAudit, extractClientInfo } from '@/lib/audit';
|
||||
|
||||
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 incidentId = searchParams.get('incidentId');
|
||||
const type = searchParams.get('type');
|
||||
const status = searchParams.get('status');
|
||||
|
||||
if (!schoolId) {
|
||||
return NextResponse.json({ error: 'schoolId is required' }, { status: 400 });
|
||||
}
|
||||
|
||||
// If not super admin, restrict to user's school
|
||||
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 (incidentId) where.incidentId = incidentId;
|
||||
if (type) where.type = type;
|
||||
if (status) where.status = status;
|
||||
|
||||
const interventions = await db.behaviorIntervention.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
student: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
incident: {
|
||||
select: { id: true, description: true, date: true, severity: true },
|
||||
},
|
||||
assignedUser: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(interventions);
|
||||
} catch (error) {
|
||||
console.error('BehaviorIntervention 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,
|
||||
incidentId,
|
||||
type,
|
||||
description,
|
||||
status: interventionStatus,
|
||||
assignedTo,
|
||||
startDate,
|
||||
endDate,
|
||||
outcome,
|
||||
isDemo,
|
||||
} = body;
|
||||
|
||||
if (!schoolId || !studentId || !type || !description) {
|
||||
return NextResponse.json(
|
||||
{ error: 'schoolId, studentId, type, and description are required' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const intervention = await db.behaviorIntervention.create({
|
||||
data: {
|
||||
schoolId,
|
||||
studentId,
|
||||
incidentId: incidentId || null,
|
||||
type,
|
||||
description,
|
||||
status: interventionStatus || 'planned',
|
||||
assignedTo: assignedTo || null,
|
||||
startDate: startDate ? new Date(startDate) : null,
|
||||
endDate: endDate ? new Date(endDate) : null,
|
||||
outcome: outcome || null,
|
||||
isDemo: isDemo ?? false,
|
||||
},
|
||||
include: {
|
||||
student: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
incident: {
|
||||
select: { id: true, description: true, date: true, severity: true },
|
||||
},
|
||||
assignedUser: {
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Audit log
|
||||
const clientInfo = extractClientInfo(request);
|
||||
await logAudit({
|
||||
userId: session.user?.id,
|
||||
schoolId,
|
||||
action: 'CREATE',
|
||||
entityType: 'BehaviorIntervention',
|
||||
entityId: intervention.id,
|
||||
changes: { after: intervention },
|
||||
...clientInfo,
|
||||
});
|
||||
|
||||
return NextResponse.json(intervention, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error('BehaviorIntervention POST error:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
import { withRateLimit } from '@/lib/rate-limit';
|
||||
|
||||
function escapeCsvField(field: string | number | null | undefined): string {
|
||||
if (field === null || field === undefined) return '';
|
||||
@@ -16,7 +17,7 @@ function toCsvRow(fields: (string | number | null | undefined)[]): string {
|
||||
return fields.map(escapeCsvField).join(',');
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
export const GET = withRateLimit(async function GET(request: Request) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session) {
|
||||
@@ -318,4 +319,4 @@ export async function GET(request: Request) {
|
||||
console.error('CSV Export error:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
}, 'heavy');
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
import { withRateLimit } from '@/lib/rate-limit';
|
||||
|
||||
function escapeCsvField(field: string | number | null | undefined): string {
|
||||
if (field === null || field === undefined) return '';
|
||||
@@ -59,7 +60,7 @@ function parseCsv(text: string): { headers: string[]; rows: ImportRow[] } {
|
||||
return { headers, rows };
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
export const POST = withRateLimit(async function POST(request: Request) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session) {
|
||||
@@ -217,7 +218,7 @@ export async function POST(request: Request) {
|
||||
console.error('Data Import error:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
}, 'heavy');
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
// GET /api/districts/[id]
|
||||
export async function GET(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const district = await db.schoolDistrict.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
include: {
|
||||
schools: {
|
||||
where: { deletedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
schoolType: true,
|
||||
country: true,
|
||||
_count: {
|
||||
select: { students: true, classGroups: true, users: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!district) {
|
||||
return NextResponse.json({ error: 'District not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(district);
|
||||
} catch (error) {
|
||||
console.error('[districts/[id]] GET error:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch district' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /api/districts/[id]
|
||||
export async function PUT(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const body = await req.json();
|
||||
const { name, code, region, country, adminEmail, isActive } = body;
|
||||
|
||||
const data: Record<string, unknown> = {};
|
||||
if (name !== undefined) data.name = name;
|
||||
if (code !== undefined) data.code = code || null;
|
||||
if (region !== undefined) data.region = region || null;
|
||||
if (country !== undefined) data.country = country;
|
||||
if (adminEmail !== undefined) data.adminEmail = adminEmail || null;
|
||||
if (isActive !== undefined) data.isActive = isActive;
|
||||
|
||||
const district = await db.schoolDistrict.update({
|
||||
where: { id },
|
||||
data,
|
||||
include: {
|
||||
schools: { select: { id: true, name: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(district);
|
||||
} catch (error) {
|
||||
console.error('[districts/[id]] PUT error:', error);
|
||||
return NextResponse.json({ error: 'Failed to update district' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/districts/[id]
|
||||
export async function DELETE(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
|
||||
// Remove district from schools first
|
||||
await db.school.updateMany({
|
||||
where: { districtId: id },
|
||||
data: { districtId: null },
|
||||
});
|
||||
|
||||
await db.schoolDistrict.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date() },
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('[districts/[id]] DELETE error:', error);
|
||||
return NextResponse.json({ error: 'Failed to delete district' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
// GET /api/districts/[id]/schools — schools in district
|
||||
export async function GET(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const district = await db.schoolDistrict.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
});
|
||||
|
||||
if (!district) {
|
||||
return NextResponse.json({ error: 'District not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const schools = await db.school.findMany({
|
||||
where: { districtId: id, deletedAt: null },
|
||||
include: {
|
||||
_count: {
|
||||
select: { students: true, classGroups: true, users: true },
|
||||
},
|
||||
},
|
||||
orderBy: { name: 'asc' },
|
||||
});
|
||||
|
||||
return NextResponse.json(schools);
|
||||
} catch (error) {
|
||||
console.error('[districts/[id]/schools] GET error:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch district schools' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/districts/[id]/schools — assign school to district
|
||||
export async function POST(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const body = await req.json();
|
||||
const { schoolId } = body;
|
||||
|
||||
if (!schoolId) {
|
||||
return NextResponse.json({ error: 'schoolId is required' }, { status: 400 });
|
||||
}
|
||||
|
||||
await db.school.update({
|
||||
where: { id: schoolId },
|
||||
data: { districtId: id },
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('[districts/[id]/schools] POST error:', error);
|
||||
return NextResponse.json({ error: 'Failed to assign school to district' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
// GET /api/districts
|
||||
export async function GET() {
|
||||
try {
|
||||
const districts = await db.schoolDistrict.findMany({
|
||||
where: { deletedAt: null },
|
||||
include: {
|
||||
schools: {
|
||||
where: { deletedAt: null },
|
||||
select: { id: true, name: true, schoolType: true, country: true },
|
||||
},
|
||||
},
|
||||
orderBy: { name: 'asc' },
|
||||
});
|
||||
|
||||
// Add computed stats
|
||||
const result = districts.map((d) => ({
|
||||
...d,
|
||||
schoolCount: d.schools.length,
|
||||
totalStudents: 0, // Would need aggregation query in production
|
||||
}));
|
||||
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
console.error('[districts] GET error:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch districts' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/districts
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const body = await req.json();
|
||||
const { name, code, region, country, adminEmail } = body;
|
||||
|
||||
if (!name) {
|
||||
return NextResponse.json({ error: 'name is required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const district = await db.schoolDistrict.create({
|
||||
data: {
|
||||
name,
|
||||
code: code || null,
|
||||
region: region || null,
|
||||
country: country || 'DE',
|
||||
adminEmail: adminEmail || null,
|
||||
},
|
||||
include: {
|
||||
schools: { select: { id: true, name: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(district, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error('[districts] POST error:', error);
|
||||
return NextResponse.json({ error: 'Failed to create district' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getRateLimitStats } from '@/lib/rate-limit';
|
||||
|
||||
// GET /api/rate-limit-stats — Get rate limit statistics (admin monitoring)
|
||||
export async function GET() {
|
||||
try {
|
||||
const stats = getRateLimitStats();
|
||||
return NextResponse.json(stats);
|
||||
} catch (error) {
|
||||
console.error('Rate limit stats error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
// GET /api/report-schedules/[id]
|
||||
export async function GET(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const schedule = await db.reportSchedule.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
include: {
|
||||
classGroup: { select: { id: true, name: true, gradeLevel: true } },
|
||||
school: { select: { id: true, name: true } },
|
||||
},
|
||||
});
|
||||
if (!schedule) {
|
||||
return NextResponse.json({ error: 'Schedule not found' }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json(schedule);
|
||||
} catch (error) {
|
||||
console.error('[report-schedules/[id]] GET error:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch schedule' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /api/report-schedules/[id]
|
||||
export async function PUT(
|
||||
req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const body = await req.json();
|
||||
const {
|
||||
classGroupId,
|
||||
template,
|
||||
frequency,
|
||||
dayOfWeek,
|
||||
dayOfMonth,
|
||||
monthOfYear,
|
||||
recipients,
|
||||
includeStudents,
|
||||
includeGrades,
|
||||
includeAttendance,
|
||||
includeBehavior,
|
||||
includeCompetencies,
|
||||
isActive,
|
||||
} = body;
|
||||
|
||||
const data: Record<string, unknown> = {};
|
||||
if (classGroupId !== undefined) data.classGroupId = classGroupId || null;
|
||||
if (template !== undefined) data.template = template;
|
||||
if (frequency !== undefined) data.frequency = frequency;
|
||||
if (dayOfWeek !== undefined) data.dayOfWeek = dayOfWeek;
|
||||
if (dayOfMonth !== undefined) data.dayOfMonth = dayOfMonth;
|
||||
if (monthOfYear !== undefined) data.monthOfYear = monthOfYear;
|
||||
if (recipients !== undefined) data.recipients = recipients ? JSON.stringify(recipients) : null;
|
||||
if (includeStudents !== undefined) data.includeStudents = includeStudents;
|
||||
if (includeGrades !== undefined) data.includeGrades = includeGrades;
|
||||
if (includeAttendance !== undefined) data.includeAttendance = includeAttendance;
|
||||
if (includeBehavior !== undefined) data.includeBehavior = includeBehavior;
|
||||
if (includeCompetencies !== undefined) data.includeCompetencies = includeCompetencies;
|
||||
if (isActive !== undefined) data.isActive = isActive;
|
||||
|
||||
// Recalculate nextRunAt if frequency or timing changed
|
||||
if (frequency || dayOfWeek !== undefined || dayOfMonth !== undefined || monthOfYear !== undefined) {
|
||||
const current = await db.reportSchedule.findUnique({ where: { id } });
|
||||
if (current) {
|
||||
const freq = frequency || current.frequency;
|
||||
const dow = dayOfWeek !== undefined ? dayOfWeek : current.dayOfWeek;
|
||||
const dom = dayOfMonth !== undefined ? dayOfMonth : current.dayOfMonth;
|
||||
const moy = monthOfYear !== undefined ? monthOfYear : current.monthOfYear;
|
||||
data.nextRunAt = calculateNextRun(freq, dow, dom, moy);
|
||||
}
|
||||
}
|
||||
|
||||
const schedule = await db.reportSchedule.update({
|
||||
where: { id },
|
||||
data,
|
||||
include: {
|
||||
classGroup: { select: { id: true, name: true, gradeLevel: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(schedule);
|
||||
} catch (error) {
|
||||
console.error('[report-schedules/[id]] PUT error:', error);
|
||||
return NextResponse.json({ error: 'Failed to update schedule' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/report-schedules/[id]
|
||||
export async function DELETE(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
await db.reportSchedule.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date() },
|
||||
});
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('[report-schedules/[id]] DELETE error:', error);
|
||||
return NextResponse.json({ error: 'Failed to delete schedule' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
function calculateNextRun(
|
||||
frequency: string,
|
||||
dayOfWeek?: number | null,
|
||||
dayOfMonth?: number | null,
|
||||
monthOfYear?: number | null,
|
||||
): Date {
|
||||
const now = new Date();
|
||||
const next = new Date(now);
|
||||
|
||||
switch (frequency) {
|
||||
case 'weekly': {
|
||||
const targetDay = dayOfWeek ?? 1;
|
||||
const currentDay = next.getDay();
|
||||
const daysUntil = ((targetDay - currentDay + 7) % 7) || 7;
|
||||
next.setDate(next.getDate() + daysUntil);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
break;
|
||||
}
|
||||
case 'monthly': {
|
||||
const targetDate = dayOfMonth ?? 1;
|
||||
next.setDate(targetDate);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
if (next <= now) next.setMonth(next.getMonth() + 1);
|
||||
break;
|
||||
}
|
||||
case 'quarterly': {
|
||||
const targetMonth = monthOfYear ?? 1;
|
||||
next.setMonth(targetMonth - 1);
|
||||
next.setDate(1);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
if (next <= now) next.setMonth(next.getMonth() + 3);
|
||||
break;
|
||||
}
|
||||
case 'end_of_term': {
|
||||
next.setMonth(6);
|
||||
next.setDate(15);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
if (next <= now) next.setFullYear(next.getFullYear() + 1);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
next.setDate(next.getDate() + 7);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
// POST /api/report-schedules/[id]/run — trigger manual run
|
||||
export async function POST(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const schedule = await db.reportSchedule.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
include: {
|
||||
classGroup: { select: { id: true, name: true, gradeLevel: true } },
|
||||
school: { select: { id: true, name: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!schedule) {
|
||||
return NextResponse.json({ error: 'Schedule not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Mark as run and calculate next run
|
||||
const now = new Date();
|
||||
const nextRunAt = calculateNextRun(
|
||||
schedule.frequency,
|
||||
schedule.dayOfWeek,
|
||||
schedule.dayOfMonth,
|
||||
schedule.monthOfYear,
|
||||
);
|
||||
|
||||
await db.reportSchedule.update({
|
||||
where: { id },
|
||||
data: { lastRunAt: now, nextRunAt },
|
||||
});
|
||||
|
||||
// In a real system, this would trigger the actual report generation pipeline
|
||||
// and send notifications to recipients. For now, we simulate success.
|
||||
const recipientIds: string[] = schedule.recipients
|
||||
? JSON.parse(schedule.recipients)
|
||||
: [];
|
||||
|
||||
// Create notifications for recipients
|
||||
if (recipientIds.length > 0) {
|
||||
try {
|
||||
await db.notification.createMany({
|
||||
data: recipientIds.map((userId) => ({
|
||||
schoolId: schedule.schoolId,
|
||||
userId,
|
||||
type: 'report_ready',
|
||||
title: `Scheduled Report Generated`,
|
||||
message: `Report schedule "${schedule.template}" for ${schedule.classGroup?.name ?? 'all classes'} has been generated.`,
|
||||
actionUrl: '/reports',
|
||||
relatedId: schedule.id,
|
||||
})),
|
||||
});
|
||||
} catch {
|
||||
// Notification creation is non-critical
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
lastRunAt: now,
|
||||
nextRunAt,
|
||||
recipientsNotified: recipientIds.length,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[report-schedules/[id]/run] POST error:', error);
|
||||
return NextResponse.json({ error: 'Failed to run schedule' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
function calculateNextRun(
|
||||
frequency: string,
|
||||
dayOfWeek?: number | null,
|
||||
dayOfMonth?: number | null,
|
||||
monthOfYear?: number | null,
|
||||
): Date {
|
||||
const now = new Date();
|
||||
const next = new Date(now);
|
||||
|
||||
switch (frequency) {
|
||||
case 'weekly': {
|
||||
const targetDay = dayOfWeek ?? 1;
|
||||
const currentDay = next.getDay();
|
||||
const daysUntil = ((targetDay - currentDay + 7) % 7) || 7;
|
||||
next.setDate(next.getDate() + daysUntil);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
break;
|
||||
}
|
||||
case 'monthly': {
|
||||
const targetDate = dayOfMonth ?? 1;
|
||||
next.setDate(targetDate);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
if (next <= now) next.setMonth(next.getMonth() + 1);
|
||||
break;
|
||||
}
|
||||
case 'quarterly': {
|
||||
const targetMonth = monthOfYear ?? 1;
|
||||
next.setMonth(targetMonth - 1);
|
||||
next.setDate(1);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
if (next <= now) next.setMonth(next.getMonth() + 3);
|
||||
break;
|
||||
}
|
||||
case 'end_of_term': {
|
||||
next.setMonth(6);
|
||||
next.setDate(15);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
if (next <= now) next.setFullYear(next.getFullYear() + 1);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
next.setDate(next.getDate() + 7);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
// GET /api/report-schedules?schoolId=xxx
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const schoolId = req.nextUrl.searchParams.get('schoolId');
|
||||
if (!schoolId) {
|
||||
return NextResponse.json({ error: 'schoolId is required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const schedules = await db.reportSchedule.findMany({
|
||||
where: { schoolId, deletedAt: null },
|
||||
include: {
|
||||
classGroup: { select: { id: true, name: true, gradeLevel: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
return NextResponse.json(schedules);
|
||||
} catch (error) {
|
||||
console.error('[report-schedules] GET error:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch report schedules' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/report-schedules
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const body = await req.json();
|
||||
const {
|
||||
schoolId,
|
||||
classGroupId,
|
||||
template,
|
||||
frequency,
|
||||
dayOfWeek,
|
||||
dayOfMonth,
|
||||
monthOfYear,
|
||||
recipients,
|
||||
includeStudents,
|
||||
includeGrades,
|
||||
includeAttendance,
|
||||
includeBehavior,
|
||||
includeCompetencies,
|
||||
} = body;
|
||||
|
||||
if (!schoolId || !template || !frequency) {
|
||||
return NextResponse.json({ error: 'schoolId, template, and frequency are required' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Calculate nextRunAt
|
||||
const nextRunAt = calculateNextRun(frequency, dayOfWeek, dayOfMonth, monthOfYear);
|
||||
|
||||
const schedule = await db.reportSchedule.create({
|
||||
data: {
|
||||
schoolId,
|
||||
classGroupId: classGroupId || null,
|
||||
template,
|
||||
frequency,
|
||||
dayOfWeek: dayOfWeek ?? null,
|
||||
dayOfMonth: dayOfMonth ?? null,
|
||||
monthOfYear: monthOfYear ?? null,
|
||||
recipients: recipients ? JSON.stringify(recipients) : null,
|
||||
includeStudents: includeStudents ?? true,
|
||||
includeGrades: includeGrades ?? true,
|
||||
includeAttendance: includeAttendance ?? true,
|
||||
includeBehavior: includeBehavior ?? false,
|
||||
includeCompetencies: includeCompetencies ?? true,
|
||||
nextRunAt,
|
||||
},
|
||||
include: {
|
||||
classGroup: { select: { id: true, name: true, gradeLevel: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(schedule, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error('[report-schedules] POST error:', error);
|
||||
return NextResponse.json({ error: 'Failed to create report schedule' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
function calculateNextRun(
|
||||
frequency: string,
|
||||
dayOfWeek?: number | null,
|
||||
dayOfMonth?: number | null,
|
||||
monthOfYear?: number | null,
|
||||
): Date {
|
||||
const now = new Date();
|
||||
const next = new Date(now);
|
||||
|
||||
switch (frequency) {
|
||||
case 'weekly': {
|
||||
const targetDay = dayOfWeek ?? 1; // Monday default
|
||||
const currentDay = next.getDay();
|
||||
const daysUntil = ((targetDay - currentDay + 7) % 7) || 7;
|
||||
next.setDate(next.getDate() + daysUntil);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
break;
|
||||
}
|
||||
case 'monthly': {
|
||||
const targetDate = dayOfMonth ?? 1;
|
||||
next.setDate(targetDate);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
if (next <= now) {
|
||||
next.setMonth(next.getMonth() + 1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'quarterly': {
|
||||
const targetMonth = monthOfYear ?? 1;
|
||||
next.setMonth(targetMonth - 1);
|
||||
next.setDate(1);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
if (next <= now) {
|
||||
next.setMonth(next.getMonth() + 3);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'end_of_term': {
|
||||
// Default: July 15 (end of German school year)
|
||||
next.setMonth(6); // July
|
||||
next.setDate(15);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
if (next <= now) {
|
||||
next.setFullYear(next.getFullYear() + 1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
next.setDate(next.getDate() + 7);
|
||||
next.setHours(8, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
import { withRateLimit } from '@/lib/rate-limit';
|
||||
|
||||
export async function GET(request: Request) {
|
||||
export const GET = withRateLimit(async function GET(request: Request) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session) {
|
||||
@@ -105,7 +106,7 @@ export async function GET(request: Request) {
|
||||
console.error('Report PDF error:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
}, 'heavy');
|
||||
|
||||
function generatePrintHtml(report: Record<string, unknown>, template: string): string {
|
||||
const student = report.student as { firstName: string; lastName: string };
|
||||
|
||||
Reference in new issue
Block a user