Files
app/src/admin/pages/TripsHistory.tsx
BOHA 1826fc7976 fix: audit fix pass #1 — all 19 verified HIGH findings + critical dep cleanup
Fixes every CRITICAL/HIGH finding from the 2026-06-09 full-codebase audit
(REVIEW_FINDINGS.md); each fix went through independent spec + code-quality
review. Plan and per-task log: docs/superpowers/plans/2026-06-10-audit-high-fix-pass.md

- attendance: schemas accept the combined local datetimes the forms/service
  use (new dateTimeString helpers in schemas/common.ts), breaks persist on
  create, AttendanceCreate submit rebuilt — every submit 400'd since 519edce
- 2fa: backup codes wired to /totp/backup-verify (+ remember-me parity),
  enrollment QR generated locally via qrcode (CSP-blocked external service
  also leaked the secret), dashboard shows per-user enrollment, not policy
- invoices/orders: per-line VAT survives re-saves (numberOr 0-respecting
  coercion in formatters.ts), billing_text persists on update, issued-order
  status transitions update UI gates
- trips: real pagination on all 3 pages, GET /trips/stats server aggregate
  (shared buildTripsWhere + legacy distance coalesce), vehicle_id applies on
  PUT with both-vehicle odometer recompute, print rebuilt (sync window.open,
  escaped template, server totals)
- orders api: attachment_data PDF blob excluded from all non-binary reads
- warehouse: unit field is a Select over UnitEnum, receipt attachments
  downloadable via new authenticated GET route
- downloads: shared RFC 5987 contentDisposition helper — Czech filenames no
  longer 500 (warehouse, received-invoices, orders endpoints)
- misc: block-env hook actually blocks (exit 2 + stderr), project create
  works with empty dates, NaN filter guards on trips endpoints
- deps: remove unused concurrently (clears both critical advisories), pin
  @hono/node-server >=1.19.13 via overrides (clears the 3 moderates without
  the Prisma 6 downgrade), drop deprecated @types stubs

Gates: tsc -b clean - vitest 30 files / 342 tests (31 new) - eslint 0 errors
- build OK

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 09:59:47 +02:00

