feat: full site build — Project/Melody schema (Option A), admin CRUD, public sections, uploads, email+SMTP, internal analytics, legal pages, docs

This commit is contained in:
2026-08-05 20:53:40 +02:00
parent d87f3033c6
commit c26f41511f
122 changed files with 15068 additions and 41 deletions
+2 -2
View File
@@ -1,7 +1,7 @@
import type { Metadata } from "next";
import { getActiveLocale, getDictionary, isLocale, type Locale } from "@/lib/i18n";
import { buildPageMetadata } from "@/lib/metadata";
import { isComingSoonMode } from "@/lib/site";
import { isSiteClosedMode } from "@/lib/site";
import { notFound, redirect } from "next/navigation";
export function generateMetadata({ params }: { params: { locale: string } }): Metadata {
@@ -17,7 +17,7 @@ export default function AboutPage({ params }: { params: { locale: string } }) {
notFound();
}
if (isComingSoonMode()) {
if (isSiteClosedMode()) {
redirect("/");
}
+25
View File
@@ -0,0 +1,25 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import ProjectDetail from "@/components/public/project-detail";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getProjectDirectoryCopy } from "@/lib/project-content";
import { getPublishedProject } from "@/lib/project-queries";
type AppDetailPageProps = {
params: { locale: string; slug: string };
};
export function generateMetadata({ params }: AppDetailPageProps): Metadata {
if (!isLocale(params.locale)) return {};
const locale = getActiveLocale(params.locale as Locale);
const copy = getProjectDirectoryCopy(locale, "APP");
return { title: copy.eyebrow, description: copy.description };
}
export default async function AppDetailPage({ params }: AppDetailPageProps) {
if (!isLocale(params.locale)) notFound();
const locale = getActiveLocale(params.locale as Locale);
const project = await getPublishedProject("APP", params.slug);
if (!project) notFound();
return <ProjectDetail locale={locale} type="APP" project={project} />;
}
+23
View File
@@ -0,0 +1,23 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import ProjectDirectory from "@/components/public/project-directory";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getProjectDirectoryCopy } from "@/lib/project-content";
type AppsPageProps = {
params: { locale: string };
searchParams: { category?: string };
};
export function generateMetadata({ params }: { params: { locale: string } }): Metadata {
if (!isLocale(params.locale)) return {};
const locale = getActiveLocale(params.locale as Locale);
const copy = getProjectDirectoryCopy(locale, "APP");
return { title: copy.title, description: copy.description };
}
export default function AppsPage({ params, searchParams }: AppsPageProps) {
if (!isLocale(params.locale)) notFound();
const locale = getActiveLocale(params.locale as Locale);
return <ProjectDirectory locale={locale} type="APP" categorySlug={searchParams.category} />;
}
+39
View File
@@ -0,0 +1,39 @@
"use server";
import { headers } from "next/headers";
import { prisma } from "@/lib/db";
import { recordAnalyticsEvent } from "@/lib/analytics";
import { sendContactMessageEmail } from "@/lib/email";
import { consumeContactRateLimit, getClientIp } from "@/lib/rate-limit";
import { contactSchema } from "@/lib/validations/contact";
export type ContactActionResult = {
success?: true;
warning?: "email-not-sent";
error?: "invalid" | "rate-limit";
};
export async function submitContactMessage(input: unknown): Promise<ContactActionResult> {
const parsed = contactSchema.safeParse(input);
if (!parsed.success) return { error: "invalid" };
if (parsed.data.website) return { success: true };
const ip = getClientIp(headers());
if (!consumeContactRateLimit(`contact:${ip}`)) return { error: "rate-limit" };
const { name, email, message } = parsed.data;
await prisma.contactMessage.create({ data: { name, email, message } });
try {
await recordAnalyticsEvent({ type: "CONTACT_SUBMITTED", path: "/contact" });
} catch (error) {
console.error("Contact analytics failed", error);
}
try {
await sendContactMessageEmail({ name, email, message });
return { success: true };
} catch (error) {
console.error("Contact email delivery failed", error);
return { success: true, warning: "email-not-sent" };
}
}
+17 -2
View File
@@ -1,8 +1,9 @@
import type { Metadata } from "next";
import { getActiveLocale, getDictionary, isLocale, type Locale } from "@/lib/i18n";
import { buildPageMetadata } from "@/lib/metadata";
import { getContactChannels, isComingSoonMode } from "@/lib/site";
import { getContactChannels, isSiteClosedMode } from "@/lib/site";
import { notFound, redirect } from "next/navigation";
import ContactForm from "@/components/public/contact-form";
export function generateMetadata({ params }: { params: { locale: string } }): Metadata {
if (!isLocale(params.locale)) {
@@ -17,7 +18,7 @@ export default function ContactPage({ params }: { params: { locale: string } })
notFound();
}
if (isComingSoonMode()) {
if (isSiteClosedMode()) {
redirect("/");
}
@@ -38,6 +39,20 @@ export default function ContactPage({ params }: { params: { locale: string } })
<p>{dictionary.contact.availabilityDescription}</p>
</article>
<ContactForm
labels={{
name: dictionary.contact.formName,
email: dictionary.contact.formEmail,
message: dictionary.contact.formMessage,
submit: dictionary.contact.formSubmit,
sending: dictionary.contact.formSending,
success: dictionary.contact.formSuccess,
savedWarning: dictionary.contact.formSavedWarning,
invalid: dictionary.contact.formInvalid,
rateLimit: dictionary.contact.formRateLimit,
}}
/>
<div className="section-heading">
<h2>{dictionary.contact.channelsTitle}</h2>
</div>
+25
View File
@@ -0,0 +1,25 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import ProjectDetail from "@/components/public/project-detail";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getProjectDirectoryCopy } from "@/lib/project-content";
import { getPublishedProject } from "@/lib/project-queries";
type DesignDetailPageProps = {
params: { locale: string; slug: string };
};
export function generateMetadata({ params }: DesignDetailPageProps): Metadata {
if (!isLocale(params.locale)) return {};
const locale = getActiveLocale(params.locale as Locale);
const copy = getProjectDirectoryCopy(locale, "DESIGN");
return { title: copy.eyebrow, description: copy.description };
}
export default async function DesignDetailPage({ params }: DesignDetailPageProps) {
if (!isLocale(params.locale)) notFound();
const locale = getActiveLocale(params.locale as Locale);
const project = await getPublishedProject("DESIGN", params.slug);
if (!project) notFound();
return <ProjectDetail locale={locale} type="DESIGN" project={project} />;
}
+23
View File
@@ -0,0 +1,23 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import ProjectDirectory from "@/components/public/project-directory";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getProjectDirectoryCopy } from "@/lib/project-content";
type DesignsPageProps = {
params: { locale: string };
searchParams: { category?: string };
};
export function generateMetadata({ params }: { params: { locale: string } }): Metadata {
if (!isLocale(params.locale)) return {};
const locale = getActiveLocale(params.locale as Locale);
const copy = getProjectDirectoryCopy(locale, "DESIGN");
return { title: copy.title, description: copy.description };
}
export default function DesignsPage({ params, searchParams }: DesignsPageProps) {
if (!isLocale(params.locale)) notFound();
const locale = getActiveLocale(params.locale as Locale);
return <ProjectDirectory locale={locale} type="DESIGN" categorySlug={searchParams.category} />;
}
+4 -2
View File
@@ -4,7 +4,8 @@ import BottomNav from "@/components/BottomNav";
import SiteFooter from "@/components/SiteFooter";
import SiteHeader from "@/components/SiteHeader";
import { getActiveLocale, getDictionary, getDirection, getEnabledLocales, isLocale, type Locale } from "@/lib/i18n";
import { isComingSoonMode } from "@/lib/site";
import { isSiteClosedMode } from "@/lib/site";
import AnalyticsTracker from "@/components/public/analytics-tracker";
export const dynamicParams = false;
@@ -23,7 +24,7 @@ export default function LocaleLayout({
notFound();
}
if (isComingSoonMode()) {
if (isSiteClosedMode()) {
redirect("/");
}
@@ -33,6 +34,7 @@ export default function LocaleLayout({
return (
<div dir={getDirection(locale)} className="site-shell">
<SiteHeader locale={locale} common={dictionary.common} />
<AnalyticsTracker event="PAGE_VIEW" />
<main className="page-content">{children}</main>
<BottomNav locale={locale} common={dictionary.common} />
<SiteFooter locale={locale} common={dictionary.common} />
+18
View File
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import LegalDocument from "@/components/public/legal-document";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getLegalDocument } from "@/lib/legal-content";
type LegalPageProps = { params: { locale: string } };
export function generateMetadata({ params }: LegalPageProps): Metadata {
if (!isLocale(params.locale)) return {};
const document = getLegalDocument(getActiveLocale(params.locale as Locale), "impressum");
return { title: document.title, description: document.intro };
}
export default function ImpressumPage({ params }: LegalPageProps) {
if (!isLocale(params.locale)) notFound();
return <LegalDocument document={getLegalDocument(getActiveLocale(params.locale as Locale), "impressum")} />;
}
+18
View File
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import LegalDocument from "@/components/public/legal-document";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getLegalDocument } from "@/lib/legal-content";
type LegalPageProps = { params: { locale: string } };
export function generateMetadata({ params }: LegalPageProps): Metadata {
if (!isLocale(params.locale)) return {};
const document = getLegalDocument(getActiveLocale(params.locale as Locale), "privacy");
return { title: document.title, description: document.intro };
}
export default function PrivacyPage({ params }: LegalPageProps) {
if (!isLocale(params.locale)) notFound();
return <LegalDocument document={getLegalDocument(getActiveLocale(params.locale as Locale), "privacy")} />;
}
+18
View File
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import LegalDocument from "@/components/public/legal-document";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getLegalDocument } from "@/lib/legal-content";
type LegalPageProps = { params: { locale: string } };
export function generateMetadata({ params }: LegalPageProps): Metadata {
if (!isLocale(params.locale)) return {};
const document = getLegalDocument(getActiveLocale(params.locale as Locale), "terms");
return { title: document.title, description: document.intro };
}
export default function TermsPage({ params }: LegalPageProps) {
if (!isLocale(params.locale)) notFound();
return <LegalDocument document={getLegalDocument(getActiveLocale(params.locale as Locale), "terms")} />;
}
+22
View File
@@ -0,0 +1,22 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import MelodyDetail from "@/components/public/melody-detail";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getPublishedMelody } from "@/lib/melody-queries";
type MelodyDetailPageProps = { params: { locale: string; slug: string } };
export async function generateMetadata({ params }: MelodyDetailPageProps): Promise<Metadata> {
if (!isLocale(params.locale)) return {};
const melody = await getPublishedMelody(params.slug);
if (!melody) return {};
return { title: getActiveLocale(params.locale as Locale) === "ar" ? melody.titleAr : melody.titleEn };
}
export default async function MelodyDetailPage({ params }: MelodyDetailPageProps) {
if (!isLocale(params.locale)) notFound();
const locale = getActiveLocale(params.locale as Locale);
const melody = await getPublishedMelody(params.slug);
if (!melody) notFound();
return <MelodyDetail locale={locale} melody={melody} />;
}
+19
View File
@@ -0,0 +1,19 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import MelodyDirectory from "@/components/public/melody-directory";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getMelodyDirectoryCopy } from "@/lib/melody-content";
type MelodiesPageProps = { params: { locale: string }; searchParams: { category?: string } };
export function generateMetadata({ params }: { params: { locale: string } }): Metadata {
if (!isLocale(params.locale)) return {};
const copy = getMelodyDirectoryCopy(getActiveLocale(params.locale as Locale));
return { title: copy.title, description: copy.description };
}
export default function MelodiesPage({ params, searchParams }: MelodiesPageProps) {
if (!isLocale(params.locale)) notFound();
const locale = getActiveLocale(params.locale as Locale);
return <MelodyDirectory locale={locale} categorySlug={searchParams.category} />;
}
+25
View File
@@ -0,0 +1,25 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import ProjectDetail from "@/components/public/project-detail";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getProjectDirectoryCopy } from "@/lib/project-content";
import { getPublishedProject } from "@/lib/project-queries";
type WebsiteDetailPageProps = {
params: { locale: string; slug: string };
};
export function generateMetadata({ params }: WebsiteDetailPageProps): Metadata {
if (!isLocale(params.locale)) return {};
const locale = getActiveLocale(params.locale as Locale);
const copy = getProjectDirectoryCopy(locale, "WEBSITE");
return { title: copy.eyebrow, description: copy.description };
}
export default async function WebsiteDetailPage({ params }: WebsiteDetailPageProps) {
if (!isLocale(params.locale)) notFound();
const locale = getActiveLocale(params.locale as Locale);
const project = await getPublishedProject("WEBSITE", params.slug);
if (!project) notFound();
return <ProjectDetail locale={locale} type="WEBSITE" project={project} />;
}
+23
View File
@@ -0,0 +1,23 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import ProjectDirectory from "@/components/public/project-directory";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getProjectDirectoryCopy } from "@/lib/project-content";
type WebsitesPageProps = {
params: { locale: string };
searchParams: { category?: string };
};
export function generateMetadata({ params }: { params: { locale: string } }): Metadata {
if (!isLocale(params.locale)) return {};
const locale = getActiveLocale(params.locale as Locale);
const copy = getProjectDirectoryCopy(locale, "WEBSITE");
return { title: copy.title, description: copy.description };
}
export default function WebsitesPage({ params, searchParams }: WebsitesPageProps) {
if (!isLocale(params.locale)) notFound();
const locale = getActiveLocale(params.locale as Locale);
return <ProjectDirectory locale={locale} type="WEBSITE" categorySlug={searchParams.category} />;
}
+25
View File
@@ -0,0 +1,25 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import ProjectDetail from "@/components/public/project-detail";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getProjectDirectoryCopy } from "@/lib/project-content";
import { getPublishedProject } from "@/lib/project-queries";
type WorkDetailPageProps = {
params: { locale: string; slug: string };
};
export function generateMetadata({ params }: WorkDetailPageProps): Metadata {
if (!isLocale(params.locale)) return {};
const locale = getActiveLocale(params.locale as Locale);
const copy = getProjectDirectoryCopy(locale, "PORTFOLIO");
return { title: copy.eyebrow, description: copy.description };
}
export default async function WorkDetailPage({ params }: WorkDetailPageProps) {
if (!isLocale(params.locale)) notFound();
const locale = getActiveLocale(params.locale as Locale);
const project = await getPublishedProject("PORTFOLIO", params.slug);
if (!project) notFound();
return <ProjectDetail locale={locale} type="PORTFOLIO" project={project} />;
}
+23
View File
@@ -0,0 +1,23 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import ProjectDirectory from "@/components/public/project-directory";
import { getActiveLocale, isLocale, type Locale } from "@/lib/i18n";
import { getProjectDirectoryCopy } from "@/lib/project-content";
type WorkPageProps = {
params: { locale: string };
searchParams: { category?: string };
};
export function generateMetadata({ params }: { params: { locale: string } }): Metadata {
if (!isLocale(params.locale)) return {};
const locale = getActiveLocale(params.locale as Locale);
const copy = getProjectDirectoryCopy(locale, "PORTFOLIO");
return { title: copy.title, description: copy.description };
}
export default function WorkPage({ params, searchParams }: WorkPageProps) {
if (!isLocale(params.locale)) notFound();
const locale = getActiveLocale(params.locale as Locale);
return <ProjectDirectory locale={locale} type="PORTFOLIO" categorySlug={searchParams.category} />;
}
+34
View File
@@ -0,0 +1,34 @@
import AdminPageHeader from "@/components/admin/admin-page-header";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { getAnalyticsSummary } from "@/lib/analytics";
const eventLabels: Record<string, string> = {
PAGE_VIEW: "Page views",
PROJECT_OPEN: "Project opens",
MELODY_PLAY: "Melody plays",
PROJECT_LINK_CLICK: "Project link clicks",
CONTACT_SUBMITTED: "Contact submissions",
};
export default async function AnalyticsPage() {
const summary = await getAnalyticsSummary();
const grouped = summary.grouped.map((item) => ({ type: item.type, count: item._count._all }));
return (
<div className="mx-auto w-full max-w-7xl">
<AdminPageHeader title="Analytics" description="Internal counters from the last 30 days. No third-party analytics service is used." />
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-5">
{Object.entries(eventLabels).map(([type, label]) => (
<Card key={type}><CardHeader className="pb-3"><CardTitle className="text-sm font-medium text-muted-foreground">{label}</CardTitle></CardHeader><CardContent><p className="text-3xl font-semibold">{grouped.find((item) => item.type === type)?.count ?? 0}</p><p className="mt-1 text-xs text-muted-foreground">Last 30 days</p></CardContent></Card>
))}
</div>
<Card className="mt-6">
<CardHeader><CardTitle>Recent events</CardTitle></CardHeader>
<CardContent>
{summary.recent.length === 0 ? <p className="text-sm text-muted-foreground">No events recorded yet.</p> : <div className="space-y-3">{summary.recent.map((event) => <div key={event.id} className="flex flex-wrap items-center justify-between gap-3 border-b border-border pb-3 text-sm last:border-0 last:pb-0"><span className="font-medium">{eventLabels[event.type] ?? event.type}</span><span className="text-muted-foreground">{event.path || "—"} · {event.createdAt.toLocaleString("en-GB")}</span></div>)}</div>}
</CardContent>
</Card>
<p className="mt-5 text-xs text-muted-foreground">Total events recorded: {summary.total}</p>
</div>
);
}
@@ -0,0 +1,43 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Button } from "@/components/ui/button";
import AdminPageHeader from "@/components/admin/admin-page-header";
import CategoryForm from "@/components/admin/category-form";
import { prisma } from "@/lib/db";
type EditCategoryPageProps = {
params: { id: string };
};
export default async function EditCategoryPage({ params }: EditCategoryPageProps) {
const category = await prisma.category.findUnique({ where: { id: params.id } });
if (!category) {
notFound();
}
return (
<div className="mx-auto w-full max-w-7xl">
<AdminPageHeader
title="Edit category"
description={`Update ${category.nameEn} and keep its slug stable for public links.`}
actions={
<Button asChild variant="outline">
<Link href="/admin/categories">Back to categories</Link>
</Button>
}
/>
<CategoryForm
mode="edit"
categoryId={category.id}
defaultValues={{
kind: category.kind,
slug: category.slug,
nameAr: category.nameAr,
nameEn: category.nameEn,
order: category.order,
}}
/>
</div>
);
}
@@ -0,0 +1,97 @@
"use server";
import { Prisma } from "@prisma/client";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { categoryIdSchema, categorySchema } from "@/lib/validations/category";
export type CategoryActionResult = {
success?: true;
error?: string;
};
async function isAdminAuthenticated() {
const session = await auth();
return Boolean(session?.user);
}
function getValidationError(error: unknown) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
return "A category with this slug already exists.";
}
return "Unable to save the category right now.";
}
export async function createCategory(input: unknown): Promise<CategoryActionResult> {
if (!(await isAdminAuthenticated())) {
return { error: "Your session has expired. Please sign in again." };
}
const parsed = categorySchema.safeParse(input);
if (!parsed.success) {
return { error: parsed.error.issues[0]?.message ?? "Invalid category data." };
}
try {
await prisma.category.create({ data: parsed.data });
revalidatePath("/admin/categories");
return { success: true };
} catch (error) {
return { error: getValidationError(error) };
}
}
export async function updateCategory(categoryId: string, input: unknown): Promise<CategoryActionResult> {
if (!(await isAdminAuthenticated())) {
return { error: "Your session has expired. Please sign in again." };
}
const validId = categoryIdSchema.safeParse(categoryId);
const parsed = categorySchema.safeParse(input);
if (!validId.success) {
return { error: "Invalid category id." };
}
if (!parsed.success) {
return { error: parsed.error.issues[0]?.message ?? "Invalid category data." };
}
try {
await prisma.category.update({ where: { id: validId.data }, data: parsed.data });
revalidatePath("/admin/categories");
revalidatePath(`/admin/categories/${validId.data}/edit`);
return { success: true };
} catch (error) {
return { error: getValidationError(error) };
}
}
export async function deleteCategory(formData: FormData) {
if (!(await isAdminAuthenticated())) {
redirect("/admin/login");
}
const validId = categoryIdSchema.safeParse(formData.get("categoryId"));
if (!validId.success) {
redirect("/admin/categories?error=invalid-id");
}
try {
await prisma.category.delete({ where: { id: validId.data } });
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2003") {
redirect("/admin/categories?error=category-in-use");
}
redirect("/admin/categories?error=delete-failed");
}
revalidatePath("/admin/categories");
redirect("/admin/categories");
}
@@ -0,0 +1,24 @@
import Link from "next/link";
import { Button } from "@/components/ui/button";
import AdminPageHeader from "@/components/admin/admin-page-header";
import CategoryForm from "@/components/admin/category-form";
export default function NewCategoryPage() {
return (
<div className="mx-auto w-full max-w-7xl">
<AdminPageHeader
title="New category"
description="Create a category that can be reused across the public content sections."
actions={
<Button asChild variant="outline">
<Link href="/admin/categories">Back to categories</Link>
</Button>
}
/>
<CategoryForm
mode="create"
defaultValues={{ kind: "PROJECT", slug: "", nameAr: "", nameEn: "", order: 0 }}
/>
</div>
);
}
+101
View File
@@ -0,0 +1,101 @@
import Link from "next/link";
import { CategoryKind } from "@prisma/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import AdminPageHeader from "@/components/admin/admin-page-header";
import { deleteCategory } from "@/app/admin/(protected)/categories/actions";
import { prisma } from "@/lib/db";
const kindLabels: Record<CategoryKind, string> = {
PROJECT: "Projects",
MELODY: "Melodies",
};
type CategoriesPageProps = {
searchParams: { error?: string };
};
function getErrorMessage(error?: string) {
if (error === "category-in-use") return "This category cannot be deleted while content is linked to it.";
if (error === "invalid-id") return "The selected category id is invalid.";
if (error === "delete-failed") return "The category could not be deleted.";
return null;
}
export default async function CategoriesPage({ searchParams }: CategoriesPageProps) {
const categories = await prisma.category.findMany({
orderBy: [{ order: "asc" }, { nameEn: "asc" }],
include: {
_count: {
select: { projects: true, melodies: true },
},
},
});
const errorMessage = getErrorMessage(searchParams.error);
return (
<div className="mx-auto w-full max-w-7xl">
<AdminPageHeader
title="Categories"
description="Organize projects and melodies into reusable sections."
actions={
<Button asChild>
<Link href="/admin/categories/new">New category</Link>
</Button>
}
/>
{errorMessage ? (
<p className="mb-6 rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">
{errorMessage}
</p>
) : null}
{categories.length === 0 ? (
<Card>
<CardContent className="p-6">
<p className="text-sm text-muted-foreground">No categories yet. Create the first one to organize content.</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{categories.map((category) => (
<Card key={category.id}>
<CardHeader className="flex-row items-start justify-between gap-4 space-y-0">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.14em] text-brand-2">
{kindLabels[category.kind]}
</p>
<CardTitle className="mt-2 text-lg">{category.nameEn}</CardTitle>
<p className="mt-1 text-sm text-muted-foreground" dir="rtl">
{category.nameAr}
</p>
</div>
<span className="rounded-pill border border-border px-2 py-1 text-xs text-muted-foreground">
#{category.order}
</span>
</CardHeader>
<CardContent>
<p className="text-xs text-muted-foreground">/{category.slug}</p>
<p className="mt-3 text-sm text-muted-foreground">
{category._count.projects + category._count.melodies} linked items
</p>
<div className="mt-5 flex items-center gap-2">
<Button asChild size="sm" variant="outline">
<Link href={`/admin/categories/${category.id}/edit`}>Edit</Link>
</Button>
<form action={deleteCategory}>
<input type="hidden" name="categoryId" value={category.id} />
<Button type="submit" size="sm" variant="ghost">
Delete
</Button>
</form>
</div>
</CardContent>
</Card>
))}
</div>
)}
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
import type { ReactNode } from "react";
import { redirect } from "next/navigation";
import AdminShell from "@/components/admin/admin-shell";
import { auth, signOut } from "@/lib/auth";
export default async function AdminProtectedLayout({ children }: { children: ReactNode }) {
const session = await auth();
if (!session?.user) {
redirect("/admin/login");
}
async function handleSignOut() {
"use server";
await signOut({ redirectTo: "/admin/login" });
}
return (
<AdminShell userEmail={session.user.email ?? "Admin"} signOutAction={handleSignOut}>
{children}
</AdminShell>
);
}
@@ -0,0 +1,21 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Button } from "@/components/ui/button";
import AdminPageHeader from "@/components/admin/admin-page-header";
import MelodyForm from "@/components/admin/melody-form";
import { prisma } from "@/lib/db";
import type { MelodyInput } from "@/lib/validations/melody";
export default async function EditMelodyPage({ params }: { params: { id: string } }) {
const [melody, categories] = await Promise.all([
prisma.melody.findUnique({ where: { id: params.id } }),
prisma.category.findMany({ where: { kind: "MELODY" }, orderBy: [{ order: "asc" }, { nameEn: "asc" }], select: { id: true, nameAr: true, nameEn: true } }),
]);
if (!melody) notFound();
const defaultValues: MelodyInput = {
slug: melody.slug, titleAr: melody.titleAr, titleEn: melody.titleEn, descAr: melody.descAr ?? "", descEn: melody.descEn ?? "",
audioFile: melody.audioFile, coverImage: melody.coverImage ?? "", durationSec: melody.durationSec, isDownloadable: melody.isDownloadable,
status: melody.status, isFeatured: melody.isFeatured, sortOrder: melody.sortOrder, categoryId: melody.categoryId,
};
return <div className="mx-auto w-full max-w-7xl"><AdminPageHeader title={`Edit ${melody.titleEn}`} description="Update the audio, artwork, category, and public visibility settings." actions={<Button asChild variant="outline"><Link href="/admin/melodies">Back to melodies</Link></Button>} /><MelodyForm mode="edit" melodyId={melody.id} categories={categories} defaultValues={defaultValues} /></div>;
}
+116
View File
@@ -0,0 +1,116 @@
"use server";
import { Prisma } from "@prisma/client";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { melodyIdSchema, melodySchema } from "@/lib/validations/melody";
export type MelodyActionResult = {
success?: true;
error?: string;
};
async function isAdminAuthenticated() {
const session = await auth();
return Boolean(session?.user);
}
function getActionError(error: unknown) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
return "A melody with this slug already exists.";
}
return "Unable to save the melody right now.";
}
async function hasMelodyCategory(categoryId: string) {
const category = await prisma.category.findFirst({
where: { id: categoryId, kind: "MELODY" },
select: { id: true },
});
return Boolean(category);
}
function normalizeMelodyInput(input: unknown) {
const parsed = melodySchema.safeParse(input);
if (!parsed.success) {
return { error: parsed.error.issues[0]?.message ?? "Invalid melody data." } as const;
}
return {
data: {
...parsed.data,
descAr: parsed.data.descAr || null,
descEn: parsed.data.descEn || null,
coverImage: parsed.data.coverImage || null,
},
} as const;
}
export async function createMelody(input: unknown): Promise<MelodyActionResult> {
if (!(await isAdminAuthenticated())) {
return { error: "Your session has expired. Please sign in again." };
}
const normalized = normalizeMelodyInput(input);
if ("error" in normalized) return normalized;
if (!(await hasMelodyCategory(normalized.data.categoryId))) {
return { error: "Choose a valid melody category." };
}
try {
await prisma.melody.create({ data: normalized.data });
revalidatePath("/admin/melodies");
revalidatePath("/en/melodies");
return { success: true };
} catch (error) {
return { error: getActionError(error) };
}
}
export async function updateMelody(melodyId: string, input: unknown): Promise<MelodyActionResult> {
if (!(await isAdminAuthenticated())) {
return { error: "Your session has expired. Please sign in again." };
}
const validId = melodyIdSchema.safeParse(melodyId);
if (!validId.success) return { error: "Invalid melody id." };
const normalized = normalizeMelodyInput(input);
if ("error" in normalized) return normalized;
if (!(await hasMelodyCategory(normalized.data.categoryId))) {
return { error: "Choose a valid melody category." };
}
try {
await prisma.melody.update({ where: { id: validId.data }, data: normalized.data });
revalidatePath("/admin/melodies");
revalidatePath(`/admin/melodies/${validId.data}/edit`);
revalidatePath("/en/melodies");
return { success: true };
} catch (error) {
return { error: getActionError(error) };
}
}
export async function deleteMelody(formData: FormData) {
if (!(await isAdminAuthenticated())) redirect("/admin/login");
const validId = melodyIdSchema.safeParse(formData.get("melodyId"));
if (!validId.success) redirect("/admin/melodies?error=invalid-id");
try {
await prisma.melody.delete({ where: { id: validId.data } });
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2025") {
redirect("/admin/melodies?error=not-found");
}
redirect("/admin/melodies?error=delete-failed");
}
revalidatePath("/admin/melodies");
revalidatePath("/en/melodies");
redirect("/admin/melodies");
}
@@ -0,0 +1,16 @@
import Link from "next/link";
import { Button } from "@/components/ui/button";
import AdminPageHeader from "@/components/admin/admin-page-header";
import MelodyForm from "@/components/admin/melody-form";
import { prisma } from "@/lib/db";
import type { MelodyInput } from "@/lib/validations/melody";
export default async function NewMelodyPage() {
const categories = await prisma.category.findMany({ where: { kind: "MELODY" }, orderBy: [{ order: "asc" }, { nameEn: "asc" }], select: { id: true, nameAr: true, nameEn: true } });
const defaultValues: MelodyInput = {
slug: "", titleAr: "", titleEn: "", descAr: "", descEn: "", audioFile: "", coverImage: "", durationSec: null,
isDownloadable: false, status: "DRAFT", isFeatured: false, sortOrder: 0, categoryId: "",
};
return <div className="mx-auto w-full max-w-7xl"><AdminPageHeader title="New melody" description="Create an audio track with its cover, category, and publishing controls." actions={<Button asChild variant="outline"><Link href="/admin/melodies">Back to melodies</Link></Button>} /><MelodyForm mode="create" categories={categories} defaultValues={defaultValues} /></div>;
}
+53
View File
@@ -0,0 +1,53 @@
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import AdminPageHeader from "@/components/admin/admin-page-header";
import { deleteMelody } from "@/app/admin/(protected)/melodies/actions";
import { prisma } from "@/lib/db";
type MelodiesPageProps = { searchParams: { error?: string } };
function getErrorMessage(error?: string) {
if (error === "invalid-id") return "The selected melody id is invalid.";
if (error === "not-found") return "The selected melody no longer exists.";
if (error === "delete-failed") return "The melody could not be deleted.";
return null;
}
export default async function MelodiesPage({ searchParams }: MelodiesPageProps) {
const melodies = await prisma.melody.findMany({
orderBy: [{ isFeatured: "desc" }, { sortOrder: "asc" }, { updatedAt: "desc" }],
include: { category: { select: { nameEn: true, nameAr: true } } },
});
const errorMessage = getErrorMessage(searchParams.error);
return (
<div className="mx-auto w-full max-w-7xl">
<AdminPageHeader title="Melodies" description="Manage audio tracks, cover art, categories, publishing, and download permissions." actions={<Button asChild><Link href="/admin/melodies/new">New melody</Link></Button>} />
{errorMessage ? <p className="mb-6 rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">{errorMessage}</p> : null}
{melodies.length === 0 ? (
<Card><CardContent className="p-6"><p className="text-sm text-muted-foreground">No melodies yet.</p></CardContent></Card>
) : (
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{melodies.map((melody) => (
<Card key={melody.id}>
<CardHeader className="flex-row items-start justify-between gap-4 space-y-0">
<div><CardTitle className="text-lg">{melody.titleEn}</CardTitle><p className="mt-1 text-sm text-muted-foreground" dir="rtl">{melody.titleAr}</p></div>
<span className="rounded-pill border border-border px-2 py-1 text-xs text-muted-foreground">{melody.status}</span>
</CardHeader>
<CardContent>
<p className="text-xs text-muted-foreground">/{melody.slug}</p>
<p className="mt-2 text-sm text-muted-foreground">{melody.category.nameEn} · {melody.category.nameAr}</p>
<p className="mt-2 text-xs text-muted-foreground">{melody.durationSec ? `${melody.durationSec}s` : "No duration"} · {melody.isDownloadable ? "Download enabled" : "Streaming only"}</p>
<div className="mt-5 flex items-center gap-2">
<Button asChild size="sm" variant="outline"><Link href={`/admin/melodies/${melody.id}/edit`}>Edit</Link></Button>
<form action={deleteMelody}><input type="hidden" name="melodyId" value={melody.id} /><Button type="submit" size="sm" variant="ghost">Delete</Button></form>
</div>
</CardContent>
</Card>
))}
</div>
)}
</div>
);
}
+48
View File
@@ -0,0 +1,48 @@
import { redirect } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import AdminPageHeader from "@/components/admin/admin-page-header";
import { auth } from "@/lib/auth";
export default async function AdminPage() {
const session = await auth();
if (!session?.user) {
redirect("/admin/login");
}
return (
<div className="mx-auto w-full max-w-7xl">
<AdminPageHeader
title="Dashboard"
description="Manage the content that will power the public website."
/>
<section aria-label="Workspace overview" className="grid gap-4 md:grid-cols-3">
<Card>
<CardHeader>
<CardTitle className="text-base">Signed-in account</CardTitle>
</CardHeader>
<CardContent>
<p className="truncate text-sm text-muted-foreground">{session.user.email}</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">Content status</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">Coming soon mode is active.</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">Next step</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">Categories and content tools are next.</p>
</CardContent>
</Card>
</section>
</div>
);
}
@@ -0,0 +1,63 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Button } from "@/components/ui/button";
import AdminPageHeader from "@/components/admin/admin-page-header";
import ProjectForm from "@/components/admin/project-form";
import { prisma } from "@/lib/db";
import type { ProjectInput } from "@/lib/validations/project";
export default async function EditProjectPage({ params }: { params: { id: string } }) {
const [project, categories] = await Promise.all([
prisma.project.findUnique({ where: { id: params.id } }),
prisma.category.findMany({
where: { kind: "PROJECT" },
orderBy: [{ order: "asc" }, { nameEn: "asc" }],
select: { id: true, nameAr: true, nameEn: true },
}),
]);
if (!project) {
notFound();
}
const defaultValues: ProjectInput = {
type: project.type,
slug: project.slug,
titleAr: project.titleAr,
titleEn: project.titleEn,
summaryAr: project.summaryAr ?? "",
summaryEn: project.summaryEn ?? "",
descAr: project.descAr ?? "",
descEn: project.descEn ?? "",
coverImage: project.coverImage ?? "",
images: project.images,
technologies: project.technologies,
externalUrl: project.externalUrl ?? "",
repoUrl: project.repoUrl ?? "",
platform: project.platform ?? "",
appStoreUrl: project.appStoreUrl ?? "",
testflightUrl: project.testflightUrl ?? "",
appVersion: project.appVersion ?? "",
supportUrl: project.supportUrl ?? "",
appPrivacyUrl: project.appPrivacyUrl ?? "",
status: project.status,
isFeatured: project.isFeatured,
sortOrder: project.sortOrder,
categoryId: project.categoryId ?? "",
};
return (
<div className="mx-auto w-full max-w-7xl">
<AdminPageHeader
title={`Edit ${project.titleEn}`}
description="Update the project details, media paths, category, and public visibility settings."
actions={
<Button asChild variant="outline">
<Link href="/admin/projects">Back to projects</Link>
</Button>
}
/>
<ProjectForm mode="edit" projectId={project.id} categories={categories} defaultValues={defaultValues} />
</div>
);
}
+150
View File
@@ -0,0 +1,150 @@
"use server";
import { Prisma } from "@prisma/client";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { projectIdSchema, projectSchema } from "@/lib/validations/project";
export type ProjectActionResult = {
success?: true;
error?: string;
};
async function isAdminAuthenticated() {
const session = await auth();
return Boolean(session?.user);
}
function getActionError(error: unknown) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
return "A project with this slug already exists.";
}
return "Unable to save the project right now.";
}
async function validateProjectCategory(categoryId: string | undefined) {
if (!categoryId) {
return null;
}
const category = await prisma.category.findFirst({
where: { id: categoryId, kind: "PROJECT" },
select: { id: true },
});
return category?.id ?? false;
}
function normalizeProjectInput(input: unknown) {
const parsed = projectSchema.safeParse(input);
if (!parsed.success) {
return { error: parsed.error.issues[0]?.message ?? "Invalid project data." } as const;
}
return {
data: {
...parsed.data,
categoryId: parsed.data.categoryId || null,
coverImage: parsed.data.coverImage || null,
summaryAr: parsed.data.summaryAr || null,
summaryEn: parsed.data.summaryEn || null,
descAr: parsed.data.descAr || null,
descEn: parsed.data.descEn || null,
externalUrl: parsed.data.externalUrl || null,
repoUrl: parsed.data.repoUrl || null,
platform: parsed.data.platform || null,
appStoreUrl: parsed.data.appStoreUrl || null,
testflightUrl: parsed.data.testflightUrl || null,
appVersion: parsed.data.appVersion || null,
supportUrl: parsed.data.supportUrl || null,
appPrivacyUrl: parsed.data.appPrivacyUrl || null,
},
} as const;
}
export async function createProject(input: unknown): Promise<ProjectActionResult> {
if (!(await isAdminAuthenticated())) {
return { error: "Your session has expired. Please sign in again." };
}
const normalized = normalizeProjectInput(input);
if ("error" in normalized) {
return normalized;
}
if ((await validateProjectCategory(normalized.data.categoryId ?? undefined)) === false) {
return { error: "Choose a valid project category." };
}
try {
await prisma.project.create({ data: normalized.data });
revalidatePath("/admin/projects");
revalidatePath("/en/work");
revalidatePath("/en/apps");
revalidatePath("/en/websites");
revalidatePath("/en/designs");
return { success: true };
} catch (error) {
return { error: getActionError(error) };
}
}
export async function updateProject(projectId: string, input: unknown): Promise<ProjectActionResult> {
if (!(await isAdminAuthenticated())) {
return { error: "Your session has expired. Please sign in again." };
}
const validId = projectIdSchema.safeParse(projectId);
if (!validId.success) {
return { error: "Invalid project id." };
}
const normalized = normalizeProjectInput(input);
if ("error" in normalized) {
return normalized;
}
if ((await validateProjectCategory(normalized.data.categoryId ?? undefined)) === false) {
return { error: "Choose a valid project category." };
}
try {
await prisma.project.update({ where: { id: validId.data }, data: normalized.data });
revalidatePath("/admin/projects");
revalidatePath(`/admin/projects/${validId.data}/edit`);
revalidatePath("/en/work");
revalidatePath("/en/apps");
revalidatePath("/en/websites");
revalidatePath("/en/designs");
return { success: true };
} catch (error) {
return { error: getActionError(error) };
}
}
export async function deleteProject(formData: FormData) {
if (!(await isAdminAuthenticated())) {
redirect("/admin/login");
}
const validId = projectIdSchema.safeParse(formData.get("projectId"));
if (!validId.success) {
redirect("/admin/projects?error=invalid-id");
}
try {
await prisma.project.delete({ where: { id: validId.data } });
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2025") {
redirect("/admin/projects?error=not-found");
}
redirect("/admin/projects?error=delete-failed");
}
revalidatePath("/admin/projects");
redirect("/admin/projects");
}
@@ -0,0 +1,55 @@
import Link from "next/link";
import { Button } from "@/components/ui/button";
import AdminPageHeader from "@/components/admin/admin-page-header";
import ProjectForm from "@/components/admin/project-form";
import { prisma } from "@/lib/db";
import type { ProjectInput } from "@/lib/validations/project";
export default async function NewProjectPage() {
const categories = await prisma.category.findMany({
where: { kind: "PROJECT" },
orderBy: [{ order: "asc" }, { nameEn: "asc" }],
select: { id: true, nameAr: true, nameEn: true },
});
const defaultValues: ProjectInput = {
type: "PORTFOLIO",
slug: "",
titleAr: "",
titleEn: "",
summaryAr: "",
summaryEn: "",
descAr: "",
descEn: "",
coverImage: "",
images: [],
technologies: [],
externalUrl: "",
repoUrl: "",
platform: "",
appStoreUrl: "",
testflightUrl: "",
appVersion: "",
supportUrl: "",
appPrivacyUrl: "",
status: "DRAFT",
isFeatured: false,
sortOrder: 0,
categoryId: "",
};
return (
<div className="mx-auto w-full max-w-7xl">
<AdminPageHeader
title="New project"
description="Create a project or app record with media, links, category, and publishing controls."
actions={
<Button asChild variant="outline">
<Link href="/admin/projects">Back to projects</Link>
</Button>
}
/>
<ProjectForm mode="create" categories={categories} defaultValues={defaultValues} />
</div>
);
}
+113
View File
@@ -0,0 +1,113 @@
import Link from "next/link";
import { ProjectType } from "@prisma/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import AdminPageHeader from "@/components/admin/admin-page-header";
import { deleteProject } from "@/app/admin/(protected)/projects/actions";
import { prisma } from "@/lib/db";
import { projectTypeFilterSchema } from "@/lib/validations/project";
const typeLabels: Record<ProjectType, string> = {
PORTFOLIO: "Portfolio",
APP: "App",
WEBSITE: "Website",
DESIGN: "Design",
};
type ProjectsPageProps = {
searchParams: { type?: string; error?: string };
};
function getErrorMessage(error?: string) {
if (error === "invalid-id") return "The selected project id is invalid.";
if (error === "not-found") return "The selected project no longer exists.";
if (error === "delete-failed") return "The project could not be deleted.";
return null;
}
export default async function ProjectsPage({ searchParams }: ProjectsPageProps) {
const type = projectTypeFilterSchema.safeParse(searchParams.type);
const selectedType = type.success ? type.data : undefined;
const projects = await prisma.project.findMany({
where: selectedType ? { type: selectedType } : undefined,
orderBy: [{ sortOrder: "asc" }, { updatedAt: "desc" }],
include: { category: { select: { nameEn: true, nameAr: true } } },
});
const errorMessage = getErrorMessage(searchParams.error);
return (
<div className="mx-auto w-full max-w-7xl">
<AdminPageHeader
title="Projects"
description="Manage portfolio work, apps, websites, designs, and the project records used by public pages."
actions={
<Button asChild>
<Link href="/admin/projects/new">New project</Link>
</Button>
}
/>
{errorMessage ? (
<p className="mb-6 rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">
{errorMessage}
</p>
) : null}
<div className="mb-6 flex flex-wrap gap-2">
<Button asChild size="sm" variant={!selectedType ? "default" : "outline"}>
<Link href="/admin/projects">All</Link>
</Button>
{Object.entries(typeLabels).map(([value, label]) => (
<Button key={value} asChild size="sm" variant={selectedType === value ? "default" : "outline"}>
<Link href={`/admin/projects?type=${value}`}>{label}</Link>
</Button>
))}
</div>
{projects.length === 0 ? (
<Card>
<CardContent className="p-6">
<p className="text-sm text-muted-foreground">No projects match this filter yet.</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{projects.map((project) => (
<Card key={project.id}>
<CardHeader className="flex-row items-start justify-between gap-4 space-y-0">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.14em] text-brand-2">{typeLabels[project.type]}</p>
<CardTitle className="mt-2 text-lg">{project.titleEn}</CardTitle>
<p className="mt-1 text-sm text-muted-foreground" dir="rtl">
{project.titleAr}
</p>
</div>
<span className="rounded-pill border border-border px-2 py-1 text-xs text-muted-foreground">{project.status}</span>
</CardHeader>
<CardContent>
<p className="text-xs text-muted-foreground">/{project.slug}</p>
<p className="mt-2 text-sm text-muted-foreground">
{project.category ? `${project.category.nameEn} · ${project.category.nameAr}` : "No category"}
</p>
<p className="mt-2 text-xs text-muted-foreground">
{project.images.length} images · {project.technologies.length} technologies
</p>
<div className="mt-5 flex items-center gap-2">
<Button asChild size="sm" variant="outline">
<Link href={`/admin/projects/${project.id}/edit`}>Edit</Link>
</Button>
<form action={deleteProject}>
<input type="hidden" name="projectId" value={project.id} />
<Button type="submit" size="sm" variant="ghost">
Delete
</Button>
</form>
</div>
</CardContent>
</Card>
))}
</div>
)}
</div>
);
}
+17
View File
@@ -0,0 +1,17 @@
import { redirect } from "next/navigation";
import LoginForm from "@/components/admin/login-form";
import { auth } from "@/lib/auth";
export default async function AdminLoginPage() {
const session = await auth();
if (session?.user) {
redirect("/admin");
}
return (
<main className="flex min-h-screen items-center justify-center bg-background p-6 text-foreground">
<LoginForm />
</main>
);
}
+19
View File
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { headers } from "next/headers";
import { recordAnalyticsEvent } from "@/lib/analytics";
import { consumeRateLimit, getClientIp } from "@/lib/rate-limit";
export async function POST(request: Request) {
const ip = getClientIp(headers());
if (!consumeRateLimit(`analytics:${ip}`, 60, 60 * 1000)) {
return NextResponse.json({ error: "rate-limited" }, { status: 429 });
}
try {
const input = await request.json();
const recorded = await recordAnalyticsEvent(input);
return recorded ? new NextResponse(null, { status: 204 }) : NextResponse.json({ error: "invalid-event" }, { status: 400 });
} catch {
return NextResponse.json({ error: "invalid-request" }, { status: 400 });
}
}
+3
View File
@@ -0,0 +1,3 @@
import { handlers } from "@/lib/auth";
export const { GET, POST } = handlers;
+33
View File
@@ -0,0 +1,33 @@
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { saveUploadedFile, UploadError } from "@/lib/upload";
import { uploadKindSchema } from "@/lib/validations/upload";
export const runtime = "nodejs";
export async function POST(request: Request) {
const session = await auth();
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized." }, { status: 401 });
}
try {
const formData = await request.formData();
const kindResult = uploadKindSchema.safeParse(formData.get("kind"));
const file = formData.get("file");
if (!kindResult.success || !(file instanceof File)) {
return NextResponse.json({ error: "A valid upload kind and file are required." }, { status: 400 });
}
const uploadedFile = await saveUploadedFile(file, kindResult.data);
return NextResponse.json(uploadedFile, { status: 201 });
} catch (error) {
if (error instanceof UploadError) {
return NextResponse.json({ error: error.message }, { status: error.statusCode });
}
console.error("Upload failed", error);
return NextResponse.json({ error: "The file could not be uploaded." }, { status: 500 });
}
}
+4
View File
@@ -1,3 +1,7 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--bg: #07111f;
--surface: rgba(11, 20, 36, 0.84);
+8 -9
View File
@@ -1,11 +1,10 @@
import type { Metadata } from "next";
import type { ReactNode } from "react";
import { siteConfig } from "@/lib/site";
import { isComingSoonMode } from "@/lib/site";
import { isSiteClosedMode, siteConfig } from "@/lib/site";
import "./globals.css";
export function generateMetadata(): Metadata {
const comingSoon = isComingSoonMode();
const siteClosed = isSiteClosedMode();
return {
metadataBase: new URL(siteConfig.siteUrl),
@@ -13,7 +12,7 @@ export function generateMetadata(): Metadata {
default: "Diyaa",
template: "%s | Diyaa",
},
description: comingSoon
description: siteClosed
? "Minimal coming soon page for the upcoming launch."
: "Bilingual professional website built for private-server deployment.",
applicationName: "Diyaa",
@@ -21,7 +20,7 @@ export function generateMetadata(): Metadata {
creator: "Diyaa",
publisher: "Diyaa",
alternates: {
languages: comingSoon
languages: siteClosed
? {
en: "/",
"x-default": "/",
@@ -36,11 +35,11 @@ export function generateMetadata(): Metadata {
}
function getThemeScript() {
const comingSoon = isComingSoonMode();
const siteClosed = isSiteClosedMode();
return `
(() => {
const locale = ${comingSoon ? '"en"' : 'window.location.pathname.split("/").filter(Boolean)[0] === "en" ? "en" : "ar"'};
const locale = ${siteClosed ? '"en"' : 'window.location.pathname.split("/").filter(Boolean)[0] === "en" ? "en" : "ar"'};
const direction = locale === "ar" ? "rtl" : "ltr";
document.documentElement.lang = locale;
document.documentElement.dir = direction;
@@ -56,10 +55,10 @@ function getThemeScript() {
}
export default function RootLayout({ children }: { children: ReactNode }) {
const comingSoon = isComingSoonMode();
const siteClosed = isSiteClosedMode();
return (
<html lang={comingSoon ? "en" : "ar"} dir={comingSoon ? "ltr" : "rtl"} data-theme="dark" suppressHydrationWarning>
<html lang={siteClosed ? "en" : "ar"} dir={siteClosed ? "ltr" : "rtl"} data-theme="dark" suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: getThemeScript() }} />
</head>
+4 -4
View File
@@ -1,8 +1,8 @@
import Link from "next/link";
import { isComingSoonMode } from "@/lib/site";
import { isSiteClosedMode } from "@/lib/site";
export default function NotFound() {
const comingSoon = isComingSoonMode();
const siteClosed = isSiteClosedMode();
return (
<main className="page-content">
@@ -11,14 +11,14 @@ export default function NotFound() {
<p className="eyebrow">404</p>
<h1>الصفحة غير موجودة</h1>
<p className="lead">
{comingSoon
{siteClosed
? "الصفحة المطلوبة غير متاحة حاليًا. يمكنك العودة إلى الصفحة الرئيسية."
: "الصفحة المطلوبة غير متاحة حاليًا. يمكنك العودة إلى النسخة العربية أو الإنجليزية من الصفحة الرئيسية."}
</p>
</div>
<div className="cta-row">
{comingSoon ? (
{siteClosed ? (
<Link href="/" className="cta-btn">
العودة إلى الرئيسية
</Link>
+2 -2
View File
@@ -1,8 +1,8 @@
import { redirect } from "next/navigation";
import { isComingSoonMode } from "@/lib/site";
import { isSiteClosedMode } from "@/lib/site";
export default function RootPage() {
if (isComingSoonMode()) {
if (isSiteClosedMode()) {
return (
<main className="coming-soon-page">
<h1 className="coming-soon-title">Coming Soon123</h1>
+5 -6
View File
@@ -1,16 +1,15 @@
import type { MetadataRoute } from "next";
import { getLocalizedPath, siteConfig } from "@/lib/site";
import { isComingSoonMode } from "@/lib/site";
import { getLocalizedPath, isSiteClosedMode, siteConfig } from "@/lib/site";
import type { Locale } from "@/lib/i18n";
const allPages = ["", "/about", "/contact"] as const;
const allPages = ["", "/about", "/contact", "/legal/privacy", "/legal/terms", "/legal/impressum"] as const;
const allLocales = ["ar", "en"] as const;
export default function sitemap(): MetadataRoute.Sitemap {
const lastModified = new Date();
const comingSoon = isComingSoonMode();
const pages: readonly (typeof allPages)[number][] = comingSoon ? [] : allPages;
const locales: readonly Locale[] = comingSoon ? [] : allLocales;
const siteClosed = isSiteClosedMode();
const pages: readonly (typeof allPages)[number][] = siteClosed ? [] : allPages;
const locales: readonly Locale[] = siteClosed ? [] : allLocales;
return [
{