HUB - Admin und Einstellungen Seiten hinzugefügt, Prisma Client Integration und Migrationen aktualisiert

This commit is contained in:
PxlLoewe
2025-02-16 01:09:33 +01:00
parent a4bdc94aa1
commit 62ae71d6b6
28 changed files with 862 additions and 234 deletions

View File

@@ -0,0 +1,99 @@
import type { Metadata } from 'next';
import {
DiscordLogoIcon,
InstagramLogoIcon,
ReaderIcon,
} from '@radix-ui/react-icons';
import { HorizontalNav, VerticalNav } from '../_components/ui/Nav';
import { Toaster } from 'react-hot-toast';
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
};
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<div
className="hero min-h-screen"
style={{
backgroundImage:
'url(https://media.discordapp.net/attachments/1086051758461173931/1336779010109341766/d-hyan.PNG?ex=67b19238&is=67b040b8&hm=5d90bef8e44a8e620d759d1bebe0f1a3649b0f3cadc735bd9a06d5e6702f2d14&=&format=webp&quality=lossless)',
}}
>
<div className="hero-overlay bg-opacity-30"></div>
<div>
<Toaster position="top-center" reverseOrder={false} />
</div>
{/* Card */}
<div className="hero-content text-neutral-content text-center w-full max-w-full h-full m-10">
<div className="card bg-base-100 shadow-2xl w-full min-h-full h-full max-h-[calc(100vh-13rem)] p-4 flex flex-col mr-24 ml-24">
{/* Top Navbar */}
<HorizontalNav />
{/* Hauptlayout: Sidebar + Content (nimmt Resthöhe ein) */}
<div className="flex flex-grow overflow-hidden">
{/* Linke Sidebar */}
<VerticalNav />
{/* Scrollbarer Content-Bereich */}
<div className="flex-grow bg-base-100 p-6 rounded-lg shadow-md ml-4 overflow-auto h-full">
{children}
</div>
</div>
{/* Footer */}
<footer className="footer flex justify-between items-center p-4 bg-base-200 mt-4 rounded-lg shadow-md">
{/* Left: Impressum & Datenschutz */}
<div className="flex gap-4 text-sm">
<a href="/impressum" className="hover:text-primary">
Impressum
</a>
<a href="/datenschutz" className="hover:text-primary">
Datenschutzerklärung
</a>
</div>
{/* Center: Copyright */}
<p className="text-sm">
Copyright © {new Date().getFullYear()} - Virtual Air Rescue
</p>
{/* Right: Social Icons */}
<div className="flex gap-4">
<div className="tooltip tooltip-top" data-tip="Discord">
<a
href="https://discord.com"
target="_blank"
rel="noopener noreferrer"
className="hover:text-primary"
>
<DiscordLogoIcon className="w-5 h-5" />
</a>
</div>
<div className="tooltip tooltip-top" data-tip="Instagram">
<a
href="https://instagram.com"
target="_blank"
rel="noopener noreferrer"
className="hover:text-primary"
>
<InstagramLogoIcon className="w-5 h-5" />
</a>
</div>
<div className="tooltip tooltip-top" data-tip="Knowledgebase">
<a href="/docs" className="hover:text-primary">
<ReaderIcon className="w-5 h-5" />
</a>
</div>
</div>
</footer>
</div>
</div>
</div>
);
}

View File

@@ -1,6 +1,6 @@
import Link from 'next/link';
import { PaginatedTable } from './_components/PaginatedTable';
import { Header } from './_components/ui/Header';
import { PaginatedTable } from '../_components/PaginatedTable';
import { Header } from '../_components/ui/Header';
import { PrismaClient } from '@repo/db';
export default async function Home() {
@@ -30,15 +30,15 @@ export default async function Home() {
},
]}
/>
gd
Map
<br />
gd
Logbuch
<br />
gd
Einlog-Zeit (7 Tage, total)
<br />
gd
Stats
<br />
gd
Badges
<br />
gd
<br />

View File