328 lines
7.7 KiB
TypeScript

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import Box from "@mui/material/Box";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import { formatDate } from "../utils/attendanceHelpers";
import { formatKm } from "../utils/formatters";
import {
tripHistoryOptions,
tripStatsOptions,
tripVehiclesOptions,
type BackendTrip,
} from "../lib/queries/trips";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import {
Card,
DataTable,
Select,
MonthField,
Pagination,
StatusChip,
PageHeader,
PageEnter,
FilterBar,
EmptyState,
LoadingState,
StatCard,
type DataColumn,
} from "../ui";
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;
}
const TripsIcon = (
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<line x1="12" y1="20" x2="12" y2="10" />
<line x1="18" y1="20" x2="18" y2="4" />
<line x1="6" y1="20" x2="6" y2="16" />
</svg>
);
const TotalIcon = (
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M22 12h-4l-3 9L9 3l-3 9H2" />
</svg>
);
const BusinessIcon = (
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<rect x="1" y="3" width="15" height="13" rx="2" ry="2" />
<path d="M16 8h2a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-1" />
<circle cx="5.5" cy="18" r="2" />
<circle cx="18.5" cy="18" r="2" />
<path d="M8 18h8" />
</svg>
);
export default function TripsHistory() {
const { user, hasPermission } = useAuth();
const [month, setMonth] = useState(() => {
const now = new Date();
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
});
const [vehicleId, setVehicleId] = useState("");
const [page, setPage] = useState(1);
const { data: vehiclesData = [] } = useQuery(tripVehiclesOptions());
const vehicles = vehiclesData;
const {
items: tripsData,
pagination,
isPending,
} = usePaginatedQuery<BackendTrip>(
tripHistoryOptions({
month,
vehicleId: vehicleId ? Number(vehicleId) : undefined,
userId: user?.id,
page,
}),
);
// Stat cards: month totals over the WHOLE filtered set (server-side
// aggregate over the same filters), not just the visible page.
const { data: stats } = useQuery(
tripStatsOptions({
month,
vehicleId: vehicleId ? Number(vehicleId) : undefined,
userId: user?.id,
}),
);
const trips: Trip[] = tripsData.map((t) => ({
id: t.id,
trip_date: t.trip_date,
spz: t.vehicles?.spz ?? "",
driver_name: t.users
? `${t.users.first_name} ${t.users.last_name}`.trim()
: "",
route_from: t.route_from,
route_to: t.route_to,
start_km: t.start_km,
end_km: t.end_km,
distance: t.distance ?? t.end_km - t.start_km,
is_business: t.is_business,
notes: t.notes ?? undefined,
}));
const totals = {
count: stats?.count ?? 0,
total: stats?.total_km ?? 0,
business: stats?.business_km ?? 0,
};
if (!hasPermission("trips.history")) return <Forbidden />;
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" });
};
const columns: DataColumn<Trip>[] = [
{
key: "trip_date",
header: "Datum",
width: "11%",
mono: true,
render: (trip) => formatDate(trip.trip_date),
},
{
key: "vehicle",
header: "Vozidlo",
width: "10%",
render: (trip) => <StatusChip label={trip.spz} color="default" />,
},
{
key: "driver",
header: "Řidič",
width: "14%",
render: (trip) => (
<Box component="span" sx={{ color: "text.secondary" }}>
{trip.driver_name}
</Box>
),
},
{
key: "route",
header: "Trasa",
width: "18%",
render: (trip) => (
<Box component="span" sx={{ whiteSpace: "nowrap" }}>
{trip.route_from} &rarr; {trip.route_to}
</Box>
),
},
{
key: "km",
header: "Stav km",
width: "13%",
mono: true,
render: (trip) => (
<Box
component="span"
sx={{ whiteSpace: "nowrap", color: "text.secondary" }}
>
{formatKm(trip.start_km)} - {formatKm(trip.end_km)}
</Box>
),
},
{
key: "distance",
header: "Vzdálenost",
width: "10%",
mono: true,
bold: true,
render: (trip) => `${formatKm(trip.distance)} km`,
},
{
key: "type",
header: "Typ",
width: "10%",
render: (trip) => (
<StatusChip
label={trip.is_business ? "Služební" : "Soukromá"}
color={trip.is_business ? "success" : "warning"}
/>
),
},
{
key: "notes",
header: "Poznámka",
width: "14%",
render: (trip) => (
<Box component="span" sx={{ color: "text.secondary" }}>
{trip.notes || "—"}
</Box>
),
},
];
return (
<PageEnter>
<PageHeader title="Historie jízd" subtitle={getMonthName(month)} />
{/* Filters */}
<FilterBar>
<Box sx={{ flex: "0 0 180px" }}>
<MonthField
value={month}
onChange={(val) => {
setMonth(val);
setPage(1);
}}
/>
</Box>
<Box sx={{ flex: "0 0 220px" }}>
<Select
value={vehicleId}
onChange={(value) => {
setVehicleId(value);
setPage(1);
}}
options={[
{ value: "", label: "Všechna vozidla" },
...vehicles.map((v) => ({
value: String(v.id),
label: `${v.spz} - ${v.name}`,
})),
]}
/>
</Box>
</FilterBar>
<Box
sx={{
display: "grid",
gridTemplateColumns: {
xs: "1fr",
sm: "1fr 1fr",
lg: "repeat(3, 1fr)",
},
gap: 2,
mt: 3,
}}
>
<StatCard
label="Počet jízd"
value={totals.count}
icon={TripsIcon}
color="info"
/>
<StatCard
label="Celkem naježděno"
value={`${formatKm(totals.total)} km`}
icon={TotalIcon}
color="default"
/>
<StatCard
label="Služební km"
value={`${formatKm(totals.business)} km`}
icon={BusinessIcon}
color="success"
/>
</Box>
{/* Trips Table */}
<Card sx={{ mt: 3 }}>
{isPending ? (
<LoadingState />
) : (
<>
<DataTable<Trip>
columns={columns}
rows={trips}
rowKey={(trip) => trip.id}
empty={
<EmptyState title="Žádné záznamy jízd pro vybrané období." />
}
/>
<Pagination
page={page}
pageCount={pagination?.total_pages ?? 1}
onChange={setPage}
/>
</>
)}
</Card>
</PageEnter>
);
}