Enhance image upload functionality for admin and improve course navigation. Added support for image uploads in course forms and generic forms, utilizing a new ImageUploadField component. Updated navigation to dynamically include course tags and refined layout components for better user experience. Configured Docker for persistent uploads with a dedicated volume.

This commit is contained in:
smhk1376 committed 2026-10-11 21:05:52 +03:30
1 parent ef1ccea0ad
commit 66a8e8f213
29 files changed
+748 -125

No files matched your search

+10 -4
View File
@@ -2,10 +2,11 @@ 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 { buildHomeNavWithCourseTags } from "@/lib/course-nav";
import { getCourses, listPublishedCourseTags } from "@/lib/data/courses";
import { getPrograms } from "@/lib/data/programs";
import { getCampaignBanners } from "@/lib/data/site";
import { homeNav, siteShortName } from "@/lib/site-config";
import { courseNavTagOrder, siteShortName } from "@/lib/site-config";
// Public CMS pages must read Postgres at request time — static bake at Docker
// build often has no DATABASE_URL and ships empty lists.
@@ -21,20 +22,25 @@ export default async function MainLayout({
let courses: Awaited<ReturnType<typeof getCourses>> = [];
let programs: Awaited<ReturnType<typeof getPrograms>> = [];
let banners: Awaited<ReturnType<typeof getCampaignBanners>> = [];
let courseTags: string[] = [...courseNavTagOrder];
try {
[courses, programs, banners] = await Promise.all([
[courses, programs, banners, courseTags] = await Promise.all([
getCourses(),
getPrograms(),
getCampaignBanners(),
listPublishedCourseTags(),
]);
if (courseTags.length === 0) courseTags = [...courseNavTagOrder];
} catch (err) {
console.error("[main/layout] CMS fetch failed:", err);
}
const navItems = buildHomeNavWithCourseTags(courseTags);
return (
<>
<SiteHeader
items={homeNav}
items={navItems}
searchLabel={t("nav.search")}
brandTitle={siteShortName}
brandSubtitle={t("nav.brandSubtitle")}
+42
View File
@@ -0,0 +1,42 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth/admin";
import { errorResponse } from "@/lib/api/response";
import { saveUploadedImage } from "@/lib/uploads/image";
import { isUploadFolder, type UploadFolder } from "@/lib/uploads/types";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
// POST /api/admin/upload — multipart image upload (admin only)
export async function POST(request: NextRequest) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let formData: FormData;
try {
formData = await request.formData();
} catch {
return errorResponse("بدنهٔ درخواست معتبر نیست", 400);
}
const file = formData.get("file");
if (!(file instanceof File)) {
return errorResponse("فیلد file الزامی است", 400);
}
const folderRaw = String(formData.get("folder") ?? "general");
if (!isUploadFolder(folderRaw)) {
return errorResponse("پوشهٔ مقصد نامعتبر است", 400);
}
const folder: UploadFolder = folderRaw;
const result = await saveUploadedImage(file, folder);
if (!result.ok) {
return errorResponse(result.error, result.status);
}
return NextResponse.json(
{ ok: true, data: { url: result.url } },
{ status: 201 },
);
}
+25 -4
View File
@@ -1,9 +1,15 @@
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 { buildCourseNavChildren } from "@/lib/course-nav";
import { getCourses, listPublishedCourseTags } from "@/lib/data/courses";
import { getPrograms } from "@/lib/data/programs";
import { professionalNav, siteShortName } from "@/lib/site-config";
import {
courseNavParentTag,
courseNavTagOrder,
professionalNav,
siteShortName,
} from "@/lib/site-config";
export const dynamic = "force-dynamic";
@@ -16,16 +22,31 @@ export default async function ProfessionalLayout({
const year = new Date().getFullYear();
let courses: Awaited<ReturnType<typeof getCourses>> = [];
let programs: Awaited<ReturnType<typeof getPrograms>> = [];
let courseTags: string[] = [...courseNavTagOrder];
try {
[courses, programs] = await Promise.all([getCourses(), getPrograms()]);
[courses, programs, courseTags] = await Promise.all([
getCourses(),
getPrograms(),
listPublishedCourseTags(),
]);
if (courseTags.length === 0) courseTags = [...courseNavTagOrder];
} catch (err) {
console.error("[professional/layout] CMS fetch failed:", err);
}
const navItems = professionalNav.map((item) =>
item.label === courseNavParentTag
? {
...item,
children: buildCourseNavChildren(courseTags),
}
: item,
);
return (
<>
<SiteHeader
items={professionalNav}
items={navItems}
searchLabel={t("nav.search")}
brandTitle={siteShortName}
brandSubtitle={t("nav.brandSubtitle")}
+8 -1
View File
@@ -20,8 +20,14 @@ export async function generateMetadata(): Promise<Metadata> {
};
}
export default async function ProfessionalPage() {
export default async function ProfessionalPage({
searchParams,
}: {
searchParams: Promise<{ tag?: string }>;
}) {
const t = await getTranslations();
const { tag: tagRaw } = await searchParams;
const initialTag = tagRaw?.trim() ?? "";
const [courses, stats, testimonials] = await Promise.all([
getCourses(),
getSiteStats(),
@@ -50,6 +56,7 @@ export default async function ProfessionalPage() {
courses={courses}
stats={stats}
testimonials={testimonials}
initialTag={initialTag}
/>
</>
);
@@ -3,6 +3,7 @@
import { useDeferredValue, useMemo, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -15,6 +16,7 @@ import {
CardTitle,
} from "@/components/ui/card";
import type { Course } from "@/lib/types";
import { courseCatalogHref, courseTagHref } from "@/lib/course-nav";
import { courseCategories } from "@/lib/site-config";
import { formatCoursePrice, formatLabel } from "@/lib/labels";
import { cn } from "@/lib/utils";
@@ -23,17 +25,31 @@ export function CategoryCourseExplorer({
courses,
findLabel,
tagsLabel = "دسته‌بندی‌ها",
initialTag = "",
}: {
courses: Course[];
findLabel: string;
tagsLabel?: string;
/** From `/professional?tag=` — filters by course tag on first paint. */
initialTag?: string;
}) {
const router = useRouter();
const pathname = usePathname();
const [query, setQuery] = useState("");
const [category, setCategory] = useState("all");
const [tag, setTag] = useState("");
const [tag, setTag] = useState(initialTag);
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
const selectTag = (next: string) => {
setTag(next);
if (pathname !== "/professional" && !pathname.startsWith("/professional")) {
return;
}
const href = next ? courseTagHref(next) : courseCatalogHref();
router.replace(href, { scroll: false });
};
// Distinct tags across all courses (stable order: most used first).
const tags = useMemo(() => {
const counts = new Map<string, number>();
@@ -62,8 +78,8 @@ export function CategoryCourseExplorer({
const resetFilters = () => {
setCategory("all");
setTag("");
setQuery("");
selectTag("");
};
return (
@@ -123,7 +139,7 @@ export function CategoryCourseExplorer({
size="sm"
variant={tag === "" ? "default" : "ghost"}
aria-selected={tag === ""}
onClick={() => setTag("")}
onClick={() => selectTag("")}
className={cn(
tag !== "" &&
"bg-background/10 text-background/85 hover:bg-background/20 hover:text-background",
@@ -138,7 +154,7 @@ export function CategoryCourseExplorer({
size="sm"
variant={tag === item ? "default" : "ghost"}
aria-selected={tag === item}
onClick={() => setTag(tag === item ? "" : item)}
onClick={() => selectTag(tag === item ? "" : item)}
className={cn(
tag !== item &&
"bg-background/10 text-background/85 hover:bg-background/20 hover:text-background",
@@ -170,7 +186,7 @@ export function CategoryCourseExplorer({
{tag}
<button
type="button"
onClick={() => setTag("")}
onClick={() => selectTag("")}
className="rounded-full p-0.5 hover:bg-foreground/10"
aria-label="حذف فیلتر تگ"
>
+107 -72
View File
@@ -2,7 +2,7 @@
import dynamic from "next/dynamic";
import Link from "next/link";
import { Menu, X } from "lucide-react";
import { ChevronDown, Menu, X } from "lucide-react";
import { useEffect, useState } from "react";
import { BrandLogo } from "@/components/atoms/BrandLogo";
import { Container } from "@/components/atoms/Container";
@@ -26,6 +26,67 @@ const AcademicsOverlay = dynamic(
{ ssr: false },
);
function NavLink({
item,
isDark,
className,
onClick,
}: {
item: NavItem;
isDark: boolean;
className?: string;
onClick?: () => void;
}) {
return (
<Link
href={item.href}
target={item.href.startsWith("http") ? "_blank" : undefined}
rel={item.href.startsWith("http") ? "noopener noreferrer" : undefined}
className={className}
onClick={onClick}
>
{item.label}
</Link>
);
}
function NavDropdown({
item,
isDark,
}: {
item: NavItem;
isDark: boolean;
}) {
const children = item.children ?? [];
return (
<DropdownMenu>
<DropdownMenuTrigger
className={cn(
"inline-flex cursor-pointer items-center gap-1 rounded-lg px-2.5 py-2 text-sm font-semibold transition-colors outline-none",
isDark
? "text-background/80 hover:text-background"
: "text-foreground/75 hover:bg-muted hover:text-primary",
)}
>
{item.label}
<ChevronDown className="size-3.5 opacity-70" aria-hidden />
</DropdownMenuTrigger>
<DropdownMenuContent className="z-[60] w-56 p-1" align="start">
{children.map((child) => (
<DropdownMenuItem key={child.href + child.label} className="p-0">
<Link
href={child.href}
className="w-full cursor-pointer px-1.5 py-1.5"
>
{child.label}
</Link>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}
export function SiteHeader({
items,
searchLabel,
@@ -92,76 +153,39 @@ export function SiteHeader({
aria-label="منوی اصلی"
>
{items.map((item) => {
if (item.label.includes("دوره‌ها") || item.label.includes("فهرست")) {
if (item.children && item.children.length > 0) {
return (
<DropdownMenu key={item.href + item.label}>
<DropdownMenuTrigger
className={cn(
"rounded-lg px-2.5 py-2 text-sm font-semibold transition-colors outline-none cursor-pointer inline-flex items-center gap-1",
isDark
? "text-background/80 hover:text-background"
: "text-foreground/75 hover:bg-muted hover:text-primary",
)}
>
{item.label}
</DropdownMenuTrigger>
<DropdownMenuContent className="z-[60] w-56 p-1">
<DropdownMenuItem>
<Link href="/professional" className="w-full cursor-pointer">
همه دوره‌ها
</Link>
</DropdownMenuItem>
<DropdownMenuItem>
<Link href="/professional#programs" className="w-full cursor-pointer">
کارگاه‌ها
</Link>
</DropdownMenuItem>
<DropdownMenuItem>
<Link href="/professional#programs" className="w-full cursor-pointer">
دوره‌های سازمانی
</Link>
</DropdownMenuItem>
<DropdownMenuItem>
<Link href="/professional#programs" className="w-full cursor-pointer">
گزیده دوره‌های برگزار شده
</Link>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<NavDropdown
key={item.href + item.label}
item={item}
isDark={isDark}
/>
);
}
return item.prominent ? (
<Link
<NavLink
key={item.href + item.label}
href={item.href}
target={item.href.startsWith("http") ? "_blank" : undefined}
rel={
item.href.startsWith("http")
? "noopener noreferrer"
: undefined
}
item={item}
isDark={isDark}
className={cn(
"ms-1 inline-flex items-center rounded-md border px-2.5 py-1 text-xs font-bold transition-all shadow-sm",
"ms-1 inline-flex items-center rounded-md border px-2.5 py-1 text-xs font-bold shadow-sm transition-all",
isDark
? "border-primary-foreground/30 bg-primary-foreground/10 text-primary-foreground hover:bg-primary-foreground hover:text-primary"
: "border-primary/30 bg-primary/10 text-primary hover:bg-primary hover:text-primary-foreground",
)}
>
{item.label}
</Link>
/>
) : (
<Link
<NavLink
key={item.href + item.label}
href={item.href}
item={item}
isDark={isDark}
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
@@ -237,25 +261,36 @@ export function SiteHeader({
<ul className="space-y-1 text-start">
{items.map((item) => (
<li key={item.href + item.label}>
<Link
href={item.href}
target={
item.href.startsWith("http") ? "_blank" : undefined
}
rel={
item.href.startsWith("http")
? "noopener noreferrer"
: undefined
}
className={cn(
"block py-3.5 text-lg font-bold transition-colors hover:text-background/70",
item.prominent &&
"inline-block text-primary underline underline-offset-4"
)}
onClick={() => setMobileOpen(false)}
>
{item.label}
</Link>
{item.children && item.children.length > 0 ? (
<div className="py-2">
<p className="text-sm font-semibold text-background/55">
{item.label}
</p>
<ul className="mt-1 space-y-0.5 border-s border-background/20 ps-3">
{item.children.map((child) => (
<li key={child.href + child.label}>
<NavLink
item={child}
isDark
className="block py-2.5 text-base font-bold transition-colors hover:text-background/70"
onClick={() => setMobileOpen(false)}
/>
</li>
))}
</ul>
</div>
) : (
<NavLink
item={item}
isDark
className={cn(
"block py-3.5 text-lg font-bold transition-colors hover:text-background/70",
item.prominent &&
"inline-block text-primary underline underline-offset-4",
)}
onClick={() => setMobileOpen(false)}
/>
)}
</li>
))}
</ul>
@@ -0,0 +1,147 @@
"use client";
import { useRef, useState } from "react";
import Image from "next/image";
import { ImageIcon, Loader2, Trash2, Upload } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { UploadFolder } from "@/lib/uploads/types";
interface ImageUploadFieldProps {
id?: string;
value: string;
onChange: (url: string) => void;
folder: UploadFolder;
required?: boolean;
disabled?: boolean;
className?: string;
}
export function ImageUploadField({
id,
value,
onChange,
folder,
required,
disabled,
className,
}: ImageUploadFieldProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(false);
const [error, setError] = useState("");
async function handleFile(file: File | undefined) {
if (!file) return;
setUploading(true);
setError("");
try {
const body = new FormData();
body.set("file", file);
body.set("folder", folder);
const res = await fetch("/api/admin/upload", {
method: "POST",
body,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError(data.error || "آپلود ناموفق بود");
return;
}
const url = data?.data?.url;
if (typeof url !== "string" || !url) {
setError("پاسخ سرور نامعتبر است");
return;
}
onChange(url);
} finally {
setUploading(false);
if (inputRef.current) inputRef.current.value = "";
}
}
return (
<div className={cn("space-y-2", className)}>
<input
ref={inputRef}
id={id}
type="file"
accept="image/jpeg,image/png,image/webp,image/gif"
className="sr-only"
disabled={disabled || uploading}
required={required && !value}
onChange={(e) => void handleFile(e.target.files?.[0])}
/>
{value ? (
<div className="overflow-hidden rounded-xl border border-border bg-muted/40">
<div className="relative aspect-[16/9] w-full max-w-md bg-muted">
<Image
src={value}
alt="پیش‌نمایش تصویر"
fill
unoptimized
className="object-cover"
sizes="(max-width: 768px) 100vw, 28rem"
/>
</div>
<div className="flex flex-wrap items-center gap-2 border-t border-border px-3 py-2">
<Button
type="button"
variant="outline"
size="sm"
disabled={disabled || uploading}
onClick={() => inputRef.current?.click()}
>
{uploading ? (
<Loader2 className="size-4 animate-spin" />
) : (
<Upload className="size-4" />
)}
تعویض تصویر
</Button>
<Button
type="button"
variant="ghost"
size="sm"
disabled={disabled || uploading}
onClick={() => onChange("")}
>
<Trash2 className="size-4" />
حذف
</Button>
</div>
</div>
) : (
<button
type="button"
disabled={disabled || uploading}
onClick={() => inputRef.current?.click()}
className={cn(
"flex w-full max-w-md flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-border bg-muted/30 px-4 py-8 text-sm transition-colors",
"hover:border-primary/40 hover:bg-muted/50",
"disabled:pointer-events-none disabled:opacity-50",
"focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50",
)}
>
{uploading ? (
<Loader2 className="size-8 animate-spin text-muted-foreground" />
) : (
<ImageIcon className="size-8 text-muted-foreground" />
)}
<span className="font-medium text-foreground">
{uploading ? "در حال بارگذاری…" : "انتخاب و بارگذاری تصویر"}
</span>
<span className="text-xs text-muted-foreground">
JPG، PNG، WebP یا GIF — حداکثر ۵ مگابایت
</span>
</button>
)}
{error ? (
<p className="text-sm text-destructive" role="alert">
{error}
</p>
) : null}
</div>
);
}
@@ -20,12 +20,10 @@ import { Badge } from "@/components/ui/badge";
import { Plus, X } from "lucide-react";
import type { AdminCourse } from "@/lib/data/admin/courses";
import { AdminFormCard } from "@/components/organisms/admin/AdminPage";
import { ImageUploadField } from "@/components/organisms/admin/ImageUploadField";
import { courseNavTagOrder } from "@/lib/site-config";
const SUGGESTED_TAGS = [
"کارگاه‌ها",
"دوره‌های سازمانی",
"گزیده دوره‌های برگزار شده",
];
const SUGGESTED_TAGS = courseNavTagOrder;
type Payload = {
slug: string;
@@ -371,7 +369,7 @@ export function CourseForm({ initial }: CourseFormProps) {
<div>
<h2 className="text-sm font-semibold text-foreground">رسانه و انتشار</h2>
<p className="mt-0.5 text-xs text-muted-foreground">
لینک ثبت‌نام، تصویر، SEO و وضعیت انتشار
لینک ثبت‌نام، بارگذاری تصویر، SEO و وضعیت انتشار
</p>
</div>
<div className="grid gap-4 sm:grid-cols-2">
@@ -385,21 +383,23 @@ export function CourseForm({ initial }: CourseFormProps) {
/>
</div>
<div className="space-y-1.5 sm:col-span-2">
<Label htmlFor="posterImageUrl">آدرس پوستر (نمایش در لیست دوره‌ها)</Label>
<Input
<Label htmlFor="posterImageUrl">پوستر (نمایش در لیست دوره‌ها)</Label>
<ImageUploadField
id="posterImageUrl"
value={form.posterImageUrl}
onChange={(e) => set("posterImageUrl", e.target.value)}
placeholder="/images/courses/..."
onChange={(url) => set("posterImageUrl", url)}
folder="courses"
disabled={loading}
/>
</div>
<div className="space-y-1.5 sm:col-span-2">
<Label htmlFor="brochureImageUrl">آدرس بروشور (نمایش در صفحه جزئیات)</Label>
<Input
<Label htmlFor="brochureImageUrl">بروشور (نمایش در صفحه جزئیات)</Label>
<ImageUploadField
id="brochureImageUrl"
value={form.brochureImageUrl}
onChange={(e) => set("brochureImageUrl", e.target.value)}
placeholder="/images/courses/..."
onChange={(url) => set("brochureImageUrl", url)}
folder="courses"
disabled={loading}
/>
</div>
<div className="space-y-1.5 sm:col-span-2">
@@ -20,6 +20,7 @@ import {
type GenericFormSpec,
} from "@/lib/admin/entities";
import { AdminFormCard } from "@/components/organisms/admin/AdminPage";
import { ImageUploadField } from "@/components/organisms/admin/ImageUploadField";
function defaultValue(field: AdminFieldSpec): unknown {
if (field.type === "stringList") return [];
@@ -33,6 +34,8 @@ function finalValue(field: AdminFieldSpec, value: unknown): unknown {
}
if (field.type === "number") return Number(value);
if (field.type === "boolean") return value;
// image fields keep "" (faculty allows empty); optional text/date → null
if (field.type === "image") return String(value ?? "");
// optional empty text/date becomes null (e.g. event endDate, program tagline)
if (!field.required && value === "") return null;
return value;
@@ -207,6 +210,17 @@ export function GenericForm({
</Button>
</div>
);
case "image":
return (
<ImageUploadField
id={field.name}
value={String(value ?? "")}
onChange={(url) => set(field.name, url)}
folder={field.uploadFolder ?? "general"}
required={field.required}
disabled={loading}
/>
);
default:
return (
<Input
@@ -15,6 +15,7 @@ export function ProfessionalLandingTemplate({
courses,
stats,
testimonials,
initialTag = "",
}: {
labels: {
pathways: string;
@@ -32,6 +33,7 @@ export function ProfessionalLandingTemplate({
courses: Course[];
stats: SiteStat[];
testimonials: Testimonial[];
initialTag?: string;
}) {
return (
<main id="main-content">
@@ -100,8 +102,10 @@ export function ProfessionalLandingTemplate({
{labels.pathways}
</p>
<CategoryCourseExplorer
key={initialTag || "all"}
courses={courses}
findLabel={labels.findProgram}
initialTag={initialTag}
/>
</Container>
</Section>
+41 -5
View File
@@ -33,7 +33,8 @@ export type AdminFieldType =
| "date"
| "select"
| "boolean"
| "stringList";
| "stringList"
| "image";
export interface AdminSelectOption {
value: string;
@@ -50,6 +51,14 @@ export interface AdminFieldSpec {
defaultValue?: unknown;
/** spans the full form row instead of one column of a 2-col grid */
full?: boolean;
/** upload subfolder under /uploads (image fields only) */
uploadFolder?:
| "courses"
| "articles"
| "topics"
| "faculty"
| "alumni"
| "general";
}
export interface AdminColumnSpec {
@@ -125,7 +134,14 @@ export const ENTITIES: Record<string, AdminEntitySpec> = {
{ name: "author", label: "نویسنده", type: "text", required: true },
{ name: "publishedAt", label: "تاریخ انتشار", type: "date", required: true },
{ name: "excerpt", label: "خلاصه", type: "textarea", required: true, full: true },
{ name: "imageUrl", label: "آدرس تصویر", type: "text", placeholder: "/images/insights/..." },
{
name: "imageUrl",
label: "تصویر",
type: "image",
required: true,
uploadFolder: "articles",
full: true,
},
{ name: "href", label: "لینک کامل", type: "text", placeholder: "/insights/..." },
{ name: "featured", label: "مقالهٔ ویژه", type: "boolean", options: yesNo, defaultValue: false },
{ name: "body", label: "متن مقاله", type: "textarea", required: true, full: true },
@@ -228,7 +244,14 @@ export const ENTITIES: Record<string, AdminEntitySpec> = {
{ name: "slug", label: "اسلاگ", type: "text", required: true },
{ name: "title", label: "عنوان", type: "text", required: true },
{ name: "href", label: "لینک", type: "text", placeholder: "/topics/..." },
{ name: "imageUrl", label: "آدرس تصویر", type: "text", placeholder: "/images/topics/..." },
{
name: "imageUrl",
label: "تصویر",
type: "image",
required: true,
uploadFolder: "topics",
full: true,
},
{ name: "description", label: "توضیح", type: "textarea", required: true, full: true },
{ name: "highlights", label: "نکات برجسته", type: "stringList", full: true },
{ name: "body", label: "متن کامل", type: "textarea", required: true, full: true },
@@ -259,7 +282,13 @@ export const ENTITIES: Record<string, AdminEntitySpec> = {
{ name: "email", label: "ایمیل", type: "text", placeholder: "name@aut.ac.ir" },
{ name: "phone", label: "تلفن داخلی", type: "text", placeholder: "۰۲۱۶۴۵۴۵۸۰۰" },
{ name: "office", label: "دفتر", type: "text", placeholder: "ساختمان زکریا رازی — اتاق …" },
{ name: "imageUrl", label: "آدرس تصویر", type: "text", placeholder: "/images/faculty/..." },
{
name: "imageUrl",
label: "تصویر",
type: "image",
uploadFolder: "faculty",
full: true,
},
{ name: "linkedinUrl", label: "لینکدین", type: "text", placeholder: "https://www.linkedin.com/in/..." },
{ name: "scholarUrl", label: "گوگل اسکولار", type: "text", placeholder: "https://scholar.google.com/..." },
{ name: "bio", label: "بیوگرافی", type: "textarea", required: true, full: true },
@@ -287,7 +316,14 @@ export const ENTITIES: Record<string, AdminEntitySpec> = {
{ name: "title", label: "عنوان", type: "text", required: true, full: true },
{ name: "name", label: "نام", type: "text", required: true },
{ name: "program", label: "برنامه", type: "text", required: true },
{ name: "imageUrl", label: "آدرس تصویر", type: "text", placeholder: "/images/alumni/..." },
{
name: "imageUrl",
label: "تصویر",
type: "image",
required: true,
uploadFolder: "alumni",
full: true,
},
{ name: "href", label: "لینک", type: "text", placeholder: "/alumni/..." },
{ name: "excerpt", label: "خلاصه", type: "textarea", required: true, full: true },
publishedField,
+78
View File
@@ -0,0 +1,78 @@
import type { NavItem } from "@/lib/types";
import {
courseNavParentTag,
courseNavTagOrder,
homeNav,
} from "@/lib/site-config";
/** Link to the full course catalog (parent / «همه»). */
export function courseCatalogHref(): string {
return "/professional";
}
/** Deep-link that opens the catalog filtered by a course tag. */
export function courseTagHref(tag: string): string {
return `/professional?tag=${encodeURIComponent(tag)}`;
}
/**
* Order tags for the courses dropdown: preferred order first, then any
* remaining tags (excluding the configured parent tag).
*/
export function orderCourseNavTags(tags: string[]): string[] {
const seen = new Set<string>();
const ordered: string[] = [];
for (const tag of courseNavTagOrder) {
if (tag === courseNavParentTag) continue;
if (tags.includes(tag) && !seen.has(tag)) {
ordered.push(tag);
seen.add(tag);
}
}
for (const tag of tags) {
if (tag === courseNavParentTag) continue;
if (!seen.has(tag)) {
ordered.push(tag);
seen.add(tag);
}
}
return ordered;
}
/** Build dropdown children: parent (all) + one item per tag. */
export function buildCourseNavChildren(tags: string[]): NavItem[] {
const children: NavItem[] = [
{ label: "همه دوره‌ها", href: courseCatalogHref() },
...orderCourseNavTags(tags).map((tag) => ({
label: tag,
href: courseTagHref(tag),
})),
];
return children;
}
/**
* Home nav with a single courses dropdown whose items come from published
* course tags. Parent label is `courseNavParentTag` in site-config.
*/
export function buildHomeNavWithCourseTags(tags: string[]): NavItem[] {
const coursesItem: NavItem = {
label: courseNavParentTag,
href: courseCatalogHref(),
children: buildCourseNavChildren(tags),
};
// Insert before the prominent external link (دانشگاه…), else append.
const insertAt = homeNav.findIndex((item) => item.prominent);
if (insertAt === -1) {
return [...homeNav, coursesItem];
}
return [
...homeNav.slice(0, insertAt),
coursesItem,
...homeNav.slice(insertAt),
];
}
+12
View File
@@ -9,6 +9,18 @@ export async function getCourses(): Promise<Course[]> {
return res.rows.map(rowToCourse);
}
/** Distinct tags on published courses, most-used first (for public nav/filters). */
export async function listPublishedCourseTags(): Promise<string[]> {
const res = await query<{ tag: string }>(
`SELECT tag
FROM courses, UNNEST(tags) AS tag
WHERE published = true
GROUP BY tag
ORDER BY COUNT(*) DESC, tag ASC`,
);
return res.rows.map((r) => r.tag);
}
export async function getCourseById(id: string): Promise<Course | null> {
const res = await query<CourseRow>(
"SELECT * FROM courses WHERE published = true AND (id = $1 OR slug = $1) LIMIT 1",
+22 -7
View File
@@ -28,24 +28,39 @@ export const siteAddress = {
mapUrl: "https://maps.google.com/?q=Amirkabir+University+of+Technology",
};
/** Main nav labels for Persian users */
/** Main nav labels for Persian users (seed/reference — runtime uses site-config + course-nav). */
export const homeNav: NavItem[] = [
{ label: "ارزش‌ها", href: "/values" },
{ label: "اساتید", href: "https://mst.aut.ac.ir/content/31094/شبکه-اساتید" },
{ label: "درباره ما", href: "/about" },
{ label: "دوره‌های کوتاه", href: "/professional" },
{ label: "دوره‌های صنعتی", href: "/professional" },
{
label: "دوره‌ها",
href: "/professional",
children: [
{ label: "همه دوره‌ها", href: "/professional" },
{ label: "کارگاه‌ها", href: "/professional?tag=کارگاه‌ها" },
{ label: "دوره‌های سازمانی", href: "/professional?tag=دوره‌های سازمانی" },
{
label: "گزیده دوره‌های برگزار شده",
href: "/professional?tag=گزیده دوره‌های برگزار شده",
},
],
},
{ label: "دانشگاه امیرکبیر", href: "https://mst.aut.ac.ir/", prominent: true },
];
export const professionalNav: NavItem[] = [
{
label: "فهرست دوره‌ها",
label: "دوره‌ها",
href: "/professional#programs",
children: [
{ label: "گواهی‌نامه‌ها", href: "/professional#certificates" },
{ label: "دوره‌های آنلاین", href: "/professional#courses" },
{ label: "دوره‌های سازمانی", href: "/professional#corporate" },
{ label: "همه دوره‌ها", href: "/professional" },
{ label: "کارگاه‌ها", href: "/professional?tag=کارگاه‌ها" },
{ label: "دوره‌های سازمانی", href: "/professional?tag=دوره‌های سازمانی" },
{
label: "گزیده دوره‌های برگزار شده",
href: "/professional?tag=گزیده دوره‌های برگزار شده",
},
],
},
{ label: "نحوه یادگیری", href: "/professional#digital" },
+25 -7
View File
@@ -20,24 +20,42 @@ export const siteAddress = {
mapUrl: "https://maps.google.com/?q=Amirkabir+University+of+Technology",
};
/** Main nav labels for Persian users */
/**
* Parent label for the single courses dropdown on the home nav.
* Change this to rename the root item; child items come from course tags.
* See docs/LINKS.md.
*/
export const courseNavParentTag = "دوره‌ها";
/**
* Preferred order of tag items inside the courses dropdown.
* Tags present on published courses but missing here still appear after these.
* Keep in sync with admin suggested tags when possible.
*/
export const courseNavTagOrder: string[] = [
"کارگاه‌ها",
"دوره‌های سازمانی",
"گزیده دوره‌های برگزار شده",
];
/** Main nav (static items). Courses dropdown is injected at runtime from tags. */
export const homeNav: NavItem[] = [
{ label: "ارزش‌ها", href: "/values" },
{ label: "اساتید", href: "https://mst.aut.ac.ir/content/31094/شبکه-اساتید" },
{ label: "درباره ما", href: "/about" },
{ label: "دوره‌های کوتاه", href: "/professional" },
{ label: "دوره‌های صنعتی", href: "/professional" },
{ label: "دانشگاه امیرکبیر", href: "https://mst.aut.ac.ir/", prominent: true },
];
export const professionalNav: NavItem[] = [
{
label: "فهرست دوره‌ها",
label: courseNavParentTag,
href: "/professional#programs",
children: [
{ label: "گواهی‌نامه‌ها", href: "/professional#certificates" },
{ label: "دوره‌های آنلاین", href: "/professional#courses" },
{ label: "دوره‌های سازمانی", href: "/professional#corporate" },
{ label: "همه دوره‌ها", href: "/professional" },
...courseNavTagOrder.map((tag) => ({
label: tag,
href: `/professional?tag=${encodeURIComponent(tag)}`,
})),
],
},
{ label: "نحوه یادگیری", href: "/professional#digital" },
+81
View File
@@ -0,0 +1,81 @@
import { randomUUID } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import {
isUploadFolder,
type UploadFolder,
} from "@/lib/uploads/types";
export { isUploadFolder, UPLOAD_FOLDERS, type UploadFolder } from "@/lib/uploads/types";
const MAX_BYTES = 5 * 1024 * 1024;
const MIME_TO_EXT = new Map<string, string>([
["image/jpeg", "jpg"],
["image/png", "png"],
["image/webp", "webp"],
["image/gif", "gif"],
]);
/** Disk root for uploaded images. Override with UPLOAD_DIR for Docker volumes. */
export function getUploadsRoot(): string {
if (process.env.UPLOAD_DIR) {
return path.resolve(process.env.UPLOAD_DIR);
}
return path.join(process.cwd(), "public", "uploads");
}
export function publicUrlFor(relativePath: string): string {
return `/uploads/${relativePath.replace(/\\/g, "/")}`;
}
export type SaveImageResult =
| { ok: true; url: string; relativePath: string }
| { ok: false; error: string; status: number };
export async function saveUploadedImage(
file: File,
folder: UploadFolder,
): Promise<SaveImageResult> {
if (!file || file.size === 0) {
return { ok: false, error: "فایلی انتخاب نشده است", status: 400 };
}
if (file.size > MAX_BYTES) {
return {
ok: false,
error: "حجم تصویر نباید بیشتر از ۵ مگابایت باشد",
status: 400,
};
}
const ext = MIME_TO_EXT.get(file.type);
if (!ext) {
return {
ok: false,
error: "فقط فایل‌های JPG، PNG، WebP یا GIF مجاز است",
status: 400,
};
}
if (!isUploadFolder(folder)) {
return { ok: false, error: "پوشهٔ مقصد نامعتبر است", status: 400 };
}
const relativePath = path.join(folder, `${randomUUID()}.${ext}`);
const absolutePath = path.join(getUploadsRoot(), relativePath);
try {
await mkdir(path.dirname(absolutePath), { recursive: true });
const buffer = Buffer.from(await file.arrayBuffer());
await writeFile(absolutePath, buffer);
} catch (err) {
console.error("saveUploadedImage error:", err);
return { ok: false, error: "ذخیرهٔ فایل ناموفق بود", status: 500 };
}
return {
ok: true,
url: publicUrlFor(relativePath),
relativePath: relativePath.replace(/\\/g, "/"),
};
}
+14
View File
@@ -0,0 +1,14 @@
export const UPLOAD_FOLDERS = [
"courses",
"articles",
"topics",
"faculty",
"alumni",
"general",
] as const;
export type UploadFolder = (typeof UPLOAD_FOLDERS)[number];
export function isUploadFolder(value: string): value is UploadFolder {
return (UPLOAD_FOLDERS as readonly string[]).includes(value);
}
+3 -2
View File
@@ -36,8 +36,9 @@ const courseFields = {
.union([z.number().int().nonnegative("قیمت نمی‌تواند منفی باشد"), z.null()])
.optional(),
registrationUrl: urlOrPath,
posterImageUrl: urlOrPath,
brochureImageUrl: urlOrPath,
/** Local upload path (/uploads/...) or legacy path/URL; empty clears. */
posterImageUrl: z.union([urlOrPath, z.literal("")]),
brochureImageUrl: z.union([urlOrPath, z.literal("")]),
tags: z.array(z.string()).default([]),
seoDescription: z.string(),
published: z.boolean(),