@@ -0,0 +1,253 @@
'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import { DiscordAccount, User } from '@repo/db';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { unlinkDiscord, updateUser } from '../actions';
import { Toaster, toast } from 'react-hot-toast';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { Button } from '../../../../_components/ui/Button';
import {
PersonIcon,
EnvelopeClosedIcon,
BookmarkIcon,
DiscordLogoIcon,
PaperPlaneIcon,
Link2Icon,
MixerHorizontalIcon,
} from '@radix-ui/react-icons';
export const ProfileForm = ({ user }: { user: User }) => {
const schema = z.object({
firstname: z.string().min(2).max(30),
lastname: z.string().min(2).max(30),
email: z.string().email({
message: 'Bitte gebe eine gültige E-Mail Adresse ein',
}),
});
const [isLoading, setIsLoading] = useState(false);
type IFormInput = z.infer<typeof schema>;
const form = useForm<IFormInput>({
defaultValues: {
firstname: user.firstname,
lastname: user.lastname,
email: user.email,
},
resolver: zodResolver(schema),
});
return (
<form
className="card-body"
onSubmit={form.handleSubmit(async (values) => {
setIsLoading(true);
await updateUser(values);
form.reset(values);
setIsLoading(false);
toast.success('Deine Änderungen wurden gespeichert!', {
style: {
background:
'var(--fallback-b1, oklch(var(--b1) / var(--tw-bg-opacity, 1)))',
color:
'var(--fallback-nc, oklch(var(--nc) / var(--tw-text-opacity, 1)))',
},
});
})}
>
<h2 className="card-title">
<MixerHorizontalIcon className="w-5 h-5" /> Persönliche Informationen
</h2>
<div className="">
<label className="form-control w-full">
<div className="label">
<span className="label-text text-lg flex items-center gap-2">
<PersonIcon /> Vorname
</span>
</div>
<input
{...form.register('firstname')}
type="text"
className="input input-bordered w-full"
defaultValue={user.firstname}
placeholder="Vorname"
/>
</label>
{form.formState.errors.firstname && (
<p className="text-error">
{form.formState.errors.firstname.message}
</p>
)}
<label className="form-control w-full">
<div className="label">
<span className="label-text text-lg flex items-center gap-2">
<PersonIcon /> Nachname
</span>
</div>
<input
{...form.register('lastname')}
type="text"
className="input input-bordered w-full"
defaultValue={user.lastname}
placeholder="Nachname"
/>
</label>
{form.formState.errors.lastname && (
<p className="text-error">
{form.formState.errors.lastname?.message}
</p>
)}
<label className="form-control w-full">
<div className="label">
<span className="label-text text-lg flex items-center gap-2">
<EnvelopeClosedIcon /> E-Mail
</span>
</div>
<input
{...form.register('email')}
type="text"
className="input input-bordered w-full"
defaultValue={user.email}
placeholder="E-Mail"
/>
</label>
{form.formState.errors.email && (
<p className="text-error">{form.formState.errors.email?.message}</p>
)}
<div className="card-actions justify-center pt-6">
<Button
role="submit"
className="btn-sm btn-wide btn-outline btn-primary"
disabled={!form.formState.isDirty}
isLoading={isLoading}
>
<BookmarkIcon /> Speichern
</Button>
</div>
</div>
</form>
);
};
export const SocialForm = ({
discordAccount,
user,
}: {
discordAccount?: DiscordAccount;
user: User;
}) => {
const [isLoading, setIsLoading] = useState(false);
const [vatsimLoading, setVatsimLoading] = useState(false);
const router = useRouter();
const schema = z.object({
vatsimCid: z.number().min(1000).max(9999999),
});
type IFormInput = z.infer<typeof schema>;
const form = useForm<IFormInput>({
defaultValues: {
vatsimCid: user?.vatsimCid || undefined,
},
resolver: zodResolver(schema),
});
if (!user) return null;
return (
<form
className="card-body"
onSubmit={form.handleSubmit(async (values) => {
form.handleSubmit(async () => {
setVatsimLoading(true);
});
await updateUser({
vatsimCid: values.vatsimCid,
});
setVatsimLoading(false);
form.reset(values);
toast.success('Deine Änderungen wurden gespeichert!', {
style: {
background:
'var(--fallback-b1, oklch(var(--b1) / var(--tw-bg-opacity, 1)))',
color:
'var(--fallback-nc, oklch(var(--nc) / var(--tw-text-opacity, 1)))',
},
});
})}
>
<h2 className="card-title">
<Link2Icon className="w-5 h-5" /> Verbindungen & Benachrichtigungen
</h2>
<div>
<div>
<div className="label">
<span className="label-text text-lg flex items-center gap-2">
<DiscordLogoIcon /> Discord
</span>
</div>
{discordAccount ? (
<Button
className="btn-success btn-block btn-outline group transition-all duration-0 hover:btn-error"
isLoading={isLoading}
onClick={async () => {
setIsLoading(true);
await unlinkDiscord(user.id);
router.refresh();
setIsLoading(false);
}}
>
<DiscordLogoIcon className="w-5 h-5" />
<span className="group-hover:hidden">
Verbunden mit {discordAccount.username}
</span>
<span className="hidden group-hover:inline">
Verbindung trennen{isLoading && '...'}
</span>
</Button>
) : (
<a href={process.env.NEXT_PUBLIC_DISCORD_URL}>
<button className="btn btn-primary btn-block">
<DiscordLogoIcon className="w-5 h-5" /> Mit Discord verbinden
</button>
</a>
)}
</div>
</div>
<div className="content-center">
<label className="form-control w-full">
<div className="label">
<span className="label-text text-lg flex items-center gap-2">
<PaperPlaneIcon /> VATSIM-CID
</span>
</div>
<input
type="number"
className="input input-bordered w-full"
placeholder="1445241"
{...form.register('vatsimCid', {
valueAsNumber: true,
})}
/>
</label>
{form.formState.errors.vatsimCid && (
<p className="text-error">
{form.formState.errors.vatsimCid.message}
</p>
)}
</div>
<div className="card-actions justify-center pt-6 mt-auto">
<Button
className="btn-sm btn-wide btn-outline btn-primary"
isLoading={vatsimLoading}
disabled={!form.formState.isDirty}
role="submit"
>
<BookmarkIcon /> Speichern
</Button>
</div>
</form>
);
};

