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:
@@ -108,15 +108,28 @@ export default async function tripsRoutes(fastify: FastifyInstance): Promise<voi
|
|||||||
});
|
});
|
||||||
|
|
||||||
// GET /api/admin/trips/last-km/:vehicleId
|
// 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) => {
|
fastify.get<{ Params: { vehicleId: string } }>('/last-km/:vehicleId', { preHandler: requireAuth }, async (request, reply) => {
|
||||||
const vehicleId = parseInt(request.params.vehicleId, 10);
|
const vehicleId = parseInt(request.params.vehicleId, 10);
|
||||||
if (isNaN(vehicleId)) return error(reply, 'Neplatné ID vozidla', 400);
|
if (isNaN(vehicleId)) return error(reply, 'Neplatné ID vozidla', 400);
|
||||||
const lastTrip = await prisma.trips.findFirst({
|
|
||||||
where: { vehicle_id: vehicleId },
|
const [lastTrip, vehicle] = await Promise.all([
|
||||||
orderBy: { id: 'desc' },
|
prisma.trips.findFirst({
|
||||||
select: { end_km: true },
|
where: { vehicle_id: vehicleId },
|
||||||
});
|
orderBy: { end_km: 'desc' },
|
||||||
return success(reply, { last_km: lastTrip ? Number(lastTrip.end_km) : 0 });
|
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) => {
|
fastify.post('/', { preHandler: requireAuth }, async (request, reply) => {
|
||||||
|
|||||||
Reference in New Issue
Block a user