Files
WearPartTracker/app/api/bikes/[id]/parts/route.ts

88 lines
2.2 KiB
TypeScript
Raw Normal View History

import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { wearPartSchema } from '@/lib/validations'
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const parts = await prisma.wearPart.findMany({
where: { bikeId: params.id },
include: {
maintenanceHistory: {
orderBy: {
date: 'desc',
},
},
},
orderBy: {
createdAt: 'desc',
},
})
return NextResponse.json(parts)
} catch (error) {
console.error('Error fetching parts:', error)
return NextResponse.json(
{ error: 'Fehler beim Laden der Verschleißteile' },
{ status: 500 }
)
}
}
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const body = await request.json()
const validatedData = wearPartSchema.parse({
...body,
bikeId: params.id,
})
const part = await prisma.wearPart.create({
data: {
bikeId: params.id,
type: validatedData.type,
brand: validatedData.brand,
model: validatedData.model,
installDate: new Date(validatedData.installDate),
installMileage: validatedData.installMileage,
serviceInterval: validatedData.serviceInterval,
status: validatedData.status,
cost: validatedData.cost,
notes: validatedData.notes,
},
})
// Erstelle automatisch einen MaintenanceHistory-Eintrag für die Installation
await prisma.maintenanceHistory.create({
data: {
wearPartId: part.id,
date: new Date(validatedData.installDate),
mileage: validatedData.installMileage,
action: 'INSTALL',
notes: validatedData.notes,
cost: validatedData.cost,
},
})
return NextResponse.json(part, { status: 201 })
} catch (error) {
console.error('Error creating part:', error)
if (error instanceof Error && error.name === 'ZodError') {
return NextResponse.json(
{ error: 'Ungültige Daten', details: error },
{ status: 400 }
)
}
return NextResponse.json(
{ error: 'Fehler beim Erstellen des Verschleißteils' },
{ status: 500 }
)
}
}