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) <noreply@anthropic.com>
This commit is contained in:
BOHA
2026-03-23 10:49:42 +01:00
parent 7ef25a077b
commit 1a175e805b

View File

@@ -108,15 +108,28 @@ export default async function tripsRoutes(fastify: FastifyInstance): Promise<voi
});
// GET /api/admin/trips/last-km/:vehicleId
// Matches PHP: COALESCE(MAX(end_km), vehicle.initial_km, 0)
fastify.get<{ Params: { vehicleId: string } }>('/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) => {