From 1a175e805b2803988e1b59e6e9b86ba6733b7337 Mon Sep 17 00:00:00 2001 From: BOHA Date: Mon, 23 Mar 2026 10:49:42 +0100 Subject: [PATCH] fix: use vehicle initial_km as start_km for first trip record When no trips exist for a vehicle, the last-km endpoint now returns the vehicle's initial_km instead of 0, matching the PHP behavior: COALESCE(MAX(end_km), vehicle.initial_km, 0) Also fixed ordering from id DESC to end_km DESC for correctness. Co-Authored-By: Claude Opus 4.6 (1M context) --- src/routes/admin/trips.ts | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/routes/admin/trips.ts b/src/routes/admin/trips.ts index 3cc3075..a6c191a 100644 --- a/src/routes/admin/trips.ts +++ b/src/routes/admin/trips.ts @@ -108,15 +108,28 @@ export default async function tripsRoutes(fastify: FastifyInstance): Promise('/last-km/:vehicleId', { preHandler: requireAuth }, async (request, reply) => { const vehicleId = parseInt(request.params.vehicleId, 10); if (isNaN(vehicleId)) return error(reply, 'Neplatné ID vozidla', 400); - const lastTrip = await prisma.trips.findFirst({ - where: { vehicle_id: vehicleId }, - orderBy: { id: 'desc' }, - select: { end_km: true }, - }); - return success(reply, { last_km: lastTrip ? Number(lastTrip.end_km) : 0 }); + + const [lastTrip, vehicle] = await Promise.all([ + prisma.trips.findFirst({ + where: { vehicle_id: vehicleId }, + orderBy: { end_km: 'desc' }, + select: { end_km: true }, + }), + prisma.vehicles.findUnique({ + where: { id: vehicleId }, + select: { initial_km: true }, + }), + ]); + + const lastKm = lastTrip + ? Number(lastTrip.end_km) + : Number(vehicle?.initial_km ?? 0); + + return success(reply, { last_km: lastKm }); }); fastify.post('/', { preHandler: requireAuth }, async (request, reply) => {