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:
1 parent
ef1ccea0ad
commit
66a8e8f213
29 files changed
+748
-125
No files matched your search
@@ -24,6 +24,10 @@
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# admin-uploaded images (keep folder via .gitkeep)
|
||||
/public/uploads/*
|
||||
!/public/uploads/.gitkeep
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
|
||||
@@ -31,6 +31,9 @@ COPY --from=builder /app/public ./public
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||
|
||||
# Writable dir for admin image uploads (mount a volume in compose for persistence)
|
||||
RUN mkdir -p ./public/uploads && chown -R nextjs:nodejs ./public/uploads
|
||||
|
||||
USER nextjs
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
@@ -18,6 +18,9 @@ COPY --chown=nextjs:nodejs . ./
|
||||
# Next warns/breaks if a legacy root-level ./static exists alongside ./public
|
||||
RUN rm -rf ./static
|
||||
|
||||
# Writable dir for admin image uploads (mount a volume in compose for persistence)
|
||||
RUN mkdir -p ./public/uploads && chown -R nextjs:nodejs ./public/uploads
|
||||
|
||||
USER nextjs
|
||||
EXPOSE 3000
|
||||
CMD ["node", "server.js"]
|
||||
@@ -13,8 +13,11 @@ services:
|
||||
- HOSTNAME=0.0.0.0
|
||||
- NEXT_PUBLIC_SITE_URL=${NEXT_PUBLIC_SITE_URL:-https://edu.mstaut.ir}
|
||||
- DATABASE_URL=${DATABASE_URL:-postgresql://managment_web:password@insaight-postgres:5432/ManagmentWebSite_Db}
|
||||
- UPLOAD_DIR=/app/public/uploads
|
||||
# Nginx Proxy Manager: edu.mstaut.ir → http://aut-management-faculty:3000
|
||||
# DB: same Docker network as container `insaight-postgres` (not the public IP).
|
||||
volumes:
|
||||
- uploads_data:/app/public/uploads
|
||||
expose:
|
||||
- "3000"
|
||||
networks:
|
||||
@@ -22,6 +25,9 @@ services:
|
||||
ports:
|
||||
- "3000:3000"
|
||||
|
||||
volumes:
|
||||
uploads_data:
|
||||
|
||||
networks:
|
||||
shared_web_network:
|
||||
external: true
|
||||
|
||||
@@ -55,6 +55,7 @@
|
||||
- لیست برنامههای هوم: ابتدا `group=standard` سپس بلوک جدا `executive`.
|
||||
- آمار لندینگ professional از mock ثابت خوانده میشود (تا اتصال analytics/DB).
|
||||
- هیچ مبلغ/ظرفیت واقعی محاسبه نمیشود تا DB وصل شود.
|
||||
- منوی صفحهٔ اصلی فقط **یک** دراپداون دوره دارد؛ لیبل ریشه = `courseNavParentTag`؛ فرزندان از تگهای منتشرشده. فیلتر پایدار: `/professional?tag=` (مستند: `docs/LINKS.md`).
|
||||
|
||||
## Locale / Format Rules
|
||||
- زبان UI: فارسی؛ `dir="rtl"`؛ اعداد نمایشی میتوانند فارسیسازی شوند در لایهٔ UI.
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# لینکهای عمومی سایت
|
||||
|
||||
مسیرهای پایدار برای ناوبری، اشتراکگذاری و فیلتر. تغییر لیبل یا ترتیب از `src/lib/site-config.ts`؛ منطق ساخت منو از `src/lib/course-nav.ts`.
|
||||
|
||||
## کاتالوگ دورهها
|
||||
|
||||
| توضیح | مسیر |
|
||||
|---|---|
|
||||
| همه دورهها (تگ پدر / ریشه) | `/professional` |
|
||||
| فیلتر با تگ | `/professional?tag=<نام-تگ>` |
|
||||
|
||||
### تگ پدر
|
||||
|
||||
- مقدار فعلی: **`دورهها`** (`courseNavParentTag` در `site-config.ts`)
|
||||
- این لیبل، عنوان همان **یک** دراپداون منوی صفحهٔ اصلی است (جای دکمههای جدا مثل «دورههای کوتاه» / «دورههای صنعتی»).
|
||||
- کلیک روی ریشه → `/professional` (بدون فیلتر).
|
||||
- آیتمهای فرزند از **تگهای دورههای منتشرشده** میآیند؛ ترتیب ترجیحی: `courseNavTagOrder`.
|
||||
|
||||
### نمونه لینک تگ
|
||||
|
||||
ساخت با `encodeURIComponent` یا هلپر زیر؛ مقدار `tag` باید دقیقاً با تگ ذخیرهشده روی دوره یکی باشد.
|
||||
|
||||
| تگ | الگو |
|
||||
|---|---|
|
||||
| کارگاهها | `/professional?tag=کارگاهها` |
|
||||
| دورههای سازمانی | `/professional?tag=دورههای سازمانی` |
|
||||
| گزیده دورههای برگزار شده | `/professional?tag=گزیده دورههای برگزار شده` |
|
||||
|
||||
در کد از هلپرها استفاده کنید:
|
||||
|
||||
```ts
|
||||
import { courseCatalogHref, courseTagHref } from "@/lib/course-nav";
|
||||
|
||||
courseCatalogHref(); // "/professional"
|
||||
courseTagHref("کارگاهها"); // "/professional?tag=..."
|
||||
```
|
||||
|
||||
## سایر مسیرهای اصلی
|
||||
|
||||
| صفحه | مسیر |
|
||||
|---|---|
|
||||
| صفحه اصلی | `/` |
|
||||
| ارزشها | `/values` |
|
||||
| درباره ما | `/about` |
|
||||
| تماس | `/contact` |
|
||||
| رویدادها | `/events` |
|
||||
| بینشها | `/insights` |
|
||||
| ثبتنام دوره | `/register/<slug>` |
|
||||
@@ -11,6 +11,13 @@
|
||||
گزینههای محتمل: ...
|
||||
-->
|
||||
|
||||
### ابهام 01 — ⏳ در انتظار پاسخ
|
||||
تاریخ: 2026-10-11
|
||||
سوال: لیبل تگ پدر منوی دورهها فعلاً «دورهها» (`courseNavParentTag`) است. همین بماند؟
|
||||
گزینههای محتمل:
|
||||
- الف) «دورهها» (پیشفرض فعلی)
|
||||
- ب) نام دیگری که شما مشخص کنید (مثلاً «برنامهها» یا «کارگاهها»)
|
||||
|
||||
## سوالات پاسخدادهشده
|
||||
|
||||
<!-- بعد از پاسخ به اینجا منتقل میشود:
|
||||
|
||||
@@ -28,3 +28,4 @@
|
||||
| 2026-09-24 | D21 — ادمین عمومی با رجیستری `ENTITIES` در `src/lib/admin/entities.ts` (fields/columns/apiPath/idColumn/preview/list/get) + صفحات یکپارچهٔ داینامیک `/admin/[entity]` (list/new/[id]/edit) بهجای صفحهٔ جدا برای هر entity؛ orgهای عمومی `GenericTable` (سرور) / `GenericFilters`، `GenericForm`، `GenericDeleteDialog`، `PublishToggle` (کلاینت)؛ استاتیکها (`courses`، `login`، `registrations`) بر داینامیک ارجحند؛ `GenericForm` فقط **نسخهٔ قابلserialize** از spec را میگیرد چون توابع (list/get/preview) نمیتوانند به Client Component برسند | ۱۰ entity with شش شکل رکورد متفاوت = یک فرمول؛ کاهش تکرار شدید؛ D19/D20 تعمیم یافته |
|
||||
| 2026-09-24 | D22 — فاز G/H: ثبتنام عمومی در `POST /api/registrations` (اسکیمای `publicRegistrationSchema` با zod v4؛ یافتن `course_id` از slug؛ عموم بدون وضعیت) + صفحهٔ `/admin/registrations` (فیلتر search/status در URL، تغییر status، حذف)؛ لایههای `lib/data/admin/registrations.ts` و `lib/validation/public.ts`؛ و **بازاعتبارسنجی (Phase H)** با `revalidateSite()` → `revalidatePath("/", "layout")` که در `buildInsert`/`buildUpdate` فراخوانی میشود و دستی در DELETE های raw-SQL و route های دوره/مقاله اضافه شد | فرم ثبتنام واقعاً لید میسازد تا ادمین دنبال کند؛ صفحههای استاتیک عمومی با cache قدیمی پس از هر تغییر ادمین باید invalidate شوند |
|
||||
| 2026-09-24 | D23 — پایان H: حذف کامل وابستگی runtime به mock برای محتوای با تیبل: `intersections`، `stats`، `testimonials` از DB میآیند (`getTopics`، `getSiteStats`، `getTestimonials` در `lib/data/site.ts`؛ `HomeRest` با prop `stats`)؛ هویت/ناو استاتیکِ بدونتیبل به ماژول مستقل `src/lib/site-config.ts` منتقل شد؛ `src/lib/mock/site.ts` فقط برای seed باقی ماند (کامنت هدر دارد)؛ ایندکسها با `db/migrations/002_indexes.sql` (leads/articles/events/programs/courses)؛ اسکریپت `scripts/smoke.mjs` (۴ API عمومی + login + create/delete stat) | معیار پذیرش C/H: runtime هیچ import مستقیمی از mock ندارد؛ config بدون تیبل نباید «دادهٔ mock» تلقی شود؛ smoke خواندنی + یک write ادمین میسنجد |
|
||||
| 2026-10-11 | D24 — آپلود تصویر ادمین: `POST /api/admin/upload` (multipart، فقط ادمین) فایل را در `public/uploads/{folder}/` مینویسد و مسیر عمومی `/uploads/...` برمیگرداند؛ UI با `ImageUploadField` در `CourseForm` و فیلد نوع `image` در `GenericForm`/`entities` (articles/topics/faculty/alumni)؛ persistence در Docker با volume `uploads_data` و env `UPLOAD_DIR` | ورود دستی URL اشتباه بود؛ ادمین باید فایل بارگذاری کند؛ ستونهای DB همچنان path/URL میمانند |
|
||||
@@ -1,7 +1,7 @@
|
||||
# Active Context
|
||||
|
||||
## Current Goal
|
||||
ساختار اولیه کامل است (فازهای A تا H پلن `docs/04-development-plan.md`). طبق دستور کاربر محتوای واقعی وارد نشده — بعداً از پنل ادمین کنترل میشود. هیچ کار ساختاری باقی نمانده؛ پیشرفت بعدی = محتوای واقعی.
|
||||
منوی صفحهٔ اصلی: یک دراپداون دوره از تگها (`courseNavParentTag` + `docs/LINKS.md`). در انتظار تأیید لیبل تگ پدر (ابهام 01).
|
||||
|
||||
## Current Work
|
||||
کار ساختاری به پایان رسید و همهٔ چکهای نهایی سبزند (2026-09-24):
|
||||
@@ -13,11 +13,14 @@
|
||||
- **docs**: `00-brief.md` (ادمین دیگر out نیست)، `01-architecture.md` (پستگرس + ادمین همان اپ + الگوی registry)، `03-database.md` (بینقص: جداول + migrate/seed + ایندکس ۰۰۲)، `04-development-plan.md` (چکلیست H کامل)، `README.md` (دستورات dev/migrate/seed/admin/smoke) بهروز شدند.
|
||||
|
||||
## Current Blockers
|
||||
بدون مانع. تصمیمهای باز (حذف vs unpublish؛ آپلود تصویر؛ ORM؛ محتوای واقعی) در بخش ۱۵ پلن برای پرسش هنگام نیاز آمدهاند.
|
||||
بدون مانع. تصمیمهای باز (حذف vs unpublish؛ ORM؛ محتوای واقعی) در بخش ۱۵ پلن برای پرسش هنگام نیاز آمدهاند.
|
||||
|
||||
## Next Steps
|
||||
1. محتوای واقعی از پنل ادمین (طبق دستور کاربر بعداً — فعلاً چیزی بقای ساختاری نمانده).
|
||||
2. (اختیاری، بخش ۱۰ پلن) rate limit روی `POST /api/registrations`؛ آپلود تصویر.
|
||||
2. (اختیاری، بخش ۱۰ پلن) rate limit روی `POST /api/registrations`.
|
||||
|
||||
## آپلود تصویر (D24 — 2026-10-11)
|
||||
ادمین فایل را از UI بارگذاری میکند (`ImageUploadField` + `POST /api/admin/upload`). مسیر در DB بهصورت `/uploads/...` ذخیره میشود. در Docker volume `uploads_data` را نگه دارید.
|
||||
|
||||
## نکته برای ادامهٔ کار
|
||||
صفحات جدید داخل `src/app/admin/(guard)/` و کامپوننتهای رابط در `src/components/organisms/admin/*`. افزودن primitive shadcn جدید فقط با `npx shadcn@latest add <name>` (بدون دستنویسی). **انتقال spec به Client Component نباید تابع داشته باشد** (list/get/preview → فقط `GenericFormSpec` serialize میشود؛ `GenericTable` سرور است و spec کامل مجاز است). Select بیس UI مقدار `null` هم میفرستد (`(v) => v ?? "all"`). در PowerShell مسیرهای حاوی `[id]` به `-LiteralPath` نیاز دارند؛ `Start-Process cmd` باید با `-ArgumentList @('/c', 'npm run start -- -p 3100 > server.log 2>&1')` ساخته شود. تست زنده: `npm run build` سپس سرور روی `-p 3100` و لاگین با `admin@aut.ac.ir/admin123` (cookie دارای Secure است؛ روی http باید دستی ارسال شود). smoke: `SMOKE_ADMIN_EMAIL/PASSWORD` بگذار و `node scripts/smoke.mjs` بزن.
|
||||
@@ -37,7 +37,7 @@
|
||||
|
||||
## Doing
|
||||
|
||||
هیچ — ساختار کامل است؛ فقط محتوای واقعی مانده که طبق دستور کاربر از ادمین کنترل میشود.
|
||||
- [x] منوی هوم: حذف دکمههای جدا «دورههای کوتاه/صنعتی» → یک دراپداون از تگها؛ تگ پدر در `courseNavParentTag`؛ لینک پایدار `?tag=`؛ مستند `docs/LINKS.md`
|
||||
|
||||
## Next
|
||||
- [x] فاز H باقیمانده — ایندکسها، docs/README نهایی، حذف وابستگی runtime به mock، smoke script
|
||||
|
||||
Whitespace-only changes.
@@ -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")}
|
||||
|
||||
@@ -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 },
|
||||
);
|
||||
}
|
||||
@@ -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")}
|
||||
|
||||
@@ -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="حذف فیلتر تگ"
|
||||
>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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),
|
||||
];
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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" },
|
||||
|
||||
@@ -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, "/"),
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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(),
|
||||
|
||||
Reference in new issue
Block a user