Round 19: Professional Notebooks, Digital Rewards, GDPR, Role-Based Dashboard, Deep Styling Polish
- Fixed attendance API 403: added TEACHER school membership check - Fixed competitions API 403: cross-school access, null schoolId, public fallback - Fixed GDPR export API 500: 16 Prisma field name mismatches - Enhanced notebooks: page templates (Cornell, Mind Map, Venn, T-Chart, Weekly Planner), sticky notes, search, page duplication, sections/chapters, highlighter tool - Added scratch pad with DrawingCanvas in assessments for hand-written solutions - Role-based dashboard: TEACHER (competence radar, upcoming lessons), STUDENT (grades trend, competitions), PARENT (children grades, calendar), SCHOOL_ADMIN (system health, audit log, user management) - Digital reward system: 16 demo rewards, points earning/redemption, categories (streaming, shopping, experiences, merchandise, privileges) - GDPR compliance: consent management, data retention, cookie consent - Deep styling polish: glassmorphism, gradient headers, animated sidebar, card hover effects, progress bar animations, timeline dots, FAB button - 160+ new i18n keys (DE/EN)
This commit is contained in:
1 parent
86e4b504e4
commit
6d9b42ac37
43 files changed
+4569
-140
No files matched your search
@@ -54,7 +54,7 @@ export async function GET(request: Request) {
|
||||
}
|
||||
|
||||
if (
|
||||
session.user?.role === 'SCHOOL_ADMIN' &&
|
||||
(session.user?.role === 'SCHOOL_ADMIN' || session.user?.role === 'TEACHER') &&
|
||||
session.user.schoolId &&
|
||||
classGroup.schoolId !== session.user.schoolId
|
||||
) {
|
||||
@@ -200,7 +200,7 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
if (
|
||||
session.user?.role === 'SCHOOL_ADMIN' &&
|
||||
(session.user?.role === 'SCHOOL_ADMIN' || session.user?.role === 'TEACHER') &&
|
||||
session.user.schoolId &&
|
||||
classGroup.schoolId !== session.user.schoolId
|
||||
) {
|
||||
|
||||
@@ -24,13 +24,25 @@ async function getLeaderboard(
|
||||
return NextResponse.json({ error: 'Competition not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Access control
|
||||
// Access control: authenticated users can see their own school's competitions or public ones
|
||||
// Also allow participants (e.g. inter-school competitions) and users without a schoolId viewing public ones
|
||||
const userSchoolId = session.user?.schoolId;
|
||||
const isSameSchool = userSchoolId === competition.schoolId;
|
||||
if (
|
||||
session.user?.role !== 'SUPER_ADMIN' &&
|
||||
session.user?.schoolId !== competition.schoolId &&
|
||||
!isSameSchool &&
|
||||
!competition.isPublic
|
||||
) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
// Check if the user is a participant in this competition
|
||||
const participant = await db.competitionParticipant.findFirst({
|
||||
where: {
|
||||
competitionId: id,
|
||||
userId: session.user!.id,
|
||||
},
|
||||
});
|
||||
if (!participant) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
}
|
||||
|
||||
const leaderboard = await db.competitionLeaderboard.findMany({
|
||||
|
||||
@@ -49,13 +49,25 @@ async function getRewards(
|
||||
return NextResponse.json({ error: 'Competition not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Access control
|
||||
// Access control: authenticated users can see their own school's competitions or public ones
|
||||
// Also allow participants (e.g. inter-school competitions) and users without a schoolId viewing public ones
|
||||
const userSchoolId = session.user?.schoolId;
|
||||
const isSameSchool = userSchoolId === competition.schoolId;
|
||||
if (
|
||||
session.user?.role !== 'SUPER_ADMIN' &&
|
||||
session.user?.schoolId !== competition.schoolId &&
|
||||
!isSameSchool &&
|
||||
!competition.isPublic
|
||||
) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
// Check if the user is a participant in this competition
|
||||
const participant = await db.competitionParticipant.findFirst({
|
||||
where: {
|
||||
competitionId: id,
|
||||
userId: session.user!.id,
|
||||
},
|
||||
});
|
||||
if (!participant) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
}
|
||||
|
||||
const rewards = await db.competitionReward.findMany({
|
||||
|
||||
@@ -88,11 +88,19 @@ async function getCompetition(
|
||||
return NextResponse.json({ error: 'Competition not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Access control: non-admins can only see their own school's competitions or public ones
|
||||
// Access control: authenticated users can see their own school's competitions or public ones
|
||||
// Users without a schoolId (e.g. some PARENTs) can still see public competitions
|
||||
// Participants can always view the competition they are in
|
||||
const userSchoolId = session.user?.schoolId;
|
||||
const isSameSchool = userSchoolId === competition.schoolId;
|
||||
const isParticipant = competition.participants?.some(
|
||||
(p) => p.userId === session.user!.id || p.participantId === session.user!.id
|
||||
);
|
||||
if (
|
||||
session.user?.role !== 'SUPER_ADMIN' &&
|
||||
session.user?.schoolId !== competition.schoolId &&
|
||||
!competition.isPublic
|
||||
!isSameSchool &&
|
||||
!competition.isPublic &&
|
||||
!isParticipant
|
||||
) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
|
||||
@@ -53,13 +53,72 @@ async function getCompetitions(request: Request): Promise<NextResponse> {
|
||||
const offset = parseInt(searchParams.get('offset') || '0');
|
||||
|
||||
let schoolId: string | undefined;
|
||||
if (session.user?.role === 'SCHOOL_ADMIN') {
|
||||
if (session.user?.role === 'SUPER_ADMIN') {
|
||||
// Super admins can query any school or see all
|
||||
schoolId = schoolIdParam ?? undefined;
|
||||
} else if (session.user?.role === 'SCHOOL_ADMIN') {
|
||||
schoolId = session.user.schoolId ?? undefined;
|
||||
} else {
|
||||
schoolId = schoolIdParam ?? session.user?.schoolId ?? undefined;
|
||||
// TEACHER, STUDENT, PARENT — always use the session schoolId to prevent
|
||||
// cross-school access which would lead to 403 on sub-resources
|
||||
schoolId = session.user?.schoolId ?? undefined;
|
||||
}
|
||||
|
||||
if (!schoolId) return NextResponse.json({ competitions: [], total: 0 });
|
||||
if (!schoolId) {
|
||||
// SUPER_ADMIN without a schoolId filter, or users without a schoolId
|
||||
if (session.user?.role === 'SUPER_ADMIN') {
|
||||
// Super admins can see all competitions
|
||||
const where: Record<string, unknown> = { deletedAt: null };
|
||||
if (statusParam) where.status = statusParam;
|
||||
if (competitionTypeParam) where.competitionType = competitionTypeParam;
|
||||
if (categoryParam) where.category = categoryParam;
|
||||
|
||||
const isPublicParam = searchParams.get('isPublic');
|
||||
if (isPublicParam === 'true') where.isPublic = true;
|
||||
|
||||
const [competitions, total] = await Promise.all([
|
||||
db.competition.findMany({
|
||||
where,
|
||||
orderBy: [{ startDate: 'desc' }, { createdAt: 'desc' }],
|
||||
skip: offset,
|
||||
take: limit,
|
||||
include: {
|
||||
school: { select: { id: true, name: true } },
|
||||
createdBy: { select: { id: true, firstName: true, lastName: true } },
|
||||
subject: { select: { id: true, name: true } },
|
||||
_count: { select: { participants: true, rewards: true } },
|
||||
},
|
||||
}),
|
||||
db.competition.count({ where }),
|
||||
]);
|
||||
|
||||
return NextResponse.json({ competitions, total });
|
||||
}
|
||||
|
||||
// Other users without a schoolId can still see public competitions
|
||||
const where: Record<string, unknown> = { isPublic: true, deletedAt: null };
|
||||
if (statusParam) where.status = statusParam;
|
||||
if (competitionTypeParam) where.competitionType = competitionTypeParam;
|
||||
if (categoryParam) where.category = categoryParam;
|
||||
|
||||
const [competitions, total] = await Promise.all([
|
||||
db.competition.findMany({
|
||||
where,
|
||||
orderBy: [{ startDate: 'desc' }, { createdAt: 'desc' }],
|
||||
skip: offset,
|
||||
take: limit,
|
||||
include: {
|
||||
school: { select: { id: true, name: true } },
|
||||
createdBy: { select: { id: true, firstName: true, lastName: true } },
|
||||
subject: { select: { id: true, name: true } },
|
||||
_count: { select: { participants: true, rewards: true } },
|
||||
},
|
||||
}),
|
||||
db.competition.count({ where }),
|
||||
]);
|
||||
|
||||
return NextResponse.json({ competitions, total });
|
||||
}
|
||||
|
||||
const where: Record<string, unknown> = { schoolId, deletedAt: null };
|
||||
if (statusParam) where.status = statusParam;
|
||||
|
||||
@@ -55,8 +55,9 @@ export async function GET() {
|
||||
select: {
|
||||
id: true,
|
||||
competencyId: true,
|
||||
level: true,
|
||||
comment: true,
|
||||
masteryLevelValue: true,
|
||||
note: true,
|
||||
date: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
@@ -83,12 +84,12 @@ export async function GET() {
|
||||
where: { generatedByUserId: userId },
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
period: true,
|
||||
status: true,
|
||||
createdAt: true,
|
||||
generatedAt: true,
|
||||
},
|
||||
take: 200,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
orderBy: { generatedAt: 'desc' },
|
||||
});
|
||||
|
||||
// Fetch audit log entries
|
||||
@@ -97,12 +98,12 @@ export async function GET() {
|
||||
select: {
|
||||
id: true,
|
||||
action: true,
|
||||
entity: true,
|
||||
entityType: true,
|
||||
entityId: true,
|
||||
createdAt: true,
|
||||
timestamp: true,
|
||||
},
|
||||
take: 200,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
orderBy: { timestamp: 'desc' },
|
||||
});
|
||||
|
||||
// Fetch data export requests
|
||||
@@ -121,7 +122,7 @@ export async function GET() {
|
||||
|
||||
// Fetch teacher notes
|
||||
const teacherNotes = await db.teacherNote.findMany({
|
||||
where: { userId },
|
||||
where: { teacherId: userId },
|
||||
select: {
|
||||
id: true,
|
||||
content: true,
|
||||
@@ -154,7 +155,7 @@ export async function GET() {
|
||||
type: true,
|
||||
title: true,
|
||||
message: true,
|
||||
read: true,
|
||||
isRead: true,
|
||||
createdAt: true,
|
||||
},
|
||||
take: 200,
|
||||
@@ -176,7 +177,7 @@ export async function GET() {
|
||||
|
||||
// Fetch homework
|
||||
const homeworks = await db.homework.findMany({
|
||||
where: { createdById: userId },
|
||||
where: { teacherId: userId },
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
@@ -191,13 +192,17 @@ export async function GET() {
|
||||
let studentData = null;
|
||||
if (user.role === 'STUDENT') {
|
||||
const student = await db.student.findFirst({
|
||||
where: { email: user.email, deletedAt: null },
|
||||
where: {
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
schoolId: user.schoolId ?? undefined,
|
||||
deletedAt: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
dateOfBirth: true,
|
||||
gender: true,
|
||||
enrollments: {
|
||||
select: {
|
||||
id: true,
|
||||
@@ -209,8 +214,8 @@ export async function GET() {
|
||||
learningProgressEntries: {
|
||||
select: {
|
||||
id: true,
|
||||
level: true,
|
||||
comment: true,
|
||||
masteryLevelValue: true,
|
||||
note: true,
|
||||
createdAt: true,
|
||||
},
|
||||
take: 200,
|
||||
@@ -220,11 +225,9 @@ export async function GET() {
|
||||
select: {
|
||||
id: true,
|
||||
score: true,
|
||||
comment: true,
|
||||
createdAt: true,
|
||||
note: true,
|
||||
},
|
||||
take: 200,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -235,7 +238,7 @@ export async function GET() {
|
||||
let parentLinks = null;
|
||||
if (user.role === 'PARENT') {
|
||||
parentLinks = await db.parentStudentLink.findMany({
|
||||
where: { userId },
|
||||
where: { parentId: userId },
|
||||
select: {
|
||||
id: true,
|
||||
relationship: true,
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
// GET /api/reward-points — Get points balance and history
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const userId = session.userId;
|
||||
const schoolId = session.user?.schoolId;
|
||||
if (!schoolId) {
|
||||
return NextResponse.json({ error: 'No school associated' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const limit = parseInt(searchParams.get('limit') || '50', 10);
|
||||
|
||||
// Fetch points entries
|
||||
const pointsEntries = await db.rewardPoints.findMany({
|
||||
where: { userId, schoolId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: limit,
|
||||
});
|
||||
|
||||
// Fetch redemptions (spent points)
|
||||
const redemptions = await db.rewardRedemption.findMany({
|
||||
where: { userId, status: { in: ['pending', 'approved', 'fulfilled'] } },
|
||||
include: { reward: { select: { title: true, category: true } } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: limit,
|
||||
});
|
||||
|
||||
// Calculate balance
|
||||
const totalEarned = pointsEntries.reduce((sum, e) => sum + e.points, 0);
|
||||
const totalSpent = redemptions.reduce((sum, r) => sum + r.pointsSpent, 0);
|
||||
const balance = totalEarned - totalSpent;
|
||||
|
||||
return NextResponse.json({
|
||||
balance,
|
||||
totalEarned,
|
||||
totalSpent,
|
||||
pointsHistory: pointsEntries,
|
||||
redemptions,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching reward points:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/reward-points — Award points to a user
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const role = session.user?.role;
|
||||
if (role !== 'SCHOOL_ADMIN' && role !== 'SUPER_ADMIN' && role !== 'TEACHER') {
|
||||
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
|
||||
}
|
||||
|
||||
const schoolId = session.user?.schoolId;
|
||||
if (!schoolId) {
|
||||
return NextResponse.json({ error: 'No school associated' }, { status: 400 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { userId, points, source, sourceId, description } = body;
|
||||
|
||||
if (!userId || !points || !source) {
|
||||
return NextResponse.json({ error: 'userId, points, and source are required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const validSources = ['competition', 'grade', 'attendance', 'homework', 'bonus'];
|
||||
if (!validSources.includes(source)) {
|
||||
return NextResponse.json({ error: 'Invalid source' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Verify the target user belongs to the same school
|
||||
const targetUser = await db.user.findFirst({
|
||||
where: { id: userId, schoolId, deletedAt: null },
|
||||
});
|
||||
if (!targetUser) {
|
||||
return NextResponse.json({ error: 'Target user not found in your school' }, { status: 404 });
|
||||
}
|
||||
|
||||
const pointsEntry = await db.rewardPoints.create({
|
||||
data: {
|
||||
userId,
|
||||
schoolId,
|
||||
points: parseInt(String(points), 10),
|
||||
source,
|
||||
sourceId: sourceId || null,
|
||||
description: description || null,
|
||||
},
|
||||
});
|
||||
|
||||
// Create audit log
|
||||
await db.auditLog.create({
|
||||
data: {
|
||||
userId: session.userId,
|
||||
schoolId,
|
||||
action: 'POINTS_AWARDED',
|
||||
entityType: 'RewardPoints',
|
||||
entityId: pointsEntry.id,
|
||||
changes: JSON.stringify({
|
||||
targetUserId: userId,
|
||||
points: pointsEntry.points,
|
||||
source,
|
||||
description: description || null,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(pointsEntry, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error('Error awarding points:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
// GET /api/rewards/[id] — Get a single reward
|
||||
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 reward = await db.reward.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
include: {
|
||||
_count: {
|
||||
select: { redemptions: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!reward) {
|
||||
return NextResponse.json({ error: 'Reward not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(reward);
|
||||
} catch (error) {
|
||||
console.error('Error fetching reward:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /api/rewards/[id] — Update a reward
|
||||
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 role = session.user?.role;
|
||||
if (role !== 'SCHOOL_ADMIN' && role !== 'SUPER_ADMIN' && role !== 'TEACHER') {
|
||||
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const existing = await db.reward.findFirst({ where: { id, deletedAt: null } });
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: 'Reward not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { title, description, category, pointsCost, image, stock, isActive } = body;
|
||||
|
||||
const reward = await db.reward.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(title !== undefined && { title }),
|
||||
...(description !== undefined && { description: description || null }),
|
||||
...(category !== undefined && { category }),
|
||||
...(pointsCost !== undefined && { pointsCost: parseInt(String(pointsCost), 10) }),
|
||||
...(image !== undefined && { image: image || null }),
|
||||
...(stock !== undefined && { stock: stock != null ? parseInt(String(stock), 10) : null }),
|
||||
...(isActive !== undefined && { isActive }),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(reward);
|
||||
} catch (error) {
|
||||
console.error('Error updating reward:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/rewards/[id] — Soft delete a reward
|
||||
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 role = session.user?.role;
|
||||
if (role !== 'SCHOOL_ADMIN' && role !== 'SUPER_ADMIN') {
|
||||
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const existing = await db.reward.findFirst({ where: { id, deletedAt: null } });
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: 'Reward not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
await db.reward.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date() },
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('Error deleting reward:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
// POST /api/rewards/redeem — Redeem a reward
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const userId = session.userId;
|
||||
const schoolId = session.user?.schoolId;
|
||||
if (!schoolId) {
|
||||
return NextResponse.json({ error: 'No school associated' }, { status: 400 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { rewardId } = body;
|
||||
|
||||
if (!rewardId) {
|
||||
return NextResponse.json({ error: 'rewardId is required' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Fetch the reward
|
||||
const reward = await db.reward.findFirst({
|
||||
where: { id: rewardId, deletedAt: null, isActive: true },
|
||||
});
|
||||
|
||||
if (!reward) {
|
||||
return NextResponse.json({ error: 'Reward not found or inactive' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Check stock
|
||||
if (reward.stock !== null && reward.stock <= 0) {
|
||||
return NextResponse.json({ error: 'Out of stock' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Calculate user's current points balance
|
||||
const pointsEntries = await db.rewardPoints.findMany({
|
||||
where: { userId, schoolId },
|
||||
select: { points: true },
|
||||
});
|
||||
const totalEarned = pointsEntries.reduce((sum, e) => sum + e.points, 0);
|
||||
|
||||
const redemptions = await db.rewardRedemption.findMany({
|
||||
where: { userId, status: { in: ['pending', 'approved', 'fulfilled'] } },
|
||||
select: { pointsSpent: true },
|
||||
});
|
||||
const totalSpent = redemptions.reduce((sum, r) => sum + r.pointsSpent, 0);
|
||||
const currentBalance = totalEarned - totalSpent;
|
||||
|
||||
// Check if user has enough points
|
||||
if (currentBalance < reward.pointsCost) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Insufficient points', currentBalance, pointsCost: reward.pointsCost },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Create redemption
|
||||
const redemption = await db.rewardRedemption.create({
|
||||
data: {
|
||||
rewardId,
|
||||
userId,
|
||||
pointsSpent: reward.pointsCost,
|
||||
status: 'pending',
|
||||
},
|
||||
});
|
||||
|
||||
// Decrement stock if applicable
|
||||
if (reward.stock !== null) {
|
||||
await db.reward.update({
|
||||
where: { id: rewardId },
|
||||
data: { stock: reward.stock - 1 },
|
||||
});
|
||||
}
|
||||
|
||||
// Create audit log
|
||||
await db.auditLog.create({
|
||||
data: {
|
||||
userId,
|
||||
schoolId,
|
||||
action: 'REWARD_REDEEMED',
|
||||
entityType: 'Reward',
|
||||
entityId: rewardId,
|
||||
changes: JSON.stringify({
|
||||
rewardTitle: reward.title,
|
||||
pointsSpent: reward.pointsCost,
|
||||
redemptionId: redemption.id,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
...redemption,
|
||||
newBalance: currentBalance - reward.pointsCost,
|
||||
}, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error('Error redeeming reward:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
// GET /api/rewards — List rewards for the user's school
|
||||
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 category = searchParams.get('category');
|
||||
const includeInactive = searchParams.get('includeInactive') === 'true';
|
||||
|
||||
const schoolId = session.user?.schoolId;
|
||||
if (!schoolId) {
|
||||
return NextResponse.json({ error: 'No school associated' }, { status: 400 });
|
||||
}
|
||||
|
||||
const where: Record<string, unknown> = {
|
||||
schoolId,
|
||||
deletedAt: null,
|
||||
};
|
||||
|
||||
if (!includeInactive) {
|
||||
where.isActive = true;
|
||||
}
|
||||
|
||||
if (category && category !== 'all') {
|
||||
where.category = category;
|
||||
}
|
||||
|
||||
const rewards = await db.reward.findMany({
|
||||
where,
|
||||
include: {
|
||||
_count: {
|
||||
select: { redemptions: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
return NextResponse.json(rewards);
|
||||
} catch (error) {
|
||||
console.error('Error fetching rewards:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/rewards — Create a new reward
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const role = session.user?.role;
|
||||
if (role !== 'SCHOOL_ADMIN' && role !== 'SUPER_ADMIN' && role !== 'TEACHER') {
|
||||
return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
|
||||
}
|
||||
|
||||
const schoolId = session.user?.schoolId;
|
||||
if (!schoolId) {
|
||||
return NextResponse.json({ error: 'No school associated' }, { status: 400 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { title, description, category, pointsCost, image, stock, isActive, isDemo } = body;
|
||||
|
||||
if (!title || !category || !pointsCost) {
|
||||
return NextResponse.json({ error: 'Title, category, and pointsCost are required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const validCategories = ['streaming', 'shopping', 'experience', 'merchandise', 'privilege'];
|
||||
if (!validCategories.includes(category)) {
|
||||
return NextResponse.json({ error: 'Invalid category' }, { status: 400 });
|
||||
}
|
||||
|
||||
const reward = await db.reward.create({
|
||||
data: {
|
||||
schoolId,
|
||||
title,
|
||||
description: description || null,
|
||||
category,
|
||||
pointsCost: parseInt(String(pointsCost), 10),
|
||||
image: image || null,
|
||||
stock: stock != null ? parseInt(String(stock), 10) : null,
|
||||
isActive: isActive !== false,
|
||||
isDemo: isDemo === true,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(reward, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error('Error creating reward:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user