This commit is contained in:
smhk1376 committed 2026-10-15 10:10:30 +03:30
1 parent a99af426db
commit 8886aa8640
91 files changed
+2823 -773

No files matched your search

+7 -7
View File
@@ -3,10 +3,11 @@ import { CampaignBanners } from "@/components/organisms/CampaignBanners";
import { SiteFooter } from "@/components/organisms/SiteFooter";
import { SiteHeader } from "@/components/organisms/SiteHeader";
import { buildHomeNavWithCourseTags } from "@/lib/course-nav";
import { getCourses, listPublishedCourseTags } from "@/lib/data/courses";
import { getCourses } from "@/lib/data/courses";
import { listPublishedCourseTags } from "@/lib/data/taxonomy";
import { getPrograms } from "@/lib/data/programs";
import { getCampaignBanners } from "@/lib/data/site";
import { courseNavTagOrder, siteShortName } from "@/lib/site-config";
import { 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.
@@ -22,20 +23,19 @@ 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];
let navTags: Awaited<ReturnType<typeof listPublishedCourseTags>> = [];
try {
[courses, programs, banners, courseTags] = await Promise.all([
[courses, programs, banners, navTags] = await Promise.all([
getCourses(),
getPrograms(),
getCampaignBanners(),
listPublishedCourseTags(),
listPublishedCourseTags({ navOnly: true }),
]);
if (courseTags.length === 0) courseTags = [...courseNavTagOrder];
} catch (err) {
console.error("[main/layout] CMS fetch failed:", err);
}
const navItems = buildHomeNavWithCourseTags(courseTags);
const navItems = buildHomeNavWithCourseTags(navTags);
return (
<>
@@ -1,5 +1,6 @@
import { notFound } from "next/navigation";
import { ENTITIES } from "@/lib/admin/entities";
import { isAdminEntityEnabled } from "@/lib/admin/disabled-entities";
import { GenericForm } from "@/components/organisms/admin/generic/GenericForm";
import {
AdminPage,
@@ -15,7 +16,7 @@ export default async function AdminEntityEditPage({
}) {
const { entity, id } = await params;
const spec = ENTITIES[entity];
if (!spec) notFound();
if (!spec || !isAdminEntityEnabled(entity)) notFound();
const row = (await spec.get(id)) as Record<string, unknown>;
if (!row) notFound();
+2 -1
View File
@@ -1,5 +1,6 @@
import { notFound } from "next/navigation";
import { ENTITIES } from "@/lib/admin/entities";
import { isAdminEntityEnabled } from "@/lib/admin/disabled-entities";
import { GenericForm } from "@/components/organisms/admin/generic/GenericForm";
import {
AdminPage,
@@ -15,7 +16,7 @@ export default async function AdminEntityCreatePage({
}) {
const { entity } = await params;
const spec = ENTITIES[entity];
if (!spec) notFound();
if (!spec || !isAdminEntityEnabled(entity)) notFound();
return (
<AdminPage>
+2 -1
View File
@@ -1,6 +1,7 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { ENTITIES } from "@/lib/admin/entities";
import { isAdminEntityEnabled } from "@/lib/admin/disabled-entities";
import { GenericFilters } from "@/components/organisms/admin/generic/GenericFilters";
import { GenericTable } from "@/components/organisms/admin/generic/GenericTable";
import {
@@ -23,7 +24,7 @@ export default async function AdminEntityListPage({
}) {
const { entity } = await params;
const spec = ENTITIES[entity];
if (!spec) notFound();
if (!spec || !isAdminEntityEnabled(entity)) notFound();
const { search = "", published: publishedRaw } = await searchParams;
const published =
@@ -5,6 +5,10 @@ import {
AdminPage,
AdminPageHeader,
} from "@/components/organisms/admin/AdminPage";
import {
listAdminCourseCategories,
listAdminCourseTags,
} from "@/lib/data/admin/taxonomy";
export const dynamic = "force-dynamic";
@@ -14,7 +18,11 @@ export default async function EditCoursePage({
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const course = await getAdminCourseById(id);
const [course, categories, tags] = await Promise.all([
getAdminCourseById(id),
listAdminCourseCategories(),
listAdminCourseTags(),
]);
if (!course) notFound();
return (
@@ -25,7 +33,7 @@ export default async function EditCoursePage({
backHref="/admin/courses"
backLabel="بازگشت به دوره‌ها"
/>
<CourseForm initial={course} />
<CourseForm initial={course} categories={categories} tags={tags} />
</AdminPage>
);
}
+11 -2
View File
@@ -3,10 +3,19 @@ import {
AdminPage,
AdminPageHeader,
} from "@/components/organisms/admin/AdminPage";
import {
listAdminCourseCategories,
listAdminCourseTags,
} from "@/lib/data/admin/taxonomy";
export const dynamic = "force-dynamic";
export default function NewCoursePage() {
export default async function NewCoursePage() {
const [categories, tags] = await Promise.all([
listAdminCourseCategories(),
listAdminCourseTags(),
]);
return (
<AdminPage>
<AdminPageHeader
@@ -15,7 +24,7 @@ export default function NewCoursePage() {
backHref="/admin/courses"
backLabel="بازگشت به دوره‌ها"
/>
<CourseForm />
<CourseForm categories={categories} tags={tags} />
</AdminPage>
);
}
+25 -5
View File
@@ -1,5 +1,6 @@
import Link from "next/link";
import { listAdminCourses, listCourseTags } from "@/lib/data/admin/courses";
import { listAdminCourseCategories } from "@/lib/data/admin/taxonomy";
import { CourseTable } from "@/components/organisms/admin/courses/CourseTable";
import { CourseFilters } from "@/components/organisms/admin/courses/CourseFilters";
import {
@@ -16,14 +17,27 @@ export const dynamic = "force-dynamic";
export default async function AdminCoursesPage({
searchParams,
}: {
searchParams: Promise<{ search?: string; published?: string; tag?: string }>;
searchParams: Promise<{
search?: string;
published?: string;
tag?: string;
category?: string;
}>;
}) {
const { search = "", published: publishedRaw, tag } = await searchParams;
const {
search = "",
published: publishedRaw,
tag,
category,
} = await searchParams;
const published =
publishedRaw === "true" ? true : publishedRaw === "false" ? false : undefined;
const courses = await listAdminCourses({ search, published, tag });
const availableTags = await listCourseTags();
const [courses, availableTags, availableCategories] = await Promise.all([
listAdminCourses({ search, published, tag, category }),
listCourseTags(),
listAdminCourseCategories(),
]);
return (
<AdminPage>
@@ -37,12 +51,18 @@ export default async function AdminCoursesPage({
}
/>
<AdminToolbarCard description="جستجو بر اساس عنوان یا اسلاگ، فیلتر وضعیت انتشار و تگ‌ها">
<AdminToolbarCard description="جستجو بر اساس عنوان یا اسلاگ، فیلتر وضعیت انتشار، دسته و تگ">
<CourseFilters
initialSearch={search}
initialPublished={publishedRaw ?? "all"}
initialTag={tag ?? ""}
initialCategory={category ?? ""}
availableTags={availableTags}
availableCategories={availableCategories.map((c) => ({
id: c.id,
slug: c.slug,
label: c.label,
}))}
/>
</AdminToolbarCard>
+3 -2
View File
@@ -24,6 +24,7 @@ import {
AdminPage,
AdminPageHeader,
} from "@/components/organisms/admin/AdminPage";
import { isAdminEntityEnabled } from "@/lib/admin/disabled-entities";
export const dynamic = "force-dynamic";
@@ -51,7 +52,7 @@ const countCards = [
{ 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;
].filter((card) => isAdminEntityEnabled(card.key));
export default async function AdminDashboardPage() {
const [counts, leadsRes] = await Promise.all([
@@ -77,7 +78,7 @@ export default async function AdminDashboardPage() {
<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">
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-3">
{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">
+7
View File
@@ -6,6 +6,7 @@ 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";
import { disabledAdminEntityResponse } from "@/lib/admin/disabled-entities";
export const dynamic = "force-dynamic";
@@ -24,6 +25,9 @@ export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const disabled = disabledAdminEntityResponse("alumni");
if (disabled) return disabled;
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
@@ -63,6 +67,9 @@ export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const disabled = disabledAdminEntityResponse("alumni");
if (disabled) return disabled;
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
+4
View File
@@ -5,11 +5,15 @@ 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";
import { disabledAdminEntityResponse } from "@/lib/admin/disabled-entities";
export const dynamic = "force-dynamic";
// POST /api/admin/alumni — create alumni story (admin only)
export async function POST(request: NextRequest) {
const disabled = disabledAdminEntityResponse("alumni");
if (disabled) return disabled;
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
+7
View File
@@ -6,6 +6,7 @@ import { articlePatchSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { isUniqueViolation } from "@/lib/db/errors";
import { revalidateSite } from "@/lib/api/revalidate";
import { disabledAdminEntityResponse } from "@/lib/admin/disabled-entities";
export const dynamic = "force-dynamic";
@@ -27,6 +28,9 @@ export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const disabled = disabledAdminEntityResponse("articles");
if (disabled) return disabled;
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
@@ -84,6 +88,9 @@ export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const disabled = disabledAdminEntityResponse("articles");
if (disabled) return disabled;
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
+4
View File
@@ -7,11 +7,15 @@ import { articleCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { isUniqueViolation } from "@/lib/db/errors";
import { revalidateSite } from "@/lib/api/revalidate";
import { disabledAdminEntityResponse } from "@/lib/admin/disabled-entities";
export const dynamic = "force-dynamic";
// POST /api/admin/articles — create article (admin only)
export async function POST(request: NextRequest) {
const disabled = disabledAdminEntityResponse("articles");
if (disabled) return disabled;
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
@@ -0,0 +1,78 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { requireAdmin } from "@/lib/auth/admin";
import { courseCategoryPatchSchema } 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";
import { getAdminCourseCategoryById } from "@/lib/data/admin/taxonomy";
export const dynamic = "force-dynamic";
const COLUMNS: Record<string, string> = {
slug: "slug",
label: "label",
sortOrder: "sort_order",
showInFilter: "show_in_filter",
published: "published",
};
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 = courseCategoryPatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const spec = buildUpdate("course_categories", "id", COLUMNS, parsed.data);
if (spec.empty) return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
try {
const res = await query(spec.sql, [...spec.params, id]);
if (res.rows.length === 0) return errorResponse("دسته یافت نشد", 404);
const data = await getAdminCourseCategoryById(id);
return NextResponse.json({ ok: true, data });
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "course_categories_slug_key") {
return errorResponse("این slug قبلاً استفاده شده است", 409);
}
console.error("admin update course-category error:", err);
return errorResponse("خطای سرور", 500);
}
}
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 course_categories 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-category error:", err);
return errorResponse("خطای سرور", 500);
}
}
@@ -0,0 +1,46 @@
import { NextResponse } from "next/server";
import { query } from "@/lib/db";
import { requireAdmin } from "@/lib/auth/admin";
import { courseCategoryCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { makeId, parseJsonBody, buildInsert } from "@/lib/api/crud";
import { isUniqueViolation } from "@/lib/db/errors";
import { getAdminCourseCategoryById } from "@/lib/data/admin/taxonomy";
export const dynamic = "force-dynamic";
export async function POST(request: Request) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = courseCategoryCreateSchema.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(
"course_categories",
["id", "slug", "label", "sort_order", "show_in_filter", "published"],
[id, d.slug, d.label, d.sortOrder, d.showInFilter, d.published],
);
await query(sql, params);
const data = await getAdminCourseCategoryById(id);
return NextResponse.json({ ok: true, data }, { status: 201 });
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "course_categories_slug_key") {
return errorResponse("این slug قبلاً استفاده شده است", 409);
}
console.error("admin create course-category error:", err);
return errorResponse("خطای سرور", 500);
}
}
@@ -0,0 +1,79 @@
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { requireAdmin } from "@/lib/auth/admin";
import { courseTagPatchSchema } 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";
import { getAdminCourseTagById } from "@/lib/data/admin/taxonomy";
export const dynamic = "force-dynamic";
const COLUMNS: Record<string, string> = {
slug: "slug",
label: "label",
sortOrder: "sort_order",
showInNav: "show_in_nav",
showInFilter: "show_in_filter",
published: "published",
};
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 = courseTagPatchSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const spec = buildUpdate("course_tags", "id", COLUMNS, parsed.data);
if (spec.empty) return errorResponse("حداقل یک فیلد برای ویرایش لازم است", 400);
try {
const res = await query(spec.sql, [...spec.params, id]);
if (res.rows.length === 0) return errorResponse("تگ یافت نشد", 404);
const data = await getAdminCourseTagById(id);
return NextResponse.json({ ok: true, data });
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "course_tags_slug_key") {
return errorResponse("این slug قبلاً استفاده شده است", 409);
}
console.error("admin update course-tag error:", err);
return errorResponse("خطای سرور", 500);
}
}
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 course_tags 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-tag error:", err);
return errorResponse("خطای سرور", 500);
}
}
+62
View File
@@ -0,0 +1,62 @@
import { NextResponse } from "next/server";
import { query } from "@/lib/db";
import { requireAdmin } from "@/lib/auth/admin";
import { courseTagCreateSchema } from "@/lib/validation/admin";
import { errorResponse } from "@/lib/api/response";
import { makeId, parseJsonBody, buildInsert } from "@/lib/api/crud";
import { isUniqueViolation } from "@/lib/db/errors";
import { getAdminCourseTagById } from "@/lib/data/admin/taxonomy";
export const dynamic = "force-dynamic";
export async function POST(request: Request) {
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
let body: unknown;
try {
body = await parseJsonBody(request);
} catch {
return errorResponse("بدنهٔ درخواست JSON معتبر نیست", 400);
}
const parsed = courseTagCreateSchema.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(
"course_tags",
[
"id",
"slug",
"label",
"sort_order",
"show_in_nav",
"show_in_filter",
"published",
],
[
id,
d.slug,
d.label,
d.sortOrder,
d.showInNav,
d.showInFilter,
d.published,
],
);
await query(sql, params);
const data = await getAdminCourseTagById(id);
return NextResponse.json({ ok: true, data }, { status: 201 });
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "course_tags_slug_key") {
return errorResponse("این slug قبلاً استفاده شده است", 409);
}
console.error("admin create course-tag error:", err);
return errorResponse("خطای سرور", 500);
}
}
+34 -14
View File
@@ -1,12 +1,15 @@
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";
import {
setCourseCategories,
setCourseTags,
} from "@/lib/data/admin/taxonomy";
export const dynamic = "force-dynamic";
@@ -33,7 +36,6 @@ const COURSE_COLUMNS: Record<string, string> = {
slug: "slug",
title: "title",
summary: "summary",
category: "category",
durationHours: "duration_hours",
format: "format",
price: "price",
@@ -41,7 +43,6 @@ const COURSE_COLUMNS: Record<string, string> = {
posterImageUrl: "poster_image_url",
brochureImageUrl: "brochure_image_url",
seoDescription: "seo_description",
tags: "tags",
published: "published",
};
@@ -67,29 +68,48 @@ export async function PATCH(
return errorResponse(parsed.error.issues[0]?.message ?? "داده نادرست", 400);
}
const { categoryIds, tagIds, ...rest } = parsed.data;
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];
const v = rest[key as keyof typeof rest];
if (v !== undefined) {
values.push(v);
sets.push(`${column} = $${values.length}`);
if (key === "posterImageUrl") {
values.push(v);
sets.push(`image_url = $${values.length}`);
}
}
}
if (sets.length === 0) {
if (sets.length === 0 && categoryIds === undefined && tagIds === undefined) {
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];
if (sets.length > 0) {
values.push(id);
const res = await query(
`UPDATE courses SET ${sets.join(", ")} WHERE id = $${values.length} RETURNING id`,
values,
);
if (res.rows.length === 0) return errorResponse("دوره یافت نشد", 404);
} else {
const exists = await getAdminCourseById(id);
if (!exists) return errorResponse("دوره یافت نشد", 404);
}
if (categoryIds !== undefined) {
await setCourseCategories(id, categoryIds);
}
if (tagIds !== undefined) {
await setCourseTags(id, tagIds);
}
const course = await getAdminCourseById(id);
revalidateSite();
return NextResponse.json({ ok: true, data: { ...rowToCourse(row), published: row.published } });
return NextResponse.json({ ok: true, data: course });
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "courses_slug_key") {
return errorResponse("این slug قبلاً استفاده شده است", 409);
@@ -117,4 +137,4 @@ export async function DELETE(
console.error("admin delete course error:", err);
return errorResponse("خطای سرور", 500);
}
}
}
+31 -15
View File
@@ -1,18 +1,23 @@
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";
import {
getAdminCourseById,
listAdminCourses,
} from "@/lib/data/admin/courses";
import {
setCourseCategories,
setCourseTags,
} from "@/lib/data/admin/taxonomy";
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);
@@ -25,6 +30,8 @@ export async function GET(request: NextRequest) {
const data = await listAdminCourses({
search: searchParams.get("search") ?? undefined,
published: published ?? undefined,
tag: searchParams.get("tag") ?? undefined,
category: searchParams.get("category") ?? undefined,
});
return NextResponse.json({ ok: true, data });
} catch (err) {
@@ -55,21 +62,30 @@ export async function POST(request: NextRequest) {
try {
await query(
`INSERT INTO courses
(id, slug, title, summary, category, duration_hours, format, price,
registration_url, poster_image_url, brochure_image_url, image_url, seo_description, tags, published)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)`,
(id, slug, title, summary, duration_hours, format, price,
registration_url, poster_image_url, brochure_image_url, image_url, seo_description, published)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`,
[
id, d.slug, d.title, d.summary, d.category, d.durationHours ?? null, d.format,
d.price ?? null, d.registrationUrl, d.posterImageUrl, d.brochureImageUrl, d.posterImageUrl, d.seoDescription, d.tags ?? [], d.published,
id,
d.slug,
d.title,
d.summary,
d.durationHours ?? null,
d.format,
d.price ?? null,
d.registrationUrl,
d.posterImageUrl,
d.brochureImageUrl,
d.posterImageUrl,
d.seoDescription,
d.published,
],
);
const res = await query<CourseRow>(`SELECT * FROM courses WHERE id = $1`, [id]);
const row = res.rows[0];
await setCourseCategories(id, d.categoryIds ?? []);
await setCourseTags(id, d.tagIds ?? []);
const course = await getAdminCourseById(id);
revalidateSite();
return NextResponse.json(
{ ok: true, data: { ...rowToCourse(row), published: row.published } },
{ status: 201 },
);
return NextResponse.json({ ok: true, data: course }, { status: 201 });
} catch (err) {
if (isUniqueViolation(err) && err.constraint === "courses_slug_key") {
return errorResponse("این slug قبلاً استفاده شده است", 409);
@@ -77,4 +93,4 @@ export async function POST(request: NextRequest) {
console.error("admin create course error:", err);
return errorResponse("خطای سرور", 500);
}
}
}
+7
View File
@@ -6,6 +6,7 @@ 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";
import { disabledAdminEntityResponse } from "@/lib/admin/disabled-entities";
export const dynamic = "force-dynamic";
@@ -24,6 +25,9 @@ export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const disabled = disabledAdminEntityResponse("events");
if (disabled) return disabled;
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
@@ -60,6 +64,9 @@ export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const disabled = disabledAdminEntityResponse("events");
if (disabled) return disabled;
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
+4
View File
@@ -5,11 +5,15 @@ 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";
import { disabledAdminEntityResponse } from "@/lib/admin/disabled-entities";
export const dynamic = "force-dynamic";
// POST /api/admin/events — create event (admin only)
export async function POST(request: NextRequest) {
const disabled = disabledAdminEntityResponse("events");
if (disabled) return disabled;
const session = await requireAdmin();
if (!session) return errorResponse("عدم دسترسی — ورود لازم است", 401);
+6 -7
View File
@@ -2,11 +2,11 @@ import { getTranslations } from "next-intl/server";
import { SiteFooter } from "@/components/organisms/SiteFooter";
import { SiteHeader } from "@/components/organisms/SiteHeader";
import { buildCourseNavChildren } from "@/lib/course-nav";
import { getCourses, listPublishedCourseTags } from "@/lib/data/courses";
import { getCourses } from "@/lib/data/courses";
import { listPublishedCourseTags } from "@/lib/data/taxonomy";
import { getPrograms } from "@/lib/data/programs";
import {
courseNavParentTag,
courseNavTagOrder,
professionalNav,
siteShortName,
} from "@/lib/site-config";
@@ -22,14 +22,13 @@ 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];
let navTags: Awaited<ReturnType<typeof listPublishedCourseTags>> = [];
try {
[courses, programs, courseTags] = await Promise.all([
[courses, programs, navTags] = await Promise.all([
getCourses(),
getPrograms(),
listPublishedCourseTags(),
listPublishedCourseTags({ navOnly: true }),
]);
if (courseTags.length === 0) courseTags = [...courseNavTagOrder];
} catch (err) {
console.error("[professional/layout] CMS fetch failed:", err);
}
@@ -38,7 +37,7 @@ export default async function ProfessionalLayout({
item.label === courseNavParentTag
? {
...item,
children: buildCourseNavChildren(courseTags),
children: buildCourseNavChildren(navTags),
}
: item,
);
+18 -7
View File
@@ -2,6 +2,10 @@ import type { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import { ProfessionalLandingTemplate } from "@/components/templates/ProfessionalLandingTemplate";
import { getCourses } from "@/lib/data/courses";
import {
listPublishedCourseCategories,
listPublishedCourseTags,
} from "@/lib/data/taxonomy";
import { getSiteStats, getTestimonials } from "@/lib/data/site";
import { courseJsonLd, JsonLd } from "@/lib/seo/json-ld";
@@ -23,16 +27,20 @@ export async function generateMetadata(): Promise<Metadata> {
export default async function ProfessionalPage({
searchParams,
}: {
searchParams: Promise<{ tag?: string }>;
searchParams: Promise<{ tag?: string; category?: string }>;
}) {
const t = await getTranslations();
const { tag: tagRaw } = await searchParams;
const { tag: tagRaw, category: categoryRaw } = await searchParams;
const initialTag = tagRaw?.trim() ?? "";
const [courses, stats, testimonials] = await Promise.all([
getCourses(),
getSiteStats(),
getTestimonials(),
]);
const initialCategory = categoryRaw?.trim() ?? "";
const [courses, stats, testimonials, filterCategories, filterTags] =
await Promise.all([
getCourses(),
getSiteStats(),
getTestimonials(),
listPublishedCourseCategories({ filterOnly: true }),
listPublishedCourseTags({ filterOnly: true }),
]);
return (
<>
@@ -56,7 +64,10 @@ export default async function ProfessionalPage({
courses={courses}
stats={stats}
testimonials={testimonials}
filterCategories={filterCategories}
filterTags={filterTags}
initialTag={initialTag}
initialCategory={initialCategory}
/>
</>
);
@@ -15,73 +15,94 @@ import {
CardHeader,
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 type { Course, TaxonomyRef } from "@/lib/types";
import {
courseCatalogHref,
courseCategoryHref,
courseTagHref,
} from "@/lib/course-nav";
import { formatCoursePrice, formatLabel } from "@/lib/labels";
import { cn } from "@/lib/utils";
export function CategoryCourseExplorer({
courses,
findLabel,
tagsLabel = "دسته‌بندی‌ها",
categoriesLabel = "دسته‌بندی‌ها",
tagsLabel = "تگ‌ها",
filterCategories,
filterTags,
initialTag = "",
initialCategory = "",
}: {
courses: Course[];
findLabel: string;
categoriesLabel?: string;
tagsLabel?: string;
/** From `/professional?tag=` — filters by course tag on first paint. */
filterCategories: TaxonomyRef[];
filterTags: TaxonomyRef[];
/** From `/professional?tag=` (slug). */
initialTag?: string;
/** From `/professional?category=` (slug). */
initialCategory?: string;
}) {
const router = useRouter();
const pathname = usePathname();
const [query, setQuery] = useState("");
const [category, setCategory] = useState("all");
const [tag, setTag] = useState(initialTag);
const [categorySlug, setCategorySlug] = useState(initialCategory);
const [tagSlug, setTagSlug] = useState(initialTag);
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
const selectTag = (next: string) => {
setTag(next);
const syncUrl = (nextTag: string, nextCategory: string) => {
if (pathname !== "/professional" && !pathname.startsWith("/professional")) {
return;
}
const href = next ? courseTagHref(next) : courseCatalogHref();
router.replace(href, { scroll: false });
const params = new URLSearchParams();
if (nextTag) params.set("tag", nextTag);
if (nextCategory) params.set("category", nextCategory);
const qs = params.toString();
router.replace(qs ? `/professional?${qs}` : courseCatalogHref(), {
scroll: false,
});
};
// Distinct tags across all courses (stable order: most used first).
const tags = useMemo(() => {
const counts = new Map<string, number>();
for (const course of courses) {
for (const t of course.tags ?? []) {
counts.set(t, (counts.get(t) ?? 0) + 1);
}
}
return [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([t]) => t);
}, [courses]);
const selectTag = (slug: string) => {
const next = tagSlug === slug ? "" : slug;
setTagSlug(next);
syncUrl(next, categorySlug);
};
const selectCategory = (slug: string) => {
const next = categorySlug === slug ? "" : slug;
setCategorySlug(next);
syncUrl(tagSlug, next);
};
const filtered = useMemo(() => {
return courses.filter((course) => {
const matchesCategory =
category === "all" ||
category === "best" ||
course.category === category;
const matchesTag = !tag || (course.tags ?? []).includes(tag);
!categorySlug ||
course.categories.some((c) => c.slug === categorySlug);
const matchesTag =
!tagSlug || course.tags.some((t) => t.slug === tagSlug);
const matchesQuery =
!deferredQuery ||
course.title.includes(deferredQuery) ||
course.summary.includes(deferredQuery);
return matchesCategory && matchesTag && matchesQuery;
});
}, [courses, category, tag, deferredQuery]);
}, [courses, categorySlug, tagSlug, deferredQuery]);
const resetFilters = () => {
setCategory("all");
setCategorySlug("");
setTagSlug("");
setQuery("");
selectTag("");
syncUrl("", "");
};
const activeCategory = filterCategories.find((c) => c.slug === categorySlug);
const activeTag = filterTags.find((t) => t.slug === tagSlug);
return (
<div className="space-y-8">
<form
@@ -104,31 +125,55 @@ export function CategoryCourseExplorer({
</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",
)}
{filterCategories.length > 0 ? (
<div className="space-y-3">
<span className="text-sm font-semibold text-background/80">
{categoriesLabel}
</span>
<div
className="flex flex-wrap gap-2"
role="tablist"
aria-label={categoriesLabel}
>
{item.label}
</Button>
))}
</div>
<Button
type="button"
role="tab"
size="sm"
variant={categorySlug === "" ? "default" : "ghost"}
aria-selected={categorySlug === ""}
onClick={() => {
setCategorySlug("");
syncUrl(tagSlug, "");
}}
className={cn(
categorySlug !== "" &&
"bg-background/10 text-background/85 hover:bg-background/20 hover:text-background",
)}
>
همه
</Button>
{filterCategories.map((item) => (
<Button
key={item.id}
type="button"
role="tab"
size="sm"
variant={categorySlug === item.slug ? "default" : "ghost"}
aria-selected={categorySlug === item.slug}
onClick={() => selectCategory(item.slug)}
className={cn(
categorySlug !== item.slug &&
"bg-background/10 text-background/85 hover:bg-background/20 hover:text-background",
)}
>
{item.label}
</Button>
))}
</div>
</div>
) : null}
{tags.length > 0 ? (
{filterTags.length > 0 ? (
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm font-semibold text-background/80">
@@ -137,75 +182,100 @@ export function CategoryCourseExplorer({
<Button
type="button"
size="sm"
variant={tag === "" ? "default" : "ghost"}
aria-selected={tag === ""}
onClick={() => selectTag("")}
variant={tagSlug === "" ? "default" : "ghost"}
aria-selected={tagSlug === ""}
onClick={() => {
setTagSlug("");
syncUrl("", categorySlug);
}}
className={cn(
tag !== "" &&
tagSlug !== "" &&
"bg-background/10 text-background/85 hover:bg-background/20 hover:text-background",
)}
>
همه
</Button>
{tags.map((item) => (
{filterTags.map((item) => (
<Button
key={item}
key={item.id}
type="button"
size="sm"
variant={tag === item ? "default" : "ghost"}
aria-selected={tag === item}
onClick={() => selectTag(tag === item ? "" : item)}
variant={tagSlug === item.slug ? "default" : "ghost"}
aria-selected={tagSlug === item.slug}
onClick={() => selectTag(item.slug)}
className={cn(
tag !== item &&
tagSlug !== item.slug &&
"bg-background/10 text-background/85 hover:bg-background/20 hover:text-background",
)}
>
{item}
{item.label}
</Button>
))}
</div>
{(tag !== "" || category !== "all") && (
<div className="flex flex-wrap items-center gap-2 text-xs text-background/60">
<span>فیلترهای فعال:</span>
{category !== "all" && (
<Badge variant="secondary" className="gap-1 py-0.5 pe-1">
{courseCategories.find((c) => c.id === category)?.label ?? category}
<button
type="button"
onClick={() => setCategory("all")}
className="rounded-full p-0.5 hover:bg-foreground/10"
aria-label="حذف فیلتر دسته‌بندی"
>
×
</button>
</Badge>
)}
{tag !== "" && (
<Badge variant="secondary" className="gap-1 py-0.5 pe-1">
{tag}
<button
type="button"
onClick={() => selectTag("")}
className="rounded-full p-0.5 hover:bg-foreground/10"
aria-label="حذف فیلتر تگ"
>
×
</button>
</Badge>
)}
<button
type="button"
onClick={resetFilters}
className="underline underline-offset-4 hover:text-background"
>
پاک‌کردن همه
</button>
</div>
)}
</div>
) : null}
{(tagSlug !== "" || categorySlug !== "") && (
<div className="flex flex-wrap items-center gap-2 text-xs text-background/60">
<span>فیلترهای فعال:</span>
{activeCategory ? (
<Badge variant="secondary" className="gap-1 py-0.5 pe-1">
{activeCategory.label}
<button
type="button"
onClick={() => {
setCategorySlug("");
syncUrl(tagSlug, "");
}}
className="rounded-full p-0.5 hover:bg-foreground/10"
aria-label="حذف فیلتر دسته"
>
×
</button>
</Badge>
) : null}
{activeTag ? (
<Badge variant="secondary" className="gap-1 py-0.5 pe-1">
{activeTag.label}
<button
type="button"
onClick={() => {
setTagSlug("");
syncUrl("", categorySlug);
}}
className="rounded-full p-0.5 hover:bg-foreground/10"
aria-label="حذف فیلتر تگ"
>
×
</button>
</Badge>
) : null}
<button
type="button"
onClick={resetFilters}
className="underline underline-offset-4 hover:text-background"
>
پاک‌کردن همه
</button>
{activeTag ? (
<Link
href={courseTagHref(activeTag.slug)}
className="sr-only"
>
{activeTag.label}
</Link>
) : null}
{activeCategory ? (
<Link
href={courseCategoryHref(activeCategory.slug)}
className="sr-only"
>
{activeCategory.label}
</Link>
) : null}
</div>
)}
{filtered.length === 0 ? (
<p className="py-10 text-center text-sm text-background/60">
دوره‌ای با این فیلترها یافت نشد.
@@ -247,19 +317,28 @@ export function CategoryCourseExplorer({
<CardDescription className="line-clamp-3 text-background/70">
{course.summary}
</CardDescription>
{course.tags && course.tags.length > 0 ? (
{(course.categories.length > 0 || course.tags.length > 0) && (
<div className="flex flex-wrap gap-1.5">
{course.tags.map((t) => (
{course.categories.map((c) => (
<Badge
key={t}
key={`cat:${c.id}`}
variant="outline"
className="border-background/25 text-[10px] text-background/80"
>
{t}
{c.label}
</Badge>
))}
{course.tags.map((t) => (
<Badge
key={`tag:${t.id}`}
variant="outline"
className="border-background/25 text-[10px] text-background/80"
>
{t.label}
</Badge>
))}
</div>
) : null}
)}
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-background/55">
<span>
{course.durationHours
@@ -286,4 +365,4 @@ export function CategoryCourseExplorer({
)}
</div>
);
}
}
+7 -6
View File
@@ -73,7 +73,7 @@ function NavDropdown({
</DropdownMenuTrigger>
<DropdownMenuContent className="z-[60] w-56 p-1" align="start">
{children.map((child) => (
<DropdownMenuItem key={child.href + child.label} className="p-0">
<DropdownMenuItem key={`nav:${child.href}:${child.label}`} className="p-0">
<Link
href={child.href}
className="w-full cursor-pointer px-1.5 py-1.5"
@@ -153,10 +153,11 @@ export function SiteHeader({
aria-label="منوی اصلی"
>
{items.map((item) => {
const itemKey = `nav:${item.href}:${item.label}`;
if (item.children && item.children.length > 0) {
return (
<NavDropdown
key={item.href + item.label}
key={itemKey}
item={item}
isDark={isDark}
/>
@@ -164,7 +165,7 @@ export function SiteHeader({
}
return item.prominent ? (
<NavLink
key={item.href + item.label}
key={itemKey}
item={item}
isDark={isDark}
className={cn(
@@ -176,7 +177,7 @@ export function SiteHeader({
/>
) : (
<NavLink
key={item.href + item.label}
key={itemKey}
item={item}
isDark={isDark}
className={cn(
@@ -260,7 +261,7 @@ export function SiteHeader({
<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}>
<li key={`nav:${item.href}:${item.label}`}>
{item.children && item.children.length > 0 ? (
<div className="py-2">
<p className="text-sm font-semibold text-background/55">
@@ -268,7 +269,7 @@ export function SiteHeader({
</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}>
<li key={`nav:${child.href}:${child.label}`}>
<NavLink
item={child}
isDark
+61 -40
View File
@@ -33,6 +33,7 @@ import {
} from "@/components/ui/sidebar";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { LogoutButton } from "@/components/organisms/admin/LogoutButton";
import { isAdminEntityEnabled } from "@/lib/admin/disabled-entities";
const NAV_GROUPS = [
{
@@ -42,27 +43,39 @@ const NAV_GROUPS = [
{
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 },
{ href: "/admin/courses", label: "دوره‌ها", icon: BookOpen, entity: "courses" },
{
href: "/admin/course-categories",
label: "دسته‌بندی دوره‌ها",
icon: Tags,
entity: "course-categories",
},
{
href: "/admin/course-tags",
label: "تگ‌های دوره",
icon: Tags,
entity: "course-tags",
},
{ href: "/admin/programs", label: "برنامه‌ها", icon: GraduationCap, entity: "programs" },
{ href: "/admin/events", label: "رویدادها", icon: Calendar, entity: "events" },
{ href: "/admin/articles", label: "مقالات", icon: Newspaper, entity: "articles" },
{ href: "/admin/topics", label: "موضوعات", icon: Tags, entity: "topics" },
],
},
{
label: "جامعه",
items: [
{ href: "/admin/faculty", label: "اساتید", icon: Users },
{ href: "/admin/alumni", label: "دانش‌آموختگان", icon: MessageSquareQuote },
{ href: "/admin/faculty", label: "اساتید", icon: Users, entity: "faculty" },
{ href: "/admin/alumni", label: "دانش‌آموختگان", icon: MessageSquareQuote, entity: "alumni" },
],
},
{
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 },
{ href: "/admin/banners", label: "بنرهای کمپین", icon: Megaphone, entity: "banners" },
{ href: "/admin/stats", label: "آمار", icon: BarChart3, entity: "stats" },
{ href: "/admin/testimonials", label: "نظرات", icon: FileText, entity: "testimonials" },
{ href: "/admin/legal", label: "صفحات قانونی", icon: Scale, entity: "legal" },
],
},
{
@@ -117,35 +130,43 @@ export function AdminSidebar({ userName }: { userName: string }) {
</SidebarHeader>
<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>
))}
{NAV_GROUPS.map((group) => {
const items = group.items.filter(
(item) =>
!("entity" in item) ||
isAdminEntityEnabled(item.entity),
);
if (items.length === 0) return null;
return (
<SidebarGroup key={group.label}>
<SidebarGroupLabel>{group.label}</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
{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">
@@ -12,11 +12,17 @@ import {
SelectValue,
} from "@/components/ui/select";
function buildUrl(search: string, published: string, tag: string) {
function buildUrl(
search: string,
published: string,
tag: string,
category: string,
) {
const params = new URLSearchParams();
if (search.trim()) params.set("search", search.trim());
if (published && published !== "all") params.set("published", published);
if (tag && tag.trim()) params.set("tag", tag.trim());
if (category && category.trim()) params.set("category", category.trim());
const qs = params.toString();
return qs ? `/admin/courses?${qs}` : "/admin/courses";
}
@@ -25,36 +31,47 @@ export function CourseFilters({
initialSearch,
initialPublished,
initialTag,
initialCategory,
availableTags,
availableCategories,
}: {
initialSearch: string;
initialPublished: string;
initialTag: string;
availableTags: string[];
initialCategory: string;
availableTags: { id: string; slug: string; label: string }[];
availableCategories: { id: string; slug: string; label: string }[];
}) {
const router = useRouter();
const [search, setSearch] = useState(initialSearch);
const [published, setPublished] = useState(initialPublished);
const [tag, setTag] = useState(initialTag);
const hasFilters = Boolean(search.trim()) || published !== "all" || Boolean(tag.trim());
const [category, setCategory] = useState(initialCategory);
const hasFilters =
Boolean(search.trim()) ||
published !== "all" ||
Boolean(tag.trim()) ||
Boolean(category.trim());
function apply(e: React.FormEvent) {
e.preventDefault();
router.push(buildUrl(search, published, tag));
router.push(buildUrl(search, published, tag, category));
}
function clear() {
setSearch("");
setPublished("all");
setTag("");
setCategory("");
router.push("/admin/courses");
}
return (
<form onSubmit={apply} className="flex flex-wrap items-end gap-3">
{/* ... search input ... */}
<div className="w-full max-w-xs space-y-1.5">
<label htmlFor="course-search" className="text-sm font-medium">جستجو</label>
<label htmlFor="course-search" className="text-sm font-medium">
جستجو
</label>
<Input
id="course-search"
placeholder="عنوان یا اسلاگ..."
@@ -63,10 +80,14 @@ export function CourseFilters({
/>
</div>
{/* ... published select ... */}
<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")}>
<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>
@@ -78,26 +99,50 @@ export function CourseFilters({
</Select>
</div>
{/* ... tag select ... */}
<div className="w-full max-w-[12rem] space-y-1.5">
<label htmlFor="course-tag" className="text-sm font-medium">تگ</label>
<Select value={tag} onValueChange={(v) => setTag(v ?? "")}>
<label htmlFor="course-category" className="text-sm font-medium">
دسته
</label>
<Select value={category || "all"} onValueChange={(v) => setCategory(v === "all" ? "" : (v ?? ""))}>
<SelectTrigger id="course-category" className="w-full">
<SelectValue placeholder="همه" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">همه</SelectItem>
{availableCategories.map((c) => (
<SelectItem key={c.id} value={c.slug}>
{c.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="w-full max-w-[12rem] space-y-1.5">
<label htmlFor="course-tag" className="text-sm font-medium">
تگ
</label>
<Select value={tag || "all"} onValueChange={(v) => setTag(v === "all" ? "" : (v ?? ""))}>
<SelectTrigger id="course-tag" className="w-full">
<SelectValue placeholder="همه" />
</SelectTrigger>
<SelectContent>
<SelectItem value="">همه</SelectItem>
<SelectItem value="all">همه</SelectItem>
{availableTags.map((t) => (
<SelectItem key={t} value={t}>{t}</SelectItem>
<SelectItem key={t.id} value={t.slug}>
{t.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Button type="submit">اعمال فیلتر</Button>
{hasFilters && (
<Button type="button" variant="ghost" onClick={clear}>پاک‌کردن فیلترها</Button>
)}
{hasFilters ? (
<Button type="button" variant="ghost" onClick={clear}>
پاک‌کردن فیلترها
</Button>
) : null}
</form>
);
}
}
@@ -17,19 +17,17 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Plus, X } from "lucide-react";
import type { AdminCourse } from "@/lib/data/admin/courses";
import type { AdminCourseCategory, AdminCourseTag } from "@/lib/data/admin/taxonomy";
import { AdminFormCard } from "@/components/organisms/admin/AdminPage";
import { ImageUploadField } from "@/components/organisms/admin/ImageUploadField";
import { courseNavTagOrder } from "@/lib/site-config";
const SUGGESTED_TAGS = courseNavTagOrder;
type Payload = {
slug: string;
title: string;
summary: string;
category: string;
categoryIds: string[];
tagIds: string[];
durationHours: number | null;
format: string;
price: number | null;
@@ -37,22 +35,28 @@ type Payload = {
posterImageUrl: string;
brochureImageUrl: string;
seoDescription: string;
tags: string[];
published: boolean;
};
interface CourseFormProps {
initial?: AdminCourse;
categories: AdminCourseCategory[];
tags: AdminCourseTag[];
}
export function CourseForm({ initial }: CourseFormProps) {
function toggleId(ids: string[], id: string): string[] {
return ids.includes(id) ? ids.filter((x) => x !== id) : [...ids, id];
}
export function CourseForm({ initial, categories, tags }: 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",
categoryIds: initial?.categoryIds ?? [],
tagIds: initial?.tagIds ?? [],
durationHours: initial?.durationHours ?? null,
format: initial?.format ?? "in-person",
price: initial?.price ?? null,
@@ -60,13 +64,11 @@ export function CourseForm({ initial }: CourseFormProps) {
posterImageUrl: initial?.posterImageUrl ?? "",
brochureImageUrl: initial?.brochureImageUrl ?? "",
seoDescription: initial?.seoDescription ?? "",
tags: initial?.tags ?? [],
published: initial?.published ?? true,
});
const [priceInput, setPriceInput] = useState(
initial?.price != null ? String(initial.price) : "",
);
const [customTagInput, setCustomTagInput] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
@@ -74,29 +76,6 @@ export function CourseForm({ initial }: CourseFormProps) {
setForm((f) => ({ ...f, [key]: value }));
}
function toggleTag(tag: string) {
setForm((f) => {
const exists = f.tags.includes(tag);
return {
...f,
tags: exists ? f.tags.filter((t) => t !== tag) : [...f.tags, tag],
};
});
}
function addCustomTag() {
const trimmed = customTagInput.trim();
if (!trimmed) return;
if (!form.tags.includes(trimmed)) {
set("tags", [...form.tags, trimmed]);
}
setCustomTagInput("");
}
function removeTag(tagToRemove: string) {
set("tags", form.tags.filter((t) => t !== tagToRemove));
}
function onPriceChange(raw: string) {
setPriceInput(raw);
const trimmed = raw.trim();
@@ -137,7 +116,7 @@ export function CourseForm({ initial }: CourseFormProps) {
<form onSubmit={handleSubmit}>
<AdminFormCard
title={isEdit ? "ویرایش دوره" : "ثبت دوره جدید"}
description="فیلدهای ستاره‌دار الزامی‌اند. قیمت اختیاری است."
description="فیلدهای ستاره‌دار الزامی‌اند. دسته و تگ از فهرست ادمین انتخاب می‌شوند."
footer={
<>
<Button type="submit" disabled={loading}>
@@ -152,284 +131,287 @@ export function CourseForm({ initial }: CourseFormProps) {
</>
}
>
<div className="space-y-8">
{error ? (
<p
className="mb-6 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive"
role="alert"
>
<p className="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">
شناسه، عنوان و خلاصهٔ نمایشی دوره
<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)}
required
placeholder="ai-fluency"
/>
</div>
<div className="space-y-1.5 sm:col-span-2">
<Label htmlFor="title">عنوان *</Label>
<Input
id="title"
value={form.title}
onChange={(e) => set("title", e.target.value)}
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)}
required
rows={3}
/>
</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="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) => {
const raw = e.target.value;
set("durationHours", raw === "" ? null : Number(raw));
}}
placeholder="اختیاری"
/>
</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="خالی = بدون نمایش قیمت"
/>
</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="space-y-2">
<Label>دسته‌بندی‌ها</Label>
{categories.length === 0 ? (
<p className="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 className="flex flex-wrap gap-2">
{categories.map((item) => {
const active = form.categoryIds.includes(item.id);
return (
<Button
key={item.id}
type="button"
size="sm"
variant={active ? "default" : "outline"}
aria-pressed={active}
onClick={() => set("categoryIds", toggleId(form.categoryIds, item.id))}
className="h-8 px-3 text-xs"
>
{item.label}
</Button>
);
})}
</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="technology">هوش مصنوعی و تحول سازمان</SelectItem>
<SelectItem value="digital">برند و بازاریابی</SelectItem>
<SelectItem value="innovation">برندینگ</SelectItem>
<SelectItem value="leadership">هم‌اندیشی مدیریتی</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) => {
const raw = e.target.value;
set(
"durationHours",
raw === "" ? null : Number(raw),
);
}}
placeholder="اختیاری"
/>
</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">
برچسب‌هایی که دوره در فیلترها و دسته‌بندی سایت نمایش داده می‌شود (مثلاً کارگاه‌ها، دوره‌های سازمانی، گزیده دوره‌های برگزارشده)
</p>
</div>
<div className="space-y-3">
<div>
<Label className="text-xs text-muted-foreground">تگ‌های پیشنهادی</Label>
<div className="mt-2 flex flex-wrap gap-2">
{SUGGESTED_TAGS.map((tag) => {
const active = form.tags.includes(tag);
return (
<Button
key={tag}
)}
{form.categoryIds.length > 0 ? (
<div className="flex flex-wrap gap-1.5 pt-1">
{form.categoryIds.map((id) => {
const item = categories.find((c) => c.id === id);
return (
<Badge key={id} variant="secondary" className="gap-1 py-1 pe-1">
{item?.label ?? id}
<button
type="button"
size="sm"
variant={active ? "default" : "outline"}
aria-pressed={active}
onClick={() => toggleTag(tag)}
className="h-8 px-3 text-xs"
onClick={() =>
set(
"categoryIds",
form.categoryIds.filter((x) => x !== id),
)
}
className="rounded-full p-0.5 hover:bg-foreground/10"
aria-label="حذف دسته"
>
{tag}
</Button>
);
})}
</div>
×
</button>
</Badge>
);
})}
</div>
) : null}
</div>
<div className="flex items-end gap-2">
<div className="flex-1 space-y-1.5">
<Label htmlFor="newTag">افزودن تگ دلخواه</Label>
<Input
id="newTag"
value={customTagInput}
onChange={(e) => setCustomTagInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
addCustomTag();
}
}}
placeholder="مثلاً دوره‌های ویژه مدیران"
/>
</div>
<Button
type="button"
variant="outline"
onClick={addCustomTag}
className="shrink-0"
>
<Plus className="size-4" />
افزودن
</Button>
</div>
<div className="space-y-1.5">
<Label className="text-xs text-muted-foreground">
تگ‌های این دوره ({form.tags.length})
</Label>
{form.tags.length > 0 ? (
<div className="flex flex-wrap gap-1.5">
{form.tags.map((tag) => (
<Badge key={tag} variant="secondary" className="gap-1 py-1 pe-1">
{tag}
<button
type="button"
onClick={() => removeTag(tag)}
className="rounded-full p-0.5 transition-colors hover:bg-foreground/10"
aria-label={`حذف تگ ${tag}`}
>
<X className="size-3" />
</button>
</Badge>
))}
</div>
) : (
<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 و وضعیت انتشار
<div className="space-y-2">
<Label>تگ‌ها</Label>
{tags.length === 0 ? (
<p className="text-xs text-muted-foreground">
هنوز تگی تعریف نشده. از «تگ‌های دوره» اضافه کنید.
</p>
) : (
<div className="flex flex-wrap gap-2">
{tags.map((item) => {
const active = form.tagIds.includes(item.id);
return (
<Button
key={item.id}
type="button"
size="sm"
variant={active ? "default" : "outline"}
aria-pressed={active}
onClick={() => set("tagIds", toggleId(form.tagIds, item.id))}
className="h-8 px-3 text-xs"
>
{item.label}
</Button>
);
})}
</div>
)}
{form.tagIds.length > 0 ? (
<div className="flex flex-wrap gap-1.5 pt-1">
{form.tagIds.map((id) => {
const item = tags.find((t) => t.id === id);
return (
<Badge key={id} variant="secondary" className="gap-1 py-1 pe-1">
{item?.label ?? id}
<button
type="button"
onClick={() =>
set(
"tagIds",
form.tagIds.filter((x) => x !== id),
)
}
className="rounded-full p-0.5 hover:bg-foreground/10"
aria-label="حذف تگ"
>
×
</button>
</Badge>
);
})}
</div>
) : null}
</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)}
required
/>
</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="posterImageUrl">پوستر (نمایش در لیست دوره‌ها)</Label>
<ImageUploadField
id="posterImageUrl"
value={form.posterImageUrl}
onChange={(url) => set("posterImageUrl", url)}
folder="courses"
disabled={loading}
/>
</div>
<div className="space-y-1.5 sm:col-span-2">
<Label htmlFor="brochureImageUrl">بروشور (نمایش در صفحه جزئیات)</Label>
<ImageUploadField
id="brochureImageUrl"
value={form.brochureImageUrl}
onChange={(url) => set("brochureImageUrl", url)}
folder="courses"
disabled={loading}
/>
</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 className="space-y-1.5 sm:col-span-2">
<Label>پوستر</Label>
<ImageUploadField
id="posterImageUrl"
value={form.posterImageUrl}
onChange={(url) => set("posterImageUrl", url)}
folder="courses"
/>
</div>
</section>
<div className="space-y-1.5 sm:col-span-2">
<Label>بروشور</Label>
<ImageUploadField
id="brochureImageUrl"
value={form.brochureImageUrl}
onChange={(url) => set("brochureImageUrl", url)}
folder="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={3}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="published">وضعیت انتشار</Label>
<Select
value={form.published ? "true" : "false"}
onValueChange={(v) => set("published", v === "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>
);
}
}
@@ -9,7 +9,7 @@ import {
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import type { AdminCourse } from "@/lib/data/admin/courses";
import { categoryLabel, formatCoursePrice, formatLabel } from "@/lib/labels";
import { formatCoursePrice, formatLabel } from "@/lib/labels";
import { PublishToggle } from "@/components/organisms/admin/courses/PublishToggle";
import { DeleteCourseDialog } from "@/components/organisms/admin/courses/DeleteCourseDialog";
@@ -44,18 +44,32 @@ export function CourseTable({ courses }: { courses: AdminCourse[] }) {
<TableRow key={course.id}>
<TableCell className="font-medium">
<div>{course.title}</div>
{course.tags && course.tags.length > 0 ? (
{course.tags.length > 0 ? (
<div className="mt-1 flex flex-wrap gap-1">
{course.tags.map((tag) => (
<Badge key={tag} variant="outline" className="text-[10px] px-1.5 py-0">
{tag}
<Badge
key={`tag:${tag.id}`}
variant="outline"
className="px-1.5 py-0 text-[10px]"
>
{tag.label}
</Badge>
))}
</div>
) : null}
</TableCell>
<TableCell>
<Badge variant="secondary">{categoryLabel(course.category)}</Badge>
<div className="flex flex-wrap gap-1">
{course.categories.length > 0 ? (
course.categories.map((cat) => (
<Badge key={`cat:${cat.id}`} variant="secondary">
{cat.label}
</Badge>
))
) : (
<span className="text-muted-foreground">—</span>
)}
</div>
</TableCell>
<TableCell className="text-muted-foreground">
{formatLabel(course.format)}
@@ -94,4 +108,4 @@ export function CourseTable({ courses }: { courses: AdminCourse[] }) {
</Table>
</div>
);
}
}
@@ -7,11 +7,7 @@ import { PageHero } from "@/components/molecules/PageHero";
import { CourseRegisterGate } from "@/components/organisms/CourseRegisterGate";
import { Separator } from "@/components/ui/separator";
import type { Course } from "@/lib/types";
import {
categoryLabel,
formatCoursePrice,
formatLabel,
} from "@/lib/labels";
import { formatCoursePrice, formatLabel } from "@/lib/labels";
import { JsonLd, courseJsonLd } from "@/lib/seo/json-ld";
export type CourseDetailLabels = {
@@ -40,11 +36,13 @@ export function CourseDetailTemplate({
labels: CourseDetailLabels;
}) {
const priceLabel = formatCoursePrice(course.price);
const categoryText =
course.categories.map((c) => c.label).join(" · ") || "—";
const specs = [
{
icon: Tag,
label: labels.category,
value: categoryLabel(course.category),
value: categoryText,
},
{
icon: Layers,
@@ -77,7 +75,11 @@ export function CourseDetailTemplate({
<PageHero
title={course.title}
intro={course.summary}
eyebrow={categoryLabel(course.category)}
eyebrow={
course.categories[0]?.label ??
course.tags[0]?.label ??
undefined
}
imageUrl={course.posterImageUrl}
/>
@@ -7,7 +7,7 @@ import { Section } from "@/components/atoms/Section";
import { QuoteBlock } from "@/components/molecules/Cards";
import { SurfaceCard } from "@/components/molecules/SurfaceCard";
import { CategoryCourseExplorer } from "@/components/organisms/CategoryCourseExplorer";
import type { Course, SiteStat, Testimonial } from "@/lib/types";
import type { Course, SiteStat, TaxonomyRef, Testimonial } from "@/lib/types";
import { AnimatedMetric } from "@/components/atoms/AnimatedMetric";
export function ProfessionalLandingTemplate({
@@ -15,7 +15,10 @@ export function ProfessionalLandingTemplate({
courses,
stats,
testimonials,
filterCategories,
filterTags,
initialTag = "",
initialCategory = "",
}: {
labels: {
pathways: string;
@@ -33,7 +36,10 @@ export function ProfessionalLandingTemplate({
courses: Course[];
stats: SiteStat[];
testimonials: Testimonial[];
filterCategories: TaxonomyRef[];
filterTags: TaxonomyRef[];
initialTag?: string;
initialCategory?: string;
}) {
return (
<main id="main-content">
@@ -102,10 +108,13 @@ export function ProfessionalLandingTemplate({
{labels.pathways}
</p>
<CategoryCourseExplorer
key={initialTag || "all"}
key={`${initialTag}|${initialCategory}`}
courses={courses}
findLabel={labels.findProgram}
filterCategories={filterCategories}
filterTags={filterTags}
initialTag={initialTag}
initialCategory={initialCategory}
/>
</Container>
</Section>
+23
View File
@@ -0,0 +1,23 @@
import { errorResponse } from "@/lib/api/response";
/**
* Admin entities temporarily hidden from the panel (nav, dashboard, pages, APIs).
* Code and DB remain intact — remove a key from this set to re-enable.
*
* Matches public-site temporary hide: articles (insights), events, alumni.
*/
export const DISABLED_ADMIN_ENTITIES = new Set([
"articles",
"events",
"alumni",
]);
export function isAdminEntityEnabled(key: string): boolean {
return !DISABLED_ADMIN_ENTITIES.has(key);
}
/** For Route Handlers: 404 while the feature is paused. */
export function disabledAdminEntityResponse(key: string) {
if (isAdminEntityEnabled(key)) return null;
return errorResponse("این بخش فعلاً غیرفعال است", 404);
}
+77
View File
@@ -25,6 +25,12 @@ import {
listAdminTestimonials,
listAdminTopics,
} from "@/lib/data/admin/cms";
import {
getAdminCourseCategoryById,
getAdminCourseTagById,
listAdminCourseCategories,
listAdminCourseTags,
} from "@/lib/data/admin/taxonomy";
export type AdminFieldType =
| "text"
@@ -435,6 +441,77 @@ export const ENTITIES: Record<string, AdminEntitySpec> = {
list: listAdminTestimonials,
get: getAdminTestimonialById,
},
"course-categories": {
key: "course-categories",
navLabel: "دسته‌بندی دوره‌ها",
noun: "دسته",
apiPath: "/api/admin/course-categories",
idColumn: "id",
searchCols: ["label", "slug"],
searchHint: "عنوان یا اسلاگ",
hasPublished: true,
fields: [
{ name: "slug", label: "اسلاگ", type: "text", required: true, placeholder: "technology" },
{ name: "label", label: "عنوان", type: "text", required: true },
{ name: "sortOrder", label: "ترتیب", type: "number", defaultValue: 0 },
{
name: "showInFilter",
label: "نمایش در فیلتر سایت",
type: "boolean",
defaultValue: true,
options: yesNo,
},
publishedField,
],
columns: [
{ name: "label", label: "عنوان" },
{ name: "slug", label: "اسلاگ" },
{ name: "sortOrder", label: "ترتیب" },
publishedCol,
],
list: listAdminCourseCategories,
get: getAdminCourseCategoryById,
},
"course-tags": {
key: "course-tags",
navLabel: "تگ‌های دوره",
noun: "تگ",
apiPath: "/api/admin/course-tags",
idColumn: "id",
searchCols: ["label", "slug"],
searchHint: "عنوان یا اسلاگ",
hasPublished: true,
fields: [
{ name: "slug", label: "اسلاگ", type: "text", required: true, placeholder: "workshops" },
{ name: "label", label: "عنوان", type: "text", required: true },
{ name: "sortOrder", label: "ترتیب", type: "number", defaultValue: 0 },
{
name: "showInNav",
label: "نمایش در منوی سایت",
type: "boolean",
defaultValue: true,
options: yesNo,
},
{
name: "showInFilter",
label: "نمایش در فیلتر سایت",
type: "boolean",
defaultValue: true,
options: yesNo,
},
publishedField,
],
columns: [
{ name: "label", label: "عنوان" },
{ name: "slug", label: "اسلاگ" },
{ name: "sortOrder", label: "ترتیب" },
publishedCol,
],
list: listAdminCourseTags,
get: getAdminCourseTagById,
},
};
/** Stable insertion order for nav/menus. */
+23 -45
View File
@@ -1,71 +1,49 @@
import type { NavItem } from "@/lib/types";
import {
courseNavParentTag,
courseNavTagOrder,
homeNav,
} from "@/lib/site-config";
import type { NavItem, TaxonomyRef } from "@/lib/types";
import { courseNavParentTag, 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)}`;
/** Deep-link filtered by tag slug. */
export function courseTagHref(slug: string): string {
return `/professional?tag=${encodeURIComponent(slug)}`;
}
/**
* 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;
/** Deep-link filtered by category slug. */
export function courseCategoryHref(slug: string): string {
return `/professional?category=${encodeURIComponent(slug)}`;
}
/** Build dropdown children: parent (all) + one item per tag. */
export function buildCourseNavChildren(tags: string[]): NavItem[] {
const children: NavItem[] = [
/** Build dropdown children: parent (all) + one item per nav tag. */
export function buildCourseNavChildren(
tags: Pick<TaxonomyRef, "slug" | "label">[],
): NavItem[] {
return [
{ label: "همه دوره‌ها", href: courseCatalogHref() },
...orderCourseNavTags(tags).map((tag) => ({
label: tag,
href: courseTagHref(tag),
})),
...tags
.filter((tag) => typeof tag.slug === "string" && typeof tag.label === "string")
.map((tag) => ({
label: tag.label,
href: courseTagHref(tag.slug),
})),
];
return children;
}
/**
* Home nav with a single courses dropdown whose items come from published
* course tags. Parent label is `courseNavParentTag` in site-config.
* nav tags. Parent label is `courseNavParentTag` in site-config.
*/
export function buildHomeNavWithCourseTags(tags: string[]): NavItem[] {
export function buildHomeNavWithCourseTags(
tags: Pick<TaxonomyRef, "slug" | "label">[],
): 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];
+47 -18
View File
@@ -1,47 +1,76 @@
import { query } from "@/lib/db";
import type { Course } from "@/lib/types";
import { rowToCourse, type CourseRow } from "@/lib/db/mappers";
import { COURSE_WITH_TAXONOMY_SELECT } from "@/lib/data/course-taxonomy-sql";
import { listAdminCourseTags } from "@/lib/data/admin/taxonomy";
/** Course as returned to admin (includes rows that are not yet published). */
export interface AdminCourse extends Course {
published: boolean;
categoryIds: string[];
tagIds: string[];
}
function toAdminCourse(row: CourseRow): AdminCourse {
return { ...rowToCourse(row), published: row.published };
const course = rowToCourse(row);
return {
...course,
published: row.published,
categoryIds: course.categories.map((c) => c.id),
tagIds: course.tags.map((t) => t.id),
};
}
export async function listAdminCourses(opts?: {
search?: string;
published?: boolean;
tag?: string;
category?: string;
}): Promise<AdminCourse[]> {
const search = opts?.search?.trim() ?? "";
const published = opts?.published ?? null;
const tag = opts?.tag?.trim() ?? "";
const category = opts?.category?.trim() ?? "";
const res = await query<CourseRow>(
`SELECT * FROM courses
WHERE ($1 = '' OR title ILIKE '%' || $1 || '%' OR slug ILIKE '%' || $1 || '%')
AND ($2::boolean IS NULL OR published = $2)
AND ($3 = '' OR $3 = ANY(tags))
ORDER BY updated_at DESC`,
[search, published, tag],
`${COURSE_WITH_TAXONOMY_SELECT}
WHERE ($1 = '' OR c.title ILIKE '%' || $1 || '%' OR c.slug ILIKE '%' || $1 || '%')
AND ($2::boolean IS NULL OR c.published = $2)
AND (
$3 = ''
OR EXISTS (
SELECT 1 FROM course_tag_links l
JOIN course_tags t ON t.id = l.tag_id
WHERE l.course_id = c.id AND (t.slug = $3 OR t.id = $3 OR t.label = $3)
)
)
AND (
$4 = ''
OR EXISTS (
SELECT 1 FROM course_category_links l
JOIN course_categories cat ON cat.id = l.category_id
WHERE l.course_id = c.id AND (cat.slug = $4 OR cat.id = $4 OR cat.label = $4)
)
)
ORDER BY c.updated_at DESC`,
[search, published, tag, category],
);
return res.rows.map(toAdminCourse);
}
export async function getAdminCourseById(id: string): Promise<AdminCourse | null> {
const res = await query<CourseRow>("SELECT * FROM courses WHERE id = $1 LIMIT 1", [id]);
const res = await query<CourseRow>(
`${COURSE_WITH_TAXONOMY_SELECT}
WHERE c.id = $1
LIMIT 1`,
[id],
);
return res.rows[0] ? toAdminCourse(res.rows[0]) : null;
}
/** Distinct tags across all courses (admin view — includes unpublished), sorted by usage. */
export async function listCourseTags(): Promise<string[]> {
const res = await query<{ tag: string; count: string }>(
`SELECT tag, COUNT(*)::text AS count
FROM courses, UNNEST(tags) AS tag
GROUP BY tag
ORDER BY COUNT(*) DESC, tag ASC`,
);
return res.rows.map((r) => r.tag);
}
/** Distinct tags for admin filter dropdown (id + label). */
export async function listCourseTags(): Promise<
{ id: string; slug: string; label: string }[]
> {
const tags = await listAdminCourseTags();
return tags.map((t) => ({ id: t.id, slug: t.slug, label: t.label }));
}
+108
View File
@@ -0,0 +1,108 @@
import { query } from "@/lib/db";
import {
getContentRow,
listContentRows,
type AdminListOpts,
} from "@/lib/data/admin/helpers";
export interface AdminCourseCategory {
id: string;
slug: string;
label: string;
sortOrder: number;
showInFilter: boolean;
published: boolean;
}
export interface AdminCourseTag {
id: string;
slug: string;
label: string;
sortOrder: number;
showInNav: boolean;
showInFilter: boolean;
published: boolean;
}
function mapCategory(row: Record<string, unknown>): AdminCourseCategory {
return {
id: String(row.id),
slug: String(row.slug),
label: String(row.label),
sortOrder: Number(row.sort_order ?? 0),
showInFilter: Boolean(row.show_in_filter),
published: Boolean(row.published),
};
}
function mapTag(row: Record<string, unknown>): AdminCourseTag {
return {
id: String(row.id),
slug: String(row.slug),
label: String(row.label),
sortOrder: Number(row.sort_order ?? 0),
showInNav: Boolean(row.show_in_nav),
showInFilter: Boolean(row.show_in_filter),
published: Boolean(row.published),
};
}
export function listAdminCourseCategories(opts?: AdminListOpts) {
return listContentRows(
"course_categories",
["label", "slug"],
mapCategory,
opts,
"sort_order ASC, label ASC",
);
}
export function getAdminCourseCategoryById(id: string) {
return getContentRow("course_categories", "id", id, mapCategory);
}
export function listAdminCourseTags(opts?: AdminListOpts) {
return listContentRows(
"course_tags",
["label", "slug"],
mapTag,
opts,
"sort_order ASC, label ASC",
);
}
export function getAdminCourseTagById(id: string) {
return getContentRow("course_tags", "id", id, mapTag);
}
/** Replace category links for a course. */
export async function setCourseCategories(
courseId: string,
categoryIds: string[],
): Promise<void> {
await query(`DELETE FROM course_category_links WHERE course_id = $1`, [
courseId,
]);
for (const categoryId of categoryIds) {
await query(
`INSERT INTO course_category_links (course_id, category_id)
VALUES ($1, $2) ON CONFLICT DO NOTHING`,
[courseId, categoryId],
);
}
}
/** Replace tag links for a course. */
export async function setCourseTags(
courseId: string,
tagIds: string[],
): Promise<void> {
await query(`DELETE FROM course_tag_links WHERE course_id = $1`, [courseId]);
for (const tagId of tagIds) {
await query(
`INSERT INTO course_tag_links (course_id, tag_id)
VALUES ($1, $2) ON CONFLICT DO NOTHING`,
[courseId, tagId],
);
}
}
+29
View File
@@ -0,0 +1,29 @@
/** Shared SELECT fragment: course row + JSON arrays of categories/tags. */
export const COURSE_WITH_TAXONOMY_SELECT = `
SELECT c.*,
COALESCE(
(
SELECT json_agg(
json_build_object('id', cat.id, 'slug', cat.slug, 'label', cat.label)
ORDER BY cat.sort_order ASC, cat.label ASC
)
FROM course_category_links l
JOIN course_categories cat ON cat.id = l.category_id
WHERE l.course_id = c.id
),
'[]'::json
) AS categories,
COALESCE(
(
SELECT json_agg(
json_build_object('id', t.id, 'slug', t.slug, 'label', t.label)
ORDER BY t.sort_order ASC, t.label ASC
)
FROM course_tag_links l
JOIN course_tags t ON t.id = l.tag_id
WHERE l.course_id = c.id
),
'[]'::json
) AS tags
FROM courses c
`;
+8 -15
View File
@@ -1,30 +1,23 @@
import { query } from "@/lib/db";
import type { Course } from "@/lib/types";
import { rowToCourse, type CourseRow } from "@/lib/db/mappers";
import { COURSE_WITH_TAXONOMY_SELECT } from "@/lib/data/course-taxonomy-sql";
export async function getCourses(): Promise<Course[]> {
const res = await query<CourseRow>(
"SELECT * FROM courses WHERE published = true ORDER BY title ASC",
`${COURSE_WITH_TAXONOMY_SELECT}
WHERE c.published = true
ORDER BY c.title ASC`,
);
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",
`${COURSE_WITH_TAXONOMY_SELECT}
WHERE c.published = true AND (c.id = $1 OR c.slug = $1)
LIMIT 1`,
[id],
);
return res.rows[0] ? rowToCourse(res.rows[0]) : null;
}
}
+88
View File
@@ -0,0 +1,88 @@
import { query } from "@/lib/db";
import type { TaxonomyRef } from "@/lib/types";
export interface CourseCategoryRecord extends TaxonomyRef {
sortOrder: number;
showInFilter: boolean;
published: boolean;
}
export interface CourseTagRecord extends TaxonomyRef {
sortOrder: number;
showInNav: boolean;
showInFilter: boolean;
published: boolean;
}
type CategoryRow = {
id: string;
slug: string;
label: string;
sort_order: number;
show_in_filter: boolean;
published: boolean;
};
type TagRow = {
id: string;
slug: string;
label: string;
sort_order: number;
show_in_nav: boolean;
show_in_filter: boolean;
published: boolean;
};
function mapCategory(row: CategoryRow): CourseCategoryRecord {
return {
id: row.id,
slug: row.slug,
label: row.label,
sortOrder: row.sort_order,
showInFilter: row.show_in_filter,
published: row.published,
};
}
function mapTag(row: TagRow): CourseTagRecord {
return {
id: row.id,
slug: row.slug,
label: row.label,
sortOrder: row.sort_order,
showInNav: row.show_in_nav,
showInFilter: row.show_in_filter,
published: row.published,
};
}
export async function listPublishedCourseCategories(opts?: {
filterOnly?: boolean;
}): Promise<CourseCategoryRecord[]> {
const filterOnly = opts?.filterOnly ?? false;
const res = await query<CategoryRow>(
`SELECT * FROM course_categories
WHERE published = true
AND ($1::boolean = false OR show_in_filter = true)
ORDER BY sort_order ASC, label ASC`,
[filterOnly],
);
return res.rows.map(mapCategory);
}
export async function listPublishedCourseTags(opts?: {
navOnly?: boolean;
filterOnly?: boolean;
}): Promise<CourseTagRecord[]> {
const navOnly = opts?.navOnly ?? false;
const filterOnly = opts?.filterOnly ?? false;
const res = await query<TagRow>(
`SELECT * FROM course_tags
WHERE published = true
AND ($1::boolean = false OR show_in_nav = true)
AND ($2::boolean = false OR show_in_filter = true)
ORDER BY sort_order ASC, label ASC`,
[navOnly, filterOnly],
);
return res.rows.map(mapTag);
}
+33 -14
View File
@@ -2,30 +2,49 @@ import pg from "pg";
const { Pool } = pg;
let poolInstance: pg.Pool | null = null;
function getPool(): pg.Pool {
const url = process.env.DATABASE_URL?.trim();
if (!url) {
throw new Error(
"DATABASE_URL is not set. Copy .env.example to .env.local and set the Postgres URL (local/dev DB).",
);
}
if (!poolInstance) {
poolInstance = new Pool({
connectionString: url,
max: 5,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000,
});
poolInstance.on("error", (err) => {
console.error("[db] idle client error:", err.message);
});
}
return poolInstance;
}
/**
* Shared Postgres pool for server-side use.
* Connection details: docs/03-database.md
* Production must use DATABASE_URL → 185.36.145.12 (not Docker-internal DNS).
* Local/dev: DATABASE_URL in .env.local
* Production: DATABASE_URL from /etc/edu-production.env (insaight-postgres).
*/
export const pool = new Pool({
connectionString:
process.env.DATABASE_URL ||
undefined, // Rely on process.env.DATABASE_URL, or ensure it's set upstream
max: 5,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 10000,
});
pool.on("error", (err) => {
console.error("[db] idle client error:", err.message);
});
export const pool = {
query: <T extends pg.QueryResultRow = pg.QueryResultRow>(
text: string,
params?: unknown[],
) => getPool().query<T>(text, params),
end: () => (poolInstance ? poolInstance.end() : Promise.resolve()),
};
export async function query<T extends pg.QueryResultRow = pg.QueryResultRow>(
text: string,
params?: unknown[],
) {
try {
return await pool.query<T>(text, params);
return await getPool().query<T>(text, params);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.error("[db] query failed:", message, { text: text.slice(0, 120) });
+26 -8
View File
@@ -9,6 +9,7 @@ import type {
LegalPage,
Program,
SiteStat,
TaxonomyRef,
Testimonial,
} from "@/lib/types";
@@ -41,37 +42,54 @@ export interface CourseRow {
slug: string;
title: string;
summary: string;
category: string;
duration_hours: number | null;
format: string;
price: string | number | null;
registration_url: string;
poster_image_url: string;
brochure_image_url: string;
image_url?: string;
seo_description: string;
tags: string[];
published: boolean;
/** Present when SELECT aggregates taxonomy as JSON. */
categories?: unknown;
tags?: unknown;
}
/** Seed/upsert row for courses table (no taxonomy columns). */
export function courseToRow(course: Course): CourseRow {
return {
id: course.id,
slug: course.slug,
title: course.title,
summary: course.summary,
category: course.category,
duration_hours: course.durationHours ?? null,
format: course.format,
price: course.price ?? null,
registration_url: course.registrationUrl,
poster_image_url: course.posterImageUrl,
brochure_image_url: course.brochureImageUrl,
image_url: course.posterImageUrl,
seo_description: course.seoDescription,
tags: course.tags ?? [],
published: true,
};
}
function asTaxonomyRefs(value: unknown): TaxonomyRef[] {
if (!Array.isArray(value)) return [];
return value
.map((item) => {
if (!item || typeof item !== "object") return null;
const o = item as Record<string, unknown>;
const id = typeof o.id === "string" ? o.id : "";
const slug = typeof o.slug === "string" ? o.slug : "";
const label = typeof o.label === "string" ? o.label : "";
if (!id || !slug || !label) return null;
return { id, slug, label };
})
.filter((x): x is TaxonomyRef => x != null);
}
export interface ProgramRow {
id: string;
slug: string;
@@ -329,15 +347,15 @@ export function rowToCourse(row: CourseRow): Course {
slug: row.slug,
title: row.title,
summary: row.summary,
category: row.category as Course["category"],
categories: asTaxonomyRefs(row.categories),
tags: asTaxonomyRefs(row.tags),
durationHours: row.duration_hours,
format: row.format as Course["format"],
price: Number.isFinite(price) ? price : null,
registrationUrl: row.registration_url,
posterImageUrl: row.poster_image_url ?? (row as unknown as { image_url?: string }).image_url ?? "",
brochureImageUrl: row.brochure_image_url ?? (row as unknown as { image_url?: string }).image_url ?? "",
posterImageUrl: row.poster_image_url ?? row.image_url ?? "",
brochureImageUrl: row.brochure_image_url ?? row.image_url ?? "",
seoDescription: row.seo_description,
tags: asStringArray(row.tags),
};
}
+7 -1
View File
@@ -13,7 +13,13 @@ export const COURSE_FORMAT_LABELS: Record<string, string> = {
"in-person": "حضوری",
};
export function categoryLabel(value: string): string {
/** Resolve a legacy category slug (or TaxonomyRef) to a display label. */
export function categoryLabel(value: unknown): string {
if (value && typeof value === "object" && "label" in value) {
const label = (value as { label: unknown }).label;
if (typeof label === "string" && label) return label;
}
if (typeof value !== "string" || !value) return "—";
return COURSE_CATEGORY_LABELS[value] ?? value;
}
+51 -8
View File
@@ -1,4 +1,40 @@
import type { Course } from "@/lib/types";
import type { Course, TaxonomyRef } from "@/lib/types";
const C = {
technology: {
id: "cat-technology",
slug: "technology",
label: "هوش مصنوعی و تحول سازمان",
},
digital: {
id: "cat-digital",
slug: "digital",
label: "برند و بازاریابی",
},
innovation: {
id: "cat-innovation",
slug: "innovation",
label: "برندینگ",
},
leadership: {
id: "cat-leadership",
slug: "leadership",
label: "هم‌اندیشی مدیریتی",
},
} as const satisfies Record<string, TaxonomyRef>;
const T = {
workshops: {
id: "tag-workshops",
slug: "workshops",
label: "کارگاه‌ها",
},
corporate: {
id: "tag-corporate",
slug: "corporate",
label: "دوره‌های سازمانی",
},
} as const satisfies Record<string, TaxonomyRef>;
/** Seed/reference courses from docs/cources + برنامه تحول سازمانی با AI. */
export const courses: Course[] = [
@@ -8,7 +44,8 @@ export const courses: Course[] = [
title: "تحول سازمانی با هوش مصنوعی",
summary:
"دوره تخصصی دوروزه؛ درک روشن از اینکه هوش مصنوعی کجا و چگونه به سازمان کمک می‌کند.",
category: "technology",
categories: [C.technology],
tags: [T.workshops],
durationHours: null,
format: "in-person",
registrationUrl: "/register/ai-organizational-transformation",
@@ -23,7 +60,8 @@ export const courses: Course[] = [
title: "AI Fluency؛ کارگاه عملی کاربرد هوش مصنوعی",
summary:
"از پرامپت دقیق تا ایجنت قابل اعتماد — یاد بگیرید، بسازید، ارزیابی کنید.",
category: "technology",
categories: [C.technology],
tags: [T.workshops],
durationHours: null,
format: "in-person",
registrationUrl: "/register/ai-fluency",
@@ -38,7 +76,8 @@ export const courses: Course[] = [
title: "مهندسی پرامپت در منابع انسانی",
summary:
"کارگاهی درباره هدایت هوش مصنوعی مولد در مسائل منابع انسانی؛ با تمرکز بر تحلیل رزومه، شرح شغل، شایستگی‌ها و طراحی پرامپت‌های تخصصی و قابل تکرار.",
category: "technology",
categories: [C.technology],
tags: [T.workshops],
durationHours: null,
format: "in-person",
registrationUrl: "/register/hr-prompt-engineering",
@@ -53,7 +92,8 @@ export const courses: Course[] = [
title: "برندینگ",
summary:
"بررسی هویت و جایگاه برند در ارتباط با تجربه مخاطب، ارتباطات و ارزش برند؛ با مطالعه نمونه‌ها و کار عملی طراحی و توسعه برند.",
category: "innovation",
categories: [C.innovation],
tags: [T.workshops],
durationHours: null,
format: "in-person",
registrationUrl: "/register/branding",
@@ -68,7 +108,8 @@ export const courses: Course[] = [
title: "مارکتینگ",
summary:
"بررسی مسیر تصمیم‌گیری بازاریابی، از شناخت مشتری و ارزش پیشنهادی تا استراتژی، کمپین و ارزیابی عملکرد؛ با توجه به کاربرد داده و هوش مصنوعی.",
category: "digital",
categories: [C.digital],
tags: [T.workshops],
durationHours: null,
format: "in-person",
registrationUrl: "/register/marketing",
@@ -83,7 +124,8 @@ export const courses: Course[] = [
title: "برندینگ و مارکتینگ در عمل",
summary:
"نگاهی یکپارچه به هویت برند، استراتژی بازاریابی و عملکرد بازار؛ همراه با مطالعه موردی و پروژه عملی برای بررسی ارتباط این تصمیم‌ها.",
category: "digital",
categories: [C.digital, C.innovation],
tags: [T.workshops],
durationHours: null,
format: "in-person",
registrationUrl: "/register/branding-marketing-in-practice",
@@ -98,7 +140,8 @@ export const courses: Course[] = [
title: "هم‌اندیشی مدیریتی",
summary:
"گفت‌وگوی یک‌به‌یک مدیر با استاد یا متخصص مرتبط، برای بررسی مسئله واقعی سازمان، بازبینی فرض‌ها و روشن‌ترشدن گزینه‌های تصمیم.",
category: "leadership",
categories: [C.leadership],
tags: [T.corporate],
durationHours: null,
format: "in-person",
registrationUrl: "/register/managerial-dialogue",
+6 -15
View File
@@ -38,11 +38,11 @@ export const homeNav: NavItem[] = [
href: "/professional",
children: [
{ label: "همه دوره‌ها", href: "/professional" },
{ label: "کارگاه‌ها", href: "/professional?tag=کارگاه‌ها" },
{ label: "دوره‌های سازمانی", href: "/professional?tag=دوره‌های سازمانی" },
{ label: "کارگاه‌ها", href: "/professional?tag=workshops" },
{ label: "دوره‌های سازمانی", href: "/professional?tag=corporate" },
{
label: "گزیده دوره‌های برگزار شده",
href: "/professional?tag=گزیده دوره‌های برگزار شده",
href: "/professional?tag=archive",
},
],
},
@@ -55,11 +55,11 @@ export const professionalNav: NavItem[] = [
href: "/professional#programs",
children: [
{ label: "همه دوره‌ها", href: "/professional" },
{ label: "کارگاه‌ها", href: "/professional?tag=کارگاه‌ها" },
{ label: "دوره‌های سازمانی", href: "/professional?tag=دوره‌های سازمانی" },
{ label: "کارگاه‌ها", href: "/professional?tag=workshops" },
{ label: "دوره‌های سازمانی", href: "/professional?tag=corporate" },
{
label: "گزیده دوره‌های برگزار شده",
href: "/professional?tag=گزیده دوره‌های برگزار شده",
href: "/professional?tag=archive",
},
],
},
@@ -433,12 +433,3 @@ export const testimonials: Testimonial[] = [
courseTitle: "تحول دیجیتال سازمان",
},
];
export const courseCategories: { id: string; label: string }[] = [
{ id: "best", label: "پیشنهاد ویژه" },
{ id: "technology", label: "هوش مصنوعی و تحول سازمان" },
{ id: "digital", label: "برند و بازاریابی" },
{ id: "innovation", label: "برندینگ" },
{ id: "leadership", label: "هم‌اندیشی مدیریتی" },
{ id: "all", label: "همه برنامه‌ها" },
];
+3 -28
View File
@@ -22,22 +22,11 @@ export const siteAddress = {
/**
* Parent label for the single courses dropdown on the home nav.
* Change this to rename the root item; child items come from course tags.
* Child items come from published course tags (`show_in_nav`) in the DB.
* 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" },
@@ -46,17 +35,12 @@ export const homeNav: NavItem[] = [
{ label: "دانشگاه امیرکبیر", href: "https://mst.aut.ac.ir/", prominent: true },
];
/** Professional layout nav; courses children filled at runtime from DB tags. */
export const professionalNav: NavItem[] = [
{
label: courseNavParentTag,
href: "/professional#programs",
children: [
{ label: "همه دوره‌ها", href: "/professional" },
...courseNavTagOrder.map((tag) => ({
label: tag,
href: `/professional?tag=${encodeURIComponent(tag)}`,
})),
],
children: [{ label: "همه دوره‌ها", href: "/professional" }],
},
{ label: "نحوه یادگیری", href: "/professional#digital" },
{ label: "درباره ما", href: "/about" },
@@ -109,12 +93,3 @@ export const valuesContent = {
},
],
};
export const courseCategories: { id: string; label: string }[] = [
{ id: "best", label: "پیشنهاد ویژه" },
{ id: "technology", label: "هوش مصنوعی و تحول سازمان" },
{ id: "digital", label: "برند و بازاریابی" },
{ id: "innovation", label: "برندینگ" },
{ id: "leadership", label: "هم‌اندیشی مدیریتی" },
{ id: "all", label: "همه برنامه‌ها" },
];
+34
View File
@@ -0,0 +1,34 @@
/** Canonical seed taxonomy (stable ids/slugs). Used by mock seed + migration docs. */
export const SEED_COURSE_CATEGORIES = [
{ id: "cat-technology", slug: "technology", label: "هوش مصنوعی و تحول سازمان", sortOrder: 10 },
{ id: "cat-digital", slug: "digital", label: "برند و بازاریابی", sortOrder: 20 },
{ id: "cat-innovation", slug: "innovation", label: "برندینگ", sortOrder: 30 },
{ id: "cat-leadership", slug: "leadership", label: "هم‌اندیشی مدیریتی", sortOrder: 40 },
{ id: "cat-energy", slug: "energy", label: "انرژی", sortOrder: 50 },
{ id: "cat-design", slug: "design", label: "طراحی", sortOrder: 60 },
] as const;
export const SEED_COURSE_TAGS = [
{
id: "tag-workshops",
slug: "workshops",
label: "کارگاه‌ها",
sortOrder: 10,
showInNav: true,
},
{
id: "tag-corporate",
slug: "corporate",
label: "دوره‌های سازمانی",
sortOrder: 20,
showInNav: true,
},
{
id: "tag-archive",
slug: "archive",
label: "گزیده دوره‌های برگزار شده",
sortOrder: 30,
showInNav: true,
},
] as const;
+10 -10
View File
@@ -1,19 +1,21 @@
export type CourseFormat = "online" | "blended" | "in-person";
export type CourseCategory =
| "leadership"
| "technology"
| "innovation"
| "energy"
| "design"
| "digital";
/** Category (topic) or tag (type) attached to a course. */
export interface TaxonomyRef {
id: string;
slug: string;
label: string;
}
export interface Course {
id: string;
slug: string;
title: string;
summary: string;
category: CourseCategory;
/** Topic categories (many-to-many; admin-managed). */
categories: TaxonomyRef[];
/** Type tags for nav/filters (many-to-many; admin-managed). */
tags: TaxonomyRef[];
/** Hours; null/omit when not confirmed in source materials */
durationHours?: number | null;
format: CourseFormat;
@@ -23,8 +25,6 @@ export interface Course {
posterImageUrl: string;
brochureImageUrl: string;
seoDescription: string;
/** Tags for filtering (e.g., "کارگاه", "دوره سازمانی", "گزیده") */
tags?: string[];
}
export type ProgramGroup = "standard" | "executive";
+48 -2
View File
@@ -26,7 +26,8 @@ const courseFields = {
slug: slugField,
title: z.string().min(1, "title الزامی است"),
summary: z.string().min(1, "summary الزامی است"),
category: z.enum(["leadership", "technology", "innovation", "energy", "design", "digital"]),
categoryIds: z.array(z.string().min(1)).default([]),
tagIds: z.array(z.string().min(1)).default([]),
durationHours: z
.union([z.number().int().positive("durationHours باید عدد مثبت باشد"), z.null()])
.optional(),
@@ -39,11 +40,56 @@ const courseFields = {
/** 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(),
};
const courseCategoryFields = {
slug: slugField,
label: z.string().min(1, "عنوان الزامی است"),
sortOrder: z.number().int().default(0),
showInFilter: z.boolean().default(true),
published: z.boolean(),
};
export const courseCategoryCreateSchema = z.object({
...courseCategoryFields,
sortOrder: z.number().int().default(0),
showInFilter: z.boolean().default(true),
published: z.boolean().default(true),
});
export const courseCategoryPatchSchema = z
.object(courseCategoryFields)
.partial()
.refine((v) => Object.keys(v).length > 0, {
message: "حداقل یک فیلد برای ویرایش لازم است",
});
const courseTagFields = {
slug: slugField,
label: z.string().min(1, "عنوان الزامی است"),
sortOrder: z.number().int().default(0),
showInNav: z.boolean().default(true),
showInFilter: z.boolean().default(true),
published: z.boolean(),
};
export const courseTagCreateSchema = z.object({
...courseTagFields,
sortOrder: z.number().int().default(0),
showInNav: z.boolean().default(true),
showInFilter: z.boolean().default(true),
published: z.boolean().default(true),
});
export const courseTagPatchSchema = z
.object(courseTagFields)
.partial()
.refine((v) => Object.keys(v).length > 0, {
message: "حداقل یک فیلد برای ویرایش لازم است",
});
export const courseCreateSchema = z.object({
...courseFields,
seoDescription: z.string().default(""),