View File

@@ -0,0 +1,26 @@
'use server';
import { Prisma, PrismaClient } from '@repo/db';
import { getServerSession } from '../../../api/auth/[...nextauth]/auth';
export const unlinkDiscord = async (userId: string) => {
const client = new PrismaClient();
await client.discordAccount.deleteMany({
where: {
userId,
},
});
};
export const updateUser = async (changes: Prisma.UserUpdateInput) => {
const session = await getServerSession();
if (!session) return null;
const client = new PrismaClient();
await client.user.update({
where: {
id: session.user.id,
},
data: changes,
});
};

View File

@@ -0,0 +1,35 @@
import { getServerSession } from '../../../api/auth/[...nextauth]/auth';
import { PrismaClient } from '@repo/db';
import { ProfileForm, SocialForm } from './_components/forms';
import { GearIcon } from '@radix-ui/react-icons';
export default async () => {
const prisma = new PrismaClient();
const session = await getServerSession();
if (!session) return null;
const user = await prisma.user.findFirst({
where: {
id: session.user.id,
},
include: {
discordAccounts: true,
},
});
if (!user) return null;
const discordAccount = user?.discordAccounts[0];
return (
<div className="grid grid-cols-6 gap-4">
<div className="col-span-full">
<p className="text-2xl font-semibold text-left flex items-center gap-2">
<GearIcon className="w-5 h-5" /> Einstellungen
</p>
</div>
<div className="card bg-base-200 shadow-xl mb-4 col-span-6 xl:col-span-3">
<ProfileForm user={user} />
</div>
<div className="card bg-base-200 shadow-xl mb-4 col-span-6 xl:col-span-3">
<SocialForm discordAccount={discordAccount} user={user} />
</div>
</div>
);
};

View File

@@ -0,0 +1,8 @@
export default () => {
return (
<div>
<h1>Settings</h1>
<p>Settings page content</p>
</div>
);
};

View File

@@ -34,10 +34,6 @@ export const Register = () => {
const [isLoading, setIsLoading] = useState(false);
const cn = (...inputs: ClassValue[]) => {
return twMerge(clsx(inputs));
};
const form = useForm<IFormInput>({
resolver: zodResolver(schema),
defaultValues: {

View File

@@ -0,0 +1,25 @@
import { ButtonHTMLAttributes, DetailedHTMLProps } from 'react';
import { cn } from '../../../helper/cn';
export const Button = ({
isLoading,
...props
}: DetailedHTMLProps<
ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement
> & {
isLoading?: boolean;
}) => {
return (
<button
{...(props as any)}
className={cn('btn', props.className)}
disabled={isLoading || props.disabled}
>
{isLoading && (
<span className="loading loading-spinner loading-sm"></span>
)}
{props.children as any}
</button>
);
};

View File

@@ -0,0 +1,60 @@
import {
HomeIcon,
PersonIcon,
GearIcon,
ExitIcon,
} from '@radix-ui/react-icons';
import Link from 'next/link';
export const VerticalNav = () => {
return (
<div className="w-64 bg-base-300 p-4 rounded-lg shadow-md">
<ul className="menu">
<li>
<Link href="/">
<HomeIcon /> Dashboard
</Link>
</li>
<li>
<Link href="/profile">
<PersonIcon /> Profile
</Link>
</li>
<li>
<Link href="/settings/account">
<GearIcon />
Einstellungen
</Link>
</li>
</ul>
</div>
);
};
export const HorizontalNav = () => (
<div className="navbar bg-base-200 shadow-md rounded-lg mb-4">
<div className="flex-1">
<a className="btn btn-ghost normal-case text-xl">
Virtual Air Rescue - HUB
</a>
</div>
<div className="flex-none">
<ul className="flex space-x-2 px-1">
<li>
<Link href="/">
<button className="btn btn-sm btn-outline btn-primary">
Zur Leitstelle
</button>
</Link>
</li>
<li>
<Link href="/logout">
<button className="btn btn-sm">
<ExitIcon /> Logout
</button>
</Link>
</li>
</ul>
</div>
</div>
);

View File

@@ -0,0 +1,92 @@
import axios, { AxiosError } from 'axios';
import { NextRequest, NextResponse } from 'next/server';
import { DiscordAccount, PrismaClient } from '@repo/db';
import { getServerSession } from '../auth/[...nextauth]/auth';
export const GET = async (req: NextRequest) => {
const session = await getServerSession();
const prisma = new PrismaClient();
const code = req.nextUrl.searchParams.get('code');
if (!session) {
return NextResponse.redirect(`${process.env.NEXTAUTH_URL}/login`);
}
if (
!process.env.DISCORD_OAUTH_CLIENT_ID ||
!process.env.DISCORD_OAUTH_SECRET ||
!process.env.DISCORD_REDIRECT ||
!code
) {
return NextResponse.json(
{
error: 'Discord OAuth not configured',
},
{
status: 500,
}
);
}
const params = new URLSearchParams({
client_id: process.env.DISCORD_OAUTH_CLIENT_ID,
client_secret: process.env.DISCORD_OAUTH_SECRET,
redirect_uri: process.env.DISCORD_REDIRECT,
grant_type: 'authorization_code',
code,
});
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
};
try {
const { data: authData } = await axios.post(
'https://discord.com/api/oauth2/token',
params,
{
headers,
}
);
const { data: discordUser } = await axios.get(
'https://discord.com/api/users/@me',
{
headers: {
Authorization: `Bearer ${authData.access_token}`,
},
}
);
const discordObject = {
userId: session.user.id,
accessToken: authData.access_token,
refreshToken: authData.refresh_token,
discordId: discordUser.id,
email: discordUser.email,
avatar: discordUser.avatar,
username: discordUser.username,
globalName: discordUser.global_name,
verified: discordUser.verified,
tokenType: authData.token_type,
} as DiscordAccount;
const discord = await prisma.discordAccount.upsert({
where: { discordId: discordUser.id },
update: discordObject, // Updates if found
create: discordObject, // Creates if not found
});
return NextResponse.redirect(
`${process.env.NEXTAUTH_URL}/settings/account`
);
} catch (error: any) {
console.error(error);
return NextResponse.json(
{
error: "Couldn't connect to Discord",
},
{
status: 500,
}
);
}
};

View File

@@ -5,4 +5,5 @@
:root {
--background: #ffffff;
--foreground: #171717;
}
/* --p: 47.67% 0.2484 267.02; */
}

View File

@@ -1,169 +1,35 @@
import Link from "next/link";
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { getServerSession } from "next-auth";
import { NextAuthSessionProvider } from "./_components/AuthSessionProvider";
import { options } from "./api/auth/[...nextauth]/auth";
import {
ExitIcon,
DiscordLogoIcon,
InstagramLogoIcon,
ReaderIcon,
HomeIcon,
PersonIcon,
GearIcon,
} from "@radix-ui/react-icons";
import { getServerSession } from "./api/auth/[...nextauth]/auth";
import './globals.css';
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
variable: '--font-geist-sans',
subsets: ['latin'],
});
const geistMono = Geist_Mono({
variable: '--font-geist-mono',
subsets: ['latin'],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const session = await getServerSession(options);
return (
<html lang="en">
<NextAuthSessionProvider session={session}>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<div
className="hero min-h-screen"
style={{
backgroundImage:
"url(https://media.discordapp.net/attachments/1086051758461173931/1336779010109341766/d-hyan.PNG?ex=67b19238&is=67b040b8&hm=5d90bef8e44a8e620d759d1bebe0f1a3649b0f3cadc735bd9a06d5e6702f2d14&=&format=webp&quality=lossless)",
}}
export default async ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
const session = await getServerSession();
return (
<html lang="en">
<NextAuthSessionProvider session={session}>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<div className="hero-overlay bg-opacity-30"></div>
{/* Card */}
<div className="hero-content text-neutral-content text-center w-full max-w-full h-full m-10">
<div className="card bg-base-100 shadow-2xl w-full min-h-full h-full max-h-[calc(100vh-13rem)] p-4 flex flex-col mr-24 ml-24">
{/* Top Navbar */}
<div className="navbar bg-base-200 shadow-md rounded-lg mb-4">
<div className="flex-1">
<a className="btn btn-ghost normal-case text-xl">
Virtual Air Rescue - HUB
</a>
</div>
<div className="flex-none">
<ul className="flex space-x-2 px-1">
<li>
<Link href="/">
<button className="btn btn-sm btn-outline btn-info">
Zum Dispatch
</button>
</Link>
</li>
<li>
<Link href="/logout">
<button className="btn btn-sm">
<ExitIcon /> Logout
</button>
</Link>
</li>
</ul>
</div>
</div>
{/* Hauptlayout: Sidebar + Content (nimmt Resthöhe ein) */}
<div className="flex flex-grow overflow-hidden">
{/* Linke Sidebar */}
<div className="w-64 bg-base-300 p-4 rounded-lg shadow-md">
<ul className="menu">
<li>
<a>
<HomeIcon /> Dashboard
</a>
</li>
<li>
<a>
<PersonIcon /> Profile
</a>
</li>
<li>
<a>
<GearIcon /> Settings
</a>
</li>
</ul>
</div>
{/* Scrollbarer Content-Bereich */}
<div className="flex-grow bg-base-100 p-6 rounded-lg shadow-md ml-4 overflow-auto h-full">
{children}
</div>
</div>
{/* Footer */}
<footer className="footer flex justify-between items-center p-4 bg-base-200 mt-4 rounded-lg shadow-md">
{/* Left: Impressum & Datenschutz */}
<div className="flex gap-4 text-sm">
<a href="/impressum" className="hover:text-primary">
Impressum
</a>
<a href="/datenschutz" className="hover:text-primary">
Datenschutzerklärung
</a>
</div>
{/* Center: Copyright */}
<p className="text-sm">
Copyright © {new Date().getFullYear()} - VAR Luftretung
</p>
{/* Right: Social Icons */}
<div className="flex gap-4">
<div className="tooltip tooltip-top" data-tip="Discord">
<a
href="https://discord.com"
target="_blank"
rel="noopener noreferrer"
className="hover:text-primary"
>
<DiscordLogoIcon className="w-5 h-5" />
</a>
</div>
<div className="tooltip tooltip-top" data-tip="Instagram">
<a
href="https://instagram.com"
target="_blank"
rel="noopener noreferrer"
className="hover:text-primary"
>
<InstagramLogoIcon className="w-5 h-5" />
</a>
</div>
<div
className="tooltip tooltip-top"
data-tip="Knowledgebase"
>
<a href="/docs" className="hover:text-primary">
<ReaderIcon className="w-5 h-5" />
</a>
</div>
</div>
</footer>
</div>
</div>
</div>
</body>
</NextAuthSessionProvider>
</html>
);
}
{children}
</body>
</NextAuthSessionProvider>
</html>
)
}

6
apps/hub/helper/cn.ts Normal file
View File

@@ -0,0 +1,6 @@
import clsx, { ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export const cn = (...inputs: ClassValue[]) => {
return twMerge(clsx(inputs));
};

View File

@@ -12,7 +12,9 @@
"@hookform/resolvers": "^3.10.0",
"@next-auth/prisma-adapter": "^1.0.7",
"@repo/ui": "*",
"@repo/db": "*",
"@tanstack/react-table": "^8.20.6",
"axios": "^1.7.9",
"bcryptjs": "^2.4.3",
"clsx": "^2.1.1",
"jsonwebtoken": "^9.0.2",

View File

@@ -6,13 +6,5 @@ export default {
'./components/**/*.{js,ts,jsx,tsx,mdx}',
'./app/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {
colors: {
background: 'var(--background)',
foreground: 'var(--foreground)',
},
},
},
plugins: [require('daisyui')],
} satisfies Config;