Refactor admin area and remove legacy root paths
CI / quality (push) Waiting to run

This commit is contained in:
MOH
2026-03-13 16:14:04 +01:00
parent e32ac4cacb
commit db897e22bf
65 changed files with 216 additions and 140 deletions
-29
View File
@@ -1,29 +0,0 @@
import type { Metadata } from "next";
type RootLayoutProps = {
children: React.ReactNode;
};
export const metadata: Metadata = {
robots: {
index: false,
follow: false,
nocache: true,
googleBot: {
index: false,
follow: false,
noimageindex: true,
"max-image-preview": "none",
"max-snippet": -1,
"max-video-preview": -1,
},
},
};
export default function RootLayout({ children }: RootLayoutProps) {
return (
<div dir="ltr" lang="de" className="font-latin">
{children}
</div>
);
}
-43
View File
@@ -1,43 +0,0 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { routing } from "@/i18n/routing";
import { toInternalAdminPath } from "@/lib/admin-routing";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getLocalizedPath } from "@/lib/locale";
import { setMaintenanceMode } from "@/lib/app-config";
async function ensureAdmin() {
if (!(await isAdminAuthenticated())) {
await clearAdminSessionCookie();
redirect("/");
}
}
export async function updateMaintenanceModeAction(formData: FormData) {
await ensureAdmin();
const nextValue = formData.get("enabled") === "true";
const redirectPath = String(formData.get("redirectPath") ?? "/");
const redirectUrl = new URL(redirectPath, "http://localhost");
redirectUrl.searchParams.set(
"success",
nextValue ? "Wartungsmodus aktiviert." : "Wartungsmodus deaktiviert.",
);
await setMaintenanceMode(nextValue);
revalidatePath("/", "layout");
revalidatePath("/coming-soon");
revalidatePath(toInternalAdminPath("/"));
revalidatePath(toInternalAdminPath("/maintenance"));
revalidatePath(toInternalAdminPath(redirectUrl.pathname));
for (const appLocale of routing.locales) {
revalidatePath(getLocalizedPath(appLocale), "layout");
revalidatePath(getLocalizedPath(appLocale, "/coming-soon"));
}
redirect(`${redirectUrl.pathname}${redirectUrl.search}`);
}
-68
View File
@@ -1,68 +0,0 @@
import { redirect } from "next/navigation";
import { MotionFade } from "@/components/motion-fade";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getMaintenanceMode } from "@/lib/app-config";
import { AppCard } from "@/components/ui/app-card";
import { Badge } from "@/components/ui/badge";
import { CardContent } from "@/components/ui/card";
export const dynamic = "force-dynamic";
const copy = {
title: "Wartungsmodus",
subtitle: "Steuerung fuer den globalen Wartungsstatus.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "Settings",
portfolio: "Portfolio",
maintenanceText: "Wenn aktiv, werden alle Seiten auf die Coming Soon Seite weitergeleitet.",
maintenanceOn: "Aktiv",
maintenanceOff: "Inaktiv",
selectHint: "Aenderung erfolgt jetzt direkt ueber den Schalter in der Sidebar.",
logout: "Ausloggen",
backToSite: "Zur Website",
};
export default async function RootMaintenancePage() {
const authenticated = await isAdminAuthenticated();
if (!authenticated) {
redirect("/");
}
const maintenanceEnabled = await getMaintenanceMode();
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
return (
<RootDashboardShell
copy={copy}
active="maintenance"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
>
<MotionFade delay={0.1}>
<AppCard>
<CardContent className="space-y-4 p-6">
<p className="text-sm text-muted-foreground">{copy.maintenanceText}</p>
<div className="flex flex-wrap items-center gap-3">
<Badge variant={maintenanceEnabled ? "warning" : "success"}>
{maintenanceEnabled ? copy.maintenanceOn : copy.maintenanceOff}
</Badge>
<p className="text-xs text-muted-foreground">{copy.selectHint}</p>
</div>
</CardContent>
</AppCard>
</MotionFade>
</RootDashboardShell>
);
}
-84
View File
@@ -1,84 +0,0 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { isRedirectError } from "next/dist/client/components/redirect-error";
import { toInternalAdminPath } from "@/lib/admin-routing";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { updateMarqueeSettings } from "@/lib/app-config";
import { routing } from "@/i18n/routing";
import { getLocalizedPath } from "@/lib/locale";
async function ensureAdmin() {
if (!(await isAdminAuthenticated())) {
await clearAdminSessionCookie();
redirect("/");
}
}
function withMessage(pathname: string, type: "success" | "error", message: string) {
const params = new URLSearchParams();
params.set(type, message);
return `${pathname}?${params.toString()}`;
}
async function revalidateMarqueePages() {
revalidatePath(toInternalAdminPath("/"));
revalidatePath(toInternalAdminPath("/marquee"));
for (const locale of routing.locales) {
revalidatePath(getLocalizedPath(locale), "layout");
revalidatePath(getLocalizedPath(locale));
}
}
export async function saveMarqueeSettingsAction(formData: FormData) {
await ensureAdmin();
try {
const germanSettings = {
row1: String(formData.get("row1-de") ?? "").trim(),
row2: String(formData.get("row2-de") ?? "").trim(),
row3: String(formData.get("row3-de") ?? "").trim(),
row4: String(formData.get("row4-de") ?? "").trim(),
};
const settings = {
locales: {
ar: { ...germanSettings },
en: { ...germanSettings },
de: germanSettings,
},
};
if (!germanSettings.row1) {
throw new Error("Row 1 fuer de ist erforderlich.");
}
if (!germanSettings.row2) {
throw new Error("Row 2 fuer de ist erforderlich.");
}
if (!germanSettings.row3) {
throw new Error("Row 3 fuer de ist erforderlich.");
}
if (!germanSettings.row4) {
throw new Error("Row 4 fuer de ist erforderlich.");
}
await updateMarqueeSettings(settings);
await revalidateMarqueePages();
redirect(withMessage("/marquee", "success", "Marquee gespeichert."));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message = error instanceof Error ? error.message : "Marquee konnte nicht gespeichert werden.";
redirect(withMessage("/marquee", "error", message));
}
}
-60
View File
@@ -1,60 +0,0 @@
import { redirect } from "next/navigation";
import { MarqueeSettingsForm } from "@/components/root/marquee-settings-form";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { MotionFade } from "@/components/motion-fade";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getMarqueeSettings } from "@/lib/app-config";
import { saveMarqueeSettingsAction } from "./actions";
export const dynamic = "force-dynamic";
const copy = {
title: "Marquee",
subtitle: "Scrollende Textzeilen fuer die Startseite pro Sprache verwalten.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "Settings",
marquee: "Marquee",
smtp: "SMTP",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
};
export default async function RootMarqueePage() {
if (!(await isAdminAuthenticated())) {
redirect("/");
}
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
const marqueeSettings = await getMarqueeSettings();
return (
<RootDashboardShell
copy={copy}
active="marquee"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
>
<div className="space-y-6">
<MotionFade delay={0.14}>
<MarqueeSettingsForm
action={saveMarqueeSettingsAction}
initialSettings={marqueeSettings}
/>
</MotionFade>
</div>
</RootDashboardShell>
);
}
-102
View File
@@ -1,102 +0,0 @@
"use server";
import { MediaKind } from "@prisma/client";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { isRedirectError } from "next/dist/client/components/redirect-error";
import { toInternalAdminPath } from "@/lib/admin-routing";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { countMediaUsageReferences, getMediaAssetById } from "@/lib/media";
import { createStandaloneMediaAsset, deleteMediaAssetAndFile } from "@/lib/media-service";
import { isManagedMediaFilePath } from "@/lib/media-storage";
import { prisma } from "@/lib/prisma";
async function ensureAdmin() {
if (!(await isAdminAuthenticated())) {
await clearAdminSessionCookie();
redirect("/");
}
}
function withMessage(pathname: string, type: "success" | "error", message: string) {
const params = new URLSearchParams();
params.set(type, message);
return `${pathname}?${params.toString()}`;
}
function revalidateMediaPages() {
revalidatePath(toInternalAdminPath("/"));
revalidatePath(toInternalAdminPath("/media"));
revalidatePath(toInternalAdminPath("/portfolio"));
revalidatePath(toInternalAdminPath("/portfolio/projects"));
}
export async function createMediaAssetAction(formData: FormData) {
await ensureAdmin();
try {
const kindValue = String(formData.get("kind") ?? "IMAGE");
const kind = kindValue === "DOCUMENT" ? MediaKind.DOCUMENT : MediaKind.IMAGE;
await createStandaloneMediaAsset({
kind,
label: String(formData.get("label") ?? ""),
uploadFile: formData.get("file"),
});
revalidateMediaPages();
redirect(withMessage("/media", "success", "Datei gespeichert."));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message = error instanceof Error ? error.message : "Datei konnte nicht gespeichert werden.";
redirect(withMessage("/media", "error", message));
}
}
export async function deleteMediaAssetAction(formData: FormData) {
await ensureAdmin();
const assetId = String(formData.get("assetId") ?? "");
try {
const asset = await getMediaAssetById(assetId);
if (!asset) {
redirect(withMessage("/media", "error", "Datei nicht gefunden."));
}
const usageCount = await countMediaUsageReferences(asset.id);
if (usageCount > 0) {
redirect(withMessage("/media", "error", "Datei wird noch verwendet."));
}
await prisma.mediaAsset.delete({
where: {
id: asset.id,
},
});
if (isManagedMediaFilePath(asset.url)) {
await deleteMediaAssetAndFile({
assetId: asset.id,
assetUrl: asset.url,
});
}
revalidateMediaPages();
redirect(withMessage("/media", "success", "Datei geloescht."));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message = error instanceof Error ? error.message : "Datei konnte nicht geloescht werden.";
redirect(withMessage("/media", "error", message));
}
}
-50
View File
@@ -1,50 +0,0 @@
import { redirect } from "next/navigation";
import { MediaLibraryManager } from "@/components/root/media-library-manager";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getAdminMediaAssets } from "@/lib/media";
export const dynamic = "force-dynamic";
const copy = {
title: "Media Library",
subtitle: "Zentrale Dateien fuer Portfolio und spaetere Inhaltsbereiche.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "Settings",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
};
export default async function RootMediaPage() {
if (!(await isAdminAuthenticated())) {
redirect("/");
}
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
const mediaAssets = await getAdminMediaAssets();
return (
<RootDashboardShell
copy={copy}
active="media"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
>
<div className="space-y-6">
<MediaLibraryManager mediaAssets={mediaAssets} />
</div>
</RootDashboardShell>
);
}
-243
View File
@@ -1,243 +0,0 @@
import { FolderKanban, ImageIcon, LockKeyhole, ShieldAlert } from "lucide-react";
import { redirect } from "next/navigation";
import { Container } from "@/components/layout/container";
import { StatsCard } from "@/components/dashboard/stats-card";
import { MotionFade } from "@/components/motion-fade";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
clearAdminSessionCookie,
getAdminLockState,
isAdminAuthConfigured,
isAdminAuthenticated,
isPasswordValid,
registerFailedAdminAttempt,
resetAdminFailedAttempts,
setAdminSessionCookie,
} from "@/lib/admin-auth";
import { getMaintenanceMode } from "@/lib/app-config";
import { getAdminMediaAssets } from "@/lib/media";
import { getAdminPortfolioCategories, getAdminPortfolioProjects } from "@/lib/portfolio";
type RootPageProps = {
searchParams?: Promise<{
error?: string;
}>;
};
export const dynamic = "force-dynamic";
const copy = {
title: "Uebersicht",
subtitle: "Kompakter Status zu Portfolio, Media und Wartung.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
media: "Media",
siteSettings: "Settings",
portfolio: "Portfolio",
uiKit: "UI Kit",
logout: "Ausloggen",
backToSite: "Zur Website",
loginTitle: "Root Login",
loginText: "Nur autorisierte Nutzer duerfen diesen Bereich verwenden.",
passwordLabel: "Passwort",
loginButton: "Einloggen",
invalidLogin: "Falsches Passwort.",
lockedLogin: "Zu viele Fehlversuche. Bitte spaeter erneut versuchen.",
configMissing: "ADMIN_PASSWORD und ADMIN_AUTH_SECRET fehlen in env.",
basicAuthMissing: "ROOT_BASIC_AUTH_USER und ROOT_BASIC_AUTH_PASS fehlen in env.",
maintenanceOn: "Aktiv",
maintenanceOff: "Inaktiv",
portfolioOnline: "Portfolio online",
mediaImages: "Media Images",
maintenanceStatus: "Maintenance",
drafts: "Drafts",
activeCategories: "Active Categories",
};
export default async function RootPage({ searchParams }: RootPageProps) {
const resolvedSearchParams = await searchParams;
const authConfigured = isAdminAuthConfigured();
const basicConfigured = Boolean(
process.env.ROOT_BASIC_AUTH_USER && process.env.ROOT_BASIC_AUTH_PASS,
);
const authenticated = await isAdminAuthenticated();
const lockState = await getAdminLockState();
async function loginAction(formData: FormData) {
"use server";
const password = String(formData.get("password") ?? "");
const currentLockState = await getAdminLockState();
if (currentLockState.locked) {
redirect("/?error=locked");
}
if (!isAdminAuthConfigured() || !isPasswordValid(password)) {
const failState = await registerFailedAdminAttempt();
if (failState.locked) {
redirect("/?error=locked");
}
redirect("/?error=invalid");
}
await resetAdminFailedAttempts();
await setAdminSessionCookie();
redirect("/");
}
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
if (!authenticated) {
return (
<Container size="narrow" className="py-12">
<MotionFade>
<Card className="border-border/70 bg-card/95 shadow-sm">
<CardHeader>
<p className="inline-flex items-center gap-2 text-sm font-medium text-muted-foreground">
<LockKeyhole className="h-4 w-4 text-brand-primary" />
{copy.loginTitle}
</p>
<CardDescription>{copy.loginText}</CardDescription>
</CardHeader>
<CardContent>
{!authConfigured ? (
<p className="mb-4 rounded-nested border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
{copy.configMissing}
</p>
) : null}
{!basicConfigured ? (
<p className="mb-4 rounded-nested border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
{copy.basicAuthMissing}
</p>
) : null}
{resolvedSearchParams?.error === "invalid" ? (
<p className="mb-4 rounded-nested border border-status-warning/30 bg-status-warning-soft px-3 py-2 text-sm text-status-warning">
{copy.invalidLogin}
</p>
) : null}
{resolvedSearchParams?.error === "locked" || lockState.locked ? (
<p className="mb-4 rounded-nested border border-status-warning/30 bg-status-warning-soft px-3 py-2 text-sm text-status-warning">
{copy.lockedLogin}
</p>
) : null}
<form action={loginAction} className="space-y-3">
<div className="space-y-2">
<Label htmlFor="password" className="sr-only">
{copy.passwordLabel}
</Label>
<div className="relative">
<LockKeyhole className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
id="password"
type="password"
name="password"
required
placeholder={copy.passwordLabel}
className="pl-9"
/>
</div>
</div>
<Button
type="submit"
disabled={!authConfigured || !basicConfigured || lockState.locked}
>
<LockKeyhole className="h-4 w-4" />
{copy.loginButton}
</Button>
</form>
</CardContent>
</Card>
</MotionFade>
</Container>
);
}
const [maintenanceEnabled, categories, projects, mediaAssets] = await Promise.all([
getMaintenanceMode(),
getAdminPortfolioCategories(),
getAdminPortfolioProjects(),
getAdminMediaAssets(),
]);
const publishedProjects = projects.filter((project) => project.isPublished).length;
const draftProjects = projects.length - publishedProjects;
const activeCategories = categories.filter((category) => category.isActive).length;
const imageCount = mediaAssets.filter((asset) => asset.kind === "IMAGE").length;
return (
<RootDashboardShell
copy={copy}
active="overview"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
>
<div className="space-y-6">
<section className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<MotionFade delay={0.05}>
<StatsCard
title={copy.portfolioOnline}
value={String(publishedProjects)}
icon={FolderKanban}
className="h-full"
footer={(
<div className="flex flex-wrap gap-x-4 gap-y-2 text-sm text-muted-foreground">
<span>{copy.drafts}: {draftProjects}</span>
<span>{copy.activeCategories}: {activeCategories}</span>
</div>
)}
/>
</MotionFade>
<MotionFade delay={0.1}>
<StatsCard
title={copy.mediaImages}
value={String(imageCount)}
icon={ImageIcon}
description="Anzahl der Bilder innerhalb der Media Library."
className="h-full"
/>
</MotionFade>
<MotionFade delay={0.15}>
<StatsCard
title={copy.maintenanceStatus}
value={maintenanceEnabled ? copy.maintenanceOn : copy.maintenanceOff}
icon={ShieldAlert}
className="h-full"
footer={(
<div className="flex items-center justify-between gap-3 text-sm">
<span className="text-muted-foreground">
{maintenanceEnabled
? "Website ist aktuell fuer Besucher gesperrt."
: "Website ist aktuell offen."}
</span>
<Badge variant={maintenanceEnabled ? "warning" : "success"}>
{maintenanceEnabled ? copy.maintenanceOn : copy.maintenanceOff}
</Badge>
</div>
)}
/>
</MotionFade>
</section>
</div>
</RootDashboardShell>
);
}
-607
View File
@@ -1,607 +0,0 @@
"use server";
import { MediaUsageType, Prisma } from "@prisma/client";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { isRedirectError } from "next/dist/client/components/redirect-error";
import { ZodError } from "zod";
import { routing } from "@/i18n/routing";
import { toInternalAdminPath } from "@/lib/admin-routing";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { deleteEntityMediaUsages, replaceEntityMediaUsages } from "@/lib/media";
import { resolveMediaSelection } from "@/lib/media-service";
import { getLocalizedPath } from "@/lib/locale";
import { removeManagedMediaFile } from "@/lib/media-storage";
import { mediaFieldInputSchema } from "@/lib/media-validation";
import { prisma } from "@/lib/prisma";
import { isCheckedFormValue } from "@/lib/form-data";
import {
assetInputSchema,
categoryInputSchema,
projectInputSchema,
sectionInputSchema,
} from "@/lib/portfolio-validation";
async function ensureAdmin() {
if (!(await isAdminAuthenticated())) {
await clearAdminSessionCookie();
redirect("/");
}
}
function getRedirectPath(formData: FormData, fallbackPath: string) {
return String(formData.get("redirectPath") ?? fallbackPath);
}
function withMessage(pathname: string, type: "success" | "error", message: string) {
const params = new URLSearchParams();
params.set(type, message);
return `${pathname}?${params.toString()}`;
}
function normalizeCheckboxValue(formData: FormData, key: string) {
return isCheckedFormValue(formData.get(key));
}
function parseJsonArray(rawValue: FormDataEntryValue | null, key: string) {
if (typeof rawValue !== "string" || rawValue.trim() === "") {
return [];
}
try {
const parsed = JSON.parse(rawValue);
if (!Array.isArray(parsed)) {
throw new Error(`${key} muss ein Array sein.`);
}
return parsed;
} catch {
throw new Error(`Ungueltige ${key} Nutzdaten.`);
}
}
function parseJsonObject(rawValue: FormDataEntryValue | null, key: string) {
if (typeof rawValue !== "string" || rawValue.trim() === "") {
return undefined;
}
try {
const parsed = JSON.parse(rawValue);
if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") {
throw new Error(`${key} muss ein Objekt sein.`);
}
return parsed;
} catch {
throw new Error(`Ungueltige ${key} Nutzdaten.`);
}
}
function parseZodError(error: ZodError) {
return error.issues[0]?.message ?? "Validierung fehlgeschlagen.";
}
async function revalidatePortfolioPages() {
revalidatePath(toInternalAdminPath("/"));
revalidatePath(toInternalAdminPath("/media"));
revalidatePath(toInternalAdminPath("/portfolio"));
revalidatePath(toInternalAdminPath("/portfolio/categories"));
revalidatePath(toInternalAdminPath("/portfolio/projects"));
revalidatePath("/portfolio");
for (const locale of routing.locales) {
revalidatePath(getLocalizedPath(locale, "/portfolio"));
}
}
async function removeManagedPaths(paths: string[]) {
for (const filePath of Array.from(new Set(paths.filter(Boolean)))) {
await removeManagedMediaFile(filePath);
}
}
export async function upsertCategoryAction(formData: FormData) {
await ensureAdmin();
const redirectPath = getRedirectPath(formData, "/portfolio/categories");
try {
const parsed = categoryInputSchema.parse({
id: String(formData.get("id") ?? "").trim() || undefined,
slug: String(formData.get("slug") ?? ""),
nameAr: String(formData.get("nameAr") ?? ""),
nameEn: String(formData.get("nameEn") ?? ""),
nameDe: String(formData.get("nameDe") ?? ""),
descriptionAr: String(formData.get("descriptionAr") ?? ""),
descriptionEn: String(formData.get("descriptionEn") ?? ""),
descriptionDe: String(formData.get("descriptionDe") ?? ""),
sortOrder: String(formData.get("sortOrder") ?? "0"),
isActive: normalizeCheckboxValue(formData, "isActive"),
});
if (parsed.id) {
await prisma.category.update({
where: {
id: parsed.id,
},
data: parsed,
});
} else {
await prisma.category.create({
data: parsed,
});
}
await revalidatePortfolioPages();
redirect(withMessage(redirectPath, "success", "Kategorie gespeichert."));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message =
error instanceof ZodError
? parseZodError(error)
: error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002"
? "Kategorie Slug muss eindeutig sein."
: "Kategorie konnte nicht gespeichert werden.";
redirect(withMessage(redirectPath, "error", message));
}
}
export async function deleteCategoryAction(formData: FormData) {
await ensureAdmin();
const redirectPath = getRedirectPath(formData, "/portfolio/categories");
const id = String(formData.get("id") ?? "");
try {
const projectCount = await prisma.portfolioProject.count({
where: {
categoryId: id,
},
});
if (projectCount > 0) {
redirect(withMessage(redirectPath, "error", "Kategorie mit Projekten kann nicht geloescht werden."));
}
await prisma.category.delete({
where: {
id,
},
});
await revalidatePortfolioPages();
redirect(withMessage(redirectPath, "success", "Kategorie geloescht."));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
redirect(withMessage(redirectPath, "error", "Kategorie konnte nicht geloescht werden."));
}
}
export async function saveProjectAction(formData: FormData) {
await ensureAdmin();
const fallbackRedirect = String(formData.get("id") ?? "").trim()
? `/portfolio/projects/${String(formData.get("id") ?? "").trim()}`
: "/portfolio/projects/new";
const redirectPath = getRedirectPath(formData, fallbackRedirect);
const uploadedPaths: string[] = [];
const createdMediaAssetIds: string[] = [];
try {
const sections = parseJsonArray(formData.get("sections"), "sections").map((section, index) =>
sectionInputSchema.parse({
...section,
media: section.media ? mediaFieldInputSchema.parse(section.media) : undefined,
sortOrder: section.sortOrder ?? index,
}),
);
const assets = parseJsonArray(formData.get("assets"), "assets").map((asset, index) =>
assetInputSchema.parse({
...asset,
media: asset.media ? mediaFieldInputSchema.parse(asset.media) : undefined,
sortOrder: asset.sortOrder ?? index,
}),
);
const coverMedia = parseJsonObject(formData.get("coverMedia"), "coverMedia");
const parsed = projectInputSchema.parse({
id: String(formData.get("id") ?? "").trim() || undefined,
categoryId: String(formData.get("categoryId") ?? ""),
slug: String(formData.get("slug") ?? ""),
viewMode: String(formData.get("viewMode") ?? "GRID"),
titleAr: String(formData.get("titleAr") ?? ""),
titleEn: String(formData.get("titleEn") ?? ""),
titleDe: String(formData.get("titleDe") ?? ""),
summaryAr: String(formData.get("summaryAr") ?? ""),
summaryEn: String(formData.get("summaryEn") ?? ""),
summaryDe: String(formData.get("summaryDe") ?? ""),
clientName: String(formData.get("clientName") ?? ""),
projectYear: String(formData.get("projectYear") ?? ""),
serviceLabelAr: String(formData.get("serviceLabelAr") ?? ""),
serviceLabelEn: String(formData.get("serviceLabelEn") ?? ""),
serviceLabelDe: String(formData.get("serviceLabelDe") ?? ""),
previewUrl: String(formData.get("previewUrl") ?? ""),
currentCoverImagePath: String(formData.get("currentCoverImagePath") ?? ""),
coverMedia: coverMedia ? mediaFieldInputSchema.parse(coverMedia) : undefined,
sortOrder: String(formData.get("sortOrder") ?? "0"),
isFeatured: normalizeCheckboxValue(formData, "isFeatured"),
isPublished: normalizeCheckboxValue(formData, "isPublished"),
sections,
assets,
});
const existingProject = parsed.id
? await prisma.portfolioProject.findUnique({
where: {
id: parsed.id,
},
select: {
isPublished: true,
publishedAt: true,
},
})
: null;
const shouldPublishNow = parsed.isPublished && !existingProject?.publishedAt;
const coverSelection = await resolveMediaSelection({
media: parsed.coverMedia,
uploadFile: formData.get("coverFile"),
folder: "covers",
fallbackLabel: parsed.titleDe || parsed.titleEn || parsed.titleAr || parsed.slug,
required: false,
});
if (coverSelection.createdAssetId) {
createdMediaAssetIds.push(coverSelection.createdAssetId);
}
if (coverSelection.uploadedUrl) {
uploadedPaths.push(coverSelection.uploadedUrl);
}
const sectionRows: Array<{
type: (typeof parsed.sections)[number]["type"];
titleAr: string;
titleEn: string;
titleDe: string;
bodyAr: string;
bodyEn: string;
bodyDe: string;
imagePath: string | null;
imageAssetId: string | null;
linkUrl: string | null;
sortOrder: number;
}> = [];
for (let index = 0; index < parsed.sections.length; index += 1) {
const section = parsed.sections[index];
const sectionSelection = await resolveMediaSelection({
media: section.media,
uploadFile: formData.get(`section-image-upload-${index}`),
folder: "sections",
fallbackLabel: section.titleDe || section.titleEn || section.titleAr || `section-${index + 1}`,
required: false,
});
if (sectionSelection.createdAssetId) {
createdMediaAssetIds.push(sectionSelection.createdAssetId);
}
if (sectionSelection.uploadedUrl) {
uploadedPaths.push(sectionSelection.uploadedUrl);
}
sectionRows.push({
type: section.type,
titleAr: section.titleAr,
titleEn: section.titleEn,
titleDe: section.titleDe,
bodyAr: section.bodyAr,
bodyEn: section.bodyEn,
bodyDe: section.bodyDe,
imagePath: sectionSelection.url || null,
imageAssetId: sectionSelection.assetId,
linkUrl: section.linkUrl || null,
sortOrder: index,
});
}
const assetRows: Array<{
kind: (typeof parsed.assets)[number]["kind"];
filePath: string;
mediaAssetId: string | null;
altAr: string;
altEn: string;
altDe: string;
sortOrder: number;
}> = [];
for (let index = 0; index < parsed.assets.length; index += 1) {
const asset = parsed.assets[index];
const assetSelection = await resolveMediaSelection({
media: asset.media,
uploadFile: asset.fileFieldName ? formData.get(asset.fileFieldName) : null,
folder: "assets",
fallbackLabel: asset.altDe || asset.altEn || asset.altAr || `asset-${index + 1}`,
required: true,
});
if (!assetSelection.url) {
throw new Error("Jede Datei Zeile braucht eine vorhandene Datei oder einen neuen Upload.");
}
if (assetSelection.createdAssetId) {
createdMediaAssetIds.push(assetSelection.createdAssetId);
}
if (assetSelection.uploadedUrl) {
uploadedPaths.push(assetSelection.uploadedUrl);
}
assetRows.push({
kind: asset.kind,
filePath: assetSelection.url,
mediaAssetId: assetSelection.assetId,
altAr: asset.altAr,
altEn: asset.altEn,
altDe: asset.altDe,
sortOrder: index,
});
}
const projectResult = await prisma.$transaction(async (tx) => {
const currentProject = parsed.id
? await tx.portfolioProject.update({
where: {
id: parsed.id,
},
data: {
categoryId: parsed.categoryId,
slug: parsed.slug,
viewMode: parsed.viewMode,
titleAr: parsed.titleAr,
titleEn: parsed.titleEn,
titleDe: parsed.titleDe,
summaryAr: parsed.summaryAr,
summaryEn: parsed.summaryEn,
summaryDe: parsed.summaryDe,
clientName: parsed.clientName,
projectYear: parsed.projectYear,
serviceLabelAr: parsed.serviceLabelAr,
serviceLabelEn: parsed.serviceLabelEn,
serviceLabelDe: parsed.serviceLabelDe,
previewUrl: parsed.previewUrl || null,
coverImagePath: coverSelection.url || null,
isFeatured: parsed.isFeatured,
isPublished: parsed.isPublished,
publishedAt: parsed.isPublished
? shouldPublishNow
? new Date()
: existingProject?.publishedAt ?? new Date()
: null,
sortOrder: parsed.sortOrder,
},
})
: await tx.portfolioProject.create({
data: {
categoryId: parsed.categoryId,
slug: parsed.slug,
viewMode: parsed.viewMode,
titleAr: parsed.titleAr,
titleEn: parsed.titleEn,
titleDe: parsed.titleDe,
summaryAr: parsed.summaryAr,
summaryEn: parsed.summaryEn,
summaryDe: parsed.summaryDe,
clientName: parsed.clientName,
projectYear: parsed.projectYear,
serviceLabelAr: parsed.serviceLabelAr,
serviceLabelEn: parsed.serviceLabelEn,
serviceLabelDe: parsed.serviceLabelDe,
previewUrl: parsed.previewUrl || null,
coverImagePath: coverSelection.url || null,
isFeatured: parsed.isFeatured,
isPublished: parsed.isPublished,
publishedAt: parsed.isPublished ? new Date() : null,
sortOrder: parsed.sortOrder,
},
});
await tx.portfolioSection.deleteMany({
where: {
projectId: currentProject.id,
},
});
await tx.portfolioAsset.deleteMany({
where: {
projectId: currentProject.id,
},
});
const createdSections = [];
for (const section of sectionRows) {
const createdSection = await tx.portfolioSection.create({
data: {
projectId: currentProject.id,
type: section.type,
titleAr: section.titleAr,
titleEn: section.titleEn,
titleDe: section.titleDe,
bodyAr: section.bodyAr,
bodyEn: section.bodyEn,
bodyDe: section.bodyDe,
imagePath: section.imagePath || null,
linkUrl: section.linkUrl || null,
sortOrder: section.sortOrder,
},
});
createdSections.push(createdSection);
}
const createdAssets = [];
for (const asset of assetRows) {
const createdAsset = await tx.portfolioAsset.create({
data: {
projectId: currentProject.id,
kind: asset.kind,
filePath: asset.filePath,
altAr: asset.altAr,
altEn: asset.altEn,
altDe: asset.altDe,
sortOrder: asset.sortOrder,
},
});
createdAssets.push(createdAsset);
}
return {
project: currentProject,
createdSections,
createdAssets,
};
});
await replaceEntityMediaUsages({
entityType: "portfolio-project",
entityId: projectResult.project.id,
usages: [
...(coverSelection.assetId
? [
{
assetId: coverSelection.assetId,
usageType: MediaUsageType.PORTFOLIO_COVER,
fieldKey: "cover",
},
]
: []),
...projectResult.createdSections.flatMap((section, index) =>
sectionRows[index]?.imageAssetId
? [
{
assetId: sectionRows[index].imageAssetId as string,
usageType: MediaUsageType.PORTFOLIO_SECTION,
fieldKey: section.id,
},
]
: [],
),
...projectResult.createdAssets.flatMap((asset, index) =>
assetRows[index]?.mediaAssetId
? [
{
assetId: assetRows[index].mediaAssetId as string,
usageType: MediaUsageType.PORTFOLIO_ASSET,
fieldKey: asset.id,
},
]
: [],
),
],
});
await revalidatePortfolioPages();
revalidatePath(toInternalAdminPath(`/portfolio/projects/${projectResult.project.id}`));
revalidatePath(`/portfolio/${projectResult.project.slug}`);
for (const locale of routing.locales) {
revalidatePath(getLocalizedPath(locale, `/portfolio/${projectResult.project.slug}`));
}
redirect(
withMessage(`/portfolio/projects/${projectResult.project.id}`, "success", "Projekt gespeichert."),
);
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message =
error instanceof ZodError
? parseZodError(error)
: error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002"
? "Projekt Slug muss eindeutig sein."
: error instanceof Error
? error.message
: "Projekt konnte nicht gespeichert werden.";
await removeManagedPaths(uploadedPaths);
if (createdMediaAssetIds.length > 0) {
await prisma.mediaUsage.deleteMany({
where: {
assetId: {
in: createdMediaAssetIds,
},
},
});
await prisma.mediaAsset.deleteMany({
where: {
id: {
in: createdMediaAssetIds,
},
},
});
}
redirect(withMessage(redirectPath, "error", message));
}
}
export async function deleteProjectAction(formData: FormData) {
await ensureAdmin();
const id = String(formData.get("id") ?? "");
try {
const project = await prisma.portfolioProject.findUnique({
where: {
id,
},
select: {
slug: true,
},
});
if (!project) {
redirect(withMessage("/portfolio", "error", "Project not found."));
}
await prisma.portfolioProject.delete({
where: {
id,
},
});
await deleteEntityMediaUsages("portfolio-project", id);
await revalidatePortfolioPages();
revalidatePath(`/portfolio/${project.slug}`);
for (const locale of routing.locales) {
revalidatePath(getLocalizedPath(locale, `/portfolio/${project.slug}`));
}
redirect(withMessage("/portfolio", "success", "Project deleted."));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
redirect(withMessage("/portfolio", "error", "Unable to delete project."));
}
}
-61
View File
@@ -1,61 +0,0 @@
import { redirect } from "next/navigation";
import { PortfolioCategoriesManager } from "@/components/root/portfolio-categories-manager";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getAdminPortfolioCategories } from "@/lib/portfolio";
import { deleteCategoryAction, upsertCategoryAction } from "../actions";
export const dynamic = "force-dynamic";
const copy = {
title: "Portfolio Kategorien",
subtitle: "Kategorien schnell anlegen, oeffnen und direkt im Modal bearbeiten.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "Settings",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
};
export default async function RootPortfolioCategoriesPage() {
if (!(await isAdminAuthenticated())) {
redirect("/");
}
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
const categories = await getAdminPortfolioCategories();
const activeCount = categories.filter((category) => category.isActive).length;
const assignedProjects = categories.reduce((sum, category) => sum + category.projectCount, 0);
return (
<RootDashboardShell
copy={copy}
active="portfolio"
portfolioChild="categories"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
>
<div className="space-y-6">
<PortfolioCategoriesManager
categories={categories}
activeCount={activeCount}
assignedProjects={assignedProjects}
saveCategoryAction={upsertCategoryAction}
removeCategoryAction={deleteCategoryAction}
/>
</div>
</RootDashboardShell>
);
}
-5
View File
@@ -1,5 +0,0 @@
import { redirect } from "next/navigation";
export default function RootPortfolioMediaRedirectPage() {
redirect("/media");
}
-79
View File
@@ -1,79 +0,0 @@
import { redirect } from "next/navigation";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { PortfolioProjectsOverview } from "@/components/root/portfolio-projects-overview";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getAdminPortfolioCategories, getAdminPortfolioProjects } from "@/lib/portfolio";
export const dynamic = "force-dynamic";
const copy = {
title: "Portfolio",
subtitle: "Zentrale Steuerung fuer Projekte, Inhalte und Medien.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "Settings",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
};
type RootPortfolioPageProps = {
searchParams?: Promise<{
category?: string;
status?: "all" | "draft" | "published";
success?: string;
error?: string;
}>;
};
export default async function RootPortfolioPage({ searchParams }: RootPortfolioPageProps) {
const resolvedSearchParams = await searchParams;
if (!(await isAdminAuthenticated())) {
redirect("/");
}
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
const selectedCategory = resolvedSearchParams?.category && resolvedSearchParams.category !== "__all__"
? resolvedSearchParams.category
: "";
const selectedStatus = resolvedSearchParams?.status === "draft" || resolvedSearchParams?.status === "published"
? resolvedSearchParams.status
: "all";
const [categories, projects] = await Promise.all([
getAdminPortfolioCategories(),
getAdminPortfolioProjects({
categoryId: selectedCategory || undefined,
status: selectedStatus,
}),
]);
return (
<RootDashboardShell
copy={copy}
active="portfolio"
portfolioChild="overview"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
>
<div className="space-y-6">
<PortfolioProjectsOverview
categories={categories}
projects={projects}
selectedCategory={selectedCategory}
selectedStatus={selectedStatus}
/>
</div>
</RootDashboardShell>
);
}
-137
View File
@@ -1,137 +0,0 @@
import { redirect } from "next/navigation";
import { MotionFade } from "@/components/motion-fade";
import { PortfolioProjectForm } from "@/components/root/portfolio-project-form";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { AppCard } from "@/components/ui/app-card";
import { Button } from "@/components/ui/button";
import { CardContent } from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getMediaOptions } from "@/lib/media";
import {
getActivePortfolioCategories,
getAdminPortfolioProjectById,
} from "@/lib/portfolio";
import { deleteProjectAction, saveProjectAction } from "../../actions";
export const dynamic = "force-dynamic";
const copy = {
title: "Portfolio Projekt bearbeiten",
subtitle: "Projektstatus, Inhalte und Dateien anpassen.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "Settings",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
saveProject: "Projekt speichern",
dangerZone: "Gefahrenbereich",
dangerText: "Projektdaten werden aus der Datenbank entfernt. Hochgeladene Dateien bleiben auf dem Speicher erhalten.",
deleteProject: "Projekt loeschen",
};
type RootPortfolioProjectPageProps = {
params: Promise<{
id: string;
}>;
};
export default async function RootPortfolioProjectPage({
params,
}: RootPortfolioProjectPageProps) {
if (!(await isAdminAuthenticated())) {
redirect("/");
}
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
const { id } = await params;
const [categories, mediaOptions, project] = await Promise.all([
getActivePortfolioCategories(),
getMediaOptions(),
getAdminPortfolioProjectById(id),
]);
if (!project) {
redirect("/portfolio?error=Project+not+found.");
}
return (
<RootDashboardShell
copy={copy}
active="portfolio"
portfolioChild="projects"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
>
<div className="space-y-6">
<MotionFade delay={0.15}>
<PortfolioProjectForm
action={saveProjectAction}
categories={categories}
mediaOptions={mediaOptions}
project={project}
formId="portfolio-project-form"
redirectPath={`/portfolio/projects/${project.id}`}
/>
</MotionFade>
<MotionFade delay={0.2}>
<AppCard level={2}>
<CardContent className="flex flex-col gap-4 p-6 lg:flex-row lg:items-center lg:justify-between">
<div>
<p className="text-sm font-medium text-foreground">{copy.dangerZone}</p>
<p className="mt-1 text-sm text-muted-foreground">
{copy.dangerText}
</p>
</div>
<Dialog>
<DialogTrigger asChild>
<Button type="button" variant="destructive">
{copy.deleteProject}
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{copy.deleteProject}</DialogTitle>
<DialogDescription>
This action permanently removes the project data from the database.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<form action={deleteProjectAction}>
<input type="hidden" name="id" value={project.id} />
<Button type="submit" variant="destructive">
Confirm Delete
</Button>
</form>
</DialogFooter>
</DialogContent>
</Dialog>
</CardContent>
</AppCard>
</MotionFade>
</div>
</RootDashboardShell>
);
}
-66
View File
@@ -1,66 +0,0 @@
import { redirect } from "next/navigation";
import { MotionFade } from "@/components/motion-fade";
import { PortfolioProjectForm } from "@/components/root/portfolio-project-form";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getMediaOptions } from "@/lib/media";
import { getActivePortfolioCategories } from "@/lib/portfolio";
import { saveProjectAction } from "../../actions";
export const dynamic = "force-dynamic";
const copy = {
title: "Neues Portfolio Projekt",
subtitle: "Projekt mit Kategorie, Abschnitten und Dateien anlegen.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "Settings",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
};
export default async function RootNewPortfolioProjectPage() {
if (!(await isAdminAuthenticated())) {
redirect("/");
}
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
const [categories, mediaOptions] = await Promise.all([
getActivePortfolioCategories(),
getMediaOptions(),
]);
return (
<RootDashboardShell
copy={copy}
active="portfolio"
portfolioChild="new-project"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
>
<div className="space-y-6">
<MotionFade delay={0.15}>
<PortfolioProjectForm
action={saveProjectAction}
categories={categories}
mediaOptions={mediaOptions}
formId="portfolio-project-form"
redirectPath="/portfolio/projects/new"
/>
</MotionFade>
</div>
</RootDashboardShell>
);
}
-79
View File
@@ -1,79 +0,0 @@
import { redirect } from "next/navigation";
import { PortfolioProjectsOverview } from "@/components/root/portfolio-projects-overview";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getAdminPortfolioCategories, getAdminPortfolioProjects } from "@/lib/portfolio";
export const dynamic = "force-dynamic";
const copy = {
title: "Portfolio Projekte",
subtitle: "Projektliste und Einstieg in die komplette Bearbeitung.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "Settings",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
};
type RootPortfolioProjectsPageProps = {
searchParams?: Promise<{
category?: string;
status?: "all" | "draft" | "published";
}>;
};
export default async function RootPortfolioProjectsPage({
searchParams,
}: RootPortfolioProjectsPageProps) {
const resolvedSearchParams = await searchParams;
if (!(await isAdminAuthenticated())) {
redirect("/");
}
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
const selectedCategory = resolvedSearchParams?.category && resolvedSearchParams.category !== "__all__"
? resolvedSearchParams.category
: "";
const selectedStatus = resolvedSearchParams?.status === "draft" || resolvedSearchParams?.status === "published"
? resolvedSearchParams.status
: "all";
const [categories, projects] = await Promise.all([
getAdminPortfolioCategories(),
getAdminPortfolioProjects({
categoryId: selectedCategory || undefined,
status: selectedStatus,
}),
]);
return (
<RootDashboardShell
copy={copy}
active="portfolio"
portfolioChild="projects"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
>
<div className="space-y-6">
<PortfolioProjectsOverview
categories={categories}
projects={projects}
selectedCategory={selectedCategory}
selectedStatus={selectedStatus}
/>
</div>
</RootDashboardShell>
);
}
-296
View File
@@ -1,296 +0,0 @@
"use server";
import { MediaUsageType } from "@prisma/client";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { isRedirectError } from "next/dist/client/components/redirect-error";
import {
SITE_SETTINGS_DEFAULT_OG_IMAGE_FIELD_KEY,
SITE_SETTINGS_ENTITY_ID,
SITE_SETTINGS_ENTITY_TYPE,
SITE_SETTINGS_FAVICON_FIELD_KEY,
SITE_SETTINGS_LOGO_DARK_FIELD_KEY,
SITE_SETTINGS_LOGO_LIGHT_FIELD_KEY,
updateSiteSettings,
} from "@/lib/app-config";
import { toInternalAdminPath } from "@/lib/admin-routing";
import { PAGE_TITLE_TOKEN, type SiteSettings } from "@/lib/site-settings";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { replaceEntityMediaUsages } from "@/lib/media";
import { resolveMediaSelection } from "@/lib/media-service";
import { routing } from "@/i18n/routing";
import { getLocalizedPath } from "@/lib/locale";
import { removeManagedMediaFile } from "@/lib/media-storage";
import { mediaFieldInputSchema } from "@/lib/media-validation";
import { prisma } from "@/lib/prisma";
async function ensureAdmin() {
if (!(await isAdminAuthenticated())) {
await clearAdminSessionCookie();
redirect("/");
}
}
function withMessage(pathname: string, type: "success" | "error", message: string) {
const params = new URLSearchParams();
params.set(type, message);
return `${pathname}?${params.toString()}`;
}
function parseJsonObject(rawValue: FormDataEntryValue | null, key: string) {
if (typeof rawValue !== "string" || rawValue.trim() === "") {
return undefined;
}
try {
const parsed = JSON.parse(rawValue);
if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") {
throw new Error(`${key} must be an object.`);
}
return parsed;
} catch {
throw new Error(`Invalid ${key} payload.`);
}
}
async function cleanupCreatedMedia(assetIds: string[], uploadedPaths: string[]) {
if (assetIds.length > 0) {
await prisma.mediaAsset.deleteMany({
where: {
id: {
in: Array.from(new Set(assetIds)),
},
},
});
}
for (const filePath of Array.from(new Set(uploadedPaths.filter(Boolean)))) {
await removeManagedMediaFile(filePath);
}
}
async function revalidateSiteSettingsPages() {
revalidatePath("/", "layout");
revalidatePath(toInternalAdminPath("/"));
revalidatePath(toInternalAdminPath("/site-settings"));
revalidatePath("/coming-soon");
const publicPaths = ["/", "/about", "/portfolio", "/contact", "/success", "/coming-soon"];
for (const locale of routing.locales) {
revalidatePath(getLocalizedPath(locale), "layout");
for (const path of publicPaths) {
revalidatePath(getLocalizedPath(locale, path));
}
}
}
export async function saveSiteSettingsAction(formData: FormData) {
await ensureAdmin();
const createdMediaAssetIds: string[] = [];
const uploadedPaths: string[] = [];
try {
const siteLogoLightMedia = parseJsonObject(formData.get("siteLogoLightMedia"), "siteLogoLightMedia");
const siteLogoDarkMedia = parseJsonObject(formData.get("siteLogoDarkMedia"), "siteLogoDarkMedia");
const faviconMedia = parseJsonObject(formData.get("faviconMedia"), "faviconMedia");
const defaultOgImageMedia = parseJsonObject(
formData.get("defaultOgImageMedia"),
"defaultOgImageMedia",
);
const parsedSettings: SiteSettings = {
locales: {
ar: {
siteName: String(formData.get("siteNameAr") ?? "").trim(),
titleTemplate: String(formData.get("titleTemplateAr") ?? "").trim(),
siteDescription: String(formData.get("siteDescriptionAr") ?? "").trim(),
subhead: String(formData.get("subheadAr") ?? "").trim(),
},
en: {
siteName: String(formData.get("siteNameEn") ?? "").trim(),
titleTemplate: String(formData.get("titleTemplateEn") ?? "").trim(),
siteDescription: String(formData.get("siteDescriptionEn") ?? "").trim(),
subhead: String(formData.get("subheadEn") ?? "").trim(),
},
de: {
siteName: String(formData.get("siteNameDe") ?? "").trim(),
titleTemplate: String(formData.get("titleTemplateDe") ?? "").trim(),
siteDescription: String(formData.get("siteDescriptionDe") ?? "").trim(),
subhead: String(formData.get("subheadDe") ?? "").trim(),
},
},
};
for (const locale of routing.locales) {
if (!parsedSettings.locales[locale].siteName) {
throw new Error(`Site Name fuer ${locale} ist erforderlich.`);
}
if (
!parsedSettings.locales[locale].titleTemplate ||
!parsedSettings.locales[locale].titleTemplate.includes(PAGE_TITLE_TOKEN)
) {
throw new Error(`Title Template fuer ${locale} muss {pageTitle} enthalten.`);
}
}
const siteLogoLightSelection = siteLogoLightMedia
? await resolveMediaSelection({
media: mediaFieldInputSchema.parse(siteLogoLightMedia),
uploadFile: formData.get("siteLogoLightFile"),
folder: "site-settings",
fallbackLabel: `${parsedSettings.locales.de.siteName || parsedSettings.locales.en.siteName} logo light`,
required: false,
})
: {
assetId: null,
url: "",
createdAssetId: null,
uploadedUrl: null,
};
const siteLogoDarkSelection = siteLogoDarkMedia
? await resolveMediaSelection({
media: mediaFieldInputSchema.parse(siteLogoDarkMedia),
uploadFile: formData.get("siteLogoDarkFile"),
folder: "site-settings",
fallbackLabel: `${parsedSettings.locales.de.siteName || parsedSettings.locales.en.siteName} logo dark`,
required: false,
})
: {
assetId: null,
url: "",
createdAssetId: null,
uploadedUrl: null,
};
const faviconSelection = faviconMedia
? await resolveMediaSelection({
media: mediaFieldInputSchema.parse(faviconMedia),
uploadFile: formData.get("faviconFile"),
folder: "site-settings",
fallbackLabel: `${parsedSettings.locales.de.siteName || parsedSettings.locales.en.siteName} favicon`,
required: false,
})
: {
assetId: null,
url: "",
createdAssetId: null,
uploadedUrl: null,
};
const defaultOgImageSelection = defaultOgImageMedia
? await resolveMediaSelection({
media: mediaFieldInputSchema.parse(defaultOgImageMedia),
uploadFile: formData.get("defaultOgImageFile"),
folder: "site-settings",
fallbackLabel: `${parsedSettings.locales.de.siteName || parsedSettings.locales.en.siteName} og-image`,
required: false,
})
: {
assetId: null,
url: "",
createdAssetId: null,
uploadedUrl: null,
};
if (siteLogoLightSelection.createdAssetId) {
createdMediaAssetIds.push(siteLogoLightSelection.createdAssetId);
}
if (siteLogoLightSelection.uploadedUrl) {
uploadedPaths.push(siteLogoLightSelection.uploadedUrl);
}
if (siteLogoDarkSelection.createdAssetId) {
createdMediaAssetIds.push(siteLogoDarkSelection.createdAssetId);
}
if (siteLogoDarkSelection.uploadedUrl) {
uploadedPaths.push(siteLogoDarkSelection.uploadedUrl);
}
if (faviconSelection.createdAssetId) {
createdMediaAssetIds.push(faviconSelection.createdAssetId);
}
if (faviconSelection.uploadedUrl) {
uploadedPaths.push(faviconSelection.uploadedUrl);
}
if (defaultOgImageSelection.createdAssetId) {
createdMediaAssetIds.push(defaultOgImageSelection.createdAssetId);
}
if (defaultOgImageSelection.uploadedUrl) {
uploadedPaths.push(defaultOgImageSelection.uploadedUrl);
}
await updateSiteSettings(parsedSettings);
await replaceEntityMediaUsages({
entityType: SITE_SETTINGS_ENTITY_TYPE,
entityId: SITE_SETTINGS_ENTITY_ID,
usages: [
...(siteLogoLightSelection.assetId
? [
{
assetId: siteLogoLightSelection.assetId,
usageType: MediaUsageType.GENERIC,
fieldKey: SITE_SETTINGS_LOGO_LIGHT_FIELD_KEY,
},
]
: []),
...(siteLogoDarkSelection.assetId
? [
{
assetId: siteLogoDarkSelection.assetId,
usageType: MediaUsageType.GENERIC,
fieldKey: SITE_SETTINGS_LOGO_DARK_FIELD_KEY,
},
]
: []),
...(faviconSelection.assetId
? [
{
assetId: faviconSelection.assetId,
usageType: MediaUsageType.GENERIC,
fieldKey: SITE_SETTINGS_FAVICON_FIELD_KEY,
},
]
: []),
...(defaultOgImageSelection.assetId
? [
{
assetId: defaultOgImageSelection.assetId,
usageType: MediaUsageType.GENERIC,
fieldKey: SITE_SETTINGS_DEFAULT_OG_IMAGE_FIELD_KEY,
},
]
: []),
],
});
await revalidateSiteSettingsPages();
redirect(withMessage("/site-settings", "success", "Einstellungen gespeichert."));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
await cleanupCreatedMedia(createdMediaAssetIds, uploadedPaths);
const message =
error instanceof Error
? error.message
: "Einstellungen konnten nicht gespeichert werden.";
redirect(withMessage("/site-settings", "error", message));
}
}
-70
View File
@@ -1,70 +0,0 @@
import { MediaKind } from "@prisma/client";
import { redirect } from "next/navigation";
import { MotionFade } from "@/components/motion-fade";
import { SiteSettingsForm } from "@/components/root/site-settings-form";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import {
getSiteSettings,
getSiteSettingsMediaBindings,
} from "@/lib/app-config";
import { getMediaOptions } from "@/lib/media";
import { saveSiteSettingsAction } from "./actions";
export const dynamic = "force-dynamic";
const copy = {
title: "Settings",
subtitle: "Globale Titel, Copy und Brand Assets verwalten.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "Settings",
smtp: "SMTP",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
};
export default async function RootSiteSettingsPage() {
if (!(await isAdminAuthenticated())) {
redirect("/");
}
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
const [siteSettings, mediaBindings, mediaOptions] = await Promise.all([
getSiteSettings(),
getSiteSettingsMediaBindings(),
getMediaOptions({ kind: MediaKind.IMAGE }),
]);
return (
<RootDashboardShell
copy={copy}
active="site-settings"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
>
<div className="space-y-6">
<MotionFade delay={0.16}>
<SiteSettingsForm
action={saveSiteSettingsAction}
initialSettings={siteSettings}
initialBindings={mediaBindings}
mediaOptions={mediaOptions}
/>
</MotionFade>
</div>
</RootDashboardShell>
);
}
-115
View File
@@ -1,115 +0,0 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { isRedirectError } from "next/dist/client/components/redirect-error";
import { toInternalAdminPath } from "@/lib/admin-routing";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { isCheckedFormValue } from "@/lib/form-data";
import {
getMailSettings,
updateMailSettings,
} from "@/lib/app-config";
import { sendTestEmail } from "@/lib/mail";
import type { MailSettings } from "@/lib/mail-settings";
async function ensureAdmin() {
if (!(await isAdminAuthenticated())) {
await clearAdminSessionCookie();
redirect("/");
}
}
function withMessage(pathname: string, type: "success" | "error", message: string) {
const params = new URLSearchParams();
params.set(type, message);
return `${pathname}?${params.toString()}`;
}
function parsePort(value: string) {
const port = Number.parseInt(value, 10);
if (!Number.isInteger(port) || port <= 0) {
throw new Error("SMTP port must be a positive number.");
}
return port;
}
function parseMailSettingsFormData(
formData: FormData,
existingSettings: MailSettings,
): MailSettings {
const host = String(formData.get("smtpHost") ?? "").trim();
const portValue = String(formData.get("smtpPort") ?? "").trim();
const username = String(formData.get("smtpUsername") ?? "").trim();
const password = String(formData.get("smtpPassword") ?? "");
const fromEmail = String(formData.get("mailFromEmail") ?? "").trim();
const fromName = String(formData.get("mailFromName") ?? "").trim();
const contactRecipient = String(formData.get("mailContactRecipient") ?? "").trim();
const testRecipient = String(formData.get("mailTestRecipient") ?? "").trim();
return {
smtp: {
host,
port: parsePort(portValue || String(existingSettings.smtp.port)),
secure: isCheckedFormValue(formData.get("smtpSecure")),
username,
password: password.trim() ? password : existingSettings.smtp.password,
},
sender: {
email: fromEmail,
name: fromName,
},
recipients: {
contact: contactRecipient,
test: testRecipient,
},
};
}
export async function saveMailSettingsAction(formData: FormData) {
await ensureAdmin();
try {
const existingMailSettings = await getMailSettings();
const nextMailSettings = parseMailSettingsFormData(formData, existingMailSettings);
await updateMailSettings(nextMailSettings);
revalidatePath(toInternalAdminPath("/smtp"));
redirect(withMessage("/smtp", "success", "SMTP Einstellungen gespeichert."));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message =
error instanceof Error
? error.message
: "SMTP Einstellungen konnten nicht gespeichert werden.";
redirect(withMessage("/smtp", "error", message));
}
}
export async function sendTestEmailAction() {
await ensureAdmin();
try {
await sendTestEmail();
redirect(withMessage("/smtp", "success", "Test-E-Mail gesendet."));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message =
error instanceof Error
? error.message
: "Test-E-Mail konnte nicht gesendet werden.";
redirect(withMessage("/smtp", "error", message));
}
}
-112
View File
@@ -1,112 +0,0 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { isRedirectError } from "next/dist/client/components/redirect-error";
import { toInternalAdminPath } from "@/lib/admin-routing";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { isCheckedFormValue } from "@/lib/form-data";
import {
getContactProtectionSettings,
updateContactProtectionSettings,
} from "@/lib/app-config";
import type { ContactProtectionSettings } from "@/lib/contact-protection";
async function ensureAdmin() {
if (!(await isAdminAuthenticated())) {
await clearAdminSessionCookie();
redirect("/");
}
}
function withMessage(pathname: string, type: "success" | "error", message: string) {
const params = new URLSearchParams();
params.set(type, message);
return `${pathname}?${params.toString()}`;
}
function parseCount(value: string, fallback: number, label: string) {
const parsed = Number.parseInt(value || String(fallback), 10);
if (!Number.isInteger(parsed) || parsed <= 0) {
throw new Error(`${label} must be a positive number.`);
}
return parsed;
}
function parseContactProtectionFormData(
formData: FormData,
existingSettings: ContactProtectionSettings,
): ContactProtectionSettings {
const turnstileEnabled = isCheckedFormValue(formData.get("turnstileEnabled"));
const turnstileSiteKey = String(formData.get("turnstileSiteKey") ?? "").trim();
const turnstileSecretKey = String(formData.get("turnstileSecretKey") ?? "");
const rateLimitEnabled = isCheckedFormValue(formData.get("contactRateLimitEnabled"));
if (turnstileEnabled && !turnstileSiteKey) {
throw new Error("Turnstile site key is required when Turnstile is enabled.");
}
if (turnstileEnabled && !turnstileSecretKey.trim() && !existingSettings.turnstile.secretKey) {
throw new Error("Turnstile secret key is required when Turnstile is enabled.");
}
return {
turnstile: {
enabled: turnstileEnabled,
siteKey: turnstileSiteKey,
secretKey: turnstileSecretKey.trim()
? turnstileSecretKey
: existingSettings.turnstile.secretKey,
},
rateLimit: {
enabled: rateLimitEnabled,
maxRequests: parseCount(
String(formData.get("contactRateLimitMaxRequests") ?? ""),
existingSettings.rateLimit.maxRequests,
"Rate limit max requests",
),
windowMinutes: parseCount(
String(formData.get("contactRateLimitWindowMinutes") ?? ""),
existingSettings.rateLimit.windowMinutes,
"Rate limit window minutes",
),
},
};
}
export async function saveContactProtectionSettingsAction(formData: FormData) {
await ensureAdmin();
try {
const existingSettings = await getContactProtectionSettings();
const nextSettings = parseContactProtectionFormData(formData, existingSettings);
await updateContactProtectionSettings(nextSettings);
revalidatePath(toInternalAdminPath("/smtp/contact-protection"));
revalidatePath("/contact");
revalidatePath("/ar/contact");
revalidatePath("/en/contact");
redirect(
withMessage(
"/smtp/contact-protection",
"success",
"Contact Protection gespeichert.",
),
);
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message =
error instanceof Error
? error.message
: "Contact Protection konnte nicht gespeichert werden.";
redirect(withMessage("/smtp/contact-protection", "error", message));
}
}
-61
View File
@@ -1,61 +0,0 @@
import { redirect } from "next/navigation";
import { MotionFade } from "@/components/motion-fade";
import { ContactProtectionForm } from "@/components/root/contact-protection-form";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getContactProtectionFormValues } from "@/lib/app-config";
import { saveContactProtectionSettingsAction } from "./actions";
export const dynamic = "force-dynamic";
const copy = {
title: "Contact Protection",
subtitle: "Turnstile und Rate Limiting fuer das Kontaktformular.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "Settings",
smtp: "SMTP",
contactProtection: "Contact Protection",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
};
export default async function RootSMTPProtectionPage() {
if (!(await isAdminAuthenticated())) {
redirect("/");
}
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
const settings = await getContactProtectionFormValues();
return (
<RootDashboardShell
copy={copy}
active="smtp"
smtpChild="contact-protection"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
>
<div className="space-y-6">
<MotionFade delay={0.16}>
<ContactProtectionForm
action={saveContactProtectionSettingsAction}
initialSettings={settings}
/>
</MotionFade>
</div>
</RootDashboardShell>
);
}
-69
View File
@@ -1,69 +0,0 @@
import { redirect } from "next/navigation";
import { MotionFade } from "@/components/motion-fade";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { SMTPSettingsForm } from "@/components/root/smtp-settings-form";
import { Button } from "@/components/ui/button";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getMailSettingsFormValues } from "@/lib/app-config";
import { saveMailSettingsAction, sendTestEmailAction } from "./actions";
export const dynamic = "force-dynamic";
const copy = {
title: "SMTP",
subtitle: "Mailserver, Absender und Testempfaenger verwalten.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "Settings",
smtp: "SMTP",
contactProtection: "Contact Protection",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
};
export default async function RootSMTPPage() {
if (!(await isAdminAuthenticated())) {
redirect("/");
}
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
const mailSettings = await getMailSettingsFormValues();
return (
<RootDashboardShell
copy={copy}
active="smtp"
smtpChild="settings"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
headerActions={(
<form action={sendTestEmailAction}>
<Button type="submit" variant="outline">
Send test email
</Button>
</form>
)}
>
<div className="space-y-6">
<MotionFade delay={0.16}>
<SMTPSettingsForm
action={saveMailSettingsAction}
initialSettings={mailSettings}
/>
</MotionFade>
</div>
</RootDashboardShell>
);
}
-50
View File
@@ -1,50 +0,0 @@
import { redirect } from "next/navigation";
import { MotionFade } from "@/components/motion-fade";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { UiKitShowcase } from "@/components/ui/ui-kit-showcase";
export const dynamic = "force-dynamic";
const copy = {
title: "UI Kit",
subtitle: "Globale Referenz fuer das visuelle System im Root Bereich.",
maintenance: "Wartungsmodus",
overview: "Uebersicht",
uiKit: "UI Kit",
media: "Media",
siteSettings: "Settings",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
};
export default async function RootUiKitPage() {
const authenticated = await isAdminAuthenticated();
if (!authenticated) {
redirect("/");
}
async function logoutAction() {
"use server";
await clearAdminSessionCookie();
redirect("/");
}
return (
<RootDashboardShell
copy={copy}
active="ui-kit"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
>
<MotionFade delay={0.1}>
<UiKitShowcase localeKey="de" />
</MotionFade>
</RootDashboardShell>
);
}