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>
This commit is contained in:
BOHA
2026-06-10 09:59:47 +02:00
parent d08e55a41a
commit 1826fc7976
44 changed files with 2812 additions and 622 deletions

View File

@@ -1,6 +1,7 @@
import { useState, useRef } from "react";
import { motion, useReducedMotion } from "framer-motion";
import { useQueryClient } from "@tanstack/react-query";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import QRCode from "qrcode";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
@@ -134,6 +135,28 @@ export default function DashProfile({
// locks <html> scroll like the kit dialogs.
useDialogScrollLock(show2FASetup);
// Generate the enrollment QR LOCALLY from the otpauth URI. Never send the
// URI to an external QR service: the production CSP (img-src) blocks it and
// it would leak the TOTP secret to a third party. A data: URL is allowed by
// the CSP. Derived via useQuery (not an effect) per repo conventions.
const { data: totpQrDataUrl, isError: totpQrFailed } = useQuery({
queryKey: ["totp", "qr", totpQrUri],
enabled: !!totpQrUri,
staleTime: Infinity,
// The URI embeds the TOTP secret — drop it from the cache as soon as the
// enrollment UI unmounts instead of keeping it for the default 5-min GC.
gcTime: 0,
retry: false,
queryFn: async () => {
try {
return await QRCode.toDataURL(totpQrUri!, { width: 200, margin: 2 });
} catch (err) {
console.error("DashProfile: generování QR kódu selhalo", err);
throw err;
}
},
});
const [showModal, setShowModal] = useState(false);
const [formData, setFormData] = useState<ProfileFormData>({
username: "",
@@ -549,11 +572,11 @@ export default function DashProfile({
Naskenujte QR kód v autentizační aplikaci (Google Authenticator,
Authy, Microsoft Authenticator apod.)
</Typography>
{totpQrUri && (
{totpQrUri && totpQrDataUrl && (
<Box sx={{ textAlign: "center", mb: 2 }}>
<Box
component="img"
src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(totpQrUri)}`}
src={totpQrDataUrl}
alt="TOTP QR Code"
sx={{
width: 200,
@@ -561,10 +584,23 @@ export default function DashProfile({
borderRadius: 2,
border: 1,
borderColor: "divider",
// The QR must stay scannable in dark mode — keep it on a
// white tile instead of inheriting the dark paper bg.
bgcolor: "common.white",
}}
/>
</Box>
)}
{totpQrUri && totpQrFailed && (
<Typography
variant="body2"
color="warning.main"
sx={{ mb: 2, textAlign: "center" }}
>
QR kód se nepodařilo vygenerovat. Zadejte prosím klíč do
aplikace ručně.
</Typography>
)}
{totpSecret && (
<Box sx={{ mb: 2 }}>
<Typography

View File

@@ -122,7 +122,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
},
[],
);
);
const silentRefresh = useCallback(async (): Promise<boolean> => {
// Deduplicate concurrent refresh calls — token rotation means only one call can succeed
@@ -260,17 +260,32 @@ export function AuthProvider({ children }: { children: ReactNode }) {
) => {
setError(null);
try {
const response = await fetch(`${API_BASE}/login/totp`, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
login_token: loginToken,
totp_code: code,
remember_me: remember,
isBackup,
}),
});
// Backup codes have their own endpoint + schema (8-char codes would
// fail /login/totp's strict 6-digit TotpVerifySchema). Both endpoints
// complete the same login flow: tokens issued + refresh cookie set.
const response = await fetch(
isBackup
? `${API_BASE}/totp/backup-verify`
: `${API_BASE}/login/totp`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify(
isBackup
? {
login_token: loginToken,
backup_code: code,
remember_me: remember,
}
: {
login_token: loginToken,
totp_code: code,
remember_me: remember,
},
),
},
);
const data = await response.json();
if (data.success) {
setAccessTokenFn(data.data.access_token, data.data.expires_in);

View File

@@ -6,6 +6,7 @@ import {
calcProjectMinutesTotal,
calcFormWorkMinutes,
calculateWorkMinutes,
combineDatetime,
getDatePart,
getTimePart,
formatDate,
@@ -133,9 +134,6 @@ interface DeleteConfirmState {
const API_BASE = "/api/admin";
const combineDatetime = (date: string, time: string): string | null =>
date && time ? `${date}T${time}:00` : null;
/**
* Compute per-user totals from raw attendance records.
* This replaces the server-side `user_totals` that the PHP backend returned.

View File

@@ -86,3 +86,13 @@ export const require2FAOptions = () =>
queryFn: () =>
jsonQuery<{ require_2fa: boolean }>("/api/admin/totp/required"),
});
// Per-user 2FA enrollment status (users.totp_enabled) — NOT the company-wide
// require_2fa policy above. Mutations that enable/disable 2FA must invalidate
// the broad ["totp"] domain key.
export const totpStatusOptions = () =>
queryOptions({
queryKey: ["totp", "status"],
queryFn: () =>
jsonQuery<{ totp_enabled: boolean }>("/api/admin/totp/status"),
});

View File

@@ -1,5 +1,5 @@
import { queryOptions } from "@tanstack/react-query";
import { jsonQuery } from "../apiAdapter";
import { jsonQuery, paginatedJsonQuery } from "../apiAdapter";
export interface TripVehicle {
id: number;
@@ -59,7 +59,9 @@ export const tripListOptions = (filters: {
if (filters.page) params.set("page", String(filters.page));
if (filters.perPage) params.set("per_page", String(filters.perPage));
const qs = params.toString();
return jsonQuery<BackendTrip[]>(`/api/admin/trips${qs ? `?${qs}` : ""}`);
return paginatedJsonQuery<BackendTrip>(
`/api/admin/trips${qs ? `?${qs}` : ""}`,
);
},
});
@@ -81,6 +83,8 @@ export const tripHistoryOptions = (filters: {
month?: string;
vehicleId?: number;
userId?: number;
page?: number;
perPage?: number;
}) =>
queryOptions({
queryKey: [
@@ -90,6 +94,8 @@ export const tripHistoryOptions = (filters: {
month: filters.month,
vehicleId: filters.vehicleId,
userId: filters.userId,
page: filters.page,
perPage: filters.perPage,
},
],
queryFn: () => {
@@ -98,7 +104,53 @@ export const tripHistoryOptions = (filters: {
if (filters.vehicleId)
params.set("vehicle_id", String(filters.vehicleId));
if (filters.userId) params.set("user_id", String(filters.userId));
if (filters.page) params.set("page", String(filters.page));
if (filters.perPage) params.set("per_page", String(filters.perPage));
const qs = params.toString();
return jsonQuery<BackendTrip[]>(`/api/admin/trips${qs ? `?${qs}` : ""}`);
return paginatedJsonQuery<BackendTrip>(
`/api/admin/trips${qs ? `?${qs}` : ""}`,
);
},
});
export interface TripStats {
count: number;
total_km: number;
business_km: number;
private_km: number;
}
// Count/km totals over the WHOLE filtered set (not one page) — hits
// /trips/stats with the same filters the lists use. `month` accepts either a
// numeric month (paired with `year`, TripsAdmin style) or a combined
// "YYYY-MM" string (TripsHistory style); the server supports both.
export const tripStatsOptions = (filters: {
month?: number | string;
year?: number;
vehicleId?: number;
userId?: number;
}) =>
queryOptions({
queryKey: [
"trips",
"stats",
{
month: filters.month,
year: filters.year,
vehicleId: filters.vehicleId,
userId: filters.userId,
},
],
queryFn: () => {
const params = new URLSearchParams();
if (filters.month) params.set("month", String(filters.month));
if (filters.year) params.set("year", String(filters.year));
if (filters.vehicleId)
params.set("vehicle_id", String(filters.vehicleId));
if (filters.userId) params.set("user_id", String(filters.userId));
const qs = params.toString();
return jsonQuery<TripStats>(
`/api/admin/trips/stats${qs ? `?${qs}` : ""}`,
);
},
});

View File

@@ -10,6 +10,7 @@ import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import { useApiMutation } from "../lib/queries/mutations";
import { todayLocalStr } from "../utils/formatters";
import { combineDatetime } from "../utils/attendanceHelpers";
import {
Button,
Card,
@@ -41,6 +42,24 @@ interface CreateForm {
notes: string;
}
/**
* Wire payload for POST /attendance (CreateAttendanceSchema). The raw form
* above is NOT sent directly: its separate date+time inputs are combined into
* "YYYY-MM-DDTHH:MM:00" datetimes (same semantics as useAttendanceAdmin's
* create modal), and unset optional fields are null — never "".
*/
interface CreatePayload {
user_id: number;
shift_date: string;
leave_type: string;
notes: string | null;
leave_hours?: number;
arrival_time?: string | null;
departure_time?: string | null;
break_start?: string | null;
break_end?: string | null;
}
export default function AttendanceCreate() {
const alert = useAlert();
const { hasPermission } = useAuth();
@@ -52,7 +71,7 @@ export default function AttendanceCreate() {
}));
const [submitting, setSubmitting] = useState(false);
const createMutation = useApiMutation<CreateForm, { message?: string }>({
const createMutation = useApiMutation<CreatePayload, { message?: string }>({
url: () => `${API_BASE}/attendance`,
method: () => "POST",
invalidate: ["attendance", "users"],
@@ -88,7 +107,36 @@ export default function AttendanceCreate() {
setSubmitting(true);
try {
const result = await createMutation.mutateAsync(form);
const isLeave = form.leave_type !== "work";
const payload: CreatePayload = {
user_id: Number(form.user_id),
shift_date: form.shift_date,
leave_type: form.leave_type,
notes: form.notes || null,
};
if (isLeave) {
payload.leave_hours = form.leave_hours || 8;
} else {
payload.arrival_time = combineDatetime(
form.arrival_date,
form.arrival_time,
);
payload.departure_time = combineDatetime(
form.departure_date,
form.departure_time,
);
payload.break_start = combineDatetime(
form.break_start_date,
form.break_start_time,
);
payload.break_end = combineDatetime(
form.break_end_date,
form.break_end_time,
);
}
const result = await createMutation.mutateAsync(payload);
alert.success(result?.message || "Uloženo");
navigate(`/attendance/admin?month=${form.shift_date.substring(0, 7)}`);
} catch (e) {

View File

@@ -8,7 +8,7 @@ import { useAuth } from "../context/AuthContext";
import { useAlert } from "../context/AlertContext";
import apiFetch from "../utils/api";
import { dashboardOptions } from "../lib/queries/dashboard";
import { require2FAOptions } from "../lib/queries/settings";
import { totpStatusOptions } from "../lib/queries/settings";
import { getCzechDate } from "../utils/dashboardHelpers";
import { useApiMutation } from "../lib/queries/mutations";
import { Card, Button, StatusChip, PageEnter } from "../ui";
@@ -86,9 +86,11 @@ export default function Dashboard() {
const { data: dashDataRaw, isPending: dashLoading } =
useQuery(dashboardOptions());
const dashData = dashDataRaw as DashData | undefined;
// Personal 2FA enrollment (users.totp_enabled) — NOT the company-wide
// require_2fa policy flag (the banner below uses user.require2FA for that).
const { data: totpData, isPending: totpLoading } =
useQuery(require2FAOptions());
const totpEnabled = totpData?.require_2fa ?? !!user?.totpEnabled;
useQuery(totpStatusOptions());
const totpEnabled = totpData?.totp_enabled ?? !!user?.totpEnabled;
const punchMutation = useApiMutation<
Record<string, unknown>,
@@ -176,6 +178,7 @@ export default function Dashboard() {
});
const data = await response.json();
if (data.success) {
queryClient.invalidateQueries({ queryKey: ["totp"] });
queryClient.invalidateQueries({ queryKey: ["settings"] });
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
queryClient.invalidateQueries({ queryKey: ["users"] });
@@ -206,6 +209,7 @@ export default function Dashboard() {
});
const data = await response.json();
if (data.success) {
queryClient.invalidateQueries({ queryKey: ["totp"] });
queryClient.invalidateQueries({ queryKey: ["settings"] });
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
queryClient.invalidateQueries({ queryKey: ["users"] });

View File

@@ -51,7 +51,12 @@ import { invoiceDetailOptions } from "../lib/queries/invoices";
import { offerCustomersOptions } from "../lib/queries/offers";
import { bankAccountsOptions } from "../lib/queries/common";
import { jsonQuery } from "../lib/apiAdapter";
import { formatCurrency, formatDate, todayLocalStr } from "../utils/formatters";
import {
formatCurrency,
formatDate,
numberOr,
todayLocalStr,
} from "../utils/formatters";
import { normalizeDateStr } from "../utils/attendanceHelpers";
import {
Button,
@@ -686,7 +691,7 @@ export default function InvoiceDetail() {
tax_date: normalizeDateStr(inv.tax_date),
currency: inv.currency || "CZK",
apply_vat: Number(inv.apply_vat) ? 1 : 0,
vat_rate: Number(inv.vat_rate) || 21,
vat_rate: numberOr(inv.vat_rate, 21),
payment_method: inv.payment_method || "Příkazem",
constant_symbol: inv.constant_symbol || "0308",
issued_by: inv.issued_by || "",
@@ -725,7 +730,11 @@ export default function InvoiceDetail() {
quantity: Number(item.quantity) || 1,
unit: item.unit || "",
unit_price: Number(item.unit_price) || 0,
vat_rate: Number(inv.vat_rate) || 21,
// Per-line VAT: hydrate from the ITEM's own stored rate (a real DB
// column returned by the detail endpoint) — falling back to the
// invoice-level rate only when the line carries none. Hydrating
// from the invoice rate corrupted mixed-rate invoices on re-save.
vat_rate: numberOr(item.vat_rate, numberOr(inv.vat_rate, 21)),
}))
: [];
if (mappedItems.length > 0) {
@@ -781,8 +790,10 @@ export default function InvoiceDetail() {
// Pre-fill from order
if (fromOrderId && orderDataQuery.data) {
const order = orderDataQuery.data;
const vatRate =
Number(order.vat_rate) || (companySettings?.default_vat_rate ?? 21);
const vatRate = numberOr(
order.vat_rate,
companySettings?.default_vat_rate ?? 21,
);
setForm((prev) => ({
...prev,
customer_id: order.customer_id as number,

View File

@@ -44,7 +44,7 @@ import { jsonQuery } from "../lib/apiAdapter";
import { offerCustomersOptions, type Customer } from "../lib/queries/offers";
import { issuedOrderDetailOptions } from "../lib/queries/issued-orders";
import { companySettingsOptions } from "../lib/queries/settings";
import { formatCurrency, todayLocalStr } from "../utils/formatters";
import { formatCurrency, numberOr, todayLocalStr } from "../utils/formatters";
import { normalizeDateStr } from "../utils/attendanceHelpers";
import {
Button,
@@ -585,7 +585,7 @@ export default function IssuedOrderDetail() {
customer_name: d.customer_name ?? "",
currency: d.currency || "CZK",
apply_vat: d.apply_vat !== false,
vat_rate: Number(d.vat_rate) || 21,
vat_rate: numberOr(d.vat_rate, 21),
order_date: normalizeDateStr(d.order_date),
delivery_date: normalizeDateStr(d.delivery_date),
language: d.language || "cs",
@@ -605,10 +605,10 @@ export default function IssuedOrderDetail() {
id: it.id,
description: it.description || "",
item_description: it.item_description || "",
quantity: Number(it.quantity) || 1,
quantity: numberOr(it.quantity, 1),
unit: it.unit || "",
unit_price: Number(it.unit_price) || 0,
vat_rate: Number(it.vat_rate) || Number(d.vat_rate) || 21,
vat_rate: numberOr(it.vat_rate, numberOr(d.vat_rate, 21)),
}))
: [];
if (mapped.length > 0) setItems(mapped);
@@ -831,6 +831,12 @@ export default function IssuedOrderDetail() {
try {
await statusMutation.mutateAsync({ status: newStatus });
alert.success("Stav byl změněn");
// Mirror the new status into the form (same as handleSubmit's success
// path): the one-shot hydration won't re-run (dataReady stays true), so
// without this the StatusChip, the `editable` flag and the delete-button
// gate would keep reading the stale status until a full remount. The PO
// number is repopulated by the detail-query sync effect.
setForm((prev) => ({ ...prev, status: newStatus }));
} catch (err) {
alert.error(err instanceof Error ? err.message : "Chyba připojení");
} finally {

View File

@@ -172,7 +172,13 @@ export default function Projects() {
enabled: showCreate,
});
const createMutation = useApiMutation<typeof createForm, { id: number }>({
const createMutation = useApiMutation<
Omit<typeof createForm, "start_date" | "end_date"> & {
start_date: string | null;
end_date: string | null;
},
{ id: number }
>({
url: () => `${API_BASE}/projects`,
method: () => "POST",
invalidate: ["projects", "orders", "offers", "invoices", "attendance"],
@@ -204,7 +210,13 @@ export default function Projects() {
setCreating(true);
try {
await createMutation.mutateAsync(createForm);
// Server's isoDateString.nullish() accepts null but rejects "" —
// send empty date fields as null so the create doesn't 400.
await createMutation.mutateAsync({
...createForm,
start_date: createForm.start_date || null,
end_date: createForm.end_date || null,
});
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
} finally {

View File

@@ -12,9 +12,11 @@ import { formatKm, todayLocalStr } from "../utils/formatters";
import apiFetch from "../utils/api";
import {
tripListOptions,
tripStatsOptions,
tripVehiclesOptions,
type BackendTrip,
} from "../lib/queries/trips";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import { useApiMutation } from "../lib/queries/mutations";
import {
Button,
@@ -158,12 +160,20 @@ export default function Trips() {
const alert = useAlert();
const { hasPermission } = useAuth();
const { data: tripsData, isPending: tripsLoading } = useQuery(
tripListOptions({}),
);
const { data: vehiclesData } = useQuery(tripVehiclesOptions());
// "Poslední jízdy" widget — only the 10 newest rows are shown, so fetch
// exactly those; the stat cards come from the server-side stats endpoint
// (computed over the whole filtered set, not one page).
const { items: trips, isPending: tripsLoading } =
usePaginatedQuery<BackendTrip>(tripListOptions({ perPage: 10 }));
const trips = tripsData ?? [];
// Stat cards are a personal "this month" summary — the header subtitle
// shows the current month, so the stats query is scoped to match it.
const now = new Date();
const { data: stats } = useQuery(
tripStatsOptions({ month: now.getMonth() + 1, year: now.getFullYear() }),
);
const { data: vehiclesData } = useQuery(tripVehiclesOptions());
const vehicles = vehiclesData ?? [];
const [showModal, setShowModal] = useState(false);
@@ -321,19 +331,14 @@ export default function Trips() {
return <LoadingState />;
}
const totals = trips.reduce(
(acc, t) => {
const dist = t.distance ?? t.end_km - t.start_km;
acc.count++;
acc.total += dist;
if (t.is_business) acc.business += dist;
else acc.private += dist;
return acc;
},
{ total: 0, business: 0, private: 0, count: 0 },
);
const totals = {
count: stats?.count ?? 0,
total: stats?.total_km ?? 0,
business: stats?.business_km ?? 0,
private: stats?.private_km ?? 0,
};
const recentTrips = trips.slice(0, 10);
const recentTrips = trips;
const columns: DataColumn<BackendTrip>[] = [
{

View File

@@ -1,4 +1,4 @@
import { useState, useRef } from "react";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Link as RouterLink } from "react-router-dom";
import Box from "@mui/material/Box";
@@ -9,11 +9,15 @@ import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import {
tripListOptions,
tripStatsOptions,
tripVehiclesOptions,
tripUsersOptions,
type BackendTrip,
type TripStats,
} from "../lib/queries/trips";
import { companySettingsOptions } from "../lib/queries/settings";
import { jsonQuery } from "../lib/apiAdapter";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import { formatDate } from "../utils/attendanceHelpers";
import { formatKm } from "../utils/formatters";
import { useApiMutation } from "../lib/queries/mutations";
@@ -28,6 +32,7 @@ import {
Select,
DateField,
MonthField,
Pagination,
StatusChip,
FilterBar,
LoadingState,
@@ -83,6 +88,190 @@ function mapTrip(bt: BackendTrip): Trip {
};
}
/**
* Escape user-origin strings before interpolating them into the print HTML
* (the JSX hidden-div approach escaped automatically; the string template
* must do it explicitly).
*/
function escapeHtml(value: string): string {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
const PRINT_STYLES = `
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size: 10px;
line-height: 1.4;
color: #000;
background: #fff;
padding: 10mm;
}
.print-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 2px solid #333;
}
.print-header-left { display: flex; align-items: center; gap: 12px; }
.print-logo { height: 40px; width: auto; }
.print-header-text { text-align: left; }
.print-header-right { text-align: right; }
.print-header h1 { font-size: 18px; font-weight: 700; margin-bottom: 3px; }
.print-header .company { font-size: 11px; color: #666; }
.print-header .period { font-size: 13px; font-weight: 600; color: #333; margin-bottom: 2px; }
.print-header .filters { font-size: 10px; color: #666; }
.print-header .generated { font-size: 9px; color: #888; margin-top: 5px; }
.summary {
display: flex;
justify-content: space-around;
margin-bottom: 15px;
padding: 10px;
background: #f5f5f5;
border: 1px solid #ddd;
}
.summary-item { text-align: center; }
.summary-value { font-size: 14px; font-weight: 700; }
.summary-label { font-size: 9px; color: #666; }
table { width: 100%; border-collapse: collapse; margin-bottom: 15px; }
th, td { border: 1px solid #333; padding: 4px 6px; text-align: left; }
th { background: #333; color: #fff; font-weight: 600; font-size: 9px; text-transform: uppercase; }
td { font-size: 9px; }
tr:nth-child(even) { background: #f9f9f9; }
.text-center { text-align: center; }
.text-right { text-align: right; }
tfoot td { background: #eee; font-weight: 600; }
.badge {
display: inline-block;
padding: 1px 4px;
border-radius: 2px;
font-size: 8px;
font-weight: 500;
}
.badge-success { background: #dcfce7; color: #16a34a; }
.badge-warning { background: #fef3c7; color: #d97706; }
@media print {
body { padding: 5mm; }
@page { size: A4 landscape; margin: 5mm; }
thead { display: table-header-group; }
}
`;
/**
* Build the full print document from the fetched /trips/print data set —
* no hidden-div/innerHTML round-trip, so there is nothing to race against
* React's commit.
*/
function buildPrintHtml(opts: {
trips: Trip[];
totals: TripStats;
periodName: string;
companyName: string;
vehicleName: string | null;
userName: string | null;
logoUrl: string;
}): string {
const { trips, totals } = opts;
const rows = trips
.map(
(trip) => `
<tr>
<td>${formatDate(trip.trip_date)}</td>
<td>${escapeHtml(trip.driver_name)}</td>
<td>${escapeHtml(trip.spz)}</td>
<td>${escapeHtml(trip.route_from)} &rarr; ${escapeHtml(trip.route_to)}</td>
<td class="text-right">${formatKm(trip.start_km)} - ${formatKm(trip.end_km)}</td>
<td class="text-right"><strong>${formatKm(trip.distance)} km</strong></td>
<td class="text-center">
<span class="badge ${trip.is_business ? "badge-success" : "badge-warning"}">
${trip.is_business ? "Služební" : "Soukromá"}
</span>
</td>
<td>${escapeHtml(trip.notes || "")}</td>
</tr>`,
)
.join("");
return `
<!DOCTYPE html>
<html lang="cs">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kniha jízd - ${escapeHtml(opts.periodName)}</title>
<style>${PRINT_STYLES}</style>
</head>
<body>
<div class="print-header">
<div class="print-header-left">
<img src="${opts.logoUrl}" alt="" class="print-logo" />
<div class="print-header-text">
<h1>KNIHA JÍZD</h1>
<div class="company">${escapeHtml(opts.companyName)}</div>
</div>
</div>
<div class="print-header-right">
<div class="period">${escapeHtml(opts.periodName)}</div>
${opts.vehicleName ? `<div class="filters">Vozidlo: ${escapeHtml(opts.vehicleName)}</div>` : ""}
${opts.userName ? `<div class="filters">Řidič: ${escapeHtml(opts.userName)}</div>` : ""}
<div class="generated">Vygenerováno: ${new Date().toLocaleString("cs-CZ")}</div>
</div>
</div>
<div class="summary">
<div class="summary-item">
<div class="summary-value">${totals.count}</div>
<div class="summary-label">Počet jízd</div>
</div>
<div class="summary-item">
<div class="summary-value">${formatKm(totals.total_km)} km</div>
<div class="summary-label">Celkem</div>
</div>
<div class="summary-item">
<div class="summary-value">${formatKm(totals.business_km)} km</div>
<div class="summary-label">Služební</div>
</div>
<div class="summary-item">
<div class="summary-value">${formatKm(totals.private_km)} km</div>
<div class="summary-label">Soukromé</div>
</div>
</div>
<table>
<thead>
<tr>
<th style="width: 70px">Datum</th>
<th style="width: 80px">Řidič</th>
<th style="width: 70px">Vozidlo</th>
<th>Trasa</th>
<th style="width: 70px" class="text-right">Stav km</th>
<th style="width: 60px" class="text-right">Vzdálenost</th>
<th style="width: 55px" class="text-center">Typ</th>
<th>Poznámka</th>
</tr>
</thead>
<tbody>${rows}</tbody>
<tfoot>
<tr>
<td colspan="5" class="text-right">Celkem:</td>
<td class="text-right"><strong>${formatKm(totals.total_km)} km</strong></td>
<td colspan="2"></td>
</tr>
</tfoot>
</table>
</body>
</html>
`;
}
const PrintIcon = (
<svg
width="18"
@@ -188,7 +377,7 @@ export default function TripsAdmin() {
});
const [filterVehicleId, setFilterVehicleId] = useState("");
const [filterUserId, setFilterUserId] = useState("");
const printRef = useRef<HTMLDivElement>(null);
const [page, setPage] = useState(1);
const [showEditModal, setShowEditModal] = useState(false);
const [editingTrip, setEditingTrip] = useState<Trip | null>(null);
@@ -217,16 +406,27 @@ export default function TripsAdmin() {
const { data: companySettings } = useQuery(companySettingsOptions());
const companyName = companySettings?.company_name ?? "";
const { data: tripsData, isPending } = useQuery(
tripListOptions({
month: Number(filterPeriod.slice(5, 7)) || undefined,
year: Number(filterPeriod.slice(0, 4)) || undefined,
vehicleId: filterVehicleId ? Number(filterVehicleId) : undefined,
userId: filterUserId ? Number(filterUserId) : undefined,
perPage: 100,
}),
);
const trips = (tripsData ?? []).map(mapTrip);
// ONE shared filter object for the list, stats AND print requests so the
// three can never drift apart. An empty MonthField value yields
// month/year = undefined (omitted from the request), mirroring the
// `Number(...) || undefined` guard the queries always used.
const filters = {
month: Number(filterPeriod.slice(5, 7)) || undefined,
year: Number(filterPeriod.slice(0, 4)) || undefined,
vehicleId: filterVehicleId ? Number(filterVehicleId) : undefined,
userId: filterUserId ? Number(filterUserId) : undefined,
};
const {
items: tripsItems,
pagination,
isPending,
} = usePaginatedQuery<BackendTrip>(tripListOptions({ ...filters, page }));
const trips = tripsItems.map(mapTrip);
// Stat cards: totals over the WHOLE filtered set (server-side aggregate),
// not just the visible page.
const { data: stats } = useQuery(tripStatsOptions(filters));
// useApiMutation JSON.stringifies the whole TIn as the request body, so
// TIn must match the backend schema (UpdateTripSchema) shape directly —
@@ -318,10 +518,12 @@ export default function TripsAdmin() {
};
const getPeriodName = () =>
new Date(
Number(filterPeriod.slice(0, 4)),
Number(filterPeriod.slice(5, 7)) - 1,
).toLocaleString("cs-CZ", { month: "long", year: "numeric" });
filterPeriod
? new Date(
Number(filterPeriod.slice(0, 4)),
Number(filterPeriod.slice(5, 7)) - 1,
).toLocaleString("cs-CZ", { month: "long", year: "numeric" })
: "Všechna období";
const getSelectedVehicleName = () => {
if (!filterVehicleId) return null;
const v = vehicles.find((v) => String(v.id) === filterVehicleId);
@@ -333,94 +535,61 @@ export default function TripsAdmin() {
return u?.name || null;
};
const handlePrint = () => {
const periodName = getPeriodName();
const handlePrint = async () => {
// Open the print window SYNCHRONOUSLY, inside the click's transient
// activation — calling window.open after the network await can fall
// outside the activation window and get popup-blocked (which previously
// failed silently).
const printWindow = window.open("", "_blank");
if (!printWindow) {
alert.error("Tisk byl zablokován prohlížečem");
return;
}
setTimeout(() => {
if (printRef.current) {
const content = printRef.current.innerHTML;
const printWindow = window.open("", "_blank");
if (!printWindow) return;
printWindow.document.write(`
<!DOCTYPE html>
<html lang="cs">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kniha jízd - ${periodName}</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size: 10px;
line-height: 1.4;
color: #000;
background: #fff;
padding: 10mm;
}
.print-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 2px solid #333;
}
.print-header-left { display: flex; align-items: center; gap: 12px; }
.print-logo { height: 40px; width: auto; }
.print-header-text { text-align: left; }
.print-header-right { text-align: right; }
.print-header h1 { font-size: 18px; font-weight: 700; margin-bottom: 3px; }
.print-header .company { font-size: 11px; color: #666; }
.print-header .period { font-size: 13px; font-weight: 600; color: #333; margin-bottom: 2px; }
.print-header .filters { font-size: 10px; color: #666; }
.print-header .generated { font-size: 9px; color: #888; margin-top: 5px; }
.summary {
display: flex;
justify-content: space-around;
margin-bottom: 15px;
padding: 10px;
background: #f5f5f5;
border: 1px solid #ddd;
}
.summary-item { text-align: center; }
.summary-value { font-size: 14px; font-weight: 700; }
.summary-label { font-size: 9px; color: #666; }
table { width: 100%; border-collapse: collapse; margin-bottom: 15px; }
th, td { border: 1px solid #333; padding: 4px 6px; text-align: left; }
th { background: #333; color: #fff; font-weight: 600; font-size: 9px; text-transform: uppercase; }
td { font-size: 9px; }
tr:nth-child(even) { background: #f9f9f9; }
.text-center { text-align: center; }
.text-right { text-align: right; }
tfoot td { background: #eee; font-weight: 600; }
.badge {
display: inline-block;
padding: 1px 4px;
border-radius: 2px;
font-size: 8px;
font-weight: 500;
}
.badge-success { background: #dcfce7; color: #16a34a; }
.badge-warning { background: #fef3c7; color: #d97706; }
@media print {
body { padding: 5mm; }
@page { size: A4 landscape; margin: 5mm; }
thead { display: table-header-group; }
}
</style>
</head>
<body>
${content}
</body>
</html>
`);
printWindow.document.close();
printWindow.onload = () => {
printWindow.print();
};
}
}, 100);
// Fetch the FULL filtered set for the printout — the list query is
// paginated, so printing from it would truncate to the visible page.
let printTrips: Trip[];
let printTotals: TripStats;
try {
const params = new URLSearchParams();
if (filters.month) params.set("month", String(filters.month));
if (filters.year) params.set("year", String(filters.year));
if (filters.vehicleId)
params.set("vehicle_id", String(filters.vehicleId));
if (filters.userId) params.set("user_id", String(filters.userId));
const data = await jsonQuery<{ trips: BackendTrip[]; totals: TripStats }>(
`${API_BASE}/trips/print?${params.toString()}`,
);
printTrips = data.trips.map(mapTrip);
printTotals = data.totals;
} catch (e) {
printWindow.close();
console.error("Trip print data fetch failed:", e);
alert.error(e instanceof Error ? e.message : "Chyba připojení");
return;
}
// The user closed the popup while the data was loading — a deliberate
// cancel, not an error.
if (printWindow.closed) return;
// The document is built directly from the fetched data (no hidden-div /
// setTimeout round-trip), so it can be neither unmounted nor stale.
printWindow.document.write(
buildPrintHtml({
trips: printTrips,
totals: printTotals,
periodName: getPeriodName(),
companyName,
vehicleName: getSelectedVehicleName(),
userName: getSelectedUserName(),
logoUrl: `${window.location.origin}/api/admin/company-settings/logo?variant=light`,
}),
);
printWindow.document.close();
printWindow.onload = () => {
printWindow.print();
};
};
const calculateDistance = (): number => {
@@ -430,11 +599,9 @@ export default function TripsAdmin() {
};
const totals = {
count: trips.length,
total: trips.reduce((sum, t) => sum + t.distance, 0),
business: trips
.filter((t) => Number(t.is_business))
.reduce((sum, t) => sum + t.distance, 0),
count: stats?.count ?? 0,
total: stats?.total_km ?? 0,
business: stats?.business_km ?? 0,
};
const columns: DataColumn<Trip>[] = [
@@ -541,7 +708,7 @@ export default function TripsAdmin() {
>
<Typography variant="h4">Správa knihy jízd</Typography>
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
{trips.length > 0 && (
{(pagination?.total ?? 0) > 0 && (
<Button
variant="outlined"
color="inherit"
@@ -566,12 +733,21 @@ export default function TripsAdmin() {
{/* Filters */}
<FilterBar>
<Box sx={{ flex: "0 0 180px" }}>
<MonthField value={filterPeriod} onChange={setFilterPeriod} />
<MonthField
value={filterPeriod}
onChange={(val) => {
setFilterPeriod(val);
setPage(1);
}}
/>
</Box>
<Box sx={{ flex: "0 0 220px" }}>
<Select
value={filterVehicleId}
onChange={setFilterVehicleId}
onChange={(value) => {
setFilterVehicleId(value);
setPage(1);
}}
options={[
{ value: "", label: "Všechna vozidla" },
...vehicles.map((v) => ({
@@ -584,7 +760,10 @@ export default function TripsAdmin() {
<Box sx={{ flex: "0 0 220px" }}>
<Select
value={filterUserId}
onChange={setFilterUserId}
onChange={(value) => {
setFilterUserId(value);
setPage(1);
}}
options={[
{ value: "", label: "Všichni řidiči" },
...tripUsers.map((u) => ({
@@ -632,14 +811,21 @@ export default function TripsAdmin() {
{isPending ? (
<LoadingState />
) : (
<DataTable<Trip>
columns={columns}
rows={trips}
rowKey={(trip) => trip.id}
empty={
<EmptyState title="Žádné záznamy jízd pro vybrané období." />
}
/>
<>
<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>
@@ -796,120 +982,6 @@ export default function TripsAdmin() {
confirmVariant="danger"
loading={deleteMutation.isPending}
/>
{/* Hidden Print Content */}
{trips.length > 0 && (
<div ref={printRef} style={{ display: "none" }}>
<div className="print-header">
<div className="print-header-left">
<img
src="/api/admin/company-settings/logo?variant=light"
alt=""
className="print-logo"
/>
<div className="print-header-text">
<h1>KNIHA JÍZD</h1>
<div className="company">{companyName}</div>
</div>
</div>
<div className="print-header-right">
<div className="period">{getPeriodName()}</div>
{getSelectedVehicleName() && (
<div className="filters">
Vozidlo: {getSelectedVehicleName()}
</div>
)}
{getSelectedUserName() && (
<div className="filters">Řidič: {getSelectedUserName()}</div>
)}
<div className="generated">
Vygenerováno: {new Date().toLocaleString("cs-CZ")}
</div>
</div>
</div>
<div className="summary">
<div className="summary-item">
<div className="summary-value">{totals.count}</div>
<div className="summary-label">Počet jízd</div>
</div>
<div className="summary-item">
<div className="summary-value">{formatKm(totals.total)} km</div>
<div className="summary-label">Celkem</div>
</div>
<div className="summary-item">
<div className="summary-value">
{formatKm(totals.business)} km
</div>
<div className="summary-label">Služební</div>
</div>
<div className="summary-item">
<div className="summary-value">
{formatKm(totals.total - totals.business)} km
</div>
<div className="summary-label">Soukromé</div>
</div>
</div>
<table>
<thead>
<tr>
<th style={{ width: "70px" }}>Datum</th>
<th style={{ width: "80px" }}>Řidič</th>
<th style={{ width: "70px" }}>Vozidlo</th>
<th>Trasa</th>
<th style={{ width: "70px" }} className="text-right">
Stav km
</th>
<th style={{ width: "60px" }} className="text-right">
Vzdálenost
</th>
<th style={{ width: "55px" }} className="text-center">
Typ
</th>
<th>Poznámka</th>
</tr>
</thead>
<tbody>
{trips.map((trip) => (
<tr key={trip.id}>
<td>{formatDate(trip.trip_date)}</td>
<td>{trip.driver_name}</td>
<td>{trip.spz}</td>
<td>
{trip.route_from} &rarr; {trip.route_to}
</td>
<td className="text-right">
{formatKm(trip.start_km)} - {formatKm(trip.end_km)}
</td>
<td className="text-right">
<strong>{formatKm(trip.distance)} km</strong>
</td>
<td className="text-center">
<span
className={`badge ${trip.is_business ? "badge-success" : "badge-warning"}`}
>
{trip.is_business ? "Služební" : "Soukromá"}
</span>
</td>
<td>{trip.notes || ""}</td>
</tr>
))}
</tbody>
<tfoot>
<tr>
<td colSpan={5} className="text-right">
Celkem:
</td>
<td className="text-right">
<strong>{formatKm(totals.total)} km</strong>
</td>
<td colSpan={2}></td>
</tr>
</tfoot>
</table>
</div>
)}
</PageEnter>
);
}

View File

@@ -5,12 +5,19 @@ import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import { formatDate } from "../utils/attendanceHelpers";
import { formatKm } from "../utils/formatters";
import { tripHistoryOptions, tripVehiclesOptions } from "../lib/queries/trips";
import {
tripHistoryOptions,
tripStatsOptions,
tripVehiclesOptions,
type BackendTrip,
} from "../lib/queries/trips";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";
import {
Card,
DataTable,
Select,
MonthField,
Pagination,
StatusChip,
PageHeader,
PageEnter,
@@ -91,18 +98,35 @@ export default function TripsHistory() {
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 { data: tripsData, isPending } = useQuery(
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) => ({
const trips: Trip[] = tripsData.map((t) => ({
id: t.id,
trip_date: t.trip_date,
spz: t.vehicles?.spz ?? "",
@@ -118,14 +142,11 @@ export default function TripsHistory() {
notes: t.notes ?? undefined,
}));
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 totals = {
count: stats?.count ?? 0,
total: stats?.total_km ?? 0,
business: stats?.business_km ?? 0,
};
if (!hasPermission("trips.history")) return <Forbidden />;
@@ -221,12 +242,21 @@ export default function TripsHistory() {
{/* Filters */}
<FilterBar>
<Box sx={{ flex: "0 0 180px" }}>
<MonthField value={month} onChange={(val) => setMonth(val)} />
<MonthField
value={month}
onChange={(val) => {
setMonth(val);
setPage(1);
}}
/>
</Box>
<Box sx={{ flex: "0 0 220px" }}>
<Select
value={vehicleId}
onChange={(value) => setVehicleId(value)}
onChange={(value) => {
setVehicleId(value);
setPage(1);
}}
options={[
{ value: "", label: "Všechna vozidla" },
...vehicles.map((v) => ({
@@ -275,14 +305,21 @@ export default function TripsHistory() {
{isPending ? (
<LoadingState />
) : (
<DataTable<Trip>
columns={columns}
rows={trips}
rowKey={(trip) => trip.id}
empty={
<EmptyState title="Žádné záznamy jízd pro vybrané období." />
}
/>
<>
<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>

View File

@@ -59,6 +59,11 @@ interface ItemDetail extends WarehouseItem {
const API_BASE = "/api/admin/warehouse/items";
// Must match UnitEnum in src/schemas/warehouse.schema.ts — the server rejects
// any other value (CreateItemSchema/UpdateItemSchema), so free text here would
// make the save 400.
const UNIT_OPTIONS = ["ks", "m", "kg", "bal", "sada", "m2", "m3", "l"] as const;
interface ItemForm {
item_number: string;
name: string;
@@ -449,15 +454,14 @@ export default function WarehouseItemDetail() {
</Select>
</Field>
<Field label="Jednotka" required error={errors.unit}>
<TextField
<Select
value={form.unit}
error={!!errors.unit}
onChange={(e) => {
updateForm("unit", e.target.value);
onChange={(v) => {
updateForm("unit", v);
setErrors((prev) => ({ ...prev, unit: "" }));
}}
placeholder="ks, m, kg..."
fullWidth
options={UNIT_OPTIONS.map((u) => ({ value: u, label: u }))}
/>
</Field>
<Field

View File

@@ -4,10 +4,12 @@ import { useQuery } from "@tanstack/react-query";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import Link from "@mui/material/Link";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import { apiFetch } from "../utils/api";
import { formatCurrency, formatDate } from "../utils/formatters";
import {
warehouseReceiptDetailOptions,
@@ -161,6 +163,33 @@ export default function WarehouseReceiptDetail() {
}
};
// A plain <a href> cannot send the Authorization header, so attachments are
// fetched via apiFetch and handed to the browser as a temporary blob URL.
const handleDownloadAttachment = async (att: WarehouseReceiptAttachment) => {
if (!receipt) return;
try {
const response = await apiFetch(
`/api/admin/warehouse/receipts/${receipt.id}/attachments/${att.id}`,
);
if (!response.ok) {
const result = await response.json().catch(() => ({}));
alert.error(result.error || "Nepodařilo se stáhnout přílohu");
return;
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = att.file_name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 60000);
} catch (e) {
alert.error(e instanceof Error ? e.message : "Chyba připojení");
}
};
const confirming = confirmMutation.isPending;
const cancelling = cancelMutation.isPending;
@@ -249,13 +278,14 @@ export default function WarehouseReceiptDetail() {
width: "45%",
bold: true,
render: (att) => (
<a
href={`/api/admin/warehouse/receipts/${r.id}/attachments/${att.id}`}
target="_blank"
rel="noopener noreferrer"
<Link
component="button"
type="button"
onClick={() => handleDownloadAttachment(att)}
sx={{ textAlign: "left", font: "inherit" }}
>
{att.file_name}
</a>
</Link>
),
},
{

View File

@@ -110,6 +110,16 @@ export const getTimePart = (datetime: string | null | undefined): string => {
return extractTime(datetime);
};
/**
* Join a date input ("YYYY-MM-DD") and a time input ("HH:MM") into the
* combined local-datetime wire format the attendance API expects
* ("YYYY-MM-DDTHH:MM:00", validated server-side by `nullableDateTimeString`
* and parsed with `new Date(...)` as local time). Returns null when either
* part is unset — "no value" for the optional datetime fields.
*/
export const combineDatetime = (date: string, time: string): string | null =>
date && time ? `${date}T${time}:00` : null;
export const calcProjectMinutesTotal = (
logs: Array<{
project_id?: number;

View File

@@ -50,6 +50,18 @@ export function todayLocalStr(): string {
return `${d.getFullYear()}-${m}-${day}`;
}
/**
* Coerce a server-returned numeric (number | decimal-string | null/undefined)
* to a number, falling back ONLY when the value is missing or not numeric —
* NEVER on a legitimate 0 (e.g. a 0% VAT rate / reverse charge). The
* `Number(x) || fallback` idiom silently turns stored zeros into the fallback.
*/
export function numberOr(raw: unknown, fallback: number): number {
if (raw == null || raw === "") return fallback;
const n = Number(raw);
return Number.isFinite(n) ? n : fallback;
}
export function formatKm(km: number | string): string {
return new Intl.NumberFormat("cs-CZ").format(Number(km) || 0);
}