Enhance Next.js configuration and dependencies for improved functionality and localization support. Added support for internationalization with next-intl, updated global styles, and integrated new fonts. Removed default home page and updated README with project details and setup instructions.

This commit is contained in:
smhk1376 committed 2026-09-24 14:53:01 +03:30
1 parent 2911dea00b
commit 44f4fa98e2
320 files changed
+31666 -220

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { Container } from "@/components/atoms/Container";
import { Section } from "@/components/atoms/Section";
import { PageHero } from "@/components/molecules/PageHero";
import { getLegalPage } from "@/lib/data/site";
type Props = { params: Promise<{ slug: string }> };
const ALLOWED = new Set(["privacy", "accessibility", "press", "careers"]);
export async function generateStaticParams() {
return [...ALLOWED].map((slug) => ({ slug }));
}
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const page = await getLegalPage(slug);
if (!page) return { title: "صفحه یافت نشد" };
return { title: page.title, description: page.body[0] };
}
export default async function LegalSlugPage({ params }: Props) {
const { slug } = await params;
if (!ALLOWED.has(slug)) notFound();
const page = await getLegalPage(slug);
if (!page) notFound();
return (
<main id="main-content">
<PageHero title={page.title} />
<Section className="bg-gradient-to-b from-background to-muted/40">
<Container narrow className="space-y-5 rounded-2xl bg-card p-6 shadow-sm ring-1 ring-border sm:p-10">
{page.body.map((paragraph) => (
<p key={paragraph} className="leading-8 text-foreground/90">
{paragraph}
</p>
))}
</Container>
</Section>
</main>
);
}
+67
View File
@@ -0,0 +1,67 @@
import type { Metadata } from "next";
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { Container } from "@/components/atoms/Container";
import { Heading } from "@/components/atoms/Heading";
import { Section } from "@/components/atoms/Section";
import { PageHero } from "@/components/molecules/PageHero";
import { SurfaceCard } from "@/components/molecules/SurfaceCard";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { getTopics } from "@/lib/data/site";
import { aboutFocusAreas, siteMission } from "@/lib/site-config";
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("pages");
return { title: t("aboutTitle"), description: siteMission };
}
export default async function AboutPage() {
const t = await getTranslations("pages");
const topics = await getTopics();
return (
<main id="main-content">
<PageHero title={t("aboutTitle")} intro={siteMission} />
<Section className="relative overflow-hidden">
<Container>
<p className="text-xs font-bold text-primary">مسیرهای اثرگذاری</p><Heading level={2} className="mt-2 text-3xl sm:text-4xl">حوزه‌های تمرکز</Heading>
<div className="mt-8 grid gap-4 sm:grid-cols-2">
{aboutFocusAreas.map((area) => (
<SurfaceCard key={area.title}>
<Heading as="h3" level={4}>
{area.title}
</Heading>
<p className="mt-2 text-sm text-muted-foreground">
{area.description}
</p>
</SurfaceCard>
))}
</div>
</Container>
</Section>
<Section tone="muted">
<Container>
<p className="text-xs font-bold text-primary">نگاه میان‌رشته‌ای</p><Heading level={2} className="mt-2 text-3xl sm:text-4xl">تقاطع مدیریت و فناوری</Heading>
<div className="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{topics.map((topic) => (
<SurfaceCard key={topic.id} padded="sm" className="h-full">
<Link href={topic.href} className="block">
<span className="font-semibold hover:text-primary">
{topic.title}
</span>
<p className="mt-2 text-sm text-muted-foreground">
{topic.description}
</p>
</Link>
</SurfaceCard>
))}
</div>
<Link href="/programs" className={cn(buttonVariants(), "mt-8")}>
کشف برنامه‌ها
</Link>
</Container>
</Section>
</main>
);
}
+60
View File
@@ -0,0 +1,60 @@
import type { Metadata } from "next";
import Image from "next/image";
import { getTranslations } from "next-intl/server";
import { Container } from "@/components/atoms/Container";
import { Heading } from "@/components/atoms/Heading";
import { Section } from "@/components/atoms/Section";
import { BadgeLabel } from "@/components/atoms/BadgeLabel";
import { PageHero } from "@/components/molecules/PageHero";
import { SurfaceCard } from "@/components/molecules/SurfaceCard";
import { getAlumniStories } from "@/lib/data/site";
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("pages");
return { title: t("alumniTitle"), description: t("alumniIntro") };
}
export default async function AlumniPage() {
const t = await getTranslations("pages");
const stories = await getAlumniStories();
return (
<main id="main-content">
<PageHero title={t("alumniTitle")} intro={t("alumniIntro")} />
<Section className="bg-gradient-to-b from-background to-muted/40">
<Container>
<div className="grid gap-8 md:grid-cols-3">
{stories.map((story) => (
<SurfaceCard
key={story.id}
id={story.id}
padded={false}
className="group scroll-mt-24 overflow-hidden rounded-2xl"
>
<div className="relative aspect-[16/10]">
<Image
src={story.imageUrl}
alt={story.name}
fill
className="object-cover transition-transform duration-500 group-hover:scale-[1.03]"
sizes="(max-width:768px) 100vw, 33vw"
/>
</div>
<div className="p-5">
<BadgeLabel>{story.program}</BadgeLabel>
<Heading as="h2" level={4} className="mt-3">
{story.title}
</Heading>
<p className="mt-2 text-sm leading-7 text-muted-foreground">
{story.excerpt}
</p>
<p className="mt-4 text-sm font-semibold">{story.name}</p>
</div>
</SurfaceCard>
))}
</div>
</Container>
</Section>
</main>
);
}
+74
View File
@@ -0,0 +1,74 @@
import type { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import { Container } from "@/components/atoms/Container";
import { Heading } from "@/components/atoms/Heading";
import { Section } from "@/components/atoms/Section";
import { PageHero } from "@/components/molecules/PageHero";
import { ContactInterestForm } from "@/components/organisms/ContactInterestForm";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { siteAddress } from "@/lib/site-config";
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("pages");
return { title: t("contactTitle"), description: t("contactIntro") };
}
export default async function ContactPage() {
const t = await getTranslations("pages");
return (
<main id="main-content">
<PageHero title={t("contactTitle")} intro={t("contactIntro")} />
<Section className="bg-gradient-to-b from-background to-muted/40">
<Container className="grid gap-10 lg:grid-cols-2">
<div className="space-y-5 lg:pt-4">
<Heading level={2}>اطلاعات تماس</Heading>
<div className="space-y-3 text-sm leading-7 text-muted-foreground">
<p>
<span className="font-semibold text-foreground">آدرس: </span>
{siteAddress.line}
</p>
<p dir="ltr">
<span className="font-semibold text-foreground">تلفن: </span>
{siteAddress.phone}
</p>
<p>
<span className="font-semibold text-foreground">ایمیل: </span>
<a
href={`mailto:${siteAddress.email}`}
className="text-primary hover:underline"
>
{siteAddress.email}
</a>
</p>
<a
href={siteAddress.mapUrl}
className="inline-block text-primary hover:underline"
target="_blank"
rel="noreferrer"
>
مشاهده روی نقشه
</a>
</div>
</div>
<Card className="rounded-2xl border-border/70 shadow-lg">
<CardHeader>
<CardTitle>ارسال پیام</CardTitle>
</CardHeader>
<CardContent>
<ContactInterestForm
submitLabel={t("submit")}
successLabel={t("registerSuccess")}
/>
</CardContent>
</Card>
</Container>
</Section>
</main>
);
}
+35
View File
@@ -0,0 +1,35 @@
"use client";
import { useEffect } from "react";
import { DotCta } from "@/components/atoms/DotCta";
import { Button } from "@/components/ui/button";
export default function MainError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<div className="mx-auto flex min-h-[50vh] w-full max-w-7xl flex-col items-start justify-center px-5 py-20 sm:px-8 lg:px-12">
<p className="text-sm font-semibold text-primary">خطا</p>
<h1 className="mt-3 text-2xl font-bold tracking-tight sm:text-3xl">
بارگذاری صفحه ناموفق بود
</h1>
<p className="mt-3 max-w-md text-base leading-relaxed text-muted-foreground">
لطفاً دوباره تلاش کنید. اگر مشکل ادامه داشت، چند لحظه بعد بازگردید.
</p>
<div className="mt-8 flex flex-wrap gap-4">
<Button type="button" onClick={reset}>
تلاش مجدد
</Button>
<DotCta href="/">بازگشت به خانه</DotCta>
</div>
</div>
);
}
+58
View File
@@ -0,0 +1,58 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { Container } from "@/components/atoms/Container";
import { Heading } from "@/components/atoms/Heading";
import { Section } from "@/components/atoms/Section";
import { TextLink } from "@/components/atoms/TextLink";
import { PageHero } from "@/components/molecules/PageHero";
import { getEventById } from "@/lib/data/events";
type Props = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { id } = await params;
const event = await getEventById(id);
if (!event) return { title: "رویداد یافت نشد" };
return { title: event.title, description: event.summary };
}
export default async function EventDetailPage({ params }: Props) {
const { id } = await params;
const event = await getEventById(id);
if (!event) notFound();
const start = new Date(event.startDate).toLocaleDateString("fa-IR", {
year: "numeric",
month: "long",
day: "numeric",
});
const end = event.endDate
? new Date(event.endDate).toLocaleDateString("fa-IR", {
year: "numeric",
month: "long",
day: "numeric",
})
: null;
return (
<main id="main-content">
<PageHero title={event.title} intro={event.summary} />
<Section className="bg-gradient-to-b from-background to-muted/40">
<Container narrow className="space-y-5 rounded-2xl bg-card p-6 shadow-sm ring-1 ring-border sm:p-10">
<p className="text-sm">
<span className="font-semibold">زمان: </span>
{start}
{end ? ` تا ${end}` : ""}
</p>
<p className="text-sm">
<span className="font-semibold">مکان: </span>
{event.location}
</p>
<Heading level={3}>درباره رویداد</Heading>
<p className="leading-8 text-foreground/90">{event.summary}</p>
<TextLink href="/events">بازگشت به رویدادها</TextLink>
</Container>
</Section>
</main>
);
}
+32
View File
@@ -0,0 +1,32 @@
import type { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import { Container } from "@/components/atoms/Container";
import { Section } from "@/components/atoms/Section";
import { EventCard } from "@/components/molecules/Cards";
import { PageHero } from "@/components/molecules/PageHero";
import { getEvents } from "@/lib/data/events";
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("pages");
return { title: t("eventsTitle"), description: t("eventsIntro") };
}
export default async function EventsPage() {
const t = await getTranslations("pages");
const events = await getEvents();
return (
<main id="main-content">
<PageHero title={t("eventsTitle")} intro={t("eventsIntro")} />
<Section className="bg-gradient-to-b from-background to-muted/40">
<Container>
<div className="grid gap-4 md:grid-cols-2">
{events.map((event) => (
<EventCard key={event.id} {...event} variant="list" />
))}
</div>
</Container>
</Section>
</main>
);
}
+54
View File
@@ -0,0 +1,54 @@
import type { Metadata } from "next";
import Image from "next/image";
import { getTranslations } from "next-intl/server";
import { Container } from "@/components/atoms/Container";
import { Heading } from "@/components/atoms/Heading";
import { Section } from "@/components/atoms/Section";
import { PageHero } from "@/components/molecules/PageHero";
import { SurfaceCard } from "@/components/molecules/SurfaceCard";
import { getFaculty } from "@/lib/data/site";
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("pages");
return { title: t("facultyTitle"), description: t("facultyIntro") };
}
export default async function FacultyPage() {
const t = await getTranslations("pages");
const members = await getFaculty();
return (
<main id="main-content">
<PageHero title={t("facultyTitle")} intro={t("facultyIntro")} />
<Section className="bg-gradient-to-b from-background to-muted/40">
<Container>
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{members.map((member) => (
<SurfaceCard key={member.id} className="group rounded-2xl">
<div className="relative mb-5 aspect-[4/3] overflow-hidden rounded-xl bg-muted">
<Image
src={member.imageUrl}
alt={member.name}
fill
className="object-cover transition-transform duration-500 group-hover:scale-[1.03]"
sizes="(max-width:768px) 100vw, 33vw"
/>
</div>
<Heading as="h2" level={4}>
{member.name}
</Heading>
<p className="mt-1 text-sm text-primary">{member.title}</p>
<p className="mt-1 text-xs text-muted-foreground">
{member.focus}
</p>
<p className="mt-3 text-sm leading-7 text-muted-foreground">
{member.bio}
</p>
</SurfaceCard>
))}
</div>
</Container>
</Section>
</main>
);
}
+74
View File
@@ -0,0 +1,74 @@
import type { Metadata } from "next";
import Image from "next/image";
import { notFound } from "next/navigation";
import { Container } from "@/components/atoms/Container";
import { Heading } from "@/components/atoms/Heading";
import { Section } from "@/components/atoms/Section";
import { BadgeLabel } from "@/components/atoms/BadgeLabel";
import { MetamorphField } from "@/components/atoms/MetamorphField";
import { TextLink } from "@/components/atoms/TextLink";
import { getArticleById } from "@/lib/data/articles";
import { JsonLd } from "@/lib/seo/json-ld";
type Props = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { id } = await params;
const article = await getArticleById(id);
if (!article) return { title: "مقاله یافت نشد" };
return { title: article.title, description: article.excerpt };
}
export default async function InsightDetailPage({ params }: Props) {
const { id } = await params;
const article = await getArticleById(id);
if (!article) notFound();
const date = new Date(article.publishedAt).toLocaleDateString("fa-IR");
return (
<main id="main-content">
<JsonLd
data={{
"@context": "https://schema.org",
"@type": "Article",
headline: article.title,
description: article.excerpt,
datePublished: article.publishedAt,
author: { "@type": "Person", name: article.author },
image: article.imageUrl,
}}
/>
<Section tone="dark" className="relative overflow-hidden pb-16 pt-16 sm:pb-20 sm:pt-20">
<MetamorphField tone="dark" density="sparse" className="opacity-35" />
<Container narrow className="relative z-[1]">
<BadgeLabel>{article.category}</BadgeLabel>
<Heading as="h1" level={1} className="mt-4 text-background">
{article.title}
</Heading>
<p className="mt-3 text-sm text-background/60">
{article.author} · {date}
</p>
</Container>
</Section>
<Section className="bg-gradient-to-b from-background to-muted/40 pt-10">
<Container narrow>
<div className="relative mb-10 aspect-[16/9] overflow-hidden rounded-2xl bg-muted shadow-xl">
<Image
src={article.imageUrl}
alt={article.title}
fill
className="object-cover"
sizes="(max-width:768px) 100vw, 800px"
priority
/>
</div>
<p className="text-lg leading-9 text-foreground/90">{article.body}</p>
<TextLink href="/insights" className="mt-10 inline-block">
بازگشت به مقالات
</TextLink>
</Container>
</Section>
</main>
);
}
+40
View File
@@ -0,0 +1,40 @@
import type { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import { Container } from "@/components/atoms/Container";
import { Section } from "@/components/atoms/Section";
import { ArticleCard } from "@/components/molecules/Cards";
import { PageHero } from "@/components/molecules/PageHero";
import { getArticles } from "@/lib/data/articles";
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("pages");
return { title: t("insightsTitle"), description: t("insightsIntro") };
}
export default async function InsightsPage() {
const t = await getTranslations("pages");
const articles = await getArticles();
return (
<main id="main-content">
<PageHero title={t("insightsTitle")} intro={t("insightsIntro")} />
<Section className="bg-gradient-to-b from-background to-muted/40">
<Container>
<div className="mx-auto max-w-5xl">
{articles.map((article) => (
<ArticleCard
key={article.id}
title={article.title}
category={article.category}
excerpt={article.excerpt}
imageUrl={article.imageUrl}
href={article.href}
variant="list"
/>
))}
</div>
</Container>
</Section>
</main>
);
}
+52
View File
@@ -0,0 +1,52 @@
import { getTranslations } from "next-intl/server";
import { CampaignBanners } from "@/components/organisms/CampaignBanners";
import { SiteFooter } from "@/components/organisms/SiteFooter";
import { SiteHeader } from "@/components/organisms/SiteHeader";
import { getCourses } from "@/lib/data/courses";
import { getPrograms } from "@/lib/data/programs";
import { getCampaignBanners } from "@/lib/data/site";
import { homeNav, siteShortName } from "@/lib/site-config";
export default async function MainLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const t = await getTranslations();
const year = new Date().getFullYear();
const [courses, programs, banners] = await Promise.all([
getCourses(),
getPrograms(),
getCampaignBanners(),
]);
return (
<>
<SiteHeader
items={homeNav}
searchLabel={t("nav.search")}
brandTitle={siteShortName}
brandSubtitle={t("nav.brandSubtitle")}
academicsLabel={t("nav.academics")}
programSelectorTitle={t("home.programSelectorTitle")}
executiveLabel={t("home.executiveLabel")}
exploreLabel={t("home.exploreOurPrograms")}
variant="home"
courses={courses}
programs={programs}
/>
<CampaignBanners banners={banners} />
<div className="flex-1">{children}</div>
<SiteFooter
copyright={t("footer.copyright", { year })}
linksTitle={t("footer.links")}
links={[
{ label: t("footer.press"), href: "/press" },
{ label: t("footer.careers"), href: "/careers" },
{ label: t("footer.accessibility"), href: "/accessibility" },
{ label: t("footer.privacy"), href: "/privacy" },
]}
/>
</>
);
}
+98
View File
@@ -0,0 +1,98 @@
import { getTranslations } from "next-intl/server";
import {
HomeEvents,
HomeHero,
HomeIdeas,
HomeRest,
type HomeLabels,
} from "@/components/templates/HomeTemplate";
import { getArticles, getFeaturedArticle } from "@/lib/data/articles";
import { getEvents } from "@/lib/data/events";
import { getPrograms } from "@/lib/data/programs";
import { getSiteStats, getTopics } from "@/lib/data/site";
async function getLabels(): Promise<HomeLabels> {
const t = await getTranslations();
return {
executiveLabel: t("home.executiveLabel"),
exploreOurPrograms: t("home.exploreOurPrograms"),
ideasTitle: t("home.ideasTitle"),
eventsTitle: t("home.eventsTitle"),
seeAllEvents: t("nav.seeAllEvents"),
intersectionsTitle: t("home.intersectionsTitle"),
intersectionsSubtitle: t("home.intersectionsSubtitle"),
moreThanDegree: t("home.moreThanDegree"),
moreThanDegreeBody: t("home.moreThanDegreeBody"),
keepExploring: t("home.keepExploring"),
hireTitle: t("home.hireTitle"),
hireBody: t("home.hireBody"),
registerCta: t("nav.registerCta"),
missionTitle: t("home.missionTitle"),
findUsTitle: t("home.findUsTitle"),
ideasEyebrow: t("home.ideasEyebrow"),
linksTitle: t("footer.links"),
};
}
async function HeroSection() {
const [featured, labels] = await Promise.all([
getFeaturedArticle(),
getLabels(),
]);
if (!featured) return null;
return <HomeHero featured={featured} eyebrow={labels.ideasEyebrow} />;
}
async function IdeasSection() {
const [articles, labels] = await Promise.all([getArticles(), getLabels()]);
return <HomeIdeas articles={articles} title={labels.ideasTitle} />;
}
async function EventsSection() {
const [events, labels] = await Promise.all([getEvents(), getLabels()]);
return (
<HomeEvents
events={events}
title={labels.eventsTitle}
seeAllLabel={labels.seeAllEvents}
/>
);
}
async function RestSection() {
const [programs, intersections, stats, labels] = await Promise.all([
getPrograms(),
getTopics(),
getSiteStats(),
getLabels(),
]);
const carouselPrograms = programs.filter((p) =>
[
"management-core",
"evening-management",
"executive",
"leadership-fellows",
"business-analytics",
"finance",
].includes(p.slug),
);
return (
<HomeRest
labels={labels}
carouselPrograms={carouselPrograms}
intersections={intersections}
stats={stats}
/>
);
}
export default function HomePage() {
return (
<main id="main-content">
<HeroSection />
<IdeasSection />
<EventsSection />
<RestSection />
</main>
);
}
+108
View File
@@ -0,0 +1,108 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { Container } from "@/components/atoms/Container";
import { Heading } from "@/components/atoms/Heading";
import { Section } from "@/components/atoms/Section";
import { TextLink } from "@/components/atoms/TextLink";
import { PageHero } from "@/components/molecules/PageHero";
import { SurfaceCard } from "@/components/molecules/SurfaceCard";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { getCourses } from "@/lib/data/courses";
import { getProgramBySlug } from "@/lib/data/programs";
type Props = { params: Promise<{ slug: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const program = await getProgramBySlug(slug);
if (!program) return { title: "برنامه یافت نشد" };
return {
title: program.title,
description: program.blurb,
};
}
export default async function ProgramDetailPage({ params }: Props) {
const { slug } = await params;
const [program, courses, t] = await Promise.all([
getProgramBySlug(slug),
getCourses(),
getTranslations("pages"),
]);
if (!program) notFound();
const related = courses.slice(0, 3);
return (
<main id="main-content">
<PageHero
title={program.title}
intro={program.blurb}
eyebrow={program.tagline}
/>
<Section className="bg-gradient-to-b from-background to-muted/40">
<Container className="grid gap-10 lg:grid-cols-[2fr_1fr]">
<div>
<p className="text-base leading-8 text-foreground/90">{program.body}</p>
<Heading level={2} className="mt-10">
{t("highlights")}
</Heading>
<ul className="mt-4 list-disc space-y-2 ps-5 text-sm leading-7">
{program.highlights.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</div>
<aside className="h-fit space-y-4 rounded-2xl bg-card p-6 shadow-sm ring-1 ring-border">
<p className="text-sm">
<span className="font-semibold">مخاطب: </span>
{program.audience}
</p>
<p className="text-sm">
<span className="font-semibold">مدت: </span>
{program.durationLabel}
</p>
<p className="text-sm">
<span className="font-semibold">فرمت: </span>
{program.formatLabel}
</p>
<Link
href="/professional"
className={cn(buttonVariants(), "w-full")}
>
مشاهده دوره‌ها
</Link>
<TextLink href="/programs" className="block text-sm">
{t("backToPrograms")}
</TextLink>
</aside>
</Container>
</Section>
<Section tone="muted">
<Container>
<Heading level={2}>{t("relatedCourses")}</Heading>
<ul className="mt-6 grid gap-4 sm:grid-cols-3">
{related.map((course) => (
<li key={course.id}>
<SurfaceCard padded="sm" as="div" className="h-full">
<Link
href={course.registrationUrl}
className="font-semibold hover:text-primary"
>
{course.title}
</Link>
<p className="mt-2 line-clamp-3 text-sm text-muted-foreground">
{course.summary}
</p>
</SurfaceCard>
</li>
))}
</ul>
</Container>
</Section>
</main>
);
}
+90
View File
@@ -0,0 +1,90 @@
import type { Metadata } from "next";
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { Container } from "@/components/atoms/Container";
import { Heading } from "@/components/atoms/Heading";
import { Section } from "@/components/atoms/Section";
import { BadgeLabel } from "@/components/atoms/BadgeLabel";
import { PageHero } from "@/components/molecules/PageHero";
import { SurfaceCard } from "@/components/molecules/SurfaceCard";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { getPrograms } from "@/lib/data/programs";
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("pages");
return {
title: t("programsTitle"),
description: t("programsIntro"),
};
}
export default async function ProgramsPage() {
const t = await getTranslations("pages");
const programs = await getPrograms();
const standard = programs.filter((p) => p.group === "standard");
const executive = programs.filter((p) => p.group === "executive");
return (
<main id="main-content">
<PageHero title={t("programsTitle")} intro={t("programsIntro")} />
<Section className="bg-gradient-to-b from-background to-muted/40">
<Container className="space-y-10">
<ProgramGroup title={t("standardGroup")} items={standard} />
<ProgramGroup title={t("executiveGroup")} items={executive} />
</Container>
</Section>
</main>
);
}
function ProgramGroup({
title,
items,
}: {
title: string;
items: Awaited<ReturnType<typeof getPrograms>>;
}) {
return (
<div>
<Heading level={2} className="mb-6">
{title}
</Heading>
<div className="grid gap-5 md:grid-cols-2">
{items.map((program) => (
<SurfaceCard key={program.id} className="flex flex-col rounded-2xl p-6 sm:p-7">
<BadgeLabel className="w-fit">{program.tagline}</BadgeLabel>
<Heading as="h3" level={3} className="mt-3">
<Link href={program.href} className="hover:text-primary">
{program.title}
</Link>
</Heading>
<p className="mt-2 flex-1 text-sm leading-relaxed text-muted-foreground">
{program.blurb}
</p>
<dl className="mt-4 grid grid-cols-2 gap-2 text-xs text-muted-foreground">
<div>
<dt className="font-semibold text-foreground">مخاطب</dt>
<dd>{program.audience}</dd>
</div>
<div>
<dt className="font-semibold text-foreground">مدت</dt>
<dd>{program.durationLabel}</dd>
</div>
<div>
<dt className="font-semibold text-foreground">فرمت</dt>
<dd>{program.formatLabel}</dd>
</div>
</dl>
<Link
href={program.href}
className={cn(buttonVariants({ variant: "outline" }), "mt-5 w-fit")}
>
جزئیات برنامه
</Link>
</SurfaceCard>
))}
</div>
</div>
);
}
+49
View File
@@ -0,0 +1,49 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { CourseDetailTemplate } from "@/components/templates/CourseDetailTemplate";
import { getCourseById } from "@/lib/data/courses";
type Props = { params: Promise<{ slug: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const course = await getCourseById(slug);
if (!course) return { title: "دوره یافت نشد" };
return {
title: course.title,
description: course.seoDescription || course.summary,
};
}
export default async function CourseRegisterPage({ params }: Props) {
const { slug } = await params;
const [course, t] = await Promise.all([
getCourseById(slug),
getTranslations("pages"),
]);
if (!course) notFound();
return (
<CourseDetailTemplate
course={course}
labels={{
submit: t("submit"),
success: t("registerSuccess"),
cta: t("registerCtaRequest"),
formTitle: t("registerFormTitle"),
formDescription: t("registerFormDescription"),
hint: t("registerFormHint"),
cancel: t("registerFormCancel"),
backToCatalog: t("backToCourses"),
detailsTitle: t("courseDetailsTitle"),
aboutTitle: t("courseAboutTitle"),
duration: t("courseDuration"),
format: t("courseFormat"),
category: t("courseCategory"),
price: t("coursePrice"),
priceUnset: t("coursePriceUnset"),
}}
/>
);
}
+60
View File
@@ -0,0 +1,60 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { Container } from "@/components/atoms/Container";
import { Section } from "@/components/atoms/Section";
import { TextLink } from "@/components/atoms/TextLink";
import { PageHero } from "@/components/molecules/PageHero";
import { buttonVariants } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { cn } from "@/lib/utils";
import { getTopicBySlug } from "@/lib/data/site";
type Props = { params: Promise<{ slug: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const topic = await getTopicBySlug(slug);
if (!topic) return { title: "موضوع یافت نشد" };
return { title: topic.title, description: topic.description };
}
export default async function TopicPage({ params }: Props) {
const { slug } = await params;
const topic = await getTopicBySlug(slug);
if (!topic) notFound();
return (
<main id="main-content">
<PageHero
title={topic.title}
intro={topic.description}
imageUrl={topic.imageUrl}
/>
<Section className="bg-gradient-to-b from-background to-muted/40">
<Container className="grid gap-10 lg:grid-cols-[2fr_1fr]">
<div>
<p className="text-base leading-8">{topic.body}</p>
<ul className="mt-8 list-disc space-y-2 ps-5 text-sm">
{topic.highlights.map((h) => (
<li key={h}>{h}</li>
))}
</ul>
</div>
<aside className="h-fit space-y-4 rounded-2xl bg-card p-6 shadow-sm ring-1 ring-border">
<p className="text-sm text-muted-foreground">
دوره‌های مرتبط با این موضوع را در فهرست دوره‌های کوتاه ببینید.
</p>
<Link href="/professional" className={cn(buttonVariants())}>
مشاهده دوره‌ها
</Link>
<Separator />
<TextLink href="/" className="block text-sm">
بازگشت به خانه
</TextLink>
</aside>
</Container>
</Section>
</main>
);
}
+40
View File
@@ -0,0 +1,40 @@
import type { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import { Container } from "@/components/atoms/Container";
import { Section } from "@/components/atoms/Section";
import { PageHero } from "@/components/molecules/PageHero";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { valuesContent } from "@/lib/site-config";
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("pages");
return { title: t("valuesTitle"), description: valuesContent.intro };
}
export default async function ValuesPage() {
const t = await getTranslations("pages");
return (
<main id="main-content">
<PageHero title={t("valuesTitle")} intro={valuesContent.intro} />
<Section className="bg-gradient-to-b from-background to-muted/40">
<Container>
<div className="grid gap-5 sm:grid-cols-2">
{valuesContent.items.map((item) => (
<Card key={item.title} className="rounded-2xl border-border/70 shadow-sm transition-[box-shadow,border-color] hover:border-primary/20 hover:shadow-md">
<CardHeader>
<CardTitle>{item.title}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm leading-7 text-muted-foreground">
{item.text}
</p>
</CardContent>
</Card>
))}
</div>
</Container>
</Section>
</main>
);
}
@@ -0,0 +1,43 @@
import { notFound } from "next/navigation";
import { ENTITIES } from "@/lib/admin/entities";
import { GenericForm } from "@/components/organisms/admin/generic/GenericForm";
import {
AdminPage,
AdminPageHeader,
} from "@/components/organisms/admin/AdminPage";
export const dynamic = "force-dynamic";
export default async function AdminEntityEditPage({
params,
}: {
params: Promise<{ entity: string; id: string }>;
}) {
const { entity, id } = await params;
const spec = ENTITIES[entity];
if (!spec) notFound();
const row = (await spec.get(id)) as Record<string, unknown>;
if (!row) notFound();
return (
<AdminPage>
<AdminPageHeader
title={`ویرایش ${spec.noun}`}
description={String(row[spec.columns[0].name] ?? "")}
backHref={`/admin/${entity}`}
backLabel={`بازگشت به ${spec.navLabel}`}
/>
<GenericForm
spec={{
key: spec.key,
noun: spec.noun,
apiPath: spec.apiPath,
idColumn: spec.idColumn,
fields: spec.fields,
}}
initial={row}
/>
</AdminPage>
);
}
@@ -0,0 +1,43 @@
import { notFound } from "next/navigation";
import { ENTITIES } from "@/lib/admin/entities";
import { GenericForm } from "@/components/organisms/admin/generic/GenericForm";
import {
AdminPage,
AdminPageHeader,
} from "@/components/organisms/admin/AdminPage";
export const dynamic = "force-dynamic";
export default async function AdminEntityCreatePage({
params,
}: {
params: Promise<{ entity: string }>;
}) {
const { entity } = await params;
const spec = ENTITIES[entity];
if (!spec) notFound();
return (
<AdminPage>
<AdminPageHeader
title={`${spec.noun} جدید`}
description={
spec.hasPublished
? "پس از ثبت، در صورت «منتشرشده» بودن در سایت عمومی نمایش داده می‌شود."
: undefined
}
backHref={`/admin/${entity}`}
backLabel={`بازگشت به ${spec.navLabel}`}
/>
<GenericForm
spec={{
key: spec.key,
noun: spec.noun,
apiPath: spec.apiPath,
idColumn: spec.idColumn,
fields: spec.fields,
}}
/>
</AdminPage>
);
}
+61
View File
@@ -0,0 +1,61 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { ENTITIES } from "@/lib/admin/entities";
import { GenericFilters } from "@/components/organisms/admin/generic/GenericFilters";
import { GenericTable } from "@/components/organisms/admin/generic/GenericTable";
import {
AdminPage,
AdminPageHeader,
AdminTableCard,
AdminToolbarCard,
} from "@/components/organisms/admin/AdminPage";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
export const dynamic = "force-dynamic";
export default async function AdminEntityListPage({
params,
searchParams,
}: {
params: Promise<{ entity: string }>;
searchParams: Promise<{ search?: string; published?: string }>;
}) {
const { entity } = await params;
const spec = ENTITIES[entity];
if (!spec) notFound();
const { search = "", published: publishedRaw } = await searchParams;
const published =
publishedRaw === "true" ? true : publishedRaw === "false" ? false : undefined;
const rows = await spec.list({ search, published });
return (
<AdminPage>
<AdminPageHeader
title={spec.navLabel}
description={`${rows.length} مورد${search ? ` مطابق فیلتر «${search}»` : ""}`}
actions={
<Link href={`/admin/${entity}/new`} className={cn(buttonVariants())}>
+ {spec.noun} جدید
</Link>
}
/>
<AdminToolbarCard description={spec.searchHint}>
<GenericFilters
entity={entity}
searchHint={spec.searchHint}
hasPublished={spec.hasPublished}
initialSearch={search}
initialPublished={publishedRaw ?? "all"}
/>
</AdminToolbarCard>
<AdminTableCard title={`فهرست ${spec.navLabel}`}>
<GenericTable spec={spec} rows={rows} />
</AdminTableCard>
</AdminPage>
);
}
@@ -0,0 +1,31 @@
import { notFound } from "next/navigation";
import { getAdminCourseById } from "@/lib/data/admin/courses";
import { CourseForm } from "@/components/organisms/admin/courses/CourseForm";
import {
AdminPage,
AdminPageHeader,
} from "@/components/organisms/admin/AdminPage";
export const dynamic = "force-dynamic";
export default async function EditCoursePage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const course = await getAdminCourseById(id);
if (!course) notFound();
return (
<AdminPage>
<AdminPageHeader
title="ویرایش دوره"
description={course.title}
backHref="/admin/courses"
backLabel="بازگشت به دوره‌ها"
/>
<CourseForm initial={course} />
</AdminPage>
);
}
@@ -0,0 +1,21 @@
import { CourseForm } from "@/components/organisms/admin/courses/CourseForm";
import {
AdminPage,
AdminPageHeader,
} from "@/components/organisms/admin/AdminPage";
export const dynamic = "force-dynamic";
export default function NewCoursePage() {
return (
<AdminPage>
<AdminPageHeader
title="دوره جدید"
description="دوره پس از ثبت، در صورت «منتشرشده» بودن در سایت عمومی نمایش داده می‌شود."
backHref="/admin/courses"
backLabel="بازگشت به دوره‌ها"
/>
<CourseForm />
</AdminPage>
);
}
+54
View File
@@ -0,0 +1,54 @@
import Link from "next/link";
import { listAdminCourses } from "@/lib/data/admin/courses";
import { CourseTable } from "@/components/organisms/admin/courses/CourseTable";
import { CourseFilters } from "@/components/organisms/admin/courses/CourseFilters";
import {
AdminPage,
AdminPageHeader,
AdminTableCard,
AdminToolbarCard,
} from "@/components/organisms/admin/AdminPage";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
export const dynamic = "force-dynamic";
export default async function AdminCoursesPage({
searchParams,
}: {
searchParams: Promise<{ search?: string; published?: string }>;
}) {
const { search = "", published: publishedRaw } = await searchParams;
const published =
publishedRaw === "true" ? true : publishedRaw === "false" ? false : undefined;
const courses = await listAdminCourses({ search, published });
return (
<AdminPage>
<AdminPageHeader
title="دوره‌ها"
description={`${courses.length} دوره${search ? ` مطابق فیلتر «${search}»` : ""}`}
actions={
<Link href="/admin/courses/new" className={cn(buttonVariants())}>
+ دوره جدید
</Link>
}
/>
<AdminToolbarCard description="جستجو بر اساس عنوان یا اسلاگ و فیلتر وضعیت انتشار">
<CourseFilters
initialSearch={search}
initialPublished={publishedRaw ?? "all"}
/>
</AdminToolbarCard>
<AdminTableCard
title="فهرست دوره‌ها"
description="مدیریت، انتشار و پیش‌نمایش دوره‌های کوتاه"
>
<CourseTable courses={courses} />
</AdminTableCard>
</AdminPage>
);
}
+21
View File
@@ -0,0 +1,21 @@
import { redirect } from "next/navigation";
import { verifySession } from "@/lib/auth/admin";
import { AdminShell } from "@/components/organisms/admin/AdminShell";
// Authoritative admin guard + shell.
// - Verifies the session against the database for every /admin page
// (login lives outside this route group, see src/app/admin/login).
// - Proxy only does a fast cookie-presence redirect; this is the real check.
export default async function AdminGuardLayout({
children,
}: {
children: React.ReactNode;
}) {
const session = await verifySession();
if (!session) {
redirect("/admin/login");
}
return <AdminShell userName={session.name}>{children}</AdminShell>;
}
+120
View File
@@ -0,0 +1,120 @@
import Link from "next/link";
import {
BookOpen,
Calendar,
GraduationCap,
Newspaper,
Plus,
Users,
MessageSquareQuote,
} from "lucide-react";
import { query } from "@/lib/db";
import {
Card,
CardAction,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { LeadsList, type LeadForDashboard } from "@/components/organisms/admin/LeadsList";
import {
AdminPage,
AdminPageHeader,
} from "@/components/organisms/admin/AdminPage";
export const dynamic = "force-dynamic";
interface CountRow {
entity: string;
n: number;
}
const getCounts = async (): Promise<Record<string, number>> => {
const res = await query<CountRow>(
`SELECT 'courses' AS entity, count(*)::int AS n FROM courses
UNION ALL SELECT 'programs', count(*) FROM programs
UNION ALL SELECT 'events', count(*) FROM events
UNION ALL SELECT 'articles', count(*) FROM articles
UNION ALL SELECT 'faculty', count(*) FROM faculty_members
UNION ALL SELECT 'alumni', count(*) FROM alumni_stories`,
);
return Object.fromEntries(res.rows.map((r) => [r.entity, r.n]));
};
const countCards = [
{ key: "courses", label: "دوره‌ها", href: "/admin/courses", icon: BookOpen },
{ key: "programs", label: "برنامه‌ها", href: "/admin/programs", icon: GraduationCap },
{ key: "events", label: "رویدادها", href: "/admin/events", icon: Calendar },
{ key: "articles", label: "مقالات", href: "/admin/articles", icon: Newspaper },
{ key: "faculty", label: "اساتید", href: "/admin/faculty", icon: Users },
{ key: "alumni", label: "دانش‌آموختگان", href: "/admin/alumni", icon: MessageSquareQuote },
] as const;
export default async function AdminDashboardPage() {
const [counts, leadsRes] = await Promise.all([
getCounts(),
query<LeadForDashboard>(
`SELECT id, full_name, email, course_slug, status, created_at
FROM registration_leads ORDER BY created_at DESC LIMIT 5`,
),
]);
return (
<AdminPage className="space-y-8">
<AdminPageHeader
title="داشبورد"
description="نمای کلی محتوای مدیریت‌شدنی و درخواست‌های تازه"
actions={
<Link href="/admin/courses/new" className={cn(buttonVariants())}>
<Plus className="size-4" />
دوره جدید
</Link>
}
/>
<section className="space-y-3">
<h2 className="text-sm font-semibold text-muted-foreground">آمار محتوا</h2>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
{countCards.map(({ key, label, href, icon: Icon }) => (
<Link key={key} href={href} className="group">
<Card className="h-full shadow-none transition-colors group-hover:bg-muted/40">
<CardHeader className="gap-3 pb-2">
<div className="flex size-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
<Icon className="size-4" />
</div>
<CardDescription>{label}</CardDescription>
</CardHeader>
<CardContent>
<p className="text-3xl font-bold tabular-nums tracking-tight">
{counts[key] ?? 0}
</p>
</CardContent>
</Card>
</Link>
))}
</div>
</section>
<Card className="shadow-none">
<CardHeader className="border-b [.border-b]:pb-4">
<CardTitle>درخواست‌های اخیر ثبت‌نام</CardTitle>
<CardDescription>۵ درخواست آخر از برگ ثبت‌نام</CardDescription>
<CardAction>
<Link
href="/admin/registrations"
className={cn(buttonVariants({ variant: "outline", size: "sm" }))}
>
مشاهده همه
</Link>
</CardAction>
</CardHeader>
<CardContent className="pt-6">
<LeadsList leads={leadsRes.rows} />
</CardContent>
</Card>
</AdminPage>
);
}
@@ -0,0 +1,46 @@
import { listAdminRegistrations } from "@/lib/data/admin/registrations";
import { RegistrationFilters } from "@/components/organisms/admin/registrations/RegistrationFilters";
import { RegistrationsTable } from "@/components/organisms/admin/registrations/RegistrationsTable";
import { LEAD_STATUS_LABELS } from "@/components/organisms/admin/LeadsList";
import {
AdminPage,
AdminPageHeader,
AdminTableCard,
AdminToolbarCard,
} from "@/components/organisms/admin/AdminPage";
export const dynamic = "force-dynamic";
export default async function AdminRegistrationsPage({
searchParams,
}: {
searchParams: Promise<{ search?: string; status?: string }>;
}) {
const { search = "", status = "" } = await searchParams;
const rows = await listAdminRegistrations({ search, status });
const parts = [
`${rows.length} درخواست`,
search ? `جستجو: «${search}»` : null,
status && LEAD_STATUS_LABELS[status]
? `وضعیت: ${LEAD_STATUS_LABELS[status]}`
: null,
].filter(Boolean);
return (
<AdminPage>
<AdminPageHeader title="برگ ثبت‌نام" description={parts.join(" · ")} />
<AdminToolbarCard description="جستجو بر اساس نام، ایمیل یا اسلاگ دوره">
<RegistrationFilters
initialSearch={search}
initialStatus={status || "all"}
/>
</AdminToolbarCard>
<AdminTableCard title="درخواست‌ها" description="پیگیری و تغییر وضعیت لیدها">
<RegistrationsTable rows={rows} />
</AdminTableCard>
</AdminPage>
);
}
+132
View File
@@ -0,0 +1,132 @@
"use client";
import { useState, FormEvent, Suspense } from "react";
import Image from "next/image";
import { useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
export const dynamic = "force-dynamic";
function LoginForm() {
const router = useRouter();
const searchParams = useSearchParams();
const redirect = searchParams.get("redirect") || "/admin";
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(e: FormEvent) {
e.preventDefault();
setError("");
setLoading(true);
try {
const res = await fetch("/api/admin/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
const data = await res.json();
if (!res.ok) {
setError(data.error || "خطای احراز هویت");
return;
}
router.push(redirect);
router.refresh();
} catch {
setError("خطای شبکه");
} finally {
setLoading(false);
}
}
return (
<div dir="rtl" className="flex min-h-svh items-center justify-center bg-muted/40 px-4 py-12">
<Card className="w-full max-w-md shadow-sm">
<CardHeader className="space-y-3 text-center">
<div className="mx-auto relative size-14 overflow-hidden rounded-full bg-chart-3 ring-1 ring-border shadow-sm">
<Image
src="/brand/amirkabir.png"
alt="دانشگاه صنعتی امیرکبیر"
fill
sizes="56px"
className="object-cover"
priority
/>
</div>
<CardTitle className="text-2xl font-bold tracking-tight">
ورود به پنل ادمین
</CardTitle>
<CardDescription>
آموزش آزاد دانشگاه صنعتی امیرکبیر
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
{error ? (
<div
className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive"
role="alert"
>
{error}
</div>
) : null}
<div className="space-y-2">
<Label htmlFor="email">ایمیل</Label>
<Input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="admin@example.com"
required
autoComplete="email"
disabled={loading}
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">رمز عبور</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="••••••••"
required
autoComplete="current-password"
disabled={loading}
/>
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? "در حال ورود..." : "ورود"}
</Button>
</form>
</CardContent>
</Card>
</div>
);
}
export default function AdminLoginPage() {
return (
<Suspense
fallback={
<div className="flex min-h-svh items-center justify-center text-sm text-muted-foreground">
در حال بارگذاری...
</div>
}
>
<LoginForm />
</Suspense>
);
}
+79
View File
@@ -0,0 +1,79 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToAlumniStory, type AlumniStoryRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { alumniPatchSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { revalidateSite } from "@/lib/api/revalidate";
import { parseJsonBody, buildUpdate } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
const ALUMNI_COLUMNS: Record<string, string> = {
title: "title",
excerpt: "excerpt",
name: "name",
program: "program",
imageUrl: "image_url",
href: "href",
published: "published",
};
// PATCH /api/admin/alumni/[id] — update alumni story (admin only)
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = alumniPatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const spec = buildUpdate("alumni_stories", "id", ALUMNI_COLUMNS, parsed.data as Record<string, unknown>);
if (spec.empty) return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
try {
const res = await query<AlumniStoryRow>(spec.sql, [...spec.params, id]);
if (res.rows.length === 0) return errorResponse("داستان دانش‌آموخته یافت نشد", 404);
const row = res.rows[0];
return NextResponse.json({
ok: true,
data: { ...rowToAlumniStory(row), published: row.published },
});
} catch (err) {
console.error("admin update alumni error:", err);
return errorResponse("خطای سرور", 500);
}
}
// DELETE /api/admin/alumni/[id] — delete alumni story (admin only)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
try {
const res = await query(`DELETE FROM alumni_stories WHERE id = $1 RETURNING id`, [id]);
if (res.rows.length === 0) return errorResponse("داستان دانش‌آموخته یافت نشد", 404);
revalidateSite();
return NextResponse.json({ ok: true });
} catch (err) {
console.error("admin delete alumni error:", err);
return errorResponse("خطای سرور", 500);
}
}
+47
View File
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToAlumniStory, type AlumniStoryRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { alumniCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { makeId, parseJsonBody, buildInsert } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
// POST /api/admin/alumni — create alumni story (admin only)
export async function POST(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = alumniCreateSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const d = parsed.data;
const id = makeId();
try {
const { sql, params } = buildInsert(
"alumni_stories",
["id", "title", "excerpt", "name", "program", "image_url", "href", "published"],
[id, d.title, d.excerpt, d.name, d.program, d.imageUrl, d.href, d.published],
);
await query(sql, params);
const res = await query<AlumniStoryRow>(`SELECT * FROM alumni_stories WHERE id = $1`, [id]);
const row = res.rows[0];
return NextResponse.json(
{ ok: true, data: { ...rowToAlumniStory(row), published: row.published } },
{ status: 201 },
);
} catch (err) {
console.error("admin create alumni error:", err);
return errorResponse("خطای سرور", 500);
}
}
+100
View File
@@ -0,0 +1,100 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToArticle, type ArticleRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { articlePatchSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { isUniqueViolation } from "@/lib/db/errors";
import { revalidateSite } from "@/lib/api/revalidate";
export const dynamic = "force-dynamic";
const ARTICLE_COLUMNS: Record<string, string> = {
title: "title",
category: "category",
excerpt: "excerpt",
imageUrl: "image_url",
href: "href",
featured: "featured",
body: "body",
publishedAt: "published_at",
author: "author",
published: "published",
};
// PATCH /api/admin/articles/[id] — update article (admin only)
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
let body: unknown;
try {
body = await request.json();
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = articlePatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const sets: string[] = [];
const values: unknown[] = [];
for (const [key, column] of Object.entries(ARTICLE_COLUMNS)) {
const v = parsed.data[key as keyof typeof parsed.data];
if (v !== undefined) {
values.push(v);
sets.push(`${column} = $${values.length}`);
}
}
if (sets.length === 0) {
return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
}
values.push(id);
try {
const res = await query<ArticleRow>(
`UPDATE articles SET ${sets.join(", ")} WHERE id = $${values.length} RETURNING *`,
values,
);
if (res.rows.length === 0) return errorResponse("مقاله یافت نشد", 404);
const row = res.rows[0];
revalidateSite();
return NextResponse.json({
ok: true,
data: { ...rowToArticle(row), published: row.published },
});
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "articles_one_featured") {
return errorResponse("فقط یک مقالهٔ ویژهٔ منتشرشده مجاز است", 409);
}
console.error("admin update article error:", err);
return errorResponse("خطای سرور", 500);
}
}
// DELETE /api/admin/articles/[id] — delete article (admin only)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
try {
const res = await query(`DELETE FROM articles WHERE id = $1 RETURNING id`, [id]);
if (res.rows.length === 0) return errorResponse("مقاله یافت نشد", 404);
revalidateSite();
return NextResponse.json({ ok: true });
} catch (err) {
console.error("admin delete article error:", err);
return errorResponse("خطای سرور", 500);
}
}
+56
View File
@@ -0,0 +1,56 @@
import { NextRequest, NextResponse } from "next/server";
import { randomUUID } from "node:crypto";
import { query } from "@/lib/db";
import { rowToArticle, type ArticleRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { articleCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { isUniqueViolation } from "@/lib/db/errors";
import { revalidateSite } from "@/lib/api/revalidate";
export const dynamic = "force-dynamic";
// POST /api/admin/articles — create article (admin only)
export async function POST(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await request.json();
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = articleCreateSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const d = parsed.data;
const id = randomUUID();
try {
await query(
`INSERT INTO articles
(id, title, category, excerpt, image_url, href, featured, body, published_at, author, published)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`,
[
id, d.title, d.category, d.excerpt, d.imageUrl, d.href,
d.featured, d.body, d.publishedAt, d.author, d.published,
],
);
const res = await query<ArticleRow>(`SELECT * FROM articles WHERE id = $1`, [id]);
const row = res.rows[0];
revalidateSite();
return NextResponse.json(
{ ok: true, data: { ...rowToArticle(row), published: row.published } },
{ status: 201 },
);
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "articles_one_featured") {
return errorResponse("فقط یک مقالهٔ ویژهٔ منتشرشده مجاز است", 409);
}
console.error("admin create article error:", err);
return errorResponse("خطای سرور", 500);
}
}
+77
View File
@@ -0,0 +1,77 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToCampaignBanner, type CampaignBannerRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { bannerPatchSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { revalidateSite } from "@/lib/api/revalidate";
import { parseJsonBody, buildUpdate } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
const BANNER_COLUMNS: Record<string, string> = {
version: "version",
text: "text",
href: "href",
cta: "cta",
published: "published",
};
// PATCH /api/admin/banners/[id] — update banner (admin only)
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = bannerPatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const spec = buildUpdate("campaign_banners", "id", BANNER_COLUMNS, parsed.data as Record<string, unknown>);
if (spec.empty) return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
try {
const res = await query<CampaignBannerRow>(spec.sql, [...spec.params, id]);
if (res.rows.length === 0) return errorResponse("بنر یافت نشد", 404);
const row = res.rows[0];
return NextResponse.json({
ok: true,
data: { ...rowToCampaignBanner(row), published: row.published },
});
} catch (err) {
console.error("admin update banner error:", err);
return errorResponse("خطای سرور", 500);
}
}
// DELETE /api/admin/banners/[id] — delete banner (admin only)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
try {
const res = await query(`DELETE FROM campaign_banners WHERE id = $1 RETURNING id`, [id]);
if (res.rows.length === 0) return errorResponse("بنر یافت نشد", 404);
revalidateSite();
return NextResponse.json({ ok: true });
} catch (err) {
console.error("admin delete banner error:", err);
return errorResponse("خطای سرور", 500);
}
}
+47
View File
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToCampaignBanner, type CampaignBannerRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { bannerCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { makeId, parseJsonBody, buildInsert } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
// POST /api/admin/banners — create campaign banner (admin only)
export async function POST(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = bannerCreateSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const d = parsed.data;
const id = makeId();
try {
const { sql, params } = buildInsert(
"campaign_banners",
["id", "version", "text", "href", "cta", "published"],
[id, d.version, d.text, d.href, d.cta, d.published],
);
await query(sql, params);
const res = await query<CampaignBannerRow>(`SELECT * FROM campaign_banners WHERE id = $1`, [id]);
const row = res.rows[0];
return NextResponse.json(
{ ok: true, data: { ...rowToCampaignBanner(row), published: row.published } },
{ status: 201 },
);
} catch (err) {
console.error("admin create banner error:", err);
return errorResponse("خطای سرور", 500);
}
}
+118
View File
@@ -0,0 +1,118 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToCourse, type CourseRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { coursePatchSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { isUniqueViolation } from "@/lib/db/errors";
import { revalidateSite } from "@/lib/api/revalidate";
import { getAdminCourseById } from "@/lib/data/admin/courses";
export const dynamic = "force-dynamic";
// GET /api/admin/courses/[id] — single course (admin only; includes unpublished)
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
try {
const course = await getAdminCourseById(id);
if (!course) return errorResponse("دوره یافت نشد", 404);
return NextResponse.json({ ok: true, data: course });
} catch (err) {
console.error("admin get course error:", err);
return errorResponse("خطای سرور", 500);
}
}
const COURSE_COLUMNS: Record<string, string> = {
slug: "slug",
title: "title",
summary: "summary",
category: "category",
durationHours: "duration_hours",
format: "format",
price: "price",
registrationUrl: "registration_url",
imageUrl: "image_url",
seoDescription: "seo_description",
published: "published",
};
// PATCH /api/admin/courses/[id] — update course (admin only)
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
let body: unknown;
try {
body = await request.json();
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = coursePatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const sets: string[] = [];
const values: unknown[] = [];
for (const [key, column] of Object.entries(COURSE_COLUMNS)) {
const v = parsed.data[key as keyof typeof parsed.data];
if (v !== undefined) {
values.push(v);
sets.push(`${column} = $${values.length}`);
}
}
if (sets.length === 0) {
return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
}
values.push(id);
try {
const res = await query<CourseRow>(
`UPDATE courses SET ${sets.join(", ")} WHERE id = $${values.length} RETURNING *`,
values,
);
if (res.rows.length === 0) return errorResponse("دوره یافت نشد", 404);
const row = res.rows[0];
revalidateSite();
return NextResponse.json({ ok: true, data: { ...rowToCourse(row), published: row.published } });
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "courses_slug_key") {
return errorResponse("این slug قبلاً استفاده شده است", 409);
}
console.error("admin update course error:", err);
return errorResponse("خطای سرور", 500);
}
}
// DELETE /api/admin/courses/[id] — delete course (admin only)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
try {
const res = await query(`DELETE FROM courses WHERE id = $1 RETURNING id`, [id]);
if (res.rows.length === 0) return errorResponse("دوره یافت نشد", 404);
revalidateSite();
return NextResponse.json({ ok: true });
} catch (err) {
console.error("admin delete course error:", err);
return errorResponse("خطای سرور", 500);
}
}
+80
View File
@@ -0,0 +1,80 @@
import { NextRequest, NextResponse } from "next/server";
import { randomUUID } from "node:crypto";
import { query } from "@/lib/db";
import { rowToCourse, type CourseRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { courseCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { isUniqueViolation } from "@/lib/db/errors";
import { revalidateSite } from "@/lib/api/revalidate";
import { listAdminCourses } from "@/lib/data/admin/courses";
export const dynamic = "force-dynamic";
// GET /api/admin/courses — list courses (admin only; includes unpublished)
// Query: ?search=<text>&published=true|false
export async function GET(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
try {
const { searchParams } = request.nextUrl;
const publishedRaw = searchParams.get("published");
const published =
publishedRaw === "true" ? true : publishedRaw === "false" ? false : null;
const data = await listAdminCourses({
search: searchParams.get("search") ?? undefined,
published: published ?? undefined,
});
return NextResponse.json({ ok: true, data });
} catch (err) {
console.error("admin list courses error:", err);
return errorResponse("خطای سرور", 500);
}
}
// POST /api/admin/courses — create course (admin only)
export async function POST(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await request.json();
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = courseCreateSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const d = parsed.data;
const id = randomUUID();
try {
await query(
`INSERT INTO courses
(id, slug, title, summary, category, duration_hours, format, price,
registration_url, image_url, seo_description, published)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`,
[
id, d.slug, d.title, d.summary, d.category, d.durationHours, d.format,
d.price ?? null, d.registrationUrl, d.imageUrl, d.seoDescription, d.published,
],
);
const res = await query<CourseRow>(`SELECT * FROM courses WHERE id = $1`, [id]);
const row = res.rows[0];
revalidateSite();
return NextResponse.json(
{ ok: true, data: { ...rowToCourse(row), published: row.published } },
{ status: 201 },
);
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "courses_slug_key") {
return errorResponse("این slug قبلاً استفاده شده است", 409);
}
console.error("admin create course error:", err);
return errorResponse("خطای سرور", 500);
}
}
+76
View File
@@ -0,0 +1,76 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToEvent, type EventRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { eventPatchSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { revalidateSite } from "@/lib/api/revalidate";
import { parseJsonBody, buildUpdate } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
const EVENT_COLUMNS: Record<string, string> = {
title: "title",
startDate: "start_date",
endDate: "end_date",
location: "location",
href: "href",
summary: "summary",
published: "published",
};
// PATCH /api/admin/events/[id] — update event (admin only)
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = eventPatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const spec = buildUpdate("events", "id", EVENT_COLUMNS, parsed.data as Record<string, unknown>);
if (spec.empty) return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
try {
const res = await query<EventRow>(spec.sql, [...spec.params, id]);
if (res.rows.length === 0) return errorResponse("رویداد یافت نشد", 404);
const row = res.rows[0];
return NextResponse.json({ ok: true, data: { ...rowToEvent(row), published: row.published } });
} catch (err) {
console.error("admin update event error:", err);
return errorResponse("خطای سرور", 500);
}
}
// DELETE /api/admin/events/[id] — delete event (admin only)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
try {
const res = await query(`DELETE FROM events WHERE id = $1 RETURNING id`, [id]);
if (res.rows.length === 0) return errorResponse("رویداد یافت نشد", 404);
revalidateSite();
return NextResponse.json({ ok: true });
} catch (err) {
console.error("admin delete event error:", err);
return errorResponse("خطای سرور", 500);
}
}
+47
View File
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToEvent, type EventRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { eventCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { makeId, parseJsonBody, buildInsert } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
// POST /api/admin/events — create event (admin only)
export async function POST(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = eventCreateSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const d = parsed.data;
const id = makeId();
try {
const { sql, params } = buildInsert(
"events",
["id", "title", "start_date", "end_date", "location", "href", "summary", "published"],
[id, d.title, d.startDate, d.endDate, d.location, d.href, d.summary, d.published],
);
await query(sql, params);
const res = await query<EventRow>(`SELECT * FROM events WHERE id = $1`, [id]);
const row = res.rows[0];
return NextResponse.json(
{ ok: true, data: { ...rowToEvent(row), published: row.published } },
{ status: 201 },
);
} catch (err) {
console.error("admin create event error:", err);
return errorResponse("خطای سرور", 500);
}
}
+78
View File
@@ -0,0 +1,78 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToFacultyMember, type FacultyMemberRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { facultyPatchSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { revalidateSite } from "@/lib/api/revalidate";
import { parseJsonBody, buildUpdate } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
const FACULTY_COLUMNS: Record<string, string> = {
name: "name",
title: "title",
focus: "focus",
bio: "bio",
imageUrl: "image_url",
published: "published",
};
// PATCH /api/admin/faculty/[id] — update faculty member (admin only)
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = facultyPatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const spec = buildUpdate("faculty_members", "id", FACULTY_COLUMNS, parsed.data as Record<string, unknown>);
if (spec.empty) return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
try {
const res = await query<FacultyMemberRow>(spec.sql, [...spec.params, id]);
if (res.rows.length === 0) return errorResponse("عضو هیئت علمی یافت نشد", 404);
const row = res.rows[0];
return NextResponse.json({
ok: true,
data: { ...rowToFacultyMember(row), published: row.published },
});
} catch (err) {
console.error("admin update faculty error:", err);
return errorResponse("خطای سرور", 500);
}
}
// DELETE /api/admin/faculty/[id] — delete faculty member (admin only)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
try {
const res = await query(`DELETE FROM faculty_members WHERE id = $1 RETURNING id`, [id]);
if (res.rows.length === 0) return errorResponse("عضو هیئت علمی یافت نشد", 404);
revalidateSite();
return NextResponse.json({ ok: true });
} catch (err) {
console.error("admin delete faculty error:", err);
return errorResponse("خطای سرور", 500);
}
}
+47
View File
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToFacultyMember, type FacultyMemberRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { facultyCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { makeId, parseJsonBody, buildInsert } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
// POST /api/admin/faculty — create faculty member (admin only)
export async function POST(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = facultyCreateSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const d = parsed.data;
const id = makeId();
try {
const { sql, params } = buildInsert(
"faculty_members",
["id", "name", "title", "focus", "bio", "image_url", "published"],
[id, d.name, d.title, d.focus, d.bio, d.imageUrl, d.published],
);
await query(sql, params);
const res = await query<FacultyMemberRow>(`SELECT * FROM faculty_members WHERE id = $1`, [id]);
const row = res.rows[0];
return NextResponse.json(
{ ok: true, data: { ...rowToFacultyMember(row), published: row.published } },
{ status: 201 },
);
} catch (err) {
console.error("admin create faculty error:", err);
return errorResponse("خطای سرور", 500);
}
}
+80
View File
@@ -0,0 +1,80 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToLegalPage, type LegalPageRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { legalPatchSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { revalidateSite } from "@/lib/api/revalidate";
import { parseJsonBody, buildUpdate } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
const LEGAL_COLUMNS: Record<string, string> = {
title: "title",
body: "body",
published: "published",
};
// PATCH /api/admin/legal/[slug] — update legal page (admin only)
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ slug: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { slug } = await params;
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = legalPatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const data: Record<string, unknown> = { ...parsed.data };
if (data.body !== undefined) {
data.body = JSON.stringify(data.body);
}
const spec = buildUpdate("legal_pages", "slug", LEGAL_COLUMNS, data);
if (spec.empty) return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
try {
const res = await query<LegalPageRow>(spec.sql, [...spec.params, slug]);
if (res.rows.length === 0) return errorResponse("صفحهٔ حقوقی یافت نشد", 404);
const row = res.rows[0];
return NextResponse.json({
ok: true,
data: { ...rowToLegalPage(row), published: row.published },
});
} catch (err) {
console.error("admin update legal error:", err);
return errorResponse("خطای سرور", 500);
}
}
// DELETE /api/admin/legal/[slug] — delete legal page (admin only)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ slug: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { slug } = await params;
try {
const res = await query(`DELETE FROM legal_pages WHERE slug = $1 RETURNING slug`, [slug]);
if (res.rows.length === 0) return errorResponse("صفحهٔ حقوقی یافت نشد", 404);
revalidateSite();
return NextResponse.json({ ok: true });
} catch (err) {
console.error("admin delete legal error:", err);
return errorResponse("خطای سرور", 500);
}
}
+50
View File
@@ -0,0 +1,50 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToLegalPage, type LegalPageRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { legalCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { parseJsonBody, buildInsert } from "@/lib/api/crud";
import { isUniqueViolation } from "@/lib/db/errors";
export const dynamic = "force-dynamic";
// POST /api/admin/legal — create legal page (admin only)
export async function POST(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = legalCreateSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const d = parsed.data;
try {
const { sql, params } = buildInsert(
"legal_pages",
["slug", "title", "body", "published"],
[d.slug, d.title, JSON.stringify(d.body), d.published],
);
await query(sql, params);
const res = await query<LegalPageRow>(`SELECT * FROM legal_pages WHERE slug = $1`, [d.slug]);
const row = res.rows[0];
return NextResponse.json(
{ ok: true, data: { ...rowToLegalPage(row), published: row.published } },
{ status: 201 },
);
} catch (err) {
if (isUniqueViolation(err)) {
return errorResponse("این slug قبلاً استفاده شده است", 409);
}
console.error("admin create legal error:", err);
return errorResponse("خطای سرور", 500);
}
}
+34
View File
@@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { verifyPassword, createSession, setSessionCookie } from "@/lib/auth/admin";
export async function POST(request: NextRequest) {
try {
const { email, password } = await request.json();
if (!email || !password) {
return NextResponse.json({ error: "ایمیل و رمز الزامی است" }, { status: 400 });
}
const res = await query(
`SELECT id, email, password_hash, name, role FROM admin_users WHERE email = $1 LIMIT 1`,
[email],
);
if (res.rows.length === 0) {
return NextResponse.json({ error: "کاربر یافت نشد" }, { status: 401 });
}
const user = res.rows[0];
const ok = await verifyPassword(password, user.password_hash);
if (!ok) {
return NextResponse.json({ error: "رمز نادرست است" }, { status: 401 });
}
const cookieValue = await createSession(user.id);
await setSessionCookie(cookieValue);
return NextResponse.json({ ok: true, user: { id: user.id, email: user.email, name: user.name, role: user.role } });
} catch (error) {
console.error("admin login error:", error);
return NextResponse.json({ error: "خطای سرور" }, { status: 500 });
}
}
+13
View File
@@ -0,0 +1,13 @@
import { NextResponse } from "next/server";
import { destroySession, clearSessionCookie } from "@/lib/auth/admin";
export async function POST() {
try {
await destroySession();
await clearSessionCookie();
return NextResponse.json({ ok: true });
} catch (error) {
console.error("admin logout error:", error);
return NextResponse.json({ error: "خطای سرور" }, { status: 500 });
}
}
+90
View File
@@ -0,0 +1,90 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToProgram, type ProgramRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { programPatchSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { revalidateSite } from "@/lib/api/revalidate";
import { parseJsonBody, buildUpdate } from "@/lib/api/crud";
import { isUniqueViolation } from "@/lib/db/errors";
export const dynamic = "force-dynamic";
const PROGRAM_COLUMNS: Record<string, string> = {
slug: "slug",
title: "title",
blurb: "blurb",
group: "group_key",
href: "href",
tagline: "tagline",
audience: "audience",
durationLabel: "duration_label",
formatLabel: "format_label",
highlights: "highlights",
body: "body",
published: "published",
};
// PATCH /api/admin/programs/[id] — update program (admin only)
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = programPatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const data: Record<string, unknown> = { ...parsed.data };
if (data.highlights !== undefined) {
data.highlights = JSON.stringify(data.highlights);
}
const spec = buildUpdate("programs", "id", PROGRAM_COLUMNS, data);
if (spec.empty) return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
try {
const res = await query<ProgramRow>(spec.sql, [...spec.params, id]);
if (res.rows.length === 0) return errorResponse("برنامه یافت نشد", 404);
const row = res.rows[0];
return NextResponse.json({ ok: true, data: { ...rowToProgram(row), published: row.published } });
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "programs_slug_key") {
return errorResponse("این slug قبلاً استفاده شده است", 409);
}
console.error("admin update program error:", err);
return errorResponse("خطای سرور", 500);
}
}
// DELETE /api/admin/programs/[id] — delete program (admin only)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
try {
const res = await query(`DELETE FROM programs WHERE id = $1 RETURNING id`, [id]);
if (res.rows.length === 0) return errorResponse("برنامه یافت نشد", 404);
revalidateSite();
return NextResponse.json({ ok: true });
} catch (err) {
console.error("admin delete program error:", err);
return errorResponse("خطای سرور", 500);
}
}
+51
View File
@@ -0,0 +1,51 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToProgram, type ProgramRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { programCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { makeId, parseJsonBody, buildInsert } from "@/lib/api/crud";
import { isUniqueViolation } from "@/lib/db/errors";
export const dynamic = "force-dynamic";
// POST /api/admin/programs — create program (admin only)
export async function POST(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = programCreateSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const d = parsed.data;
const id = makeId();
try {
const { sql, params } = buildInsert(
"programs",
["id", "slug", "title", "blurb", "group_key", "href", "tagline", "audience", "duration_label", "format_label", "highlights", "body", "published"],
[id, d.slug, d.title, d.blurb, d.group, d.href, d.tagline ?? null, d.audience, d.durationLabel, d.formatLabel, JSON.stringify(d.highlights), d.body, d.published],
);
await query(sql, params);
const res = await query<ProgramRow>(`SELECT * FROM programs WHERE id = $1`, [id]);
const row = res.rows[0];
return NextResponse.json(
{ ok: true, data: { ...rowToProgram(row), published: row.published } },
{ status: 201 },
);
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "programs_slug_key") {
return errorResponse("این slug قبلاً استفاده شده است", 409);
}
console.error("admin create program error:", err);
return errorResponse("خطای سرور", 500);
}
}
@@ -0,0 +1,66 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { requireAdmin } from "@/lib/auth/admin";
import { registrationStatusSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { parseJsonBody } from "@/lib/api/crud";
import type { RegistrationLeadRow } from "@/app/api/admin/registrations/route";
export const dynamic = "force-dynamic";
// PATCH /api/admin/registrations/[id] — change lead status (admin only)
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = registrationStatusSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
try {
const res = await query<RegistrationLeadRow>(
`UPDATE registration_leads SET status = $1 WHERE id = $2 RETURNING *`,
[parsed.data.status, id],
);
if (res.rows.length === 0) return errorResponse("لید ثبت‌نام یافت نشد", 404);
return NextResponse.json({ ok: true, data: res.rows[0] });
} catch (err) {
console.error("admin update registration error:", err);
return errorResponse("خطای سرور", 500);
}
}
// DELETE /api/admin/registrations/[id] — delete a lead (admin only)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
try {
const res = await query(
`DELETE FROM registration_leads WHERE id = $1 RETURNING id`,
[id],
);
if (res.rows.length === 0) return errorResponse("لید ثبت‌نام یافت نشد", 404);
return NextResponse.json({ ok: true });
} catch (err) {
console.error("admin delete registration error:", err);
return errorResponse("خطای سرور", 500);
}
}
+38
View File
@@ -0,0 +1,38 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth/admin";
import { errorResponse } from "@/lib/api/response";
import { listAdminRegistrations } from "@/lib/data/admin/registrations";
export const dynamic = "force-dynamic";
export interface RegistrationLeadRow {
id: string;
course_id: string | null;
course_slug: string | null;
full_name: string;
email: string;
phone: string | null;
message: string | null;
source: string;
status: "new" | "contacted" | "enrolled" | "rejected";
created_at: string;
}
// GET /api/admin/registrations — list registration leads (admin only)
// Query: ?search=<text>&status=new|contacted|enrolled|rejected
export async function GET(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
try {
const { searchParams } = request.nextUrl;
const data = await listAdminRegistrations({
search: searchParams.get("search") ?? undefined,
status: searchParams.get("status") ?? undefined,
});
return NextResponse.json({ ok: true, data });
} catch (err) {
console.error("admin list registrations error:", err);
return errorResponse("خطای سرور", 500);
}
}
+72
View File
@@ -0,0 +1,72 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToSiteStat, type SiteStatRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { statPatchSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { revalidateSite } from "@/lib/api/revalidate";
import { parseJsonBody, buildUpdate } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
const STAT_COLUMNS: Record<string, string> = {
value: "value",
label: "label",
published: "published",
};
// PATCH /api/admin/stats/[id] — update stat (admin only)
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = statPatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const spec = buildUpdate("site_stats", "id", STAT_COLUMNS, parsed.data as Record<string, unknown>);
if (spec.empty) return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
try {
const res = await query<SiteStatRow>(spec.sql, [...spec.params, id]);
if (res.rows.length === 0) return errorResponse("آمار یافت نشد", 404);
const row = res.rows[0];
return NextResponse.json({ ok: true, data: { ...rowToSiteStat(row), published: row.published } });
} catch (err) {
console.error("admin update stat error:", err);
return errorResponse("خطای سرور", 500);
}
}
// DELETE /api/admin/stats/[id] — delete stat (admin only)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
try {
const res = await query(`DELETE FROM site_stats WHERE id = $1 RETURNING id`, [id]);
if (res.rows.length === 0) return errorResponse("آمار یافت نشد", 404);
revalidateSite();
return NextResponse.json({ ok: true });
} catch (err) {
console.error("admin delete stat error:", err);
return errorResponse("خطای سرور", 500);
}
}
+47
View File
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToSiteStat, type SiteStatRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { statCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { makeId, parseJsonBody, buildInsert } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
// POST /api/admin/stats — create site stat (admin only)
export async function POST(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = statCreateSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const d = parsed.data;
const id = makeId();
try {
const { sql, params } = buildInsert(
"site_stats",
["id", "value", "label", "published"],
[id, d.value, d.label, d.published],
);
await query(sql, params);
const res = await query<SiteStatRow>(`SELECT * FROM site_stats WHERE id = $1`, [id]);
const row = res.rows[0];
return NextResponse.json(
{ ok: true, data: { ...rowToSiteStat(row), published: row.published } },
{ status: 201 },
);
} catch (err) {
console.error("admin create stat error:", err);
return errorResponse("خطای سرور", 500);
}
}
@@ -0,0 +1,77 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToTestimonial, type TestimonialRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { testimonialPatchSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { revalidateSite } from "@/lib/api/revalidate";
import { parseJsonBody, buildUpdate } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
const TESTIMONIAL_COLUMNS: Record<string, string> = {
quote: "quote",
name: "name",
role: "role",
courseTitle: "course_title",
published: "published",
};
// PATCH /api/admin/testimonials/[id] — update testimonial (admin only)
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = testimonialPatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const spec = buildUpdate("testimonials", "id", TESTIMONIAL_COLUMNS, parsed.data as Record<string, unknown>);
if (spec.empty) return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
try {
const res = await query<TestimonialRow>(spec.sql, [...spec.params, id]);
if (res.rows.length === 0) return errorResponse("بازخورد یافت نشد", 404);
const row = res.rows[0];
return NextResponse.json({
ok: true,
data: { ...rowToTestimonial(row), published: row.published },
});
} catch (err) {
console.error("admin update testimonial error:", err);
return errorResponse("خطای سرور", 500);
}
}
// DELETE /api/admin/testimonials/[id] — delete testimonial (admin only)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
try {
const res = await query(`DELETE FROM testimonials WHERE id = $1 RETURNING id`, [id]);
if (res.rows.length === 0) return errorResponse("بازخورد یافت نشد", 404);
revalidateSite();
return NextResponse.json({ ok: true });
} catch (err) {
console.error("admin delete testimonial error:", err);
return errorResponse("خطای سرور", 500);
}
}
+47
View File
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToTestimonial, type TestimonialRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { testimonialCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { makeId, parseJsonBody, buildInsert } from "@/lib/api/crud";
export const dynamic = "force-dynamic";
// POST /api/admin/testimonials — create testimonial (admin only)
export async function POST(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = testimonialCreateSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const d = parsed.data;
const id = makeId();
try {
const { sql, params } = buildInsert(
"testimonials",
["id", "quote", "name", "role", "course_title", "published"],
[id, d.quote, d.name, d.role, d.courseTitle, d.published],
);
await query(sql, params);
const res = await query<TestimonialRow>(`SELECT * FROM testimonials WHERE id = $1`, [id]);
const row = res.rows[0];
return NextResponse.json(
{ ok: true, data: { ...rowToTestimonial(row), published: row.published } },
{ status: 201 },
);
} catch (err) {
console.error("admin create testimonial error:", err);
return errorResponse("خطای سرور", 500);
}
}
+89
View File
@@ -0,0 +1,89 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToIntersectionTopic, type IntersectionTopicRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { topicPatchSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { revalidateSite } from "@/lib/api/revalidate";
import { parseJsonBody, buildUpdate } from "@/lib/api/crud";
import { isUniqueViolation } from "@/lib/db/errors";
export const dynamic = "force-dynamic";
const TOPIC_COLUMNS: Record<string, string> = {
slug: "slug",
title: "title",
description: "description",
href: "href",
imageUrl: "image_url",
body: "body",
highlights: "highlights",
published: "published",
};
// PATCH /api/admin/topics/[id] — update topic (admin only)
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = topicPatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const data: Record<string, unknown> = { ...parsed.data };
if (data.highlights !== undefined) {
data.highlights = JSON.stringify(data.highlights);
}
const spec = buildUpdate("intersection_topics", "id", TOPIC_COLUMNS, data);
if (spec.empty) return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
try {
const res = await query<IntersectionTopicRow>(spec.sql, [...spec.params, id]);
if (res.rows.length === 0) return errorResponse("موضوع یافت نشد", 404);
const row = res.rows[0];
return NextResponse.json({
ok: true,
data: { ...rowToIntersectionTopic(row), published: row.published },
});
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "intersection_topics_slug_key") {
return errorResponse("این slug قبلاً استفاده شده است", 409);
}
console.error("admin update topic error:", err);
return errorResponse("خطای سرور", 500);
}
}
// DELETE /api/admin/topics/[id] — delete topic (admin only)
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
const { id } = await params;
try {
const res = await query(`DELETE FROM intersection_topics WHERE id = $1 RETURNING id`, [id]);
if (res.rows.length === 0) return errorResponse("موضوع یافت نشد", 404);
revalidateSite();
return NextResponse.json({ ok: true });
} catch (err) {
console.error("admin delete topic error:", err);
return errorResponse("خطای سرور", 500);
}
}
+51
View File
@@ -0,0 +1,51 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { rowToIntersectionTopic, type IntersectionTopicRow } from "@/lib/db/mappers";
import { requireAdmin } from "@/lib/auth/admin";
import { topicCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { makeId, parseJsonBody, buildInsert } from "@/lib/api/crud";
import { isUniqueViolation } from "@/lib/db/errors";
export const dynamic = "force-dynamic";
// POST /api/admin/topics — create topic (admin only)
export async function POST(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = topicCreateSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const d = parsed.data;
const id = makeId();
try {
const { sql, params } = buildInsert(
"intersection_topics",
["id", "slug", "title", "description", "href", "image_url", "body", "highlights", "published"],
[id, d.slug, d.title, d.description, d.href, d.imageUrl, d.body, JSON.stringify(d.highlights), d.published],
);
await query(sql, params);
const res = await query<IntersectionTopicRow>(`SELECT * FROM intersection_topics WHERE id = $1`, [id]);
const row = res.rows[0];
return NextResponse.json(
{ ok: true, data: { ...rowToIntersectionTopic(row), published: row.published } },
{ status: 201 },
);
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "intersection_topics_slug_key") {
return errorResponse("این slug قبلاً استفاده شده است", 409);
}
console.error("admin create topic error:", err);
return errorResponse("خطای سرور", 500);
}
}
+13
View File
@@ -0,0 +1,13 @@
import { NextResponse } from "next/server";
import { getArticleById } from "@/lib/data/articles";
type Params = { params: Promise<{ id: string }> };
export async function GET(_request: Request, { params }: Params) {
const { id } = await params;
const article = await getArticleById(id);
if (!article) {
return NextResponse.json({ error: "Article not found" }, { status: 404 });
}
return NextResponse.json({ data: article });
}
+7
View File
@@ -0,0 +1,7 @@
import { NextResponse } from "next/server";
import { getArticles } from "@/lib/data/articles";
export async function GET() {
const data = await getArticles();
return NextResponse.json({ data });
}
+13
View File
@@ -0,0 +1,13 @@
import { NextResponse } from "next/server";
import { getCourseById } from "@/lib/data/courses";
type Params = { params: Promise<{ id: string }> };
export async function GET(_request: Request, { params }: Params) {
const { id } = await params;
const course = await getCourseById(id);
if (!course) {
return NextResponse.json({ error: "Course not found" }, { status: 404 });
}
return NextResponse.json({ data: course });
}
+7
View File
@@ -0,0 +1,7 @@
import { NextResponse } from "next/server";
import { getCourses } from "@/lib/data/courses";
export async function GET() {
const data = await getCourses();
return NextResponse.json({ data });
}
+13
View File
@@ -0,0 +1,13 @@
import { NextResponse } from "next/server";
import { getEventById } from "@/lib/data/events";
type Params = { params: Promise<{ id: string }> };
export async function GET(_request: Request, { params }: Params) {
const { id } = await params;
const event = await getEventById(id);
if (!event) {
return NextResponse.json({ error: "Event not found" }, { status: 404 });
}
return NextResponse.json({ data: event });
}
+7
View File
@@ -0,0 +1,7 @@
import { NextResponse } from "next/server";
import { getEvents } from "@/lib/data/events";
export async function GET() {
const data = await getEvents();
return NextResponse.json({ data });
}
+13
View File
@@ -0,0 +1,13 @@
import { NextResponse } from "next/server";
import { getProgramBySlug } from "@/lib/data/programs";
type Params = { params: Promise<{ slug: string }> };
export async function GET(_request: Request, { params }: Params) {
const { slug } = await params;
const program = await getProgramBySlug(slug);
if (!program) {
return NextResponse.json({ error: "Program not found" }, { status: 404 });
}
return NextResponse.json({ data: program });
}
+7
View File
@@ -0,0 +1,7 @@
import { NextResponse } from "next/server";
import { getPrograms } from "@/lib/data/programs";
export async function GET() {
const data = await getPrograms();
return NextResponse.json({ data });
}
+52
View File
@@ -0,0 +1,52 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { publicRegistrationSchema } from "@/lib/validation/public";
import { errorResponse } from "@/lib/api/response";
export const dynamic = "force-dynamic";
// POST /api/registrations — create a registration lead (public).
// Used by ContactInterestForm on /register/[slug] and /contact.
export async function POST(request: NextRequest) {
let body: unknown;
try {
body = await request.json();
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = publicRegistrationSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const d = parsed.data;
const courseSlug = d.courseSlug?.trim() || null;
try {
const course = courseSlug
? await query<{ id: string }>(
"SELECT id FROM courses WHERE slug = $1 AND published = true LIMIT 1",
[courseSlug],
)
: null;
await query(
`INSERT INTO registration_leads
(course_id, course_slug, full_name, email, phone, message, source)
VALUES ($1, $2, $3, $4, NULLIF($5, ''), NULLIF($6, ''), 'register_page')`,
[
course?.rows[0]?.id ?? null,
courseSlug,
d.fullName,
d.email,
d.phone,
d.message,
],
);
return NextResponse.json({ ok: true }, { status: 201 });
} catch (err) {
console.error("create registration lead error:", err);
return errorResponse("خطای سرور", 500);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

+285 -14
View File
@@ -1,26 +1,297 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
:root {
--background: #ffffff;
--foreground: #171717;
}
@custom-variant dark (&:is(.dark *));
/*
AUT Open Education — shadcn/ui theme only
Brand identity via CSS variables (primary / accent / muted). No ds-* or --brand-*.
*/
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--font-sans: var(--font-iransans);
--font-heading: var(--font-iransans);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: 0.375rem;
--radius-md: 0.625rem;
--radius-lg: 0.875rem;
--radius-xl: 1.125rem;
--radius-2xl: 1.25rem;
--radius-3xl: 1.5rem;
--radius-4xl: 1.75rem;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
:root {
/* AUT red + gold mapped into standard shadcn tokens */
--background: #ffffff;
--foreground: #1a1a1a;
--card: #ffffff;
--card-foreground: #1a1a1a;
--popover: #ffffff;
--popover-foreground: #1a1a1a;
--primary: #a31f34;
--primary-foreground: #ffffff;
--secondary: #f0efeb;
--secondary-foreground: #1a1a1a;
--muted: #f7f6f3;
--muted-foreground: #5c5c5c;
--accent: #d9dee5;
--accent-foreground: #16202c;
--destructive: oklch(0.577 0.245 27.325);
--border: #ebe9e4;
--input: #ebe9e4;
--ring: #a31f34;
--radius: 0.625rem;
--chart-1: #a31f34;
--chart-2: #0c2d5a;
--chart-3: #061525;
--chart-4: #9aa5b1;
--chart-5: #5c5c5c;
--sidebar: #ffffff;
--sidebar-foreground: #1a1a1a;
--sidebar-primary: #a31f34;
--sidebar-primary-foreground: #ffffff;
--sidebar-accent: #f0efeb;
--sidebar-accent-foreground: #1a1a1a;
--sidebar-border: #e2e0db;
--sidebar-ring: #a31f34;
}
.dark {
--background: #0a0a0a;
--foreground: #f7f6f3;
--card: #141414;
--card-foreground: #f7f6f3;
--popover: #141414;
--popover-foreground: #f7f6f3;
--primary: #c43a4e;
--primary-foreground: #ffffff;
--secondary: #1f1f1f;
--secondary-foreground: #f7f6f3;
--muted: #1a1a1a;
--muted-foreground: #a3a3a3;
--accent: #c7ced8;
--accent-foreground: #111827;
--border: #2a2a2a;
--input: #2a2a2a;
--ring: #c43a4e;
--sidebar: #141414;
--sidebar-foreground: #f7f6f3;
--sidebar-primary: #c43a4e;
--sidebar-primary-foreground: #ffffff;
--sidebar-accent: #1f1f1f;
--sidebar-accent-foreground: #f7f6f3;
--sidebar-border: #2a2a2a;
--sidebar-ring: #c43a4e;
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground antialiased;
font-size: 16px;
line-height: 1.65;
text-align: start;
}
html {
@apply font-sans scroll-smooth;
scroll-padding-top: 6rem;
}
a {
color: inherit;
text-decoration: none;
}
img {
max-width: 100%;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
/* Metamorphism dots + lines — soft presence, not noise */
@keyframes metamorph-line-pulse {
0%,
100% {
opacity: 0.35;
}
50% {
opacity: 0.85;
}
}
@keyframes metamorph-dot-breathe {
0%,
100% {
opacity: 0.55;
transform: scale(1);
}
50% {
opacity: 1;
transform: scale(1.35);
}
}
@keyframes metamorph-field-drift {
0%,
100% {
transform: translate3d(0, 0, 0);
}
50% {
transform: translate3d(1.2%, -0.8%, 0);
}
}
@keyframes metamorph-dash-flow {
from { stroke-dashoffset: 24; }
to { stroke-dashoffset: 0; }
}
@keyframes section-reveal {
from { opacity: 0; transform: translateY(2rem); }
to { opacity: 1; transform: translateY(0); }
}
.metamorph-field__mesh {
animation: metamorph-field-drift 18s ease-in-out infinite;
}
.metamorph-field__line {
stroke-dasharray: 4 8;
animation:
metamorph-line-pulse 7s ease-in-out infinite,
metamorph-dash-flow 8s linear infinite;
}
.page-hero::after,
.home-hero::after {
position: absolute;
inset-inline: 0;
bottom: 0;
height: 1px;
content: "";
background: linear-gradient(90deg, transparent, var(--accent), transparent);
opacity: 0.5;
}
.site-header::before {
position: absolute;
inset-inline: 0;
top: 0;
height: 2px;
content: "";
background: linear-gradient(90deg, var(--primary), var(--accent), var(--primary));
}
.site-header nav a {
position: relative;
}
.site-header nav a::after {
position: absolute;
inset-inline-start: 50%;
bottom: 0.15rem;
width: 0.3rem;
height: 0.3rem;
border-radius: 999px;
content: "";
background: var(--primary);
opacity: 0;
transform: translateX(50%) scale(0);
transition: opacity 200ms ease, transform 300ms cubic-bezier(0.22, 1, 0.36, 1);
}
.site-header nav a:hover::after,
.site-header nav a:focus-visible::after {
opacity: 1;
transform: translateX(50%) scale(1);
}
.motion-section[data-tone="muted"] {
background-image: radial-gradient(color-mix(in oklab, var(--foreground) 9%, transparent) 0.7px, transparent 0.7px);
background-size: 22px 22px;
}
.motion-section[data-tone="dark"] {
background-image:
radial-gradient(circle at 10% 20%, color-mix(in oklab, var(--primary) 30%, transparent), transparent 28%),
radial-gradient(circle at 90% 80%, color-mix(in oklab, var(--accent) 10%, transparent), transparent 25%);
}
@supports (animation-timeline: view()) {
.motion-section {
animation: section-reveal both cubic-bezier(0.22, 1, 0.36, 1);
animation-timeline: view();
animation-range: entry 5% cover 28%;
}
}
@media (hover: hover) {
[data-slot="card"] img {
transition: transform 500ms cubic-bezier(0.22, 1, 0.36, 1);
}
[data-slot="card"]:hover img {
transform: scale(1.025);
}
}
.metamorph-field__dot {
transform-box: fill-box;
transform-origin: center;
animation: metamorph-dot-breathe 6s ease-in-out infinite;
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
.metamorph-field__mesh,
.metamorph-field__line,
.metamorph-field__dot {
animation: none !important;
}
.metamorph-field animate {
display: none;
}
.motion-section {
animation: none !important;
}
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

+98 -18
View File
@@ -1,29 +1,109 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import localFont from "next/font/local";
import { NextIntlClientProvider } from "next-intl";
import { getLocale, getMessages, getTranslations } from "next-intl/server";
import { JsonLd, organizationJsonLd } from "@/lib/seo/json-ld";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
const iranSans = localFont({
src: [
{
path: "../fonts/iransans/IRANSansUltraLight.woff2",
weight: "200",
style: "normal",
},
{
path: "../fonts/iransans/IRANSansLight.woff2",
weight: "300",
style: "normal",
},
{
path: "../fonts/iransans/IRANSans.woff2",
weight: "400",
style: "normal",
},
{
path: "../fonts/iransans/IRANSansMedium.woff2",
weight: "500",
style: "normal",
},
{
path: "../fonts/iransans/IRANSansBold.woff2",
weight: "600",
style: "normal",
},
{
path: "../fonts/iransans/IRANSansBold.woff2",
weight: "700",
style: "normal",
},
{
path: "../fonts/iransans/IRANSansBold.woff2",
weight: "800",
style: "normal",
},
{
path: "../fonts/iransans/IRANSansBold.woff2",
weight: "900",
style: "normal",
},
],
variable: "--font-iransans",
display: "optional",
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("meta");
return {
metadataBase: new URL("https://openedu.aut.ac.ir"),
title: {
default: t("homeTitle"),
template: `%s | ${t("homeTitle")}`,
},
description: t("homeDescription"),
icons: {
icon: [{ url: "/brand/amirkabir.png", type: "image/png" }],
apple: [{ url: "/brand/amirkabir.png", type: "image/png" }],
shortcut: "/brand/amirkabir.png",
},
openGraph: {
type: "website",
locale: "fa_IR",
siteName: t("homeTitle"),
title: t("homeTitle"),
description: t("homeDescription"),
images: [{ url: "/brand/amirkabir.png", alt: "دانشگاه صنعتی امیرکبیر" }],
},
alternates: {
canonical: "/",
languages: { fa: "/" },
},
};
}
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const locale = await getLocale();
const messages = await getMessages();
const t = await getTranslations("nav");
export default function RootLayout({ children }: LayoutProps<"/">) {
return (
<html
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col">{children}</body>
<html lang={locale} dir="rtl" className={`${iranSans.variable} h-full`}>
<body className="flex min-h-full flex-col font-sans">
<NextIntlClientProvider messages={messages}>
<a
href="#main-content"
className="sr-only focus:not-sr-only focus:absolute focus:start-4 focus:top-4 focus:z-[100] focus:bg-card focus:px-3 focus:py-2"
>
{t("skipToContent")}
</a>
<JsonLd data={organizationJsonLd()} />
{children}
</NextIntlClientProvider>
</body>
</html>
);
}
-69
View File
@@ -1,69 +0,0 @@
import Image from "next/image";
export default function Home() {
return (
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert h-5 w-[100px]"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the{" "}
<code className="rounded bg-black/[.06] px-1.5 py-0.5 font-mono text-[0.9em] dark:bg-white/[.08]">
page.tsx
</code>{" "}
file.
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert h-[14px] w-4"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={14}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</main>
</div>
);
}
+40
View File
@@ -0,0 +1,40 @@
"use client";
import { useEffect } from "react";
import { DotCta } from "@/components/atoms/DotCta";
import { Button } from "@/components/ui/button";
export default function ProfessionalError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<div className="mx-auto flex min-h-[50vh] w-full max-w-7xl flex-col items-start justify-center bg-chart-3 px-5 py-20 text-background sm:px-8 lg:px-12">
<p className="text-sm font-semibold text-accent">خطا</p>
<h1 className="mt-3 text-2xl font-bold tracking-tight text-background sm:text-3xl">
بارگذاری صفحه ناموفق بود
</h1>
<p className="mt-3 max-w-md text-background/70">لطفاً دوباره تلاش کنید.</p>
<div className="mt-8 flex flex-wrap gap-4">
<Button
type="button"
variant="outline"
className="border-background/60 bg-transparent text-background hover:bg-background hover:text-foreground"
onClick={reset}
>
تلاش مجدد
</Button>
<DotCta href="/professional" onDark>
بازگشت
</DotCta>
</div>
</div>
);
}
+47
View File
@@ -0,0 +1,47 @@
import { getTranslations } from "next-intl/server";
import { SiteFooter } from "@/components/organisms/SiteFooter";
import { SiteHeader } from "@/components/organisms/SiteHeader";
import { getCourses } from "@/lib/data/courses";
import { getPrograms } from "@/lib/data/programs";
import { professionalNav, siteShortName } from "@/lib/site-config";
export default async function ProfessionalLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const t = await getTranslations();
const year = new Date().getFullYear();
const [courses, programs] = await Promise.all([getCourses(), getPrograms()]);
return (
<>
<SiteHeader
items={professionalNav}
searchLabel={t("nav.search")}
brandTitle={siteShortName}
brandSubtitle={t("nav.brandSubtitle")}
brandHref="/professional"
academicsLabel={t("nav.academics")}
programSelectorTitle={t("home.programSelectorTitle")}
executiveLabel={t("home.executiveLabel")}
exploreLabel={t("home.exploreOurPrograms")}
variant="professional"
courses={courses}
programs={programs}
/>
<div className="flex-1">{children}</div>
<SiteFooter
variant="professional"
copyright={t("footer.copyright", { year })}
linksTitle={t("footer.links")}
links={[
{ label: t("footer.press"), href: "/press" },
{ label: t("footer.careers"), href: "/careers" },
{ label: t("footer.accessibility"), href: "/accessibility" },
{ label: t("footer.privacy"), href: "/privacy" },
]}
/>
</>
);
}
+56
View File
@@ -0,0 +1,56 @@
import type { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import { ProfessionalLandingTemplate } from "@/components/templates/ProfessionalLandingTemplate";
import { getCourses } from "@/lib/data/courses";
import { getSiteStats, getTestimonials } from "@/lib/data/site";
import { courseJsonLd, JsonLd } from "@/lib/seo/json-ld";
export async function generateMetadata(): Promise<Metadata> {
const t = await getTranslations("meta");
return {
title: t("professionalTitle"),
description: t("professionalDescription"),
openGraph: {
title: t("professionalTitle"),
description: t("professionalDescription"),
},
alternates: {
canonical: "/professional",
},
};
}
export default async function ProfessionalPage() {
const t = await getTranslations();
const [courses, stats, testimonials] = await Promise.all([
getCourses(),
getSiteStats(),
getTestimonials(),
]);
return (
<>
{courses.slice(0, 3).map((course) => (
<JsonLd key={course.id} data={courseJsonLd(course)} />
))}
<ProfessionalLandingTemplate
labels={{
pathways: t("professional.pathways"),
exploreCourses: t("nav.exploreCourses"),
heroTitle: t("professional.heroTitle"),
heroBody: t("professional.heroBody"),
findProgram: t("professional.findProgram"),
offeredBy: t("professional.offeredBy"),
dppTitle: t("professional.dppTitle"),
dppBody: t("professional.dppBody"),
statsTitle: t("professional.statsTitle"),
rankTitle: t("professional.rankTitle"),
testimonialsTitle: t("professional.testimonialsTitle"),
}}
courses={courses}
stats={stats}
testimonials={testimonials}
/>
</>
);
}
+39
View File
@@ -0,0 +1,39 @@
"use client";
import { useEffect, useRef, useState } from "react";
const PERSIAN_DIGITS = "۰۱۲۳۴۵۶۷۸۹";
const toLatin = (value: string) => value.replace(/[۰-۹]/g, (digit) => String(PERSIAN_DIGITS.indexOf(digit)));
export function AnimatedMetric({ value, className }: { value: string; className?: string }) {
const ref = useRef<HTMLSpanElement>(null);
const [display, setDisplay] = useState(value);
useEffect(() => {
const element = ref.current;
if (!element || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const latin = toLatin(value).replaceAll("٬", "");
const match = latin.match(/^(\D*)(\d+)(\D*)$/);
if (!match) return;
const [, prefix, rawNumber, suffix] = match;
const target = Number(rawNumber);
const observer = new IntersectionObserver(([entry]) => {
if (!entry.isIntersecting) return;
observer.disconnect();
const startedAt = performance.now();
const duration = 1000;
const tick = (now: number) => {
const progress = Math.min((now - startedAt) / duration, 1);
const eased = 1 - Math.pow(1 - progress, 3);
const current = Math.round(target * eased).toLocaleString("fa-IR");
setDisplay(`${prefix}${current}${suffix}`);
if (progress < 1) requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
}, { threshold: 0.55 });
observer.observe(element);
return () => observer.disconnect();
}, [value]);
return <span ref={ref} className={className}>{display}</span>;
}
+27
View File
@@ -0,0 +1,27 @@
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
type BadgeVariant = "accent" | "muted" | "inverse";
export function BadgeLabel({
className,
variant = "accent",
...props
}: React.ComponentProps<"span"> & { variant?: BadgeVariant }) {
const map = {
accent: "default" as const,
muted: "secondary" as const,
inverse: "outline" as const,
};
return (
<Badge
variant={map[variant]}
className={cn(
variant === "inverse" &&
"border-background/30 bg-background/15 text-background",
className,
)}
{...props}
/>
);
}
+73
View File
@@ -0,0 +1,73 @@
import Image from "next/image";
import Link from "next/link";
import { cn } from "@/lib/utils";
const LOGO_SRC = "/brand/amirkabir.png";
type BrandLogoProps = {
href?: string;
title: string;
subtitle?: string;
onDark?: boolean;
className?: string;
compact?: boolean;
};
/** AUT seal on a dark disc — works on light and dark headers (asset is white-on-black). */
export function BrandLogo({
href = "/",
title,
subtitle,
onDark = false,
className,
compact = false,
}: BrandLogoProps) {
return (
<Link
href={href}
className={cn(
"group flex min-w-0 items-center gap-2.5 sm:gap-3",
className,
)}
aria-label={[title, subtitle].filter(Boolean).join(" — ")}
>
<span
className={cn(
"relative shrink-0 overflow-hidden rounded-full bg-chart-3 shadow-sm ring-1",
onDark ? "ring-background/20" : "ring-border",
compact ? "size-9" : "size-11 sm:size-12",
)}
>
<Image
src={LOGO_SRC}
alt=""
fill
priority
sizes="48px"
className="object-cover"
/>
</span>
<span className="min-w-0 text-start leading-tight">
<span
className={cn(
"block truncate font-black tracking-tight transition-colors",
compact ? "text-base" : "text-base sm:text-lg",
onDark ? "group-hover:text-background/70" : "group-hover:text-primary",
)}
>
{title}
</span>
{subtitle ? (
<span
className={cn(
"mt-0.5 block truncate text-[0.7rem] font-medium sm:text-xs",
onDark ? "text-background/70" : "text-muted-foreground",
)}
>
{subtitle}
</span>
) : null}
</span>
</Link>
);
}
+22
View File
@@ -0,0 +1,22 @@
import { cn } from "@/lib/utils";
type ContainerProps = React.ComponentProps<"div"> & {
narrow?: boolean;
};
export function Container({
className,
narrow = false,
...props
}: ContainerProps) {
return (
<div
className={cn(
"mx-auto w-full px-5 sm:px-8 lg:px-12",
narrow ? "max-w-3xl" : "max-w-7xl",
className,
)}
{...props}
/>
);
}
+50
View File
@@ -0,0 +1,50 @@
import Link from "next/link";
import { MorphMark } from "@/components/atoms/MorphMark";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
type DotCtaProps = {
href: string;
children: React.ReactNode;
className?: string;
onDark?: boolean;
external?: boolean;
};
/** CTA with metamorphism mark (dots → lines on hover) */
export function DotCta({
href,
children,
className,
onDark = false,
external = false,
}: DotCtaProps) {
const classes = cn(
buttonVariants({ variant: "outline" }),
"group h-auto gap-2.5 px-5 py-3 text-sm font-bold",
onDark &&
"border-background/40 bg-background text-foreground hover:bg-background/90",
className,
);
const content = (
<>
<MorphMark />
<span>{children}</span>
</>
);
if (external) {
return (
<a href={href} target="_blank" rel="noreferrer" className={classes}>
{content}
</a>
);
}
return (
<Link href={href} className={classes}>
{content}
</Link>
);
}
+18
View File
@@ -0,0 +1,18 @@
import { cn } from "@/lib/utils";
const levels = {
1: "text-3xl font-bold tracking-tight sm:text-4xl lg:text-5xl",
2: "text-2xl font-bold tracking-tight sm:text-3xl",
3: "text-lg font-semibold sm:text-xl",
4: "text-base font-semibold sm:text-lg",
} as const;
type HeadingProps = React.ComponentProps<"h1"> & {
as?: "h1" | "h2" | "h3" | "h4";
level?: keyof typeof levels;
};
export function Heading({ as, level = 2, className, ...props }: HeadingProps) {
const Tag = as ?? (`h${level}` as "h1" | "h2" | "h3" | "h4");
return <Tag className={cn(levels[level], className)} {...props} />;
}
+221
View File
@@ -0,0 +1,221 @@
import { cn } from "@/lib/utils";
type MetamorphFieldProps = {
className?: string;
/** `dark` = light strokes on navy/hero; `light` = ink strokes on sand/muted */
tone?: "dark" | "light";
/** Visual density of the constellation */
density?: "sparse" | "normal";
};
type Node = { x: number; y: number; r?: number };
type Edge = [number, number];
/** Landscape constellation — matches typical flex section bands (≈ 2.5∶1) */
const NODES_NORMAL: Node[] = [
{ x: 40, y: 60, r: 2.1 },
{ x: 130, y: 36, r: 1.7 },
{ x: 220, y: 88, r: 2.4 },
{ x: 100, y: 140, r: 1.5 },
{ x: 190, y: 168, r: 2.0 },
{ x: 310, y: 110, r: 1.6 },
{ x: 400, y: 48, r: 2.2 },
{ x: 480, y: 130, r: 1.8 },
{ x: 560, y: 70, r: 2.5 },
{ x: 650, y: 150, r: 1.6 },
{ x: 740, y: 40, r: 1.9 },
{ x: 830, y: 120, r: 2.1 },
{ x: 920, y: 64, r: 1.7 },
{ x: 1010, y: 140, r: 2.0 },
{ x: 1100, y: 90, r: 1.5 },
{ x: 70, y: 240, r: 2.3 },
{ x: 170, y: 280, r: 1.6 },
{ x: 280, y: 230, r: 2.0 },
{ x: 370, y: 300, r: 1.8 },
{ x: 470, y: 250, r: 2.2 },
{ x: 570, y: 310, r: 1.7 },
{ x: 680, y: 260, r: 2.4 },
{ x: 780, y: 320, r: 1.6 },
{ x: 880, y: 270, r: 2.0 },
{ x: 980, y: 330, r: 1.8 },
{ x: 1080, y: 280, r: 2.1 },
{ x: 120, y: 380, r: 1.5 },
{ x: 250, y: 410, r: 2.2 },
{ x: 390, y: 390, r: 1.7 },
{ x: 530, y: 430, r: 2.0 },
{ x: 670, y: 400, r: 1.9 },
{ x: 810, y: 440, r: 1.6 },
{ x: 950, y: 410, r: 2.3 },
{ x: 1090, y: 450, r: 1.8 },
];
const EDGES_NORMAL: Edge[] = [
[0, 1], [1, 2], [0, 3], [1, 3], [2, 4], [3, 4], [2, 5], [4, 5],
[5, 6], [5, 7], [6, 7], [6, 8], [7, 8], [8, 9], [7, 9],
[8, 10], [9, 11], [10, 11], [10, 12], [11, 12], [12, 13], [11, 13], [13, 14],
[3, 15], [4, 16], [5, 17], [7, 18], [8, 19], [9, 20], [11, 21], [12, 22], [13, 23], [14, 24],
[15, 16], [16, 17], [17, 18], [18, 19], [19, 20], [20, 21], [21, 22], [22, 23], [23, 24], [24, 25],
[15, 26], [16, 27], [18, 28], [19, 29], [21, 30], [22, 31], [24, 32], [25, 33],
[26, 27], [27, 28], [28, 29], [29, 30], [30, 31], [31, 32], [32, 33],
];
const NODES_SPARSE = NODES_NORMAL.filter((_, i) => i % 2 === 0);
const EDGES_SPARSE: Edge[] = [
[0, 1], [1, 2], [0, 3], [2, 4], [3, 4], [3, 5], [4, 6], [5, 6],
[5, 7], [6, 8], [7, 8], [7, 9], [8, 10], [9, 10], [9, 11], [10, 12],
[11, 12], [11, 13], [12, 14], [13, 14], [13, 15], [14, 16], [15, 16],
];
const VIEW_W = 1200;
const VIEW_H = 480;
/**
* Decorative metamorphism field — dots joined by thin lines.
* Place inside a `relative overflow-hidden` flex/grid surface.
* The outer wrapper fills the parent; the SVG covers with landscape slice
* so density stays proportional across wide hero/footer bands.
*/
export function MetamorphField({
className,
tone = "dark",
density = "normal",
}: MetamorphFieldProps) {
const nodes = density === "sparse" ? NODES_SPARSE : NODES_NORMAL;
const edges = density === "sparse" ? EDGES_SPARSE : EDGES_NORMAL;
const stroke =
tone === "dark" ? "color-mix(in oklab, white 55%, transparent)" : "var(--foreground)";
const fill =
tone === "dark" ? "color-mix(in oklab, white 70%, transparent)" : "var(--primary)";
const accent = tone === "dark" ? "var(--accent)" : "var(--primary)";
const targets = nodes.map((node, index) => ({
x: Math.max(24, Math.min(VIEW_W - 24, node.x + Math.sin(index * 1.7) * 28)),
y: Math.max(24, Math.min(VIEW_H - 24, node.y + Math.cos(index * 1.3) * 22)),
}));
return (
<div
className={cn(
"pointer-events-none absolute inset-0 z-[1] overflow-hidden metamorph-field",
tone === "light" ? "opacity-[0.14]" : "opacity-[0.42]",
className,
)}
aria-hidden
>
<svg
className="block size-full max-h-none max-w-none"
viewBox={`0 0 ${VIEW_W} ${VIEW_H}`}
fill="none"
preserveAspectRatio="xMidYMid slice"
focusable="false"
>
<g className="metamorph-field__mesh" stroke={stroke} strokeWidth="0.9">
{edges.map(([a, b], i) => {
const n1 = nodes[a];
const n2 = nodes[b];
if (!n1 || !n2) return null;
return (
<line
key={`e-${i}`}
x1={n1.x}
y1={n1.y}
x2={n2.x}
y2={n2.y}
className="metamorph-field__line"
style={{ animationDelay: `${(i % 8) * 0.35}s` }}
>
<animate
attributeName="x1"
values={`${n1.x};${targets[a].x};${n1.x}`}
dur={`${14 + (i % 4)}s`}
repeatCount="indefinite"
/>
<animate
attributeName="y1"
values={`${n1.y};${targets[a].y};${n1.y}`}
dur={`${14 + (i % 4)}s`}
repeatCount="indefinite"
/>
<animate
attributeName="x2"
values={`${n2.x};${targets[b].x};${n2.x}`}
dur={`${14 + (i % 4)}s`}
repeatCount="indefinite"
/>
<animate
attributeName="y2"
values={`${n2.y};${targets[b].y};${n2.y}`}
dur={`${14 + (i % 4)}s`}
repeatCount="indefinite"
/>
</line>
);
})}
</g>
<g>
{nodes.map((n, i) => (
<g key={`n-${i}`}>
{i % 5 === 0 ? (
<circle
cx={n.x}
cy={n.y}
r="8"
fill="none"
stroke={accent}
strokeWidth="0.7"
opacity="0.45"
>
<animate
attributeName="cx"
values={`${n.x};${targets[i].x};${n.x}`}
dur={`${14 + (i % 4)}s`}
repeatCount="indefinite"
/>
<animate
attributeName="cy"
values={`${n.y};${targets[i].y};${n.y}`}
dur={`${14 + (i % 4)}s`}
repeatCount="indefinite"
/>
<animate
attributeName="r"
values="5;11;5"
dur={`${8 + (i % 3)}s`}
repeatCount="indefinite"
/>
<animate
attributeName="opacity"
values="0.45;0;0.45"
dur={`${8 + (i % 3)}s`}
repeatCount="indefinite"
/>
</circle>
) : null}
<circle
cx={n.x}
cy={n.y}
r={n.r ?? 2}
fill={i % 5 === 0 ? accent : fill}
className="metamorph-field__dot"
style={{ animationDelay: `${(i % 6) * 0.4}s` }}
>
<animate
attributeName="cx"
values={`${n.x};${targets[i].x};${n.x}`}
dur={`${14 + (i % 4)}s`}
repeatCount="indefinite"
/>
<animate
attributeName="cy"
values={`${n.y};${targets[i].y};${n.y}`}
dur={`${14 + (i % 4)}s`}
repeatCount="indefinite"
/>
</circle>
</g>
))}
</g>
</svg>
</div>
);
}
+37
View File
@@ -0,0 +1,37 @@
import { cn } from "@/lib/utils";
type MorphMarkProps = {
className?: string;
};
/**
* Metamorphism mark: four dots that morph into crossing lines on group hover.
* Parent must use `group` (e.g. Button).
*/
export function MorphMark({ className }: MorphMarkProps) {
return (
<svg
viewBox="0 0 16 16"
className={cn("size-4 shrink-0", className)}
aria-hidden
>
{/* Idle: four dots */}
<g className="origin-center transition-opacity duration-300 group-hover:opacity-0 group-focus-visible:opacity-0">
<circle cx="4" cy="4" r="1.65" fill="currentColor" />
<circle cx="12" cy="4" r="1.65" fill="currentColor" />
<circle cx="4" cy="12" r="1.65" fill="currentColor" />
<circle cx="12" cy="12" r="1.65" fill="currentColor" />
</g>
{/* Hover: crossing lines */}
<g
className="origin-center opacity-0 transition-opacity duration-300 group-hover:opacity-100 group-focus-visible:opacity-100"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
>
<line x1="3.5" y1="3.5" x2="12.5" y2="12.5" />
<line x1="12.5" y1="3.5" x2="3.5" y2="12.5" />
</g>
</svg>
);
}
+33
View File
@@ -0,0 +1,33 @@
import { cn } from "@/lib/utils";
type SectionProps = React.ComponentProps<"section"> & {
tone?: "default" | "muted" | "dark" | "accent";
tight?: boolean;
};
const tones = {
default: "bg-background text-foreground",
muted: "bg-muted text-foreground",
dark: "bg-chart-3 text-background",
accent: "bg-primary text-primary-foreground",
};
export function Section({
className,
tone = "default",
tight = false,
...props
}: SectionProps) {
return (
<section
data-tone={tone}
className={cn(
"motion-section relative",
tight ? "py-8 sm:py-10" : "py-16 sm:py-24",
tones[tone],
className,
)}
{...props}
/>
);
}
+25
View File
@@ -0,0 +1,25 @@
import Link from "next/link";
import { cn } from "@/lib/utils";
type TextLinkProps = React.ComponentProps<typeof Link> & {
tone?: "default" | "inverse" | "accent";
};
export function TextLink({
className,
tone = "default",
...props
}: TextLinkProps) {
return (
<Link
className={cn(
"font-medium underline-offset-4 transition-colors hover:underline",
tone === "default" && "text-chart-2 hover:text-primary",
tone === "inverse" && "text-background/90 hover:text-background",
tone === "accent" && "text-primary hover:text-foreground",
className,
)}
{...props}
/>
);
}
+288
View File
@@ -0,0 +1,288 @@
import Image from "next/image";
import Link from "next/link";
import { ArrowUpLeft, MapPin, Wifi } from "lucide-react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { blurDataURL } from "@/lib/images";
import type { Program } from "@/lib/types";
import { cn } from "@/lib/utils";
export function ProgramCard({
program,
className,
}: {
program: Program;
className?: string;
}) {
return (
<Card className={cn("group h-full gap-2 border-border/70 py-6 shadow-sm transition-[box-shadow,border-color] hover:border-primary/25 hover:shadow-lg", className)}>
<CardHeader className="gap-1">
{program.tagline ? (
<p className="text-xs font-bold text-primary">{program.tagline}</p>
) : null}
<CardTitle className="text-lg">
<Link href={program.href} className="hover:text-primary">
{program.title}
</Link>
</CardTitle>
</CardHeader>
<CardContent>
<CardDescription className="leading-relaxed">
{program.blurb}
</CardDescription>
<span className="mt-5 inline-flex items-center gap-1 text-xs font-bold text-primary">
جزئیات برنامه
<ArrowUpLeft className="size-3.5 transition-transform group-hover:-translate-x-0.5 group-hover:-translate-y-0.5" />
</span>
</CardContent>
</Card>
);
}
export function ArticleCard({
title,
category,
excerpt,
imageUrl,
href,
featured = false,
variant = "grid",
}: {
title: string;
category: string;
excerpt: string;
imageUrl: string;
href: string;
featured?: boolean;
variant?: "grid" | "list";
}) {
if (variant === "list") {
return (
<article className="group grid overflow-hidden border-b border-border py-7 first:pt-0 last:border-b-0 sm:grid-cols-[14rem_1fr] sm:gap-8 lg:grid-cols-[19rem_1fr] lg:py-9">
<Link href={href} className="relative aspect-[16/10] overflow-hidden rounded-xl bg-muted sm:aspect-auto sm:min-h-44">
<Image src={imageUrl} alt={title} fill placeholder="blur" blurDataURL={blurDataURL} className="object-cover transition-transform duration-500 group-hover:scale-[1.025]" sizes="(max-width:640px) 100vw, 304px" />
</Link>
<div className="flex min-w-0 flex-col justify-center pt-5 sm:pt-0">
<p className="text-xs font-bold text-primary">{category}</p>
<h2 className="mt-2 text-xl font-bold leading-relaxed tracking-tight sm:text-2xl">
<Link href={href} className="transition-colors hover:text-primary">{title}</Link>
</h2>
<p className="mt-3 max-w-2xl text-sm leading-7 text-muted-foreground sm:text-base">{excerpt}</p>
<Link href={href} className="mt-4 inline-flex w-fit items-center gap-2 text-sm font-semibold text-foreground/70 transition-colors hover:text-primary">
مطالعه مقاله <ArrowUpLeft className="size-4 transition-transform group-hover:-translate-x-0.5 group-hover:-translate-y-0.5" />
</Link>
</div>
</article>
);
}
return (
<article
className={cn(
"group flex h-full flex-col",
featured && "lg:flex-row lg:gap-8",
)}
>
<Link
href={href}
className={cn(
"relative block shrink-0 overflow-hidden rounded-2xl",
featured && "lg:w-[58%]",
)}
>
<div
className={cn(
"relative w-full",
featured ? "aspect-[16/10]" : "aspect-[4/3]",
)}
>
<Image
src={imageUrl}
alt={title}
fill
placeholder="blur"
blurDataURL={blurDataURL}
className="object-cover transition-transform duration-500 group-hover:scale-[1.035]"
sizes={
featured
? "(max-width:1024px) 100vw, 58vw"
: "(max-width:768px) 100vw, 33vw"
}
/>
</div>
</Link>
<div
className={cn(
"mt-4 flex flex-1 flex-col",
featured && "lg:mt-0 lg:justify-center",
)}
>
<p className="text-xs font-semibold text-muted-foreground">{category}</p>
<h3
className={cn(
featured
? "mt-2 text-2xl font-bold tracking-tight sm:text-3xl"
: "mt-1.5 text-lg font-semibold",
)}
>
<Link href={href} className="hover:text-primary">
{title}
</Link>
</h3>
{featured ? (
<p className="mt-3 max-w-md text-base leading-relaxed text-muted-foreground">
{excerpt}
</p>
) : null}
</div>
</article>
);
}
export function EventCard({
title,
startDate,
endDate,
location,
href,
variant = "home",
}: {
title: string;
startDate: string;
endDate: string | null;
location: string;
href: string;
variant?: "home" | "list";
}) {
const start = new Date(startDate);
const end = endDate ? new Date(endDate) : null;
const day = start.toLocaleDateString("fa-IR", { day: "numeric" });
const month = start.toLocaleDateString("fa-IR", { month: "short" });
const endDay = end?.toLocaleDateString("fa-IR", { day: "numeric" });
const endMonth = end?.toLocaleDateString("fa-IR", { month: "short" });
const isOnline = /آنلاین|online/i.test(location);
const body = (
<>
<div className="flex items-start gap-3">
<div>
<p className="text-xs font-semibold text-muted-foreground">{month}</p>
<p className="mt-0.5 text-2xl font-bold leading-none">{day}</p>
</div>
{end ? (
<>
<span className="mt-7 text-xs font-medium text-primary">تا</span>
<div>
<p className="text-xs font-semibold text-muted-foreground">
{endMonth}
</p>
<p className="mt-0.5 text-2xl font-bold leading-none">{endDay}</p>
</div>
</>
) : null}
</div>
<div>
<h3 className="text-lg font-semibold">
<Link href={href} className="hover:text-primary">
{title}
</Link>
</h3>
<p className="mt-2 flex items-center gap-1.5 text-sm text-muted-foreground">
{isOnline ? (
<Wifi className="size-3.5 shrink-0" aria-hidden />
) : (
<MapPin className="size-3.5 shrink-0" aria-hidden />
)}
{location}
</p>
</div>
</>
);
if (variant === "list") {
return (
<Card className="gap-4 py-5">
<CardContent className="flex flex-col gap-4">{body}</CardContent>
</Card>
);
}
return (
<article className="flex flex-col gap-4 py-4 sm:border-e sm:border-border sm:px-5 sm:py-2 sm:last:border-e-0">
{body}
</article>
);
}
export function StatItem({ value, label }: { value: string; label: string }) {
return (
<div className="text-center">
<p className="text-4xl font-extrabold text-accent">{value}</p>
<p className="mt-2 text-sm text-background/70">{label}</p>
</div>
);
}
export function QuoteBlock({
quote,
name,
role,
courseTitle,
}: {
quote: string;
name: string;
role: string;
courseTitle: string;
}) {
return (
<blockquote className="flex h-full flex-col rounded-xl bg-background/5 p-7 ring-1 ring-background/10">
<p className="flex-1 text-sm leading-8 text-background/90">«{quote}»</p>
<footer className="mt-7">
<p className="font-bold text-background">{name}</p>
<p className="mt-0.5 text-sm text-background/55">{role}</p>
<p className="mt-2 text-xs font-semibold text-accent">{courseTitle}</p>
</footer>
</blockquote>
);
}
export function IntersectionCard({
title,
description,
href,
imageUrl,
}: {
title: string;
description: string;
href: string;
imageUrl: string;
}) {
return (
<Link
href={href}
className="group relative block min-h-[16rem] overflow-hidden rounded-2xl bg-chart-3 shadow-sm sm:min-h-[18rem]"
>
<div className="absolute inset-0 overflow-hidden">
<Image
src={imageUrl}
alt={title}
fill
placeholder="blur"
blurDataURL={blurDataURL}
className="object-cover transition-transform duration-500 group-hover:scale-[1.04]"
sizes="(max-width:768px) 100vw, 25vw"
/>
</div>
<div className="absolute inset-0 bg-gradient-to-t from-chart-3 via-chart-3/50 to-transparent" />
<div className="absolute inset-x-0 bottom-0 p-6 text-background">
<div className="flex items-center justify-between gap-3"><p className="text-sm font-bold text-accent">{title}</p><ArrowUpLeft className="size-4 transition-transform group-hover:-translate-x-1 group-hover:-translate-y-1" /></div>
<p className="mt-2 text-sm font-semibold leading-relaxed text-background/80">{description}</p>
</div>
</Link>
);
}
+56
View File
@@ -0,0 +1,56 @@
import Link from "next/link";
import { ArrowLeft, GraduationCap } from "lucide-react";
import { Container } from "@/components/atoms/Container";
import { MetamorphField } from "@/components/atoms/MetamorphField";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
export function HeroFeatured({ title, href, eyebrow }: { title: string; href: string; imageUrl: string; eyebrow: string }) {
return (
<header className="home-hero relative isolate overflow-hidden bg-chart-3 text-background">
<MetamorphField tone="dark" density="sparse" className="end-0 start-auto w-[min(55vw,36rem)] opacity-20" />
<Container className="relative z-[2] flex min-h-[38rem] items-center py-20 sm:py-24">
<div className="home-hero__copy max-w-4xl">
<div className="inline-flex items-center gap-2 text-sm font-medium text-background/60">
<GraduationCap className="size-4" />
مرکز آموزش‌های آزاد دانشگاه صنعتی امیرکبیر
</div>
<h1 className="mt-8 text-4xl font-black leading-[1.25] tracking-tight sm:text-6xl lg:text-7xl">
آموزش حرفه‌ای برای
<span className="mt-2 block text-background">مدیریت در دنیای متغیر</span>
</h1>
<p className="mt-7 max-w-2xl text-base leading-8 text-background/65 sm:text-lg sm:leading-9">
دانش دانشگاهی و تجربه‌ی صنعت را کنار هم می‌آوریم تا مدیران و متخصصان برای تصمیم‌های پیچیده آماده‌تر شوند.
</p>
<div className="mt-10 flex flex-wrap gap-3">
<Link
href="/programs"
className={cn(
buttonVariants({ size: "lg" }),
"bg-primary font-bold text-primary-foreground hover:bg-primary/85",
)}
>
مشاهده دوره‌ها <ArrowLeft className="size-4" />
</Link>
<Link
href="/about"
className={cn(
buttonVariants({ variant: "outline", size: "lg" }),
"border-background/25 bg-transparent font-bold text-background hover:bg-background hover:text-foreground",
)}
>
درباره مرکز
</Link>
</div>
<div className="mt-12 border-t border-background/10 pt-6">
<Link href={href} className="group inline-flex max-w-2xl items-center gap-3 text-sm text-background/55 transition-colors hover:text-background">
<span className="shrink-0 font-semibold text-background/80">{eyebrow}</span>
<span className="truncate">{title}</span>
<ArrowLeft className="size-4 shrink-0 transition-transform group-hover:-translate-x-1" />
</Link>
</div>
</div>
</Container>
</header>
);
}
+23
View File
@@ -0,0 +1,23 @@
import Image from "next/image";
import { Container } from "@/components/atoms/Container";
import { Heading } from "@/components/atoms/Heading";
import { MetamorphField } from "@/components/atoms/MetamorphField";
export function PageHero({ title, intro, eyebrow, imageUrl }: { title: string; intro?: string; eyebrow?: string; imageUrl?: string }) {
return (
<header className="page-hero relative isolate overflow-hidden bg-chart-3 py-20 text-background sm:py-28">
{imageUrl ? (
<><Image src={imageUrl} alt="" fill priority className="object-cover opacity-25" sizes="100vw" /><div className="absolute inset-0 bg-gradient-to-l from-chart-3 via-chart-3/90 to-chart-3/60" /></>
) : <><Image src="/brand/campus-collaboration-v1.png" alt="" fill priority className="object-cover opacity-15 grayscale" sizes="100vw" /><div className="absolute inset-0 bg-gradient-to-l from-chart-3 via-chart-3/95 to-chart-3/75" /></>}
<MetamorphField tone="dark" density="normal" className="end-0 start-auto w-[min(75vw,42rem)] opacity-45" />
<div className="absolute end-0 top-0 h-px w-1/3 bg-gradient-to-l from-accent to-transparent" />
<Container className="relative z-[2]">
<div className="page-hero__content max-w-3xl text-start">
{eyebrow ? <p className="mb-4 inline-flex rounded-full border border-background/15 bg-background/5 px-3 py-1.5 text-xs font-semibold text-accent backdrop-blur-sm">{eyebrow}</p> : null}
<Heading as="h1" level={1} className="text-4xl leading-tight text-background sm:text-6xl">{title}</Heading>
{intro ? <p className="mt-5 max-w-2xl border-s border-accent/70 ps-5 text-base leading-8 text-background/70 sm:text-lg">{intro}</p> : null}
</div>
</Container>
</header>
);
}
+41
View File
@@ -0,0 +1,41 @@
import { Card } from "@/components/ui/card";
import { cn } from "@/lib/utils";
type SurfaceCardProps = {
className?: string;
children?: React.ReactNode;
id?: string;
padded?: boolean | "sm" | "md" | "lg";
as?: "article" | "div";
};
const padClass = {
true: "p-6",
sm: "p-4",
md: "p-5",
lg: "p-8",
} as const;
/** Light surface built on shadcn Card */
export function SurfaceCard({
padded = "md",
className,
children,
id,
as = "article",
}: SurfaceCardProps) {
return (
<Card
id={id}
data-slot={as === "div" ? "surface-div" : "surface-article"}
className={cn(
"gap-0 border-border/70 bg-card py-0 shadow-sm transition-[box-shadow,border-color] hover:border-primary/20 hover:shadow-md",
padded !== false &&
padClass[padded === true ? "true" : (padded as "sm" | "md" | "lg")],
className,
)}
>
{children}
</Card>
);
}
@@ -0,0 +1,108 @@
"use client";
import Link from "next/link";
import { X } from "lucide-react";
import { Container } from "@/components/atoms/Container";
import { DotCta } from "@/components/atoms/DotCta";
import { Button } from "@/components/ui/button";
import type { Program } from "@/lib/types";
export function AcademicsOverlay({
open,
onClose,
title,
executiveLabel,
exploreLabel,
standardPrograms,
executivePrograms,
}: {
open: boolean;
onClose: () => void;
title: string;
executiveLabel: string;
exploreLabel: string;
standardPrograms: Program[];
executivePrograms: Program[];
}) {
if (!open) return null;
return (
<div
className="fixed inset-0 z-[70] overflow-y-auto bg-card text-foreground"
role="dialog"
aria-modal="true"
aria-label={title}
>
<Container className="py-8">
<div className="mb-8 flex items-center justify-between gap-4">
<Button
type="button"
variant="ghost"
onClick={onClose}
className="px-0 font-semibold hover:bg-transparent hover:text-primary"
>
بازگشت به منو
</Button>
<Button
type="button"
variant="ghost"
size="icon"
onClick={onClose}
aria-label="بستن"
>
<X className="size-5" />
</Button>
</div>
<h2 className="mb-10 max-w-3xl text-start text-3xl font-bold tracking-tight sm:text-4xl">
{title}
</h2>
<ul className="grid gap-x-10 gap-y-8 sm:grid-cols-2 lg:grid-cols-3">
{standardPrograms.map((program) => (
<li key={program.id}>
<Link
href={program.href}
onClick={onClose}
className="group block"
>
<span className="text-base font-extrabold leading-snug group-hover:text-primary">
{program.title}
</span>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
{program.blurb}
</p>
</Link>
</li>
))}
</ul>
<h3 className="mt-14 mb-6 text-lg font-extrabold text-primary">
{executiveLabel}
</h3>
<ul className="grid gap-x-10 gap-y-8 sm:grid-cols-2 lg:grid-cols-3">
{executivePrograms.map((program) => (
<li key={program.id}>
<Link
href={program.href}
onClick={onClose}
className="group block"
>
<span className="text-base font-extrabold leading-snug group-hover:text-primary">
{program.title}
</span>
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
{program.blurb}
</p>
</Link>
</li>
))}
</ul>
<div className="mt-12">
<DotCta href="/programs">{exploreLabel}</DotCta>
</div>
</Container>
</div>
);
}
@@ -0,0 +1,74 @@
"use client";
import Link from "next/link";
import { X } from "lucide-react";
import { useEffect, useState } from "react";
import { Container } from "@/components/atoms/Container";
import { Button } from "@/components/ui/button";
import type { CampaignBanner } from "@/lib/types";
const STORAGE_PREFIX = "aut-banner:v1:";
export function CampaignBanners({ banners }: { banners: CampaignBanner[] }) {
const [hidden, setHidden] = useState<Record<string, boolean>>({});
const [ready, setReady] = useState(false);
useEffect(() => {
const frame = requestAnimationFrame(() => {
const next: Record<string, boolean> = {};
for (const banner of banners) {
try {
next[banner.id] =
localStorage.getItem(`${STORAGE_PREFIX}${banner.version}`) === "1";
} catch {
next[banner.id] = false;
}
}
setHidden(next);
setReady(true);
});
return () => cancelAnimationFrame(frame);
}, [banners]);
function dismiss(banner: CampaignBanner) {
try {
localStorage.setItem(`${STORAGE_PREFIX}${banner.version}`, "1");
} catch {
/* ignore */
}
setHidden((prev) => ({ ...prev, [banner.id]: true }));
}
if (!ready) return null;
const visible = banners.filter((b) => !hidden[b.id]);
if (visible.length === 0) return null;
const banner = visible[0];
return (
<div className="bg-chart-3 text-background">
<Container className="flex items-center justify-between gap-4 py-3">
<p className="min-w-0 flex-1 text-sm leading-relaxed">
<span className="text-background/90">{banner.text}</span>{" "}
<Link
href={banner.href}
className="font-bold text-background underline-offset-4 hover:underline"
>
{banner.cta}
</Link>
</p>
<Button
type="button"
variant="ghost"
size="icon"
aria-label="بستن بنر"
className="shrink-0 text-background/70 hover:bg-background/10 hover:text-background"
onClick={() => dismiss(banner)}
>
<X className="size-4" />
</Button>
</Container>
</div>
);
}
@@ -0,0 +1,152 @@
"use client";
import { useDeferredValue, useMemo, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import type { Course } from "@/lib/types";
import { courseCategories } from "@/lib/site-config";
import { formatCoursePrice, formatLabel } from "@/lib/labels";
import { cn } from "@/lib/utils";
export function CategoryCourseExplorer({
courses,
findLabel,
}: {
courses: Course[];
findLabel: string;
}) {
const [query, setQuery] = useState("");
const [category, setCategory] = useState("all");
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
const filtered = useMemo(() => {
return courses.filter((course) => {
const matchesCategory =
category === "all" ||
category === "best" ||
course.category === category;
const matchesQuery =
!deferredQuery ||
course.title.includes(deferredQuery) ||
course.summary.includes(deferredQuery);
return matchesCategory && matchesQuery;
});
}, [courses, category, deferredQuery]);
return (
<div className="space-y-8">
<form
className="flex flex-col gap-3 sm:flex-row"
onSubmit={(e) => e.preventDefault()}
role="search"
>
<Label className="sr-only" htmlFor="course-search">
{findLabel}
</Label>
<Input
id="course-search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={findLabel}
className="h-11 flex-1 border-border bg-background text-foreground placeholder:text-muted-foreground"
/>
<Button type="submit" className="h-11">
جستجو
</Button>
</form>
<div
className="flex flex-wrap gap-2"
role="tablist"
aria-label="دسته‌بندی دوره‌ها"
>
{courseCategories.map((item) => (
<Button
key={item.id}
type="button"
role="tab"
size="sm"
variant={category === item.id ? "default" : "ghost"}
aria-selected={category === item.id}
onClick={() => setCategory(item.id)}
className={cn(
category !== item.id &&
"bg-background/10 text-background/85 hover:bg-background/20 hover:text-background",
)}
>
{item.label}
</Button>
))}
</div>
<div
className={cn(
"grid gap-5 transition-opacity sm:grid-cols-2 lg:grid-cols-3",
isStale && "opacity-70",
)}
>
{filtered.map((course) => {
const priceLabel = formatCoursePrice(course.price);
return (
<Card
key={course.id}
className="gap-0 overflow-hidden bg-background/5 py-0 text-background ring-background/10"
>
<div className="relative aspect-[16/10] overflow-hidden">
<Image
src={course.imageUrl}
alt={course.title}
fill
className="object-cover"
sizes="(max-width:768px) 100vw, 33vw"
/>
</div>
<CardHeader className="gap-1 px-4 pt-4">
<CardTitle className="text-base text-background">
<Link
href={course.registrationUrl}
className="transition-opacity hover:opacity-90"
>
{course.title}
</Link>
</CardTitle>
</CardHeader>
<CardContent className="space-y-3 px-4 pb-4">
<CardDescription className="line-clamp-3 text-background/70">
{course.summary}
</CardDescription>
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-background/55">
<span>
{course.durationHours} ساعت · {formatLabel(course.format)}
</span>
{priceLabel ? (
<span className="font-semibold text-background/90">
{priceLabel}
</span>
) : null}
</div>
<Link
href={course.registrationUrl}
className="inline-flex text-sm font-semibold text-background underline-offset-4 hover:underline"
>
جزئیات و ثبت‌نام
</Link>
</CardContent>
</Card>
);
})}
</div>
</div>
);
}
@@ -0,0 +1,108 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
export function ContactInterestForm({
submitLabel,
successLabel,
courseSlug,
}: {
submitLabel: string;
successLabel: string;
courseSlug?: string;
}) {
const [form, setForm] = useState({ fullName: "", email: "", phone: "", message: "" });
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [sent, setSent] = useState(false);
function set<K extends keyof typeof form>(key: K, value: string) {
setForm((f) => ({ ...f, [key]: value }));
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError("");
try {
const res = await fetch("/api/registrations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...form, courseSlug }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
setError(data.error || "خطا در ثبت درخواست");
return;
}
setSent(true);
} finally {
setLoading(false);
}
}
if (sent) {
return (
<p className="rounded-lg border border-primary/25 bg-primary/5 p-4 text-sm text-chart-2">
{successLabel}
</p>
);
}
return (
<form className="space-y-4" onSubmit={handleSubmit}>
{error && (
<p className="rounded-lg bg-destructive/10 p-3 text-sm text-red-600" role="alert">
{error}
</p>
)}
<div className="space-y-1.5">
<Label htmlFor="name">نام و نام خانوادگی</Label>
<Input
id="name"
value={form.fullName}
onChange={(e) => set("fullName", e.target.value)}
required
className="h-11"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="email">ایمیل</Label>
<Input
id="email"
name="email"
type="email"
value={form.email}
onChange={(e) => set("email", e.target.value)}
required
className="h-11"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="phone">تلفن</Label>
<Input
id="phone"
value={form.phone}
onChange={(e) => set("phone", e.target.value)}
className="h-11"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="message">پیام</Label>
<Textarea
id="message"
value={form.message}
onChange={(e) => set("message", e.target.value)}
rows={4}
/>
</div>
<Button type="submit" disabled={loading}>
{loading ? "در حال ارسال..." : submitLabel}
</Button>
</form>
);
}
@@ -0,0 +1,79 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { ContactInterestForm } from "@/components/organisms/ContactInterestForm";
type CourseRegisterGateProps = {
courseSlug: string;
submitLabel: string;
successLabel: string;
ctaLabel: string;
formTitle: string;
formDescription: string;
hint: string;
cancelLabel: string;
};
export function CourseRegisterGate({
courseSlug,
submitLabel,
successLabel,
ctaLabel,
formTitle,
formDescription,
hint,
cancelLabel,
}: CourseRegisterGateProps) {
const [open, setOpen] = useState(false);
if (!open) {
return (
<div className="space-y-4 rounded-2xl bg-card p-6 shadow-sm ring-1 ring-border">
<div className="space-y-2">
<h2 className="text-lg font-bold tracking-tight">{formTitle}</h2>
<p className="text-sm leading-7 text-muted-foreground">{hint}</p>
</div>
<Button
type="button"
size="lg"
className="w-full font-bold"
onClick={() => setOpen(true)}
>
{ctaLabel}
</Button>
</div>
);
}
return (
<Card className="rounded-2xl border-border/70 shadow-lg" id="register-form">
<CardHeader className="space-y-1">
<CardTitle>{formTitle}</CardTitle>
<CardDescription>{formDescription}</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<ContactInterestForm
courseSlug={courseSlug}
submitLabel={submitLabel}
successLabel={successLabel}
/>
<Button
type="button"
variant="ghost"
className="w-full"
onClick={() => setOpen(false)}
>
{cancelLabel}
</Button>
</CardContent>
</Card>
);
}
@@ -0,0 +1,79 @@
"use client";
import useEmblaCarousel from "embla-carousel-react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useCallback } from "react";
import { DotCta } from "@/components/atoms/DotCta";
import { ProgramCard } from "@/components/molecules/Cards";
import { Button } from "@/components/ui/button";
import type { Program } from "@/lib/types";
export function ProgramCarousel({
title,
programs,
keepExploringLabel,
hideTitle = false,
}: {
title: string;
programs: Program[];
keepExploringLabel: string;
hideTitle?: boolean;
}) {
const [emblaRef, emblaApi] = useEmblaCarousel({
align: "start",
direction: "rtl",
loop: false,
});
const scrollPrev = useCallback(() => emblaApi?.scrollPrev(), [emblaApi]);
const scrollNext = useCallback(() => emblaApi?.scrollNext(), [emblaApi]);
return (
<div>
<div className="mb-5 flex items-end justify-between gap-4">
{!hideTitle && title ? (
<h2 className="text-2xl font-bold tracking-tight sm:text-3xl">
{title}
</h2>
) : (
<span />
)}
<div className="flex gap-1">
<Button
type="button"
variant="outline"
size="icon"
aria-label="قبلی"
onClick={scrollPrev}
>
<ChevronRight className="size-4" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
aria-label="بعدی"
onClick={scrollNext}
>
<ChevronLeft className="size-4" />
</Button>
</div>
</div>
<div className="overflow-hidden" ref={emblaRef}>
<div className="flex gap-5">
{programs.map((program) => (
<div
key={program.id}
className="min-w-0 shrink-0 basis-[88%] sm:basis-[42%] lg:basis-[30%]"
>
<ProgramCard program={program} />
</div>
))}
</div>
</div>
<div className="mt-7">
<DotCta href="/programs">{keepExploringLabel}</DotCta>
</div>
</div>
);
}
+171
View File
@@ -0,0 +1,171 @@
"use client";
import Link from "next/link";
import { Search, X } from "lucide-react";
import { useDeferredValue, useEffect, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { Course, Program } from "@/lib/types";
import { cn } from "@/lib/utils";
export function SearchOverlay({
courses,
programs,
label,
}: {
courses: Course[];
programs: Program[];
label: string;
}) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
useEffect(() => {
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") setOpen(false);
}
if (open) window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [open]);
useEffect(() => {
if (!open) return;
const previousOverflow = document.body.style.overflow;
const previousPadding = document.body.style.paddingInlineEnd;
const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
document.body.style.overflow = "hidden";
if (scrollbarWidth > 0) document.body.style.paddingInlineEnd = `${scrollbarWidth}px`;
return () => {
document.body.style.overflow = previousOverflow;
document.body.style.paddingInlineEnd = previousPadding;
};
}, [open]);
const results = useMemo(() => {
const q = deferredQuery.trim();
if (!q) {
return { programs: programs.slice(0, 4), courses: courses.slice(0, 4) };
}
return {
programs: programs.filter(
(p) => p.title.includes(q) || p.blurb.includes(q),
),
courses: courses.filter(
(c) => c.title.includes(q) || c.summary.includes(q),
),
};
}, [deferredQuery, programs, courses]);
return (
<>
<Button
variant="ghost"
size="icon"
aria-label={label}
onClick={() => setOpen(true)}
className="size-11 text-inherit hover:bg-foreground/5"
>
<Search />
</Button>
{open ? createPortal(
<div
className="fixed inset-0 z-[100] overflow-y-auto bg-background text-foreground"
role="dialog"
aria-modal="true"
aria-label={label}
>
<div className="border-b border-border bg-card">
<div className="mx-auto flex max-w-4xl items-center justify-between px-4 py-5 sm:px-6">
<p className="text-sm font-semibold text-muted-foreground">{label}</p>
<Button
variant="ghost"
size="icon"
className="text-foreground hover:bg-muted"
aria-label="بستن جستجو"
onClick={() => setOpen(false)}
>
<X />
</Button>
</div>
</div>
<div className="mx-auto flex max-w-4xl flex-col gap-8 px-4 py-8 sm:px-6 sm:py-12">
<Input
autoFocus
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="جستجوی برنامه یا دوره…"
className="h-14 rounded-xl border-border bg-card px-4 text-lg text-foreground shadow-sm placeholder:text-muted-foreground focus-visible:border-primary focus-visible:ring-primary/20 sm:text-xl"
/>
<div
className={cn(
"grid gap-8 transition-opacity sm:grid-cols-2",
isStale && "opacity-70",
)}
>
<ResultGroup
title="برنامه‌ها"
items={results.programs.map((p) => ({
href: p.href,
title: p.title,
subtitle: p.tagline,
}))}
onNavigate={() => setOpen(false)}
/>
<ResultGroup
title="دوره‌ها"
items={results.courses.map((c) => ({
href: c.registrationUrl,
title: c.title,
subtitle: c.summary,
}))}
onNavigate={() => setOpen(false)}
/>
</div>
</div>
</div>
, document.body) : null}
</>
);
}
function ResultGroup({
title,
items,
onNavigate,
}: {
title: string;
items: { href: string; title: string; subtitle?: string }[];
onNavigate: () => void;
}) {
return (
<div>
<p className="mb-3 text-xs font-bold text-muted-foreground">{title}</p>
<ul className="space-y-3">
{items.length === 0 ? (
<li className="text-sm text-muted-foreground">موردی یافت نشد</li>
) : (
items.map((item) => (
<li key={item.href + item.title}>
<Link
href={item.href}
onClick={onNavigate}
className="block rounded-xl bg-card p-4 shadow-sm ring-1 ring-border transition-[background-color,box-shadow] hover:bg-muted hover:shadow-md"
>
<span className="font-semibold">{item.title}</span>
{item.subtitle ? (
<span className="mt-1 line-clamp-2 block text-xs leading-6 text-muted-foreground">
{item.subtitle}
</span>
) : null}
</Link>
</li>
))
)}
</ul>
</div>
);
}
+95
View File
@@ -0,0 +1,95 @@
import Link from "next/link";
import { BrandLogo } from "@/components/atoms/BrandLogo";
import { Container } from "@/components/atoms/Container";
import { Separator } from "@/components/ui/separator";
import {
siteAddress,
siteShortName,
siteUniversity,
} from "@/lib/site-config";
export function SiteFooter({
copyright,
links,
linksTitle = "دسترسی سریع",
}: {
copyright: string;
links: { label: string; href: string }[];
linksTitle?: string;
variant?: "home" | "professional";
}) {
return (
<footer className="border-t border-border bg-chart-3 pb-[env(safe-area-inset-bottom)] text-background">
<Container className="py-12 sm:py-14">
<div className="grid gap-10 sm:grid-cols-2 lg:grid-cols-3 lg:gap-12">
<div className="max-w-sm space-y-4">
<BrandLogo
title={siteShortName}
subtitle={siteUniversity}
onDark
/>
<p className="text-sm leading-7 text-background/65">
{siteAddress.line}
</p>
</div>
<nav aria-label="لینک‌های پاورقی" className="space-y-4">
<p className="text-xs font-semibold tracking-wide text-background/55">
{linksTitle}
</p>
<ul className="flex flex-col gap-2.5 text-sm font-medium">
{links.map((link) => (
<li key={link.href}>
<Link
href={link.href}
className="text-background/80 transition-colors hover:text-background"
>
{link.label}
</Link>
</li>
))}
</ul>
</nav>
<div className="space-y-4 sm:max-w-xs lg:justify-self-end lg:text-end">
<p className="text-xs font-semibold tracking-wide text-background/55">
تماس
</p>
<div className="space-y-1.5 text-sm text-background/75">
<p dir="ltr">
<a
href={`tel:${siteAddress.phone}`}
className="transition-colors hover:text-background"
>
{siteAddress.phone}
</a>
</p>
<p dir="ltr">
<a
href={`mailto:${siteAddress.email}`}
className="transition-colors hover:text-background"
>
{siteAddress.email}
</a>
</p>
<p className="pt-1">
<a
href={siteAddress.mapUrl}
target="_blank"
rel="noopener noreferrer"
className="font-medium text-background/90 transition-colors hover:text-background"
>
موقعیت روی نقشه
</a>
</p>
</div>
</div>
</div>
<Separator className="my-8 bg-background/10" />
<p className="text-xs text-background/45">{copyright}</p>
</Container>
</footer>
);
}
+211
View File
@@ -0,0 +1,211 @@
"use client";
import dynamic from "next/dynamic";
import Link from "next/link";
import { Menu, X } from "lucide-react";
import { useEffect, useState } from "react";
import { BrandLogo } from "@/components/atoms/BrandLogo";
import { Container } from "@/components/atoms/Container";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { SearchOverlay } from "@/components/organisms/SearchOverlay";
import type { Course, NavItem, Program } from "@/lib/types";
import { cn } from "@/lib/utils";
const AcademicsOverlay = dynamic(
() =>
import("@/components/organisms/AcademicsOverlay").then(
(m) => m.AcademicsOverlay,
),
{ ssr: false },
);
export function SiteHeader({
items,
searchLabel,
brandHref = "/",
brandTitle,
brandSubtitle,
academicsLabel,
programSelectorTitle,
executiveLabel,
exploreLabel,
variant = "home",
courses = [],
programs = [],
}: {
items: NavItem[];
searchLabel: string;
brandHref?: string;
brandTitle: string;
brandSubtitle?: string;
academicsLabel: string;
programSelectorTitle: string;
executiveLabel: string;
exploreLabel: string;
variant?: "home" | "professional";
courses?: Course[];
programs?: Program[];
}) {
const [mobileOpen, setMobileOpen] = useState(false);
const [academicsOpen, setAcademicsOpen] = useState(false);
const isDark = variant === "professional";
const standardPrograms = programs.filter((p) => p.group === "standard");
const executivePrograms = programs.filter((p) => p.group === "executive");
useEffect(() => {
if (!mobileOpen) return;
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
document.body.style.overflow = prev;
};
}, [mobileOpen]);
return (
<>
<header
className={cn(
"site-header sticky top-0 z-50 pt-[env(safe-area-inset-top)] shadow-sm backdrop-blur-xl",
isDark
? "border-b border-background/10 bg-chart-3/95 text-background"
: "border-b border-border bg-card/95 text-foreground",
)}
>
<Container className="flex h-[4.5rem] items-center justify-start gap-3 sm:h-20 sm:gap-5" dir="rtl">
<BrandLogo
href={brandHref}
title={brandTitle}
subtitle={brandSubtitle}
onDark={isDark}
/>
<nav
className="hidden min-w-0 flex-1 items-center justify-start gap-0.5 xl:flex"
aria-label="منوی اصلی"
>
{items.map((item) => (
<Link
key={item.href + item.label}
href={item.href}
className={cn(
"rounded-lg px-2.5 py-2 text-sm font-semibold transition-colors",
isDark
? "text-background/80 hover:text-background"
: "text-foreground/75 hover:bg-muted hover:text-primary",
)}
>
{item.label}
</Link>
))}
<Button
variant="outline"
size="sm"
className={cn(
"ms-2 h-9 border-primary/20 font-bold text-primary hover:bg-primary hover:text-primary-foreground",
isDark &&
"border-background/50 bg-transparent text-background hover:bg-background hover:text-foreground",
)}
onClick={() => setAcademicsOpen(true)}
>
{academicsLabel}
</Button>
</nav>
<div
className={cn(
"ms-auto flex shrink-0 items-center gap-0.5 xl:ms-0",
isDark && "text-background",
)}
>
<SearchOverlay
courses={courses}
programs={programs}
label={searchLabel}
/>
<Button
variant="ghost"
size="icon"
className="xl:hidden"
aria-label={mobileOpen ? "بستن منو" : "باز کردن منو"}
aria-expanded={mobileOpen}
onClick={() => setMobileOpen((v) => !v)}
>
{mobileOpen ? (
<X className="size-5" />
) : (
<Menu className="size-5" />
)}
</Button>
</div>
</Container>
</header>
{mobileOpen ? (
<div
className="fixed inset-0 z-[60] flex flex-col bg-chart-3 text-background pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)] xl:hidden"
role="dialog"
aria-modal="true"
aria-label="منوی اصلی"
>
<Container className="flex h-16 items-center justify-between gap-3">
<BrandLogo
href={brandHref}
title={brandTitle}
subtitle={brandSubtitle}
onDark
compact
/>
<Button
variant="ghost"
size="icon"
className="text-background hover:bg-background/10"
aria-label="بستن منو"
onClick={() => setMobileOpen(false)}
>
<X className="size-5" />
</Button>
</Container>
<Separator className="bg-background/10" />
<Container className="flex-1 overflow-y-auto py-6">
<ul className="space-y-1 text-start">
{items.map((item) => (
<li key={item.href + item.label}>
<Link
href={item.href}
className="block py-3.5 text-lg font-bold transition-colors hover:text-background/70"
onClick={() => setMobileOpen(false)}
>
{item.label}
</Link>
</li>
))}
</ul>
<Button
variant="outline"
className="mt-8 w-full border-background/80 bg-transparent py-3.5 text-background hover:bg-background hover:text-foreground"
onClick={() => {
setMobileOpen(false);
setAcademicsOpen(true);
}}
>
{academicsLabel}
</Button>
</Container>
</div>
) : null}
{academicsOpen ? (
<AcademicsOverlay
open={academicsOpen}
onClose={() => setAcademicsOpen(false)}
title={programSelectorTitle}
executiveLabel={executiveLabel}
exploreLabel={exploreLabel}
standardPrograms={standardPrograms}
executivePrograms={executivePrograms}
/>
) : null}
</>
);
}
@@ -0,0 +1,134 @@
import type { ReactNode } from "react";
import Link from "next/link";
import { ArrowRight } from "lucide-react";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
export function AdminPageHeader({
title,
description,
actions,
backHref,
backLabel = "بازگشت",
}: {
title: string;
description?: ReactNode;
actions?: ReactNode;
backHref?: string;
backLabel?: string;
}) {
return (
<div className="flex flex-col gap-4 border-b border-border pb-6 sm:flex-row sm:items-end sm:justify-between">
<div className="min-w-0 space-y-2">
{backHref ? (
<Link
href={backHref}
className={cn(
buttonVariants({ variant: "ghost", size: "sm" }),
"-ms-2 h-8 gap-1.5 px-2 text-muted-foreground",
)}
>
<ArrowRight className="size-3.5" />
{backLabel}
</Link>
) : null}
<div className="space-y-1">
<h1 className="text-2xl font-bold tracking-tight text-foreground">
{title}
</h1>
{description ? (
<div className="text-sm text-muted-foreground">{description}</div>
) : null}
</div>
</div>
{actions ? (
<div className="flex shrink-0 flex-wrap items-center gap-2">{actions}</div>
) : null}
</div>
);
}
export function AdminToolbarCard({
title = "فیلترها",
description,
children,
}: {
title?: string;
description?: string;
children: ReactNode;
}) {
return (
<Card size="sm" className="shadow-none">
<CardHeader className="border-b [.border-b]:pb-3">
<CardTitle className="text-sm font-semibold">{title}</CardTitle>
{description ? <CardDescription>{description}</CardDescription> : null}
</CardHeader>
<CardContent className="pt-4">{children}</CardContent>
</Card>
);
}
export function AdminTableCard({
title = "فهرست",
description,
children,
}: {
title?: string;
description?: ReactNode;
children: ReactNode;
}) {
return (
<Card className="gap-0 overflow-hidden py-0 shadow-none">
<CardHeader className="border-b py-4 [.border-b]:pb-4">
<CardTitle className="text-base">{title}</CardTitle>
{description ? <CardDescription>{description}</CardDescription> : null}
</CardHeader>
<CardContent className="p-0">{children}</CardContent>
</Card>
);
}
export function AdminFormCard({
title = "جزئیات",
description,
children,
footer,
}: {
title?: string;
description?: string;
children: ReactNode;
footer?: ReactNode;
}) {
return (
<Card className="max-w-3xl shadow-none">
<CardHeader className="border-b [.border-b]:pb-4">
<CardTitle>{title}</CardTitle>
{description ? <CardDescription>{description}</CardDescription> : null}
</CardHeader>
<CardContent className="pt-6">{children}</CardContent>
{footer ? (
<CardFooter className="justify-start gap-2 border-t bg-muted/30">
{footer}
</CardFooter>
) : null}
</Card>
);
}
export function AdminPage({
children,
className,
}: {
children: ReactNode;
className?: string;
}) {
return <div className={cn("space-y-6", className)}>{children}</div>;
}
@@ -0,0 +1,63 @@
"use client";
import Image from "next/image";
import {
SidebarInset,
SidebarProvider,
SidebarTrigger,
} from "@/components/ui/sidebar";
import { Separator } from "@/components/ui/separator";
import { TooltipProvider } from "@/components/ui/tooltip";
import { AdminSidebar } from "@/components/organisms/admin/AdminSidebar";
export function AdminShell({
userName,
children,
}: {
userName: string;
children: React.ReactNode;
}) {
return (
<TooltipProvider>
<SidebarProvider
dir="rtl"
style={
{
"--sidebar-width": "16.5rem",
"--header-height": "3.5rem",
} as React.CSSProperties
}
>
<AdminSidebar userName={userName} />
<SidebarInset className="bg-muted/30 md:peer-data-[variant=inset]:ms-2 md:peer-data-[variant=inset]:me-0 md:peer-data-[variant=inset]:peer-data-[state=collapsed]:me-2">
<header className="sticky top-0 z-20 flex h-(--header-height) shrink-0 items-center gap-2 border-b bg-background/95 px-4 backdrop-blur supports-backdrop-filter:bg-background/80">
<SidebarTrigger className="-ms-1" />
<Separator orientation="vertical" className="me-1 data-[orientation=vertical]:h-4" />
<div className="flex min-w-0 flex-1 items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-2">
<span className="relative size-6 shrink-0 overflow-hidden rounded-full bg-chart-3 ring-1 ring-border md:hidden">
<Image
src="/brand/amirkabir.png"
alt=""
fill
sizes="24px"
className="object-cover"
/>
</span>
<p className="truncate text-sm font-medium text-muted-foreground">
مدیریت محتوا
</p>
</div>
<span className="hidden truncate text-sm text-muted-foreground sm:inline">
{userName}
</span>
</div>
</header>
<div className="mx-auto w-full max-w-7xl flex-1 px-4 py-6 md:px-8 md:py-8">
{children}
</div>
</SidebarInset>
</SidebarProvider>
</TooltipProvider>
);
}
@@ -0,0 +1,173 @@
"use client";
import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
BookOpen,
Calendar,
FileText,
GraduationCap,
LayoutDashboard,
Megaphone,
MessageSquareQuote,
Newspaper,
Scale,
Tags,
Users,
ClipboardList,
BarChart3,
} from "lucide-react";
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarRail,
SidebarSeparator,
} from "@/components/ui/sidebar";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { LogoutButton } from "@/components/organisms/admin/LogoutButton";
const NAV_GROUPS = [
{
label: "نمای کلی",
items: [{ href: "/admin", label: "داشبورد", icon: LayoutDashboard, exact: true }],
},
{
label: "محتوا",
items: [
{ href: "/admin/courses", label: "دوره‌ها", icon: BookOpen },
{ href: "/admin/programs", label: "برنامه‌ها", icon: GraduationCap },
{ href: "/admin/events", label: "رویدادها", icon: Calendar },
{ href: "/admin/articles", label: "مقالات", icon: Newspaper },
{ href: "/admin/topics", label: "موضوعات", icon: Tags },
],
},
{
label: "جامعه",
items: [
{ href: "/admin/faculty", label: "اساتید", icon: Users },
{ href: "/admin/alumni", label: "دانش‌آموختگان", icon: MessageSquareQuote },
],
},
{
label: "سایت",
items: [
{ href: "/admin/banners", label: "بنرهای کمپین", icon: Megaphone },
{ href: "/admin/stats", label: "آمار", icon: BarChart3 },
{ href: "/admin/testimonials", label: "نظرات", icon: FileText },
{ href: "/admin/legal", label: "صفحات قانونی", icon: Scale },
],
},
{
label: "درخواست‌ها",
items: [{ href: "/admin/registrations", label: "برگ ثبت‌نام", icon: ClipboardList }],
},
] as const;
function isActive(pathname: string, href: string, exact?: boolean) {
if (exact) return pathname === href;
return pathname === href || pathname.startsWith(`${href}/`);
}
export function AdminSidebar({ userName }: { userName: string }) {
const pathname = usePathname();
const initials = userName
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part[0])
.join("");
return (
<Sidebar side="right" collapsible="icon" variant="inset">
<SidebarHeader className="gap-3 p-3">
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
size="lg"
render={<Link href="/admin" />}
className="data-active:bg-sidebar-accent"
>
<span className="relative size-8 shrink-0 overflow-hidden rounded-lg bg-chart-3 ring-1 ring-sidebar-border">
<Image
src="/brand/amirkabir.png"
alt=""
fill
sizes="32px"
className="object-cover"
priority
/>
</span>
<div className="grid flex-1 text-start text-sm leading-tight">
<span className="truncate font-semibold">پنل مدیریت</span>
<span className="truncate text-xs text-muted-foreground">
آموزش آزاد امیرکبیر
</span>
</div>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarHeader>
<SidebarSeparator />
<SidebarContent>
{NAV_GROUPS.map((group) => (
<SidebarGroup key={group.label}>
<SidebarGroupLabel>{group.label}</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
{group.items.map((item) => {
const Icon = item.icon;
const active = isActive(
pathname,
item.href,
"exact" in item ? item.exact : false,
);
return (
<SidebarMenuItem key={item.href}>
<SidebarMenuButton
isActive={active}
tooltip={item.label}
render={<Link href={item.href} />}
>
<Icon />
<span>{item.label}</span>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
))}
</SidebarContent>
<SidebarFooter className="p-3">
<div className="flex items-center gap-2 rounded-lg border border-sidebar-border bg-sidebar px-2 py-2 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:border-0 group-data-[collapsible=icon]:p-0">
<Avatar className="size-8">
<AvatarFallback className="bg-sidebar-accent text-xs font-semibold">
{initials || "اد"}
</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1 group-data-[collapsible=icon]:hidden">
<p className="truncate text-sm font-medium">{userName}</p>
<p className="truncate text-xs text-muted-foreground">مدیر محتوا</p>
</div>
<div className="group-data-[collapsible=icon]:hidden">
<LogoutButton />
</div>
</div>
</SidebarFooter>
<SidebarRail />
</Sidebar>
);
}
@@ -0,0 +1,108 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
export const LEAD_STATUS_LABELS: Record<string, string> = {
new: "جدید",
contacted: "تماس گرفته شد",
enrolled: "ثبت‌نام شد",
rejected: "رد شد",
};
const STATUS_VARIANTS: Record<string, "default" | "secondary" | "outline" | "destructive"> = {
new: "default",
contacted: "secondary",
enrolled: "outline",
rejected: "destructive",
};
export interface LeadForDashboard {
id: string;
full_name: string;
email: string;
course_slug: string | null;
status: string;
created_at: string;
}
export function LeadsList({ leads }: { leads: LeadForDashboard[] }) {
const router = useRouter();
const [error, setError] = useState("");
async function changeStatus(id: string, status: string) {
setError("");
const res = await fetch(`/api/admin/registrations/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
setError(data.error || "خطا در تغییر وضعیت");
return;
}
router.refresh();
}
if (leads.length === 0) {
return <p className="text-sm text-muted-foreground">درخواستی ثبت نشده است.</p>;
}
return (
<div className="space-y-3">
{error && (
<p className="text-sm text-red-600" role="alert">
{error}
</p>
)}
<div className="overflow-x-auto">
<table className="w-full text-right text-sm">
<thead>
<tr className="border-b text-muted-foreground">
<th className="py-2 pe-4 font-medium">نام</th>
<th className="py-2 pe-4 font-medium">ایمیل</th>
<th className="py-2 pe-4 font-medium">دوره</th>
<th className="py-2 pe-4 font-medium">وضعیت</th>
<th className="py-2 font-medium">تغییر وضعیت</th>
</tr>
</thead>
<tbody>
{leads.map((lead) => (
<tr key={lead.id} className="border-b">
<td className="py-3 pe-4">{lead.full_name}</td>
<td className="py-3 pe-4 text-muted-foreground">{lead.email}</td>
<td className="py-3 pe-4 text-muted-foreground">
{lead.course_slug ?? "—"}
</td>
<td className="py-3 pe-4">
<Badge variant={STATUS_VARIANTS[lead.status] ?? "secondary"}>
{LEAD_STATUS_LABELS[lead.status] ?? lead.status}
</Badge>
</td>
<td className="py-3">
<Select
value={lead.status}
onValueChange={(v) => v && changeStatus(lead.id, v)}
>
<SelectTrigger className="w-40">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">جدید</SelectItem>
<SelectItem value="contacted">تماس گرفته شد</SelectItem>
<SelectItem value="enrolled">ثبت‌نام شد</SelectItem>
<SelectItem value="rejected">رد شد</SelectItem>
</SelectContent>
</Select>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
@@ -0,0 +1,28 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
export function LogoutButton() {
const router = useRouter();
const [loading, setLoading] = useState(false);
async function handleLogout() {
setLoading(true);
try {
await fetch("/api/admin/logout", { method: "POST" });
} catch {
// ignore network errors — still navigate to login
} finally {
router.push("/admin/login");
router.refresh();
}
}
return (
<Button variant="ghost" size="sm" onClick={handleLogout} disabled={loading}>
{loading ? "…" : "خروج"}
</Button>
);
}
@@ -0,0 +1,85 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
function buildUrl(search: string, published: string) {
const params = new URLSearchParams();
if (search.trim()) params.set("search", search.trim());
if (published && published !== "all") params.set("published", published);
const qs = params.toString();
return qs ? `/admin/courses?${qs}` : "/admin/courses";
}
export function CourseFilters({
initialSearch,
initialPublished,
}: {
initialSearch: string;
initialPublished: string;
}) {
const router = useRouter();
const [search, setSearch] = useState(initialSearch);
const [published, setPublished] = useState(initialPublished);
const hasFilters = Boolean(initialSearch.trim()) || initialPublished !== "all";
function apply(e: React.FormEvent) {
e.preventDefault();
router.push(buildUrl(search, published));
}
function clear() {
setSearch("");
setPublished("all");
router.push("/admin/courses");
}
return (
<form
onSubmit={apply}
className="flex flex-wrap items-end gap-3"
>
<div className="w-full max-w-xs space-y-1.5">
<label htmlFor="course-search" className="text-sm font-medium">
جستجو
</label>
<Input
id="course-search"
placeholder="عنوان یا اسلاگ دوره..."
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
<div className="w-full max-w-[12rem] space-y-1.5">
<label htmlFor="course-published" className="text-sm font-medium">
وضعیت انتشار
</label>
<Select value={published} onValueChange={(v) => setPublished(v ?? "all")}>
<SelectTrigger id="course-published" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">همه</SelectItem>
<SelectItem value="true">منتشرشده</SelectItem>
<SelectItem value="false">پیش‌نویس</SelectItem>
</SelectContent>
</Select>
</div>
<Button type="submit">اعمال فیلتر</Button>
{hasFilters && (
<Button type="button" variant="ghost" onClick={clear}>
پاک‌کردن فیلترها
</Button>
)}
</form>
);
}
@@ -0,0 +1,298 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button, buttonVariants } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import { cn } from "@/lib/utils";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import type { AdminCourse } from "@/lib/data/admin/courses";
import { AdminFormCard } from "@/components/organisms/admin/AdminPage";
type Payload = {
slug: string;
title: string;
summary: string;
category: string;
durationHours: number;
format: string;
price: number | null;
registrationUrl: string;
imageUrl: string;
seoDescription: string;
published: boolean;
};
interface CourseFormProps {
initial?: AdminCourse;
}
export function CourseForm({ initial }: CourseFormProps) {
const router = useRouter();
const isEdit = Boolean(initial);
const [form, setForm] = useState<Payload>({
slug: initial?.slug ?? "",
title: initial?.title ?? "",
summary: initial?.summary ?? "",
category: initial?.category ?? "leadership",
durationHours: initial?.durationHours ?? 16,
format: initial?.format ?? "online",
price: initial?.price ?? null,
registrationUrl: initial?.registrationUrl ?? "/register/",
imageUrl: initial?.imageUrl ?? "",
seoDescription: initial?.seoDescription ?? "",
published: initial?.published ?? true,
});
const [priceInput, setPriceInput] = useState(
initial?.price != null ? String(initial.price) : "",
);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
function set<K extends keyof Payload>(key: K, value: Payload[K]) {
setForm((f) => ({ ...f, [key]: value }));
}
function onPriceChange(raw: string) {
setPriceInput(raw);
const trimmed = raw.trim();
if (trimmed === "") {
set("price", null);
return;
}
const n = Number(trimmed.replace(/,/g, ""));
set("price", Number.isFinite(n) ? Math.round(n) : null);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError("");
try {
const res = await fetch(
isEdit ? `/api/admin/courses/${initial!.id}` : "/api/admin/courses",
{
method: isEdit ? "PATCH" : "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(form),
},
);
if (!res.ok) {
const data = await res.json().catch(() => ({}));
setError(data.error || "خطا در ذخیره دوره");
return;
}
router.push("/admin/courses");
router.refresh();
} finally {
setLoading(false);
}
}
return (
<form onSubmit={handleSubmit}>
<AdminFormCard
title={isEdit ? "ویرایش دوره" : "ثبت دوره جدید"}
description="فیلدهای ستاره‌دار الزامی‌اند. قیمت اختیاری است."
footer={
<>
<Button type="submit" disabled={loading}>
{loading ? "در حال ذخیره..." : isEdit ? "ذخیره تغییرات" : "ایجاد دوره"}
</Button>
<Link
href="/admin/courses"
className={cn(buttonVariants({ variant: "outline" }))}
>
انصراف
</Link>
</>
}
>
{error ? (
<p
className="mb-6 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive"
role="alert"
>
{error}
</p>
) : null}
<div className="space-y-8">
<section className="space-y-4">
<div>
<h2 className="text-sm font-semibold text-foreground">اطلاعات اصلی</h2>
<p className="mt-0.5 text-xs text-muted-foreground">
شناسه، عنوان و خلاصهٔ نمایشی دوره
</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1.5">
<Label htmlFor="slug">اسلاگ</Label>
<Input
id="slug"
value={form.slug}
onChange={(e) => set("slug", e.target.value)}
placeholder="ai-for-managers"
required
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="title">عنوان</Label>
<Input
id="title"
value={form.title}
onChange={(e) => set("title", e.target.value)}
placeholder="هوش مصنوعی برای مدیران"
required
/>
</div>
<div className="space-y-1.5 sm:col-span-2">
<Label htmlFor="summary">خلاصه</Label>
<Textarea
id="summary"
value={form.summary}
onChange={(e) => set("summary", e.target.value)}
rows={3}
required
/>
</div>
</div>
</section>
<Separator />
<section className="space-y-4">
<div>
<h2 className="text-sm font-semibold text-foreground">برگزاری و قیمت</h2>
<p className="mt-0.5 text-xs text-muted-foreground">
دسته، قالب، مدت و هزینهٔ اختیاری
</p>
</div>
<div className="grid gap-4 sm:grid-cols-3">
<div className="space-y-1.5">
<Label htmlFor="category">دسته‌بندی</Label>
<Select value={form.category} onValueChange={(v) => v && set("category", v)}>
<SelectTrigger id="category" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="leadership">رهبری</SelectItem>
<SelectItem value="technology">فناوری</SelectItem>
<SelectItem value="innovation">نوآوری</SelectItem>
<SelectItem value="energy">انرژی</SelectItem>
<SelectItem value="design">طراحی</SelectItem>
<SelectItem value="digital">دیجیتال</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="format">قالب برگزاری</Label>
<Select value={form.format} onValueChange={(v) => v && set("format", v)}>
<SelectTrigger id="format" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="online">آنلاین</SelectItem>
<SelectItem value="blended">ترکیبی</SelectItem>
<SelectItem value="in-person">حضوری</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="durationHours">مدت (ساعت)</Label>
<Input
id="durationHours"
type="number"
min={1}
value={form.durationHours}
onChange={(e) => set("durationHours", Number(e.target.value))}
required
/>
</div>
<div className="space-y-1.5 sm:col-span-3">
<Label htmlFor="price">قیمت (تومان)</Label>
<Input
id="price"
type="number"
min={0}
inputMode="numeric"
value={priceInput}
onChange={(e) => onPriceChange(e.target.value)}
placeholder="خالی = بدون نمایش قیمت"
/>
<p className="text-xs text-muted-foreground">
اگر خالی بماند، قیمت در سایت نمایش داده نمی‌شود.
</p>
</div>
</div>
</section>
<Separator />
<section className="space-y-4">
<div>
<h2 className="text-sm font-semibold text-foreground">رسانه و انتشار</h2>
<p className="mt-0.5 text-xs text-muted-foreground">
لینک ثبت‌نام، تصویر، SEO و وضعیت انتشار
</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1.5 sm:col-span-2">
<Label htmlFor="registrationUrl">لینک ثبت‌نام</Label>
<Input
id="registrationUrl"
value={form.registrationUrl}
onChange={(e) => set("registrationUrl", e.target.value)}
placeholder="/register/ai-for-managers"
/>
</div>
<div className="space-y-1.5 sm:col-span-2">
<Label htmlFor="imageUrl">آدرس تصویر</Label>
<Input
id="imageUrl"
value={form.imageUrl}
onChange={(e) => set("imageUrl", e.target.value)}
placeholder="/images/courses/..."
/>
</div>
<div className="space-y-1.5 sm:col-span-2">
<Label htmlFor="seoDescription">توضیح SEO</Label>
<Textarea
id="seoDescription"
value={form.seoDescription}
onChange={(e) => set("seoDescription", e.target.value)}
rows={2}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="published">وضعیت انتشار</Label>
<Select
value={form.published ? "true" : "false"}
onValueChange={(v) => set("published", (v ?? "true") === "true")}
>
<SelectTrigger id="published" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="true">منتشرشده</SelectItem>
<SelectItem value="false">پیش‌نویس</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</section>
</div>
</AdminFormCard>
</form>
);
}
Loaded 100 of 320 files, more files were not shown because too many files have changed in this diff. Show more