Error boundary

This commit is contained in:
PxlLoewe
2025-03-26 14:04:15 -07:00
parent 9551202370
commit c8d91b684f
21 changed files with 414 additions and 298 deletions

View File

@@ -1,13 +1,13 @@
import { prisma } from '@repo/db';
import { StationForm } from '../_components/Form';
import { prisma } from "@repo/db";
import { KeywordForm } from "../_components/Form";
export default async ({ params }: { params: Promise<{ id: string }> }) => {
const { id } = await params;
const station = await prisma.station.findUnique({
where: {
id: parseInt(id),
},
});
if (!station) return <div>Station not found</div>;
return <StationForm station={station} />;
const { id } = await params;
const keyword = await prisma.keyword.findUnique({
where: {
id: parseInt(id),
},
});
if (!keyword) return <div>Station not found</div>;
return <KeywordForm keyword={keyword} />;
};

View File

@@ -1,20 +1,20 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { StationOptionalDefaultsSchema } from "@repo/db/zod";
import { KeywordOptionalDefaultsSchema } from "@repo/db/zod";
import { set, useForm } from "react-hook-form";
import { z } from "zod";
import { BosUse, Country, Station } from "@repo/db";
import { BosUse, Country, KEYWORD_CATEGORY, Keyword } from "@repo/db";
import { FileText, LocateIcon, PlaneIcon } from "lucide-react";
import { Input } from "../../../../_components/ui/Input";
import { useState } from "react";
import { deleteStation, upsertStation } from "../action";
import { deleteKeyword, upsertKeyword } from "../action";
import { Button } from "../../../../_components/ui/Button";
import { redirect } from "next/navigation";
export const StationForm = ({ station }: { station?: Station }) => {
const form = useForm<z.infer<typeof StationOptionalDefaultsSchema>>({
resolver: zodResolver(StationOptionalDefaultsSchema),
defaultValues: station,
export const KeywordForm = ({ keyword }: { keyword?: Keyword }) => {
const form = useForm<z.infer<typeof KeywordOptionalDefaultsSchema>>({
resolver: zodResolver(KeywordOptionalDefaultsSchema),
defaultValues: keyword,
});
const [loading, setLoading] = useState(false);
const [deleteLoading, setDeleteLoading] = useState(false);
@@ -23,85 +23,26 @@ export const StationForm = ({ station }: { station?: Station }) => {
<form
onSubmit={form.handleSubmit(async (values) => {
setLoading(true);
const createdStation = await upsertStation(values, station?.id);
const createdKeyword = await upsertKeyword(values, keyword?.id);
setLoading(false);
if (!station) redirect(`/admin/station`);
if (!keyword) redirect(`/admin/keyword`);
})}
className="grid grid-cols-6 gap-3"
>
<div className="card bg-base-200 shadow-xl col-span-2 max-xl:col-span-6">
<div className="card bg-base-200 shadow-xl col-span-6 ">
<div className="card-body">
<h2 className="card-title">
<FileText className="w-5 h-5" /> Allgemeines
</h2>
<Input
form={form}
label="BOS Rufname"
name="bosCallsign"
className="input-sm"
/>
<Input
form={form}
label="BOS Rufname (kurz)"
name="bosCallsignShort"
className="input-sm"
/>
<Input
form={form}
label="Betreiber"
name="operator"
className="input-sm"
/>
<Input
form={form}
label="ATC Rufname"
name="atcCallsign"
className="input-sm"
/>
<Input
form={form}
label="FIR (Flight Information Region)"
name="fir"
className="input-sm"
/>
<Input
form={form}
label="Leitstelle Rufname"
name="bosRadioArea"
className="input-sm"
/>
<label className="form-control w-full">
<label className="form-control w-full ">
<span className="label-text text-lg flex items-center gap-2">
BOS Nutzung
Kategorie
</span>
<select
className="input-sm select select-bordered select-sm"
{...form.register("bosUse")}
className="input-sm select select-bordered select-sm w-full"
{...form.register("category")}
>
{Object.keys(BosUse).map((use) => (
<option key={use} value={use}>
{use}
</option>
))}
</select>
</label>
</div>
</div>
<div className="card bg-base-200 shadow-xl col-span-2 max-xl:col-span-6">
<div className="card-body">
<h2 className="card-title">
<LocateIcon className="w-5 h-5" /> Standort + Ausrüstung
</h2>
<label className="form-control w-full">
<span className="label-text text-lg flex items-center gap-2">
Land
</span>
<select
className="input-sm select select-bordered select-sm"
{...form.register("country", {})}
>
{Object.keys(Country).map((use) => (
{Object.keys(KEYWORD_CATEGORY).map((use) => (
<option key={use} value={use}>
{use}
</option>
@@ -110,109 +51,33 @@ export const StationForm = ({ station }: { station?: Station }) => {
</label>
<Input
form={form}
label="Bundesland"
name="locationState"
label="Abkürzung"
name="abreviation"
className="input-sm"
/>
<Input
form={form}
label="Bundesland (kurz)"
name="locationStateShort"
label="Name"
placeholder="Atembeschwerden, die nicht zunehmen (ohne vitale Indikation)"
name="name"
className="input-sm"
/>
<span className="label-text text-lg flex items-center gap-2">
Ausgerüstet mit:
</span>
<div className="form-control">
<label className="label cursor-pointer">
<span>Winde</span>
<input
type="checkbox"
className="toggle"
{...form.register("hasWinch")}
/>
</label>
<label className="label cursor-pointer">
<span>Nachtsicht Gerät</span>
<input
type="checkbox"
className="toggle"
{...form.register("hasNvg")}
/>
</label>
<label className="label cursor-pointer">
<span>24-Stunden Einsatzfähig</span>
<input
type="checkbox"
className="toggle"
{...form.register("is24h")}
/>
</label>
<label className="label cursor-pointer">
<span>Bergetau</span>
<input
type="checkbox"
className="toggle"
{...form.register("hasRope")}
/>
</label>
</div>
<Input
form={form}
label="zunehmende Atembeschwerden"
placeholder="Beschreibung"
name="description"
className="input-sm"
/>
<Input
form={form}
label="HPG Missionstypen"
name="hpgMissionsType"
className="input-sm"
/>
</div>
</div>
<Input
form={form}
label="Breitengrad"
name="latitude"
className="input-sm"
formOptions={{ valueAsNumber: true }}
type="number"
step="any"
/>
<Input
form={form}
label="Längengrad"
name="longitude"
className="input-sm"
formOptions={{ valueAsNumber: true }}
type="number"
step="any"
/>
<label className="label cursor-pointer">
<span className="text-lg">Reichweiten ausblenden</span>
<input
type="checkbox"
className="toggle"
{...form.register("hideRangeRings")}
/>
</label>
</div>
</div>
<div className="card bg-base-200 shadow-xl col-span-2 max-xl:col-span-6">
<div className="card-body">
<h2 className="card-title">
<PlaneIcon className="w-5 h-5" /> Hubschrauber
</h2>
<Input
form={form}
label="Hubschrauber Typ"
name="aircraft"
className="input-sm"
/>
<Input
form={form}
formOptions={{ valueAsNumber: true }}
type="number"
label="Hubschrauber Geschwindigkeit"
className="input-sm"
name="aircraftSpeed"
/>
<Input
form={form}
label="Hubschrauber Registrierung"
name="aircraftRegistration"
className="input-sm"
/>
</div>
</div>
<div className="card bg-base-200 shadow-xl col-span-6">
<div className="card-body ">
<div className="flex w-full gap-4">
@@ -223,13 +88,13 @@ export const StationForm = ({ station }: { station?: Station }) => {
>
Speichern
</Button>
{station && (
{keyword && (
<Button
isLoading={deleteLoading}
onClick={async () => {
setDeleteLoading(true);
await deleteStation(station.id);
redirect("/admin/station");
await deleteKeyword(keyword.id);
redirect("/admin/keyword");
}}
className="btn btn-error"
>

View File

@@ -1,20 +1,20 @@
"use server";
import { prisma, Prisma, Station } from "@repo/db";
import { prisma, Prisma, Keyword } from "@repo/db";
export const upsertKeyword = async (
station: Prisma.StationCreateInput,
id?: Station["id"],
keyword: Prisma.KeywordCreateInput,
id?: Keyword["id"],
) => {
const newStation = id
? await prisma.station.update({
const newKeyword = id
? await prisma.keyword.update({
where: { id: id },
data: station,
data: keyword,
})
: await prisma.station.create({ data: station });
return newStation;
: await prisma.keyword.create({ data: keyword });
return newKeyword;
};
export const deleteStation = async (id: Station["id"]) => {
await prisma.station.delete({ where: { id: id } });
export const deleteKeyword = async (id: Keyword["id"]) => {
await prisma.keyword.delete({ where: { id: id } });
};

View File

@@ -13,7 +13,7 @@ export default async ({ children }: { children: React.ReactNode }) => {
},
});
if (!user?.permissions.includes("ADMIN_STATION"))
if (!user?.permissions.includes("ADMIN_KEYWORD"))
return <Error title="Keine Berechtigung" statusCode={403} />;
return <>{children}</>;

View File

@@ -1,5 +1,5 @@
import { StationForm } from '../_components/Form';
import { KeywordForm } from "../_components/Form";
export default () => {
return <StationForm />;
return <KeywordForm />;
};

View File

@@ -1,47 +1,43 @@
import { DatabaseBackupIcon } from 'lucide-react';
import { PaginatedTable } from '../../../_components/PaginatedTable';
import Link from 'next/link';
import { DatabaseBackupIcon } from "lucide-react";
import { PaginatedTable } from "../../../_components/PaginatedTable";
import Link from "next/link";
export default () => {
return (
<>
<PaginatedTable
showEditButton
prismaModel="station"
searchFields={['bosCallsign', 'bosUse', 'country', 'operator']}
columns={[
{
header: 'BOS Name',
accessorKey: 'bosCallsign',
},
{
header: 'Bos Use',
accessorKey: 'bosUse',
},
{
header: 'Country',
accessorKey: 'country',
},
{
header: 'operator',
accessorKey: 'operator',
},
]}
leftOfSearch={
<span className="flex items-center gap-2">
<DatabaseBackupIcon className="w-5 h-5" /> Stationen
</span>
}
rightOfSearch={
<p className="text-2xl font-semibold text-left flex items-center gap-2 justify-between">
<Link href={'/admin/station/new'}>
<button className="btn btn-sm btn-outline btn-primary">
Erstellen
</button>
</Link>
</p>
}
/>
</>
);
return (
<>
<PaginatedTable
showEditButton
prismaModel="keyword"
searchFields={["name", "abreviation", "description"]}
columns={[
{
header: "Kateogrie",
accessorKey: "category",
},
{
header: "Name",
accessorKey: "name",
},
{
header: "Beschreibung",
accessorKey: "description",
},
]}
leftOfSearch={
<span className="flex items-center gap-2">
<DatabaseBackupIcon className="w-5 h-5" /> Stichwörter
</span>
}
rightOfSearch={
<p className="text-2xl font-semibold text-left flex items-center gap-2 justify-between">
<Link href={"/admin/keyword/new"}>
<button className="btn btn-sm btn-outline btn-primary">
Erstellen
</button>
</Link>
</p>
}
/>
</>
);
};

View File

@@ -123,33 +123,35 @@ export const StationForm = ({ station }: { station?: Station }) => {
<span className="label-text text-lg flex items-center gap-2">
Ausgerüstet mit:
</span>
<div className="form-control">
<label className="label cursor-pointer">
<span>Winde</span>
<div className="form-control space-y-2">
<label className="label cursor-pointer flex">
<span className="flex-1 text-left">Winde</span>
<input
type="checkbox"
className="toggle"
{...form.register("hasWinch")}
/>
</label>
<label className="label cursor-pointer">
<span>Nachtsicht Gerät</span>
<label className="label cursor-pointer flex">
<span className="flex-1 text-left">Nachtsicht gerät</span>
<input
type="checkbox"
className="toggle"
{...form.register("hasNvg")}
/>
</label>
<label className="label cursor-pointer">
<span>24-Stunden Einsatzfähig</span>
<label className="label cursor-pointer flex">
<span className="flex-1 text-left">
24-Stunden Einsatzfähig
</span>
<input
type="checkbox"
className="toggle"
{...form.register("is24h")}
/>
</label>
<label className="label cursor-pointer">
<span>Bergetau</span>
<label className="label cursor-pointer flex">
<span className="flex-1 text-left">Bergetau</span>
<input
type="checkbox"
className="toggle"
@@ -176,8 +178,10 @@ export const StationForm = ({ station }: { station?: Station }) => {
type="number"
step="any"
/>
<label className="label cursor-pointer">
<span className="text-lg">Reichweiten ausblenden</span>
<label className="label cursor-pointer flex">
<span className="text-lg flex-1 text-left">
Reichweiten ausblenden
</span>
<input
type="checkbox"
className="toggle"

View File

@@ -1,5 +1,7 @@
"use client";
import { Error as ErrorComp } from "_components/Error";
import { ErrorBoundary } from "react-error-boundary";
import { NextPage } from "next";
import { ReactNode } from "react";
const AuthLayout: NextPage<
Readonly<{
@@ -15,11 +17,30 @@ const AuthLayout: NextPage<
>
<div className="hero-overlay bg-neutral/60"></div>
<div className="hero-content text-center ">
<div className="max-w-lg">
<div className="card rounded-2xl bg-base-100 w-full min-w-[500px] shadow-2xl max-md:min-w-[400px]">
{children}
<ErrorBoundary
fallbackRender={({ error, resetErrorBoundary }) => {
console.log(error);
let errorTest;
let errorCode = 500;
if ("statusCode" in error) {
errorCode = error.statusCode;
}
if ("message" in error || error instanceof Error) {
errorTest = error.message;
} else if (typeof error === "string") {
errorTest = error;
} else {
errorTest = "Ein unerwarteter Fehler ist aufgetreten.";
}
return <ErrorComp title={errorTest} statusCode={errorCode} />;
}}
>
<div className="max-w-lg">
<div className="card rounded-2xl bg-base-100 w-full min-w-[500px] shadow-2xl max-md:min-w-[400px]">
{children}
</div>
</div>
</div>
</ErrorBoundary>
</div>
</div>
);

View File

@@ -8,8 +8,10 @@ import { useForm } from "react-hook-form";
import { Toaster, toast } from "react-hot-toast";
import { z } from "zod";
import { Button } from "../../../_components/ui/Button";
import { useErrorBoundary } from "react-error-boundary";
export const Login = () => {
const { showBoundary } = useErrorBoundary();
const [isLoading, setIsLoading] = useState(false);
const searchParams = useSearchParams();
const schema = z.object({
@@ -28,22 +30,26 @@ export const Login = () => {
className="card-body"
onSubmit={form.handleSubmit(async () => {
setIsLoading(true);
const data = await signIn("credentials", {
redirect: false,
email: form.getValues("email"),
password: form.getValues("password"),
});
setIsLoading(false);
if (!data || data.error) {
toast.error("E-Mail / Passwort ist falsch!", {
style: {
background: "var(--color-base-100)",
color: "var(--color-base-content)",
},
try {
const data = await signIn("credentials", {
redirect: false,
email: form.getValues("email"),
password: form.getValues("password"),
});
return;
setIsLoading(false);
if (!data || data.error) {
toast.error("E-Mail / Passwort ist falsch!", {
style: {
background: "var(--color-base-100)",
color: "var(--color-base-content)",
},
});
return;
}
redirect(searchParams.get("redirect") || "/");
} catch (error) {
showBoundary(error);
}
redirect(searchParams.get("redirect") || "/");
})}
>
<div>
@@ -99,6 +105,11 @@ export const Login = () => {
className="grow"
/>
</label>
<span className="text-sm font-medium flex justify-end">
<Link href="/passwort-reset" className="link link-accent link-hover ">
Passwort vergessen?
</Link>
</span>
<div className="card-actions mt-6">
<Button
disabled={isLoading}

View File

@@ -3,8 +3,10 @@ import { redirect, useSearchParams } from "next/navigation";
import { Service } from "../page";
import { generateToken } from "./action";
import { useSession } from "next-auth/react";
import { useErrorBoundary } from "react-error-boundary";
export const Authorize = ({ service }: { service: Service }) => {
const { showBoundary } = useErrorBoundary();
const searchParams = useSearchParams();
const legitimeUrl = service.approvedUrls.some((url) =>
searchParams.get("redirect_uri")?.startsWith(url),
@@ -35,15 +37,19 @@ export const Authorize = ({ service }: { service: Service }) => {
type="submit"
className="btn btn-primary"
onClick={async () => {
const code = await generateToken(service);
const url = new URL(searchParams.get("redirect_uri") as string);
url.searchParams.append("code", code?.accessToken as string);
url.searchParams.append(
"state",
searchParams.get("state") as string,
);
try {
const code = await generateToken(service);
const url = new URL(searchParams.get("redirect_uri") as string);
url.searchParams.append("code", code?.accessToken as string);
url.searchParams.append(
"state",
searchParams.get("state") as string,
);
window.location.href = url.href;
window.location.href = url.href;
} catch (error) {
showBoundary(error);
}
}}
>
Zulassen

View File

@@ -0,0 +1,97 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Toaster, toast } from "react-hot-toast";
import { z } from "zod";
import { Button } from "../../../_components/ui/Button";
import { resetPassword } from "(auth)/passwort-reset/action";
import { useErrorBoundary } from "react-error-boundary";
export const PasswortReset = () => {
const { showBoundary } = useErrorBoundary();
const [isLoading, setIsLoading] = useState(false);
const schema = z.object({
email: z.string().email(),
});
const navigate = useRouter();
type schemaType = z.infer<typeof schema>;
const form = useForm<schemaType>({
resolver: zodResolver(schema),
});
return (
<form
className="card-body"
onSubmit={form.handleSubmit(async () => {
try {
setIsLoading(true);
const { error } = await resetPassword(form.getValues().email);
setIsLoading(false);
if (error) {
return toast.error(error, {
style: {
background: "var(--color-base-100)",
color: "var(--color-base-content)",
},
});
}
toast.success("Passwort wurde zurückgesetzt!", {
style: {
background: "var(--color-base-100)",
color: "var(--color-base-content)",
},
});
navigate.push("/login");
} catch (error) {
showBoundary(error);
}
})}
>
<div>
<Toaster position="top-center" reverseOrder={false} />
</div>
<h1 className="text-3xl font-bold">Passwort zurücksetzen</h1>
<label className="input input-bordered flex items-center gap-2 w-full">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
fill="currentColor"
className="h-4 w-4 opacity-70"
>
<path d="M2.5 3A1.5 1.5 0 0 0 1 4.5v.793c.026.009.051.02.076.032L7.674 8.51c.206.1.446.1.652 0l6.598-3.185A.755.755 0 0 1 15 5.293V4.5A1.5 1.5 0 0 0 13.5 3h-11Z" />
<path d="M15 6.954 8.978 9.86a2.25 2.25 0 0 1-1.956 0L1 6.954V11.5A1.5 1.5 0 0 0 2.5 13h11a1.5 1.5 0 0 0 1.5-1.5V6.954Z" />
</svg>
<input
type="text"
className="grow"
{...form.register("email")}
placeholder="Email"
/>
</label>
<p className="text-error">
{typeof form.formState.errors.email?.message === "string"
? form.formState.errors.email.message
: ""}
</p>
<span className="text-sm font-medium flex justify-end">
<Link href="/passwort-reset" className="link link-accent link-hover ">
Passwort vergessen?
</Link>
</span>
<div className="card-actions mt-6">
<Button
disabled={isLoading}
isLoading={isLoading}
className="btn btn-primary btn-block"
>
Login
</Button>
</div>
</form>
);
};

View File

@@ -0,0 +1,42 @@
"use server";
import { prisma } from "@repo/db";
import { sendMailByTemplate } from "../../../helper/mail";
import bcrypt from "bcryptjs";
export const resetPassword = async (email: string) => {
try {
const user = await prisma.user.findFirst({
where: {
email,
},
});
if (!user) {
return { error: "Nutzer nicht gefunden" };
}
const password = Math.random().toString(36).slice(-8);
const hashedPassword = await bcrypt.hash(password, 15);
await prisma.user.update({
where: {
email,
},
data: {
password: hashedPassword,
},
});
await sendMailByTemplate(user.email, "password-change", {
user: user,
password: password,
});
return {};
} catch (error) {
if (error instanceof Error) {
return { error: error.message };
} else {
return { error: "Ein Fehler ist aufgetreten" };
}
}
};

View File

@@ -0,0 +1,9 @@
import { PasswortReset } from "./_components/PasswortReset";
export default async () => {
return (
<>
<PasswortReset />
</>
);
};

View File

@@ -9,8 +9,10 @@ import { useState } from "react";
import clsx, { ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
import { Button } from "../../../_components/ui/Button";
import { useErrorBoundary } from "react-error-boundary";
export const Register = () => {
const { showBoundary } = useErrorBoundary();
const schema = z
.object({
email: z.string().email({
@@ -48,20 +50,24 @@ export const Register = () => {
<form
className="card-body"
onSubmit={form.handleSubmit(async () => {
setIsLoading(true);
const values = form.getValues();
const user = await register({
email: form.getValues("email"),
password: form.getValues("password"),
firstname: form.getValues("firstname"),
lastname: form.getValues("lastname"),
});
await signIn("credentials", {
callbackUrl: "/",
email: user.email,
password: values.password,
});
setIsLoading(false);
try {
setIsLoading(true);
const values = form.getValues();
const user = await register({
email: form.getValues("email"),
password: form.getValues("password"),
firstname: form.getValues("firstname"),
lastname: form.getValues("lastname"),
});
await signIn("credentials", {
callbackUrl: "/",
email: user.email,
password: values.password,
});
setIsLoading(false);
} catch (error) {
showBoundary(error);
}
})}
>
<h1 className="text-3xl font-bold">Registrierung</h1>

View File

@@ -1,5 +1,7 @@
"use client";
import { useEffect } from "react";
export const Error = ({
statusCode,
title,
@@ -8,8 +10,8 @@ export const Error = ({
title: string;
}) => {
return (
<div className="flex items-center justify-center ">
<div className="shadow-lg rounded-2xl p-8 text-center max-w-md w-full ">
<div className="flex-1 flex items-center justify-center h-full">
<div className="rounded-2xl bg-base-300 p-8 text-center max-w-md w-full">
<h1 className="text-6xl font-bold text-red-500">{statusCode}</h1>
<p className="text-xl font-semibold mt-4">
Oh nein! Ein Fehler ist aufgetreten.
@@ -27,3 +29,30 @@ export const Error = ({
</div>
);
};
export const ErrorFallback = ({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) => {
useEffect(() => {
// Log the error to an error reporting service
console.error(error);
}, [error]);
return (
<div>
<h2>Something went wrong!</h2>
<button
onClick={
// Attempt to recover by trying to re-render the segment
() => reset()
}
>
Try again
</button>
</div>
);
};

View File

@@ -48,6 +48,9 @@ export const VerticalNav = () => {
<li>
<Link href="/admin/station">Stationen</Link>
</li>
<li>
<Link href="/admin/keyword">Stichworte</Link>
</li>
<li>
<Link href="/admin/event">Events</Link>
</li>

View File

@@ -32,6 +32,7 @@
"react-datepicker": "^8.1.0",
"react-day-picker": "^9.6.2",
"react-dom": "^19.0.0",
"react-error-boundary": "^5.0.0",
"react-hook-form": "^7.54.2",
"react-hot-toast": "^2.5.1",
"react-select": "^5.10.0",