Falsche Zeitzone bei Buchungen und HTTP status codes als Fehlermeldung behoben

This commit is contained in:
PxlLoewe
2025-10-01 22:23:27 +02:00
parent dc4a3ab4d8
commit ada041bd4a
4 changed files with 64 additions and 44 deletions

View File

@@ -20,10 +20,12 @@ export const getBookingsAPI = async (filter: Prisma.BookingWhereInput) => {
export const createBookingAPI = async (booking: Omit<Prisma.BookingCreateInput, "User">) => { export const createBookingAPI = async (booking: Omit<Prisma.BookingCreateInput, "User">) => {
const response = await axios.post("/api/bookings", booking); const response = await axios.post("/api/bookings", booking);
console.log("Response from createBookingAPI:", response);
if (response.status !== 201) { if (response.status !== 201) {
console.error("Error creating booking:", response); console.error("Error creating booking:", response);
throw new Error("Failed to create booking"); throw new Error("Failed to create booking");
} }
console.log("Booking created:", response.data);
return response.data; return response.data;
}; };

View File

@@ -7,6 +7,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { deleteBookingAPI, getBookingsAPI } from "(app)/_querys/bookings"; import { deleteBookingAPI, getBookingsAPI } from "(app)/_querys/bookings";
import { Button } from "@repo/shared-components"; import { Button } from "@repo/shared-components";
import { formatTimeRange } from "../../helper/timerange"; import { formatTimeRange } from "../../helper/timerange";
import toast from "react-hot-toast";
interface BookingTimelineModalProps { interface BookingTimelineModalProps {
isOpen: boolean; isOpen: boolean;
@@ -75,6 +76,9 @@ export const BookingTimelineModal = ({
await deleteBookingAPI(bookingId); await deleteBookingAPI(bookingId);
queryClient.invalidateQueries({ queryKey: ["bookings"] }); queryClient.invalidateQueries({ queryKey: ["bookings"] });
}, },
onSuccess: () => {
toast.success("Buchung erfolgreich gelöscht");
},
}); });
// Check if user can create bookings // Check if user can create bookings

View File

@@ -9,6 +9,10 @@ import { getStationsAPI } from "(app)/_querys/stations";
import { createBookingAPI } from "(app)/_querys/bookings"; import { createBookingAPI } from "(app)/_querys/bookings";
import { Button } from "@repo/shared-components"; import { Button } from "@repo/shared-components";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { AxiosError } from "axios";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { DateInput } from "_components/ui/DateInput";
interface NewBookingFormData { interface NewBookingFormData {
type: "STATION" | "LST_01" | "LST_02" | "LST_03" | "LST_04"; type: "STATION" | "LST_01" | "LST_02" | "LST_03" | "LST_04";
@@ -41,13 +45,46 @@ export const NewBookingModal = ({
const { mutate: createBooking, isPending: isCreateBookingLoading } = useMutation({ const { mutate: createBooking, isPending: isCreateBookingLoading } = useMutation({
mutationKey: ["createBooking"], mutationKey: ["createBooking"],
mutationFn: createBookingAPI, mutationFn: createBookingAPI,
onMutate() {
// Optionally show a loading toast or indicator
toast.loading("Buchung wird erstellt...", { id: "createBooking" });
},
onError(error: AxiosError) {
const errorData = error.response?.data as { error?: string };
toast.error(errorData?.error || "Fehler beim Erstellen der Buchung", { id: "createBooking" });
},
onSuccess: () => { onSuccess: () => {
toast.success("Buchung erfolgreich erstellt", { id: "createBooking" });
queryClient.invalidateQueries({ queryKey: ["bookings"] }); queryClient.invalidateQueries({ queryKey: ["bookings"] });
onBookingCreated(); onBookingCreated();
onClose();
router.refresh();
}, },
}); });
const newBookingSchema = z
.object({
type: z.enum(["STATION", "LST_01", "LST_02", "LST_03", "LST_04"], {
message: "Bitte wähle einen Typ aus",
}),
stationId: z.number().optional(),
startTime: z.string(),
endTime: z.string(),
title: z.string().optional(),
description: z.string().optional(),
})
.superRefine((data, ctx) => {
const start = new Date(data.startTime);
const end = new Date(data.endTime);
if (end <= start) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Endzeit muss nach der Startzeit liegen",
path: ["endTime"],
});
}
});
const { const {
register, register,
handleSubmit, handleSubmit,
@@ -55,7 +92,9 @@ export const NewBookingModal = ({
setValue, setValue,
reset, reset,
formState: { errors }, formState: { errors },
} = useForm<NewBookingFormData>(); } = useForm<NewBookingFormData>({
resolver: zodResolver(newBookingSchema),
});
const selectedType = watch("type"); const selectedType = watch("type");
const hasDISPOPermission = userPermissions.includes("DISPO"); const hasDISPOPermission = userPermissions.includes("DISPO");
@@ -81,28 +120,6 @@ export const NewBookingModal = ({
} }
}, [isOpen, reset, setValue]); }, [isOpen, reset, setValue]);
const onSubmit = async (data: NewBookingFormData) => {
try {
// Validate that end time is after start time
if (new Date(data.endTime) <= new Date(data.startTime)) {
toast.error("Endzeit muss nach der Startzeit liegen");
return;
}
const response = await createBooking(data);
console.log("Booking created:", response);
toast.success("Buchung erfolgreich erstellt!");
onBookingCreated();
onClose();
router.refresh();
} catch (error) {
console.error("Error creating booking:", error);
toast.error("Fehler beim Erstellen der Buchung");
}
};
if (!isOpen) return null; if (!isOpen) return null;
return ( return (
@@ -120,16 +137,13 @@ export const NewBookingModal = ({
</div> </div>
{/* Form */} {/* Form */}
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6"> <form onSubmit={handleSubmit((data) => createBooking(data))} className="space-y-6">
{/* Resource Type Selection */} {/* Resource Type Selection */}
<div className="form-control"> <div className="form-control">
<label className="label"> <label className="label">
<span className="label-text font-semibold">Station *</span> <span className="label-text font-semibold">Station *</span>
</label> </label>
<select <select {...register("type")} className="select select-bordered w-full">
{...register("type", { required: "Bitte wählen Sie einen Typ aus" })}
className="select select-bordered w-full"
>
<option value="">Typ auswählen...</option> <option value="">Typ auswählen...</option>
<option value="STATION">Station</option> <option value="STATION">Station</option>
{hasDISPOPermission && ( {hasDISPOPermission && (
@@ -186,19 +200,16 @@ export const NewBookingModal = ({
Startzeit * Startzeit *
</span> </span>
</label> </label>
<input <DateInput
type="datetime-local" type="datetime-local"
{...register("startTime", { value={new Date(watch("startTime") || Date.now())}
required: "Startzeit ist erforderlich", onChange={(date) => {
onChange: (e) => { setValue("startTime", date.toISOString());
if (new Date(e.target.value) >= new Date(watch("endTime"))) { if (new Date(date) >= new Date(watch("endTime"))) {
const newEndTime = new Date( const newEndTime = new Date(new Date(date).getTime() + 60 * 60 * 3000);
new Date(e.target.value).getTime() + 60 * 60 * 3000,
);
setValue("endTime", newEndTime.toISOString().slice(0, 16)); setValue("endTime", newEndTime.toISOString().slice(0, 16));
} }
}, }}
})}
className="input input-bordered w-full" className="input input-bordered w-full"
/> />
{errors.startTime && ( {errors.startTime && (
@@ -215,9 +226,12 @@ export const NewBookingModal = ({
Endzeit * Endzeit *
</span> </span>
</label> </label>
<input <DateInput
type="datetime-local" type="datetime-local"
{...register("endTime", { required: "Endzeit ist erforderlich" })} value={new Date(watch("endTime") || Date.now())}
onChange={(date) => {
setValue("endTime", date.toISOString());
}}
className="input input-bordered w-full" className="input input-bordered w-full"
/> />
{errors.endTime && ( {errors.endTime && (

View File

@@ -12,7 +12,7 @@ export const DateInput = ({
<input <input
type="datetime-local" type="datetime-local"
className="input" className="input"
value={formatDate(value || new Date(), "yyyy-MM-dd hh:mm")} value={formatDate(value || new Date(), "yyyy-MM-dd HH:mm")}
onChange={(e) => { onChange={(e) => {
const date = e.target.value ? new Date(e.target.value) : null; const date = e.target.value ? new Date(e.target.value) : null;
if (!date) return; if (!date) return;