1
0
Fork 0
fahrPool/web/lib/auftraege/validate-fahrt.ts

71 lines
2.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { FIN_FEHLER, istGueltigeFin, normalisiereFin } from "@/lib/orte-fahrzeuge/fin";
export type FahrtBeginnValidationResult =
| { valid: true; startKm: number }
| { valid: false; error: string };
export type FahrtEndeValidationResult =
| { valid: true; endKm: number }
| { valid: false; error: string };
function parseKm(value: FormDataEntryValue | null): number | null {
if (typeof value !== "string" || value.trim() === "") {
return null;
}
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
export function validateFahrtBeginn(input: { startKm: FormDataEntryValue | null }): FahrtBeginnValidationResult {
const startKm = parseKm(input.startKm);
if (startKm === null) {
return { valid: false, error: "Bitte einen KM-Stand eingeben." };
}
if (startKm < 0) {
return { valid: false, error: "Der KM-Stand darf nicht negativ sein." };
}
return { valid: true, startKm };
}
export function validateFahrtEnde(input: {
endKm: FormDataEntryValue | null;
startKm: number;
}): FahrtEndeValidationResult {
const endKm = parseKm(input.endKm);
if (endKm === null) {
return { valid: false, error: "Bitte einen End-KM-Stand eingeben." };
}
if (endKm < input.startKm) {
return {
valid: false,
error: `Der End-KM-Stand darf nicht kleiner als der Start-KM-Stand (${input.startKm}) sein.`,
};
}
return { valid: true, endKm };
}
export type StartFinValidationResult = { valid: true; fin: string | null } | { valid: false; error: string };
// Nur UX/Defense-in-Depth: die eigentliche Pruefung und der Vermerk passieren
// in der DB-Funktion fin_bei_fahrtbeginn. Die Bestaetigungspflicht bei
// Abweichung wird hier serverseitig erzwungen, weil die Checkbox im Client
// umgehbar ist.
export function validateStartFin(input: {
startFin: FormDataEntryValue | null;
hinterlegteFin: string | null;
abweichungBestaetigt: FormDataEntryValue | null;
}): StartFinValidationResult {
const fin = typeof input.startFin === "string" ? normalisiereFin(input.startFin) : "";
if (!fin) {
return { valid: true, fin: null };
}
if (!istGueltigeFin(fin)) {
return { valid: false, error: FIN_FEHLER };
}
if (input.hinterlegteFin && input.hinterlegteFin !== fin && input.abweichungBestaetigt !== "on") {
return { valid: false, error: "Die FIN weicht von der hinterlegten FIN ab – bitte die Abweichung bestätigen." };
}
return { valid: true, fin };
}