|
| 1 | +import { prisma } from '@utils/prisma'; |
| 2 | +import { NextResponse } from 'next/server'; |
| 3 | + |
| 4 | +export async function PUT(req: Request) { |
| 5 | + try { |
| 6 | + const body = await req.json(); |
| 7 | + const { id, lessonPlanFile, ...fields } = body; |
| 8 | + |
| 9 | + if (!id) { |
| 10 | + return NextResponse.json( |
| 11 | + { error: 'Missing absence ID' }, |
| 12 | + { status: 400 } |
| 13 | + ); |
| 14 | + } |
| 15 | + |
| 16 | + const updatedAbsence = await prisma.$transaction(async (tx) => { |
| 17 | + const existing = await tx.absence.findUnique({ |
| 18 | + where: { id }, |
| 19 | + include: { lessonPlan: true }, |
| 20 | + }); |
| 21 | + |
| 22 | + if (!existing) { |
| 23 | + throw new Error(`Absence with ID ${id} not found.`); |
| 24 | + } |
| 25 | + |
| 26 | + const dataToUpdate: any = {}; |
| 27 | + |
| 28 | + if ('lessonDate' in fields) |
| 29 | + dataToUpdate.lessonDate = new Date(fields.lessonDate); |
| 30 | + if ('reasonOfAbsence' in fields) |
| 31 | + dataToUpdate.reasonOfAbsence = fields.reasonOfAbsence; |
| 32 | + if ('notes' in fields) dataToUpdate.notes = fields.notes || null; |
| 33 | + if ('absentTeacherId' in fields) |
| 34 | + dataToUpdate.absentTeacherId = fields.absentTeacherId; |
| 35 | + if ('substituteTeacherId' in fields) |
| 36 | + dataToUpdate.substituteTeacherId = fields.substituteTeacherId || null; |
| 37 | + if ('locationId' in fields) dataToUpdate.locationId = fields.locationId; |
| 38 | + if ('subjectId' in fields) dataToUpdate.subjectId = fields.subjectId; |
| 39 | + if ('roomNumber' in fields) |
| 40 | + dataToUpdate.roomNumber = fields.roomNumber || null; |
| 41 | + |
| 42 | + if (lessonPlanFile) { |
| 43 | + if (existing.lessonPlanId) { |
| 44 | + await tx.absence.update({ |
| 45 | + where: { id }, |
| 46 | + data: { lessonPlanId: null }, |
| 47 | + }); |
| 48 | + await tx.lessonPlanFile.delete({ |
| 49 | + where: { id: existing.lessonPlanId }, |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | + const newLessonPlan = await tx.lessonPlanFile.create({ |
| 54 | + data: { |
| 55 | + name: lessonPlanFile.name, |
| 56 | + url: lessonPlanFile.url, |
| 57 | + size: lessonPlanFile.size, |
| 58 | + }, |
| 59 | + }); |
| 60 | + |
| 61 | + dataToUpdate.lessonPlanId = newLessonPlan.id; |
| 62 | + } |
| 63 | + |
| 64 | + const updated = await tx.absence.update({ |
| 65 | + where: { id }, |
| 66 | + data: dataToUpdate, |
| 67 | + }); |
| 68 | + |
| 69 | + return updated; |
| 70 | + }); |
| 71 | + |
| 72 | + return NextResponse.json(updatedAbsence, { status: 200 }); |
| 73 | + } catch (err) { |
| 74 | + console.error('Error in PUT /api/editAbsence:', err.message || err); |
| 75 | + return NextResponse.json( |
| 76 | + { error: 'Internal Server Error', details: err.message }, |
| 77 | + { status: 500 } |
| 78 | + ); |
| 79 | + } |
| 80 | +} |
0 commit comments