CompetenceTrack v8 - Complete UI/UX redesign, Digital Notebooks, Drawing Canvas, Demo Data Cleanup
Features: - Complete UI/UX redesign for tablet/stylus optimization - Digital Notebook system (lined, grid, blank, dotted, music, calligraphy) - Drawing Canvas with stylus/pen support, pressure sensitivity - Art class mode with tutorial guides and shape templates - Demo data one-click cleanup for production transition - Subject-specific notebook filtering - Environmental messaging (Papier sparen, Umwelt schützen) - 44px minimum touch targets for tablet - No emojis - Lucide icons throughout - 700+ i18n keys (German/English) - Notebook types: lined, grid, blank, dotted, music, calligraphy - Drawing tools: pencil, pen, line, rectangle, circle, eraser - Undo/redo, color picker, stroke width, export PNG - Archive/unarchive notebooks - White backgrounds throughout - Emerald accent color theme Backend: - Notebook CRUD API routes - Drawing CRUD API routes - Demo data cleanup API - Prisma schema with Notebook, NotebookPage, Drawing models - isDemo flags on all new models
This commit is contained in:
1 parent
456cdf9714
commit
04034dca62
22 files changed
+4716
-53
No files matched your search
@@ -0,0 +1,165 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
// ── GET: Get demo data statistics ──
|
||||
export async function GET() {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
// Only SCHOOL_ADMIN or SUPER_ADMIN can view demo data stats
|
||||
if (!['SCHOOL_ADMIN', 'SUPER_ADMIN'].includes(session.user.role)) {
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
// Get demo user IDs for cascade counting
|
||||
const demoUsers = await db.user.findMany({
|
||||
where: { isDemo: true },
|
||||
select: { id: true },
|
||||
});
|
||||
const demoUserIds = demoUsers.map((u) => u.id);
|
||||
|
||||
const [
|
||||
demoUserCount,
|
||||
demoNotebookCount,
|
||||
demoDrawingCount,
|
||||
cascadeNotebookCount,
|
||||
cascadeDrawingCount,
|
||||
] = await Promise.all([
|
||||
db.user.count({ where: { isDemo: true } }),
|
||||
db.notebook.count({ where: { isDemo: true } }),
|
||||
db.drawing.count({ where: { isDemo: true } }),
|
||||
demoUserIds.length > 0
|
||||
? db.notebook.count({
|
||||
where: { ownerId: { in: demoUserIds }, isDemo: false },
|
||||
})
|
||||
: 0,
|
||||
demoUserIds.length > 0
|
||||
? db.drawing.count({
|
||||
where: { ownerId: { in: demoUserIds }, isDemo: false },
|
||||
})
|
||||
: 0,
|
||||
]);
|
||||
|
||||
return NextResponse.json({
|
||||
User: demoUserCount,
|
||||
Notebook: demoNotebookCount,
|
||||
Drawing: demoDrawingCount,
|
||||
_cascadeNotebooks: cascadeNotebookCount,
|
||||
_cascadeDrawings: cascadeDrawingCount,
|
||||
_total:
|
||||
demoUserCount +
|
||||
demoNotebookCount +
|
||||
demoDrawingCount +
|
||||
cascadeNotebookCount +
|
||||
cascadeDrawingCount,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Demo data stats error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── DELETE: Delete ALL demo data ──
|
||||
export async function DELETE() {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
// Only SCHOOL_ADMIN or SUPER_ADMIN can delete demo data
|
||||
if (!['SCHOOL_ADMIN', 'SUPER_ADMIN'].includes(session.user.role)) {
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
const summary: Record<string, number> = {};
|
||||
|
||||
// 1. Get all demo user IDs for cascade deletion
|
||||
const demoUsers = await db.user.findMany({
|
||||
where: { isDemo: true },
|
||||
select: { id: true },
|
||||
});
|
||||
const demoUserIds = demoUsers.map((u) => u.id);
|
||||
|
||||
// 2. Delete NotebookPages for notebooks owned by demo users
|
||||
// (NotebookPage has cascade delete on Notebook, but we need to handle
|
||||
// notebooks where isDemo=true OR ownerId is a demo user)
|
||||
const demoNotebookIds = await db.notebook.findMany({
|
||||
where: {
|
||||
OR: [{ isDemo: true }, { ownerId: { in: demoUserIds } }],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
const demoNotebookIdList = demoNotebookIds.map((n) => n.id);
|
||||
|
||||
let deletedPages = 0;
|
||||
if (demoNotebookIdList.length > 0) {
|
||||
deletedPages = (await db.notebookPage.deleteMany({
|
||||
where: { notebookId: { in: demoNotebookIdList } },
|
||||
})) as unknown as number;
|
||||
summary.NotebookPage = typeof deletedPages === 'number' ? deletedPages : (deletedPages as { count: number }).count ?? 0;
|
||||
} else {
|
||||
summary.NotebookPage = 0;
|
||||
}
|
||||
|
||||
// 3. Delete notebooks where isDemo=true OR ownerId is a demo user
|
||||
const deletedNotebooks = await db.notebook.deleteMany({
|
||||
where: {
|
||||
OR: [{ isDemo: true }, { ownerId: { in: demoUserIds } }],
|
||||
},
|
||||
});
|
||||
summary.Notebook =
|
||||
typeof deletedNotebooks === 'number'
|
||||
? deletedNotebooks
|
||||
: (deletedNotebooks as { count: number }).count ?? 0;
|
||||
|
||||
// 4. Delete drawings where isDemo=true OR ownerId is a demo user
|
||||
const deletedDrawings = await db.drawing.deleteMany({
|
||||
where: {
|
||||
OR: [{ isDemo: true }, { ownerId: { in: demoUserIds } }],
|
||||
},
|
||||
});
|
||||
summary.Drawing =
|
||||
typeof deletedDrawings === 'number'
|
||||
? deletedDrawings
|
||||
: (deletedDrawings as { count: number }).count ?? 0;
|
||||
|
||||
// 5. Delete demo users (soft-deleted users that are demo)
|
||||
const deletedUsers = await db.user.deleteMany({
|
||||
where: { isDemo: true },
|
||||
});
|
||||
summary.User =
|
||||
typeof deletedUsers === 'number'
|
||||
? deletedUsers
|
||||
: (deletedUsers as { count: number }).count ?? 0;
|
||||
|
||||
// 6. Log the cleanup in AuditLog
|
||||
await db.auditLog.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
schoolId: session.user.schoolId,
|
||||
action: 'DEMO_DATA_CLEANUP',
|
||||
entityType: 'System',
|
||||
metadata: JSON.stringify(summary),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Demo data cleanup completed',
|
||||
deleted: summary,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Demo data cleanup error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
const updateDrawingSchema = z.object({
|
||||
title: z.string().min(1).optional(),
|
||||
description: z.string().nullable().optional(),
|
||||
drawingData: z.string().optional(),
|
||||
imageData: z.string().nullable().optional(),
|
||||
subjectId: z.string().nullable().optional(),
|
||||
classGroupId: z.string().nullable().optional(),
|
||||
isPublic: z.boolean().optional(),
|
||||
});
|
||||
|
||||
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 drawing = await db.drawing.findUnique({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
if (!drawing) {
|
||||
return NextResponse.json({ error: 'Drawing not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Only owner or public drawings
|
||||
if (drawing.ownerId !== session.userId && !drawing.isPublic) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
|
||||
return NextResponse.json(drawing);
|
||||
} catch (error) {
|
||||
console.error('Drawing GET by 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;
|
||||
|
||||
// Check ownership
|
||||
const existing = await db.drawing.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: 'Drawing not found' }, { status: 404 });
|
||||
}
|
||||
if (existing.ownerId !== session.userId) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const parsed = updateDrawingSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Validation failed', details: parsed.error.issues },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const drawing = await db.drawing.update({
|
||||
where: { id },
|
||||
data: parsed.data,
|
||||
});
|
||||
|
||||
return NextResponse.json(drawing);
|
||||
} catch (error) {
|
||||
console.error('Drawing 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 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
// Check ownership
|
||||
const existing = await db.drawing.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: 'Drawing not found' }, { status: 404 });
|
||||
}
|
||||
if (existing.ownerId !== session.userId && session.user?.role !== 'SUPER_ADMIN' && session.user?.role !== 'SCHOOL_ADMIN') {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
|
||||
await db.drawing.delete({ where: { id } });
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('Drawing DELETE error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
const createDrawingSchema = z.object({
|
||||
title: z.string().min(1).default('Untitled Drawing'),
|
||||
description: z.string().optional(),
|
||||
drawingData: z.string().min(1),
|
||||
imageData: z.string().optional(),
|
||||
schoolId: z.string().optional(),
|
||||
subjectId: z.string().optional(),
|
||||
classGroupId: z.string().optional(),
|
||||
isPublic: z.boolean().default(false),
|
||||
});
|
||||
|
||||
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 ?? undefined;
|
||||
const subjectId = searchParams.get('subjectId');
|
||||
|
||||
const where: Record<string, unknown> = {};
|
||||
if (schoolId) {
|
||||
where.schoolId = schoolId;
|
||||
}
|
||||
if (subjectId) {
|
||||
where.subjectId = subjectId;
|
||||
}
|
||||
|
||||
// Show own drawings + public drawings from the same school
|
||||
const drawings = await db.drawing.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ ownerId: session.userId },
|
||||
{ isPublic: true, ...(schoolId ? { schoolId } : {}) },
|
||||
],
|
||||
...(subjectId ? { subjectId } : {}),
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
});
|
||||
|
||||
return NextResponse.json(drawings);
|
||||
} catch (error) {
|
||||
console.error('Drawings 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 parsed = createDrawingSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Validation failed', details: parsed.error.issues },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const drawing = await db.drawing.create({
|
||||
data: {
|
||||
schoolId: parsed.data.schoolId ?? session.user?.schoolId ?? 'default',
|
||||
ownerId: session.userId,
|
||||
title: parsed.data.title,
|
||||
description: parsed.data.description ?? null,
|
||||
drawingData: parsed.data.drawingData,
|
||||
imageData: parsed.data.imageData ?? null,
|
||||
subjectId: parsed.data.subjectId ?? null,
|
||||
classGroupId: parsed.data.classGroupId ?? null,
|
||||
isPublic: parsed.data.isPublic,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(drawing, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error('Drawings POST error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
// ── PUT: Update a page ──
|
||||
const updatePageSchema = z.object({
|
||||
textContent: z.string().optional().nullable(),
|
||||
drawingData: z.string().optional().nullable(),
|
||||
background: z
|
||||
.enum(['lined', 'grid', 'blank', 'dotted', 'music'])
|
||||
.optional(),
|
||||
isBookmark: z.boolean().optional(),
|
||||
title: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
export async function PUT(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string; pageId: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { id, pageId } = await params;
|
||||
|
||||
const page = await db.notebookPage.findUnique({
|
||||
where: { id: pageId },
|
||||
include: { notebook: true },
|
||||
});
|
||||
|
||||
if (!page || page.notebookId !== id) {
|
||||
return NextResponse.json({ error: 'Page not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (page.notebook.deletedAt) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Notebook has been deleted' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (page.notebook.ownerId !== session.user.id) {
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const parsed = updatePageSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Validation failed', details: parsed.error.issues },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const updatedPage = await db.notebookPage.update({
|
||||
where: { id: pageId },
|
||||
data: parsed.data,
|
||||
});
|
||||
|
||||
// Audit log
|
||||
await db.auditLog.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
schoolId: page.notebook.schoolId,
|
||||
action: 'UPDATE',
|
||||
entityType: 'NotebookPage',
|
||||
entityId: pageId,
|
||||
metadata: JSON.stringify({
|
||||
notebookId: id,
|
||||
pageNumber: page.pageNumber,
|
||||
updatedFields: Object.keys(parsed.data),
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(updatedPage);
|
||||
} catch (error) {
|
||||
console.error('Notebook page update error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── DELETE: Delete a page ──
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string; pageId: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { id, pageId } = await params;
|
||||
|
||||
const page = await db.notebookPage.findUnique({
|
||||
where: { id: pageId },
|
||||
include: { notebook: true },
|
||||
});
|
||||
|
||||
if (!page || page.notebookId !== id) {
|
||||
return NextResponse.json({ error: 'Page not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (page.notebook.ownerId !== session.user.id) {
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
await db.notebookPage.delete({
|
||||
where: { id: pageId },
|
||||
});
|
||||
|
||||
// Audit log
|
||||
await db.auditLog.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
schoolId: page.notebook.schoolId,
|
||||
action: 'DELETE',
|
||||
entityType: 'NotebookPage',
|
||||
entityId: pageId,
|
||||
metadata: JSON.stringify({
|
||||
notebookId: id,
|
||||
pageNumber: page.pageNumber,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Page deleted',
|
||||
id: pageId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Notebook page delete error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
// ── GET: List pages in a notebook ──
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const notebook = await db.notebook.findUnique({
|
||||
where: { id, deletedAt: null },
|
||||
});
|
||||
|
||||
if (!notebook) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Notebook not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Access check
|
||||
if (
|
||||
notebook.ownerId !== session.user.id &&
|
||||
!(notebook.isPublic && notebook.schoolId === session.user.schoolId)
|
||||
) {
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
const pages = await db.notebookPage.findMany({
|
||||
where: { notebookId: id },
|
||||
orderBy: { pageNumber: 'asc' },
|
||||
});
|
||||
|
||||
return NextResponse.json(pages);
|
||||
} catch (error) {
|
||||
console.error('Notebook pages list error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── POST: Add a new page to a notebook ──
|
||||
const createPageSchema = z.object({
|
||||
pageNumber: z.number().int().optional(),
|
||||
contentType: z.enum(['text', 'drawing', 'mixed']).default('text'),
|
||||
textContent: z.string().optional().nullable(),
|
||||
drawingData: z.string().optional().nullable(),
|
||||
background: z
|
||||
.enum(['lined', 'grid', 'blank', 'dotted', 'music'])
|
||||
.default('lined'),
|
||||
title: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
export async function POST(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const notebook = await db.notebook.findUnique({
|
||||
where: { id, deletedAt: null },
|
||||
});
|
||||
|
||||
if (!notebook) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Notebook not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
if (notebook.ownerId !== session.user.id) {
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const parsed = createPageSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Validation failed', details: parsed.error.issues },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Auto-increment pageNumber if not provided
|
||||
let pageNumber = parsed.data.pageNumber;
|
||||
if (!pageNumber) {
|
||||
const maxPage = await db.notebookPage.findFirst({
|
||||
where: { notebookId: id },
|
||||
orderBy: { pageNumber: 'desc' },
|
||||
select: { pageNumber: true },
|
||||
});
|
||||
pageNumber = maxPage ? maxPage.pageNumber + 1 : 1;
|
||||
}
|
||||
|
||||
// Use notebook's notebookType as default background if not specified differently
|
||||
const background =
|
||||
parsed.data.background ||
|
||||
(['lined', 'grid', 'blank', 'dotted', 'music'].includes(
|
||||
notebook.notebookType
|
||||
)
|
||||
? notebook.notebookType
|
||||
: 'lined');
|
||||
|
||||
const page = await db.notebookPage.create({
|
||||
data: {
|
||||
notebookId: id,
|
||||
pageNumber,
|
||||
title: parsed.data.title,
|
||||
contentType: parsed.data.contentType,
|
||||
textContent: parsed.data.textContent,
|
||||
drawingData: parsed.data.drawingData,
|
||||
background,
|
||||
},
|
||||
});
|
||||
|
||||
// Audit log
|
||||
await db.auditLog.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
schoolId: notebook.schoolId,
|
||||
action: 'CREATE',
|
||||
entityType: 'NotebookPage',
|
||||
entityId: page.id,
|
||||
metadata: JSON.stringify({
|
||||
notebookId: id,
|
||||
pageNumber,
|
||||
contentType: parsed.data.contentType,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(page, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error('Notebook page create error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
// ── GET: Get a single notebook with its pages ──
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const notebook = await db.notebook.findUnique({
|
||||
where: { id, deletedAt: null },
|
||||
include: {
|
||||
subject: { select: { id: true, name: true } },
|
||||
classGroup: { select: { id: true, name: true } },
|
||||
pages: {
|
||||
orderBy: { pageNumber: 'asc' },
|
||||
},
|
||||
owner: { select: { id: true, firstName: true, lastName: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!notebook) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Notebook not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Access check: owner or public notebook in the same school
|
||||
if (
|
||||
notebook.ownerId !== session.user.id &&
|
||||
!(notebook.isPublic && notebook.schoolId === session.user.schoolId)
|
||||
) {
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
return NextResponse.json(notebook);
|
||||
} catch (error) {
|
||||
console.error('Notebook get error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── PUT: Update notebook ──
|
||||
const updateNotebookSchema = z.object({
|
||||
title: z.string().min(1).max(200).optional(),
|
||||
description: z.string().max(1000).optional().nullable(),
|
||||
notebookType: z
|
||||
.enum(['lined', 'grid', 'blank', 'dotted', 'music', 'calligraphy'])
|
||||
.optional(),
|
||||
color: z.string().optional(),
|
||||
icon: z.string().optional().nullable(),
|
||||
isArchived: z.boolean().optional(),
|
||||
isPublic: z.boolean().optional(),
|
||||
sortOrder: z.number().int().optional(),
|
||||
});
|
||||
|
||||
export async function PUT(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const existing = await db.notebook.findUnique({
|
||||
where: { id, deletedAt: null },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Notebook not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
if (existing.ownerId !== session.user.id) {
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const parsed = updateNotebookSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Validation failed', details: parsed.error.issues },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const notebook = await db.notebook.update({
|
||||
where: { id },
|
||||
data: parsed.data,
|
||||
include: {
|
||||
subject: { select: { id: true, name: true } },
|
||||
classGroup: { select: { id: true, name: true } },
|
||||
_count: { select: { pages: true } },
|
||||
},
|
||||
});
|
||||
|
||||
// Audit log
|
||||
await db.auditLog.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
schoolId: existing.schoolId,
|
||||
action: 'UPDATE',
|
||||
entityType: 'Notebook',
|
||||
entityId: id,
|
||||
metadata: JSON.stringify({ updatedFields: Object.keys(parsed.data) }),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(notebook);
|
||||
} catch (error) {
|
||||
console.error('Notebook update error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── DELETE: Soft delete notebook ──
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const existing = await db.notebook.findUnique({
|
||||
where: { id, deletedAt: null },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Notebook not found' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
if (existing.ownerId !== session.user.id) {
|
||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
const deleted = await db.notebook.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date() },
|
||||
});
|
||||
|
||||
// Audit log
|
||||
await db.auditLog.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
schoolId: existing.schoolId,
|
||||
action: 'DELETE',
|
||||
entityType: 'Notebook',
|
||||
entityId: id,
|
||||
metadata: JSON.stringify({ title: existing.title }),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Notebook deleted',
|
||||
id: deleted.id,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Notebook delete error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
import { db } from '@/lib/db';
|
||||
import { getSession } from '@/lib/auth';
|
||||
|
||||
// ── GET: List notebooks for the current user ──
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const schoolId = searchParams.get('schoolId');
|
||||
const subjectId = searchParams.get('subjectId');
|
||||
const classGroupId = searchParams.get('classGroupId');
|
||||
const isArchived = searchParams.get('isArchived');
|
||||
|
||||
const where: Record<string, unknown> = {
|
||||
ownerId: session.user.id,
|
||||
deletedAt: null,
|
||||
};
|
||||
|
||||
if (schoolId) where.schoolId = schoolId;
|
||||
if (subjectId) where.subjectId = subjectId;
|
||||
if (classGroupId) where.classGroupId = classGroupId;
|
||||
if (isArchived !== null && isArchived !== undefined) {
|
||||
where.isArchived = isArchived === 'true';
|
||||
}
|
||||
|
||||
// Default schoolId from user session
|
||||
if (!schoolId && session.user.schoolId) {
|
||||
where.schoolId = session.user.schoolId;
|
||||
}
|
||||
|
||||
const notebooks = await db.notebook.findMany({
|
||||
where,
|
||||
include: {
|
||||
subject: { select: { id: true, name: true } },
|
||||
classGroup: { select: { id: true, name: true } },
|
||||
_count: { select: { pages: true } },
|
||||
},
|
||||
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
|
||||
});
|
||||
|
||||
return NextResponse.json(notebooks);
|
||||
} catch (error) {
|
||||
console.error('Notebooks list error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── POST: Create a new notebook ──
|
||||
const createNotebookSchema = z.object({
|
||||
title: z.string().min(1).max(200),
|
||||
description: z.string().max(1000).optional().nullable(),
|
||||
notebookType: z
|
||||
.enum(['lined', 'grid', 'blank', 'dotted', 'music', 'calligraphy'])
|
||||
.default('lined'),
|
||||
color: z.string().default('#10b981'),
|
||||
icon: z.string().optional().nullable(),
|
||||
subjectId: z.string().optional().nullable(),
|
||||
classGroupId: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session?.user) {
|
||||
return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const parsed = createNotebookSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Validation failed', details: parsed.error.issues },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { title, description, notebookType, color, icon, subjectId, classGroupId } =
|
||||
parsed.data;
|
||||
|
||||
const schoolId = session.user.schoolId;
|
||||
if (!schoolId) {
|
||||
return NextResponse.json(
|
||||
{ error: 'User must belong to a school to create notebooks' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const notebook = await db.notebook.create({
|
||||
data: {
|
||||
schoolId,
|
||||
ownerId: session.user.id,
|
||||
ownerType: 'TEACHER',
|
||||
title,
|
||||
description,
|
||||
notebookType,
|
||||
color,
|
||||
icon,
|
||||
subjectId,
|
||||
classGroupId,
|
||||
},
|
||||
include: {
|
||||
subject: { select: { id: true, name: true } },
|
||||
classGroup: { select: { id: true, name: true } },
|
||||
_count: { select: { pages: true } },
|
||||
},
|
||||
});
|
||||
|
||||
// Audit log
|
||||
await db.auditLog.create({
|
||||
data: {
|
||||
userId: session.user.id,
|
||||
schoolId,
|
||||
action: 'CREATE',
|
||||
entityType: 'Notebook',
|
||||
entityId: notebook.id,
|
||||
metadata: JSON.stringify({ title }),
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(notebook, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error('Notebook create error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Internal server error' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user