import { useState, useEffect, useCallback } from "react"; import { useAlert } from "../context/AlertContext"; import { useAuth } from "../context/AuthContext"; import { motion } from "framer-motion"; import AdminDatePicker from "../components/AdminDatePicker"; import Forbidden from "../components/Forbidden"; import { formatDate } from "../utils/attendanceHelpers"; import { formatKm } from "../utils/formatters"; import FormField from "../components/FormField"; import apiFetch from "../utils/api"; const API_BASE = "/api/admin"; interface Vehicle { id: number | string; spz: string; name: string; } interface Trip { id: number; trip_date: string; spz: string; driver_name: string; route_from: string; route_to: string; start_km: number; end_km: number; distance: number; is_business: number | boolean; notes?: string; } export default function TripsHistory() { const alert = useAlert(); const { user, hasPermission } = useAuth(); const [loading, setLoading] = useState(true); const [month, setMonth] = useState(() => { const now = new Date(); return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`; }); const [vehicleId, setVehicleId] = useState(""); const [trips, setTrips] = useState([]); const [vehicles, setVehicles] = useState([]); const totals = trips.reduce( (acc, t) => ({ total: acc.total + (t.distance || 0), business: acc.business + (t.is_business ? t.distance || 0 : 0), count: acc.count + 1, }), { total: 0, business: 0, count: 0 }, ); const fetchData = useCallback(async () => { setLoading(true); try { const params = new URLSearchParams({ month }); if (user?.id) params.set("user_id", String(user.id)); if (vehicleId) params.set("vehicle_id", vehicleId); const [tripsRes, vehiclesRes] = await Promise.all([ apiFetch(`${API_BASE}/trips?${params}`), apiFetch(`${API_BASE}/vehicles`), ]); if (tripsRes.status === 401) return; const tripsResult = await tripsRes.json(); const vehiclesResult = await vehiclesRes.json(); if (tripsResult.success) { const raw = Array.isArray(tripsResult.data) ? tripsResult.data : tripsResult.data?.items || []; setTrips( raw.map((t: Record) => ({ ...t, spz: (t.vehicles as Record)?.spz || "", driver_name: t.users ? `${(t.users as Record).first_name || ""} ${(t.users as Record).last_name || ""}`.trim() : "", distance: ((t.end_km as number) || 0) - ((t.start_km as number) || 0), })), ); } if (vehiclesResult.success) { setVehicles( Array.isArray(vehiclesResult.data) ? vehiclesResult.data : [], ); } } catch { alert.error("Nepodařilo se načíst data"); } finally { setLoading(false); } }, [month, vehicleId, alert, user?.id]); useEffect(() => { fetchData(); }, [fetchData]); if (!hasPermission("trips.history")) return ; const getMonthName = (monthStr: string): string => { const [yearStr, monthNum] = monthStr.split("-"); const date = new Date(parseInt(yearStr), parseInt(monthNum) - 1); return date.toLocaleDateString("cs-CZ", { month: "long", year: "numeric" }); }; return (

Historie jízd

{getMonthName(month)}

{/* Filters */}
setMonth(val)} />
{totals.count} Počet jízd
{formatKm(totals.total)} km Celkem naježděno
{formatKm(totals.business)} km Služební km
{/* Trips Table */}
{loading && (
{[0, 1, 2, 3, 4].map((i) => (
))}
)} {!loading && trips.length === 0 && (

Žádné záznamy jízd pro vybrané období.

)} {!loading && trips.length > 0 && (
{trips.map((trip) => ( ))}
Datum Vozidlo Řidič Trasa Stav km Vzdálenost Typ Poznámka
{formatDate(trip.trip_date)} {trip.spz} {trip.driver_name} {trip.route_from} → {trip.route_to} {formatKm(trip.start_km)} - {formatKm(trip.end_km)} {formatKm(trip.distance)} km {trip.is_business ? "Služební" : "Soukromá"} {trip.notes || "—"}
)}
); }