changes
No files matched your search
@@ -0,0 +1,148 @@
|
||||
-- Course taxonomy: admin-managed categories (topics) + tags (types), many-to-many.
|
||||
-- Backfills from legacy courses.category (enum) and courses.tags (text[]), then drops them.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS course_categories (
|
||||
id TEXT PRIMARY KEY,
|
||||
slug TEXT UNIQUE NOT NULL,
|
||||
label TEXT NOT NULL,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
show_in_filter BOOLEAN NOT NULL DEFAULT true,
|
||||
published BOOLEAN NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS course_tags (
|
||||
id TEXT PRIMARY KEY,
|
||||
slug TEXT UNIQUE NOT NULL,
|
||||
label TEXT NOT NULL,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
show_in_nav BOOLEAN NOT NULL DEFAULT true,
|
||||
show_in_filter BOOLEAN NOT NULL DEFAULT true,
|
||||
published BOOLEAN NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS course_category_links (
|
||||
course_id TEXT NOT NULL REFERENCES courses(id) ON DELETE CASCADE,
|
||||
category_id TEXT NOT NULL REFERENCES course_categories(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (course_id, category_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS course_tag_links (
|
||||
course_id TEXT NOT NULL REFERENCES courses(id) ON DELETE CASCADE,
|
||||
tag_id TEXT NOT NULL REFERENCES course_tags(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (course_id, tag_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_course_category_links_category
|
||||
ON course_category_links (category_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_course_tag_links_tag
|
||||
ON course_tag_links (tag_id);
|
||||
|
||||
-- Seed canonical categories (stable ids = cat-<slug>)
|
||||
INSERT INTO course_categories (id, slug, label, sort_order, show_in_filter, published)
|
||||
VALUES
|
||||
('cat-technology', 'technology', 'هوش مصنوعی و تحول سازمان', 10, true, true),
|
||||
('cat-digital', 'digital', 'برند و بازاریابی', 20, true, true),
|
||||
('cat-innovation', 'innovation', 'برندینگ', 30, true, true),
|
||||
('cat-leadership', 'leadership', 'هماندیشی مدیریتی', 40, true, true),
|
||||
('cat-energy', 'energy', 'انرژی', 50, true, true),
|
||||
('cat-design', 'design', 'طراحی', 60, true, true)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
slug = EXCLUDED.slug,
|
||||
label = EXCLUDED.label,
|
||||
sort_order = EXCLUDED.sort_order;
|
||||
|
||||
-- Seed known nav tags
|
||||
INSERT INTO course_tags (id, slug, label, sort_order, show_in_nav, show_in_filter, published)
|
||||
VALUES
|
||||
('tag-workshops', 'workshops', 'کارگاهها', 10, true, true, true),
|
||||
('tag-corporate', 'corporate', 'دورههای سازمانی', 20, true, true, true),
|
||||
('tag-archive', 'archive', 'گزیده دورههای برگزار شده', 30, true, true, true)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
slug = EXCLUDED.slug,
|
||||
label = EXCLUDED.label,
|
||||
sort_order = EXCLUDED.sort_order;
|
||||
|
||||
-- Any extra free-text tags from legacy column → new tag rows (slug derived)
|
||||
DO $$
|
||||
DECLARE
|
||||
r RECORD;
|
||||
new_id TEXT;
|
||||
new_slug TEXT;
|
||||
n INT := 100;
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'courses' AND column_name = 'tags'
|
||||
) THEN
|
||||
FOR r IN
|
||||
SELECT DISTINCT trim(t) AS label
|
||||
FROM courses, UNNEST(tags) AS t
|
||||
WHERE trim(t) <> ''
|
||||
AND trim(t) NOT IN (
|
||||
SELECT label FROM course_tags
|
||||
)
|
||||
LOOP
|
||||
new_slug := 'tag-' || substr(md5(r.label), 1, 12);
|
||||
new_id := 'tag-auto-' || substr(md5(r.label), 1, 12);
|
||||
INSERT INTO course_tags (id, slug, label, sort_order, show_in_nav, show_in_filter, published)
|
||||
VALUES (new_id, new_slug, r.label, n, true, true, true)
|
||||
ON CONFLICT (slug) DO NOTHING;
|
||||
n := n + 10;
|
||||
END LOOP;
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Link courses → categories from legacy category column
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'courses' AND column_name = 'category'
|
||||
) THEN
|
||||
INSERT INTO course_category_links (course_id, category_id)
|
||||
SELECT c.id, cat.id
|
||||
FROM courses c
|
||||
JOIN course_categories cat ON cat.slug = c.category
|
||||
ON CONFLICT DO NOTHING;
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Link courses → tags from legacy tags array (match by label)
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'courses' AND column_name = 'tags'
|
||||
) THEN
|
||||
INSERT INTO course_tag_links (course_id, tag_id)
|
||||
SELECT DISTINCT c.id, t.id
|
||||
FROM courses c
|
||||
CROSS JOIN LATERAL UNNEST(c.tags) AS raw(label)
|
||||
JOIN course_tags t ON t.label = trim(raw.label)
|
||||
WHERE trim(raw.label) <> ''
|
||||
ON CONFLICT DO NOTHING;
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Drop legacy columns
|
||||
ALTER TABLE courses DROP CONSTRAINT IF EXISTS courses_category_check;
|
||||
ALTER TABLE courses DROP COLUMN IF EXISTS category;
|
||||
ALTER TABLE courses DROP COLUMN IF EXISTS tags;
|
||||
|
||||
-- updated_at triggers
|
||||
DROP TRIGGER IF EXISTS trg_course_categories_set_updated_at ON course_categories;
|
||||
CREATE TRIGGER trg_course_categories_set_updated_at
|
||||
BEFORE UPDATE ON course_categories
|
||||
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_course_tags_set_updated_at ON course_tags;
|
||||
CREATE TRIGGER trg_course_tags_set_updated_at
|
||||
BEFORE UPDATE ON course_tags
|
||||
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
|
||||
@@ -20,6 +20,10 @@ import {
|
||||
stats,
|
||||
testimonials,
|
||||
} from "../src/lib/mock/site.ts";
|
||||
import {
|
||||
SEED_COURSE_CATEGORIES,
|
||||
SEED_COURSE_TAGS,
|
||||
} from "../src/lib/taxonomy.ts";
|
||||
|
||||
import {
|
||||
alumniStoryToRow,
|
||||
@@ -81,8 +85,42 @@ async function main() {
|
||||
results.push([table, n]);
|
||||
});
|
||||
|
||||
await upsert(
|
||||
"course_categories",
|
||||
SEED_COURSE_CATEGORIES.map((c) => ({
|
||||
id: c.id,
|
||||
slug: c.slug,
|
||||
label: c.label,
|
||||
sort_order: c.sortOrder,
|
||||
show_in_filter: true,
|
||||
published: true,
|
||||
})),
|
||||
["id", "slug", "label", "sort_order", "show_in_filter", "published"],
|
||||
);
|
||||
await upsert(
|
||||
"course_tags",
|
||||
SEED_COURSE_TAGS.map((t) => ({
|
||||
id: t.id,
|
||||
slug: t.slug,
|
||||
label: t.label,
|
||||
sort_order: t.sortOrder,
|
||||
show_in_nav: t.showInNav,
|
||||
show_in_filter: true,
|
||||
published: true,
|
||||
})),
|
||||
[
|
||||
"id",
|
||||
"slug",
|
||||
"label",
|
||||
"sort_order",
|
||||
"show_in_nav",
|
||||
"show_in_filter",
|
||||
"published",
|
||||
],
|
||||
);
|
||||
|
||||
await upsert("courses", courses.map(courseToRow), [
|
||||
"id", "slug", "title", "summary", "category", "duration_hours", "format", "price",
|
||||
"id", "slug", "title", "summary", "duration_hours", "format", "price",
|
||||
"registration_url", "poster_image_url", "brochure_image_url", "image_url", "seo_description", "published",
|
||||
]);
|
||||
const courseIds = courses.map((c) => c.id);
|
||||
@@ -91,6 +129,31 @@ async function main() {
|
||||
[courseIds],
|
||||
);
|
||||
results.push(["courses_pruned", courseIds.length]);
|
||||
|
||||
await client.query(`DELETE FROM course_category_links`);
|
||||
await client.query(`DELETE FROM course_tag_links`);
|
||||
let catLinks = 0;
|
||||
let tagLinks = 0;
|
||||
for (const course of courses) {
|
||||
for (const cat of course.categories ?? []) {
|
||||
await client.query(
|
||||
`INSERT INTO course_category_links (course_id, category_id)
|
||||
VALUES ($1, $2) ON CONFLICT DO NOTHING`,
|
||||
[course.id, cat.id],
|
||||
);
|
||||
catLinks += 1;
|
||||
}
|
||||
for (const tag of course.tags ?? []) {
|
||||
await client.query(
|
||||
`INSERT INTO course_tag_links (course_id, tag_id)
|
||||
VALUES ($1, $2) ON CONFLICT DO NOTHING`,
|
||||
[course.id, tag.id],
|
||||
);
|
||||
tagLinks += 1;
|
||||
}
|
||||
}
|
||||
results.push(["course_category_links", catLinks]);
|
||||
results.push(["course_tag_links", tagLinks]);
|
||||
await upsert("programs", programs.map(programToRow), [
|
||||
"id", "slug", "title", "blurb", "group_key", "href", "tagline", "audience",
|
||||
"duration_label", "format_label", "highlights", "body", "published",
|
||||
|
||||
@@ -45,7 +45,8 @@
|
||||
|
||||
| فیلد | توضیح |
|
||||
|---|---|
|
||||
| `course.category` | یکی از دستههای فیلتر لندینگ professional |
|
||||
| `course.categories` | many-to-many با `course_categories` (موضوع؛ ادمین) |
|
||||
| `course.tags` | many-to-many با `course_tags` (نوع/منو؛ ادمین) |
|
||||
| `program.group` | `standard` یا `executive` برای selector هوم |
|
||||
| `event.endDate` | اگر null باشد رویداد تکروزه است |
|
||||
| `article.featured` | حداکثر یک مقاله featured در هوم |
|
||||
@@ -55,7 +56,8 @@
|
||||
- لیست برنامههای هوم: ابتدا `group=standard` سپس بلوک جدا `executive`.
|
||||
- آمار لندینگ professional از mock ثابت خوانده میشود (تا اتصال analytics/DB).
|
||||
- هیچ مبلغ/ظرفیت واقعی محاسبه نمیشود تا DB وصل شود.
|
||||
- منوی صفحهٔ اصلی فقط **یک** دراپداون دوره دارد؛ لیبل ریشه = `courseNavParentTag`؛ فرزندان از تگهای منتشرشده. فیلتر پایدار: `/professional?tag=` (مستند: `docs/LINKS.md`).
|
||||
- منوی صفحهٔ اصلی فقط **یک** دراپداون دوره دارد؛ لیبل ریشه = `courseNavParentTag`؛ فرزندان = تگهای `show_in_nav`. فیلتر پایدار با **slug**: `/professional?tag=` و `/professional?category=` (مستند: `docs/LINKS.md`).
|
||||
- دسته و تگ فقط از ادمین تعریف میشوند (`/admin/course-categories`، `/admin/course-tags`)؛ هر دوره میتواند چند دسته و چند تگ داشته باشد.
|
||||
|
||||
## Locale / Format Rules
|
||||
- زبان UI: فارسی؛ `dir="rtl"`؛ اعداد نمایشی میتوانند فارسیسازی شوند در لایهٔ UI.
|
||||
|
||||
@@ -1,38 +1,40 @@
|
||||
# لینکهای عمومی سایت
|
||||
|
||||
مسیرهای پایدار برای ناوبری، اشتراکگذاری و فیلتر. تغییر لیبل یا ترتیب از `src/lib/site-config.ts`؛ منطق ساخت منو از `src/lib/course-nav.ts`.
|
||||
مسیرهای پایدار برای ناوبری، اشتراکگذاری و فیلتر. لیبل ریشهٔ منو از `courseNavParentTag` در [`src/lib/site-config.ts`](../src/lib/site-config.ts)؛ آیتمها و فیلترها از جداول ادمینمحور `course_tags` / `course_categories` (slug پایدار).
|
||||
|
||||
## کاتالوگ دورهها
|
||||
|
||||
| توضیح | مسیر |
|
||||
|---|---|
|
||||
| همه دورهها (تگ پدر / ریشه) | `/professional` |
|
||||
| فیلتر با تگ | `/professional?tag=<نام-تگ>` |
|
||||
| همه دورهها (ریشهٔ منو) | `/professional` |
|
||||
| فیلتر با تگ | `/professional?tag=<slug>` |
|
||||
| فیلتر با دسته | `/professional?category=<slug>` |
|
||||
| هر دو فیلتر | `/professional?tag=<slug>&category=<slug>` |
|
||||
|
||||
### تگ پدر
|
||||
### تگ پدر (لیبل منو)
|
||||
|
||||
- مقدار فعلی: **`دورهها`** (`courseNavParentTag` در `site-config.ts`)
|
||||
- این لیبل، عنوان همان **یک** دراپداون منوی صفحهٔ اصلی است (جای دکمههای جدا مثل «دورههای کوتاه» / «دورههای صنعتی»).
|
||||
- کلیک روی ریشه → `/professional` (بدون فیلتر).
|
||||
- آیتمهای فرزند از **تگهای دورههای منتشرشده** میآیند؛ ترتیب ترجیحی: `courseNavTagOrder`.
|
||||
- مقدار فعلی: **`دورهها`** (`courseNavParentTag`)
|
||||
- یک دراپداون در منوی اصلی؛ فرزندان = تگهای منتشرشده با `show_in_nav`
|
||||
- کلیک روی ریشه → `/professional`
|
||||
|
||||
### نمونه لینک تگ
|
||||
### نمونه slugهای seed
|
||||
|
||||
ساخت با `encodeURIComponent` یا هلپر زیر؛ مقدار `tag` باید دقیقاً با تگ ذخیرهشده روی دوره یکی باشد.
|
||||
| نوع | slug | لیبل |
|
||||
|---|---|---|
|
||||
| تگ | `workshops` | کارگاهها |
|
||||
| تگ | `corporate` | دورههای سازمانی |
|
||||
| تگ | `archive` | گزیده دورههای برگزار شده |
|
||||
| دسته | `technology` | هوش مصنوعی و تحول سازمان |
|
||||
| دسته | `digital` | برند و بازاریابی |
|
||||
|
||||
| تگ | الگو |
|
||||
|---|---|
|
||||
| کارگاهها | `/professional?tag=کارگاهها` |
|
||||
| دورههای سازمانی | `/professional?tag=دورههای سازمانی` |
|
||||
| گزیده دورههای برگزار شده | `/professional?tag=گزیده دورههای برگزار شده` |
|
||||
|
||||
در کد از هلپرها استفاده کنید:
|
||||
در کد:
|
||||
|
||||
```ts
|
||||
import { courseCatalogHref, courseTagHref } from "@/lib/course-nav";
|
||||
import { courseCatalogHref, courseTagHref, courseCategoryHref } from "@/lib/course-nav";
|
||||
|
||||
courseCatalogHref(); // "/professional"
|
||||
courseTagHref("کارگاهها"); // "/professional?tag=..."
|
||||
courseTagHref("workshops"); // "/professional?tag=workshops"
|
||||
courseCategoryHref("technology"); // "/professional?category=technology"
|
||||
```
|
||||
|
||||
## سایر مسیرهای اصلی
|
||||
@@ -46,3 +48,11 @@ courseTagHref("کارگاهها"); // "/professional?tag=..."
|
||||
| رویدادها | `/events` |
|
||||
| بینشها | `/insights` |
|
||||
| ثبتنام دوره | `/register/<slug>` |
|
||||
|
||||
## ادمین تاکسونومی
|
||||
|
||||
| بخش | مسیر |
|
||||
|---|---|
|
||||
| دستهبندی دورهها | `/admin/course-categories` |
|
||||
| تگهای دوره | `/admin/course-tags` |
|
||||
| دورهها | `/admin/courses` |
|
||||
@@ -0,0 +1,21 @@
|
||||
1- در بار بالا، فاصله بین دکمه ها بیشتر شود تا تناسب برقرار باشد بین فاصله های اکشن های چپ و راست
|
||||
2- دکمه تماس باما کنار دکمه سرچ باشد
|
||||
3- فونت بشود وزیر متن
|
||||
4- دکمه دانشگداه از بالا جذف شود و به دسترسی سریع برود اما به دانشکد (لینک استاتید بدون آدرس صفحه)
|
||||
5- درباره ما در بعد از دوره ها باشد
|
||||
6- برنامه ها فعلا هاید شود (لینکش هم در دسترس نباشد)
|
||||
7- لوگو دانشکده باید گذاشته شود (بهت میدمش) اگر میتونی لوگو های اینچا https://mst.aut.ac.ir را دانلود کن)
|
||||
8- چرا دانشگاه .... باید بردش حذف شود
|
||||
9- عدد بالا در چرا دانشگاه (اون یک دو سه) برداشته شود
|
||||
10- دانشگاه صنعتی امیرکبیر باشد در این قسمت نه امیرکبیر خالی و البته همه جا
|
||||
11- پلت رنگی عووض میشه و باید بگیریمش (اگر میتونی اینو ببین https://mst.aut.ac.ir و ازش پلت رنگی بساز)
|
||||
12- قبل از "رویکرد آموزشی ما" باید یک سرچ بیاید که مانند صفحه دوره ها باشد و همان عمل را صدا کن
|
||||
13 کلمه "رویکرد آموزشی ما" و کلا متونی مانند این برای معرفی هر سکشن باید بزرگ تر باشد
|
||||
14- تمام سکشن ها باید عرض یکسان داشته باشند و هیچکدام تمام صفحه نشوند
|
||||
15- رویداد ها فعلا هاید شود
|
||||
16- دسترسی سریع باید سایت دانشکده و شبکه اساتید را داشته باشد
|
||||
17- ماهم باید اساتید را از دانشکده کپی کنیم (خودت بخون) و صرفا رفرنسشان را داشته باشیم تا در دوره ها اگر نیاز شد بهشون لینک بدیم (به صفحشون تو دانشکده)
|
||||
18- در صفحه دوره ها باید دسته بندی ها بزرک تر باشه، تگ ها از اون یکی یکم کوچک تر
|
||||
19- سرچ بار هامون باید آیکون باشه و با زدن آیکون سرچ بار باز بشه. یعنی همه جا سرچ آیکون با دسته بندی ها باشه و با انیمشن سرچ اینچپوپ جایگزین دسته بندی بشه (به جز هدر که دسته بندی نمی خواد)
|
||||
20 -روی کارت دوره ها همش قابل کلیک باشد ننه صرفا دکمه جزییات
|
||||
21- لیبل روی کارت دوره ها هم کلیلک پذیر باشد تا فیلتر دسته بندی و تگ را هم انجام دهد برای کاربر. در جزییات دوره هم همین باشد
|
||||
@@ -5,10 +5,13 @@ Pushes to `master` run `.gitea/workflows/deploy.yml` on the existing
|
||||
`local-host` runner. The checkout lives at `/opt/prod/Aut.ManagementFaculty`.
|
||||
|
||||
`scripts/deploy-production.sh` builds a Next.js standalone Docker image,
|
||||
backs up the database, applies versioned migrations, checks a candidate
|
||||
container, and replaces `aut-management-faculty`. It retains the previous
|
||||
container and automatically restores it if the new container fails its
|
||||
initial HTTPS check. Database migrations are not automatically reversed.
|
||||
backs up the database to `/opt/backups/edu`, applies versioned migrations
|
||||
(`node db/migrate.mjs` — idempotent via `schema_migrations`), checks a
|
||||
candidate container, and replaces `aut-management-faculty`. It retains the
|
||||
previous container and automatically restores it if the new container fails
|
||||
its initial HTTPS check. Database migrations are forward-only (not
|
||||
automatically reversed); the dump before migrate is the recovery path.
|
||||
Uploaded admin images persist in the Docker volume `edu-uploads`.
|
||||
|
||||
Production settings are stored in `/etc/edu-production.env`, owned by root
|
||||
with mode `600`. It contains `DATABASE_URL`, `NEXT_PUBLIC_SITE_URL`,
|
||||
|
||||
@@ -11,15 +11,13 @@
|
||||
گزینههای محتمل: ...
|
||||
-->
|
||||
|
||||
### ابهام 01 — ⏳ در انتظار پاسخ
|
||||
تاریخ: 2026-10-11
|
||||
سوال: لیبل تگ پدر منوی دورهها فعلاً «دورهها» (`courseNavParentTag`) است. همین بماند؟
|
||||
گزینههای محتمل:
|
||||
- الف) «دورهها» (پیشفرض فعلی)
|
||||
- ب) نام دیگری که شما مشخص کنید (مثلاً «برنامهها» یا «کارگاهها»)
|
||||
|
||||
## سوالات پاسخدادهشده
|
||||
|
||||
### ابهام 01 — ✅ پاسخ داده شد
|
||||
تاریخ: 2026-10-11 / پاسخ عملی 2026-10-12
|
||||
سوال: لیبل تگ پدر منوی دورهها؟
|
||||
پاسخ: لیبل نمایشی ریشه «دورهها» (`courseNavParentTag`) میماند؛ فرزندان از تگهای DB با `show_in_nav` میآیند (D25).
|
||||
|
||||
<!-- بعد از پاسخ به اینجا منتقل میشود:
|
||||
### ابهام NN — ✅ پاسخ داده شد
|
||||
تاریخ: ...
|
||||
|
||||
@@ -28,4 +28,5 @@
|
||||
| 2026-09-24 | D21 — ادمین عمومی با رجیستری `ENTITIES` در `src/lib/admin/entities.ts` (fields/columns/apiPath/idColumn/preview/list/get) + صفحات یکپارچهٔ داینامیک `/admin/[entity]` (list/new/[id]/edit) بهجای صفحهٔ جدا برای هر entity؛ orgهای عمومی `GenericTable` (سرور) / `GenericFilters`، `GenericForm`، `GenericDeleteDialog`، `PublishToggle` (کلاینت)؛ استاتیکها (`courses`، `login`، `registrations`) بر داینامیک ارجحند؛ `GenericForm` فقط **نسخهٔ قابلserialize** از spec را میگیرد چون توابع (list/get/preview) نمیتوانند به Client Component برسند | ۱۰ entity with شش شکل رکورد متفاوت = یک فرمول؛ کاهش تکرار شدید؛ D19/D20 تعمیم یافته |
|
||||
| 2026-09-24 | D22 — فاز G/H: ثبتنام عمومی در `POST /api/registrations` (اسکیمای `publicRegistrationSchema` با zod v4؛ یافتن `course_id` از slug؛ عموم بدون وضعیت) + صفحهٔ `/admin/registrations` (فیلتر search/status در URL، تغییر status، حذف)؛ لایههای `lib/data/admin/registrations.ts` و `lib/validation/public.ts`؛ و **بازاعتبارسنجی (Phase H)** با `revalidateSite()` → `revalidatePath("/", "layout")` که در `buildInsert`/`buildUpdate` فراخوانی میشود و دستی در DELETE های raw-SQL و route های دوره/مقاله اضافه شد | فرم ثبتنام واقعاً لید میسازد تا ادمین دنبال کند؛ صفحههای استاتیک عمومی با cache قدیمی پس از هر تغییر ادمین باید invalidate شوند |
|
||||
| 2026-09-24 | D23 — پایان H: حذف کامل وابستگی runtime به mock برای محتوای با تیبل: `intersections`، `stats`، `testimonials` از DB میآیند (`getTopics`، `getSiteStats`، `getTestimonials` در `lib/data/site.ts`؛ `HomeRest` با prop `stats`)؛ هویت/ناو استاتیکِ بدونتیبل به ماژول مستقل `src/lib/site-config.ts` منتقل شد؛ `src/lib/mock/site.ts` فقط برای seed باقی ماند (کامنت هدر دارد)؛ ایندکسها با `db/migrations/002_indexes.sql` (leads/articles/events/programs/courses)؛ اسکریپت `scripts/smoke.mjs` (۴ API عمومی + login + create/delete stat) | معیار پذیرش C/H: runtime هیچ import مستقیمی از mock ندارد؛ config بدون تیبل نباید «دادهٔ mock» تلقی شود؛ smoke خواندنی + یک write ادمین میسنجد |
|
||||
| 2026-10-12 | D25 — تاکسونومی دوره دو لایهٔ ادمینمحور: `course_categories` (موضوع) + `course_tags` (نوع/منو) با junction many-to-many؛ حذف `courses.category` enum و `courses.tags` text[]؛ لینک پایدار با slug (`?tag=` / `?category=`)؛ CRUD در `/admin/course-categories` و `/admin/course-tags` | دسته و تگ باید پویا و قابل تعریف در ادمین باشند؛ لیبل فارسی جدا از slug است |
|
||||
| 2026-10-11 | D24 — آپلود تصویر ادمین: `POST /api/admin/upload` (multipart، فقط ادمین) فایل را در `public/uploads/{folder}/` مینویسد و مسیر عمومی `/uploads/...` برمیگرداند؛ UI با `ImageUploadField` در `CourseForm` و فیلد نوع `image` در `GenericForm`/`entities` (articles/topics/faculty/alumni)؛ persistence در Docker با volume `uploads_data` و env `UPLOAD_DIR` | ورود دستی URL اشتباه بود؛ ادمین باید فایل بارگذاری کند؛ ستونهای DB همچنان path/URL میمانند |
|
||||
@@ -0,0 +1,238 @@
|
||||
# بازبینی صفحات سایت — اسکرینشات و یافتهها
|
||||
|
||||
تاریخ اسکرین: ۲۰۲۶-۱۰-۱۱
|
||||
پایه: `http://localhost:3000`
|
||||
Viewport: دسکتاپ ۱۴۴۰×۹۰۰ — اسکرین full-page
|
||||
فایلها: `docs/review/screenshots/*.png`
|
||||
اسکریپت تکرار: `node scripts/capture-page-screenshots.mjs`
|
||||
|
||||
---
|
||||
|
||||
## خلاصهٔ وضعیت
|
||||
|
||||
| وضعیت | تعداد | توضیح |
|
||||
|---|---|---|
|
||||
| OK (۲۰۰) | ۲۳ | صفحه رندر شد و اسکرین گرفته شد |
|
||||
| باگ واقعی داخل اپ | ۲ | `/privacy` و `/accessibility` → **۴۰۴** با وجود داده در DB |
|
||||
| ریدایرکت خارجی | ۱ | `/faculty` → سایت mst.aut.ac.ir (مسدود/فایروال از محیط اسکرین) |
|
||||
| نمونهٔ جزئیات | چند مسیر | از هر نوع entity یک نمونه؛ همهٔ slugها تکرار نشدند |
|
||||
|
||||
---
|
||||
|
||||
## یافتههای مهم برای بررسی
|
||||
|
||||
### ۱) `/privacy` و `/accessibility` — ۴۰۴ اشتباه
|
||||
در DB هر دو slug موجود و `published=true` هستند، ولی در کد فقط `press` و `careers` مجازند:
|
||||
|
||||
```18:33:src/app/(main)/(legal)/[slug]/page.tsx
|
||||
const ALLOWED = new Set(["press", "careers"]);
|
||||
// ...
|
||||
if (!ALLOWED.has(slug)) notFound();
|
||||
```
|
||||
|
||||
**نتیجه:** لینکهای حریم خصوصی / دسترسیپذیری اگر جایی باشند، ۴۰۴ میشوند.
|
||||
|
||||
### ۲) `/faculty` — صفحهٔ داخلی نیست
|
||||
در `next.config.ts` ریدایرکت دائم به
|
||||
`https://mst.aut.ac.ir/content/31094/شبکه-اساتید`
|
||||
از محیط اسکرینشات، سایت مقصد پاسخ «درخواست شما مسدود گردید» داد (فایروال/WAF دانشگاه). خود ریدایرکت اپ درست است؛ اسکرین مقصد قابل اتکا نیست.
|
||||
|
||||
### ۳) منوی «دورهها» روی هوم
|
||||
تگهای دوره در DB فعلاً خالیاند (`tags: []` برای همهٔ دورهها). dropdown دورهها از تگ ساخته میشود؛ اگر خالی به نظر برسد علتش داده است نه باگ UI.
|
||||
|
||||
### ۴) آپلود تصویر در ادمین
|
||||
در `/admin/courses/new` و `/admin/articles/new` فیلد **انتخاب و بارگذاری تصویر** دیده میشود (دیگر input آدرس متنی نیست).
|
||||
|
||||
### ۵) جزئیات رویداد نازک است
|
||||
صفحهٔ `/events/evt-1` فقط زمان/مکان/خلاصه دارد؛ CTA ثبتنام یا تصویر رویداد ندارد (ممکن است عمدی باشد).
|
||||
|
||||
---
|
||||
|
||||
## صفحات عمومی
|
||||
|
||||
### صفحه اصلی (`/`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
- هیرو تیره + CTA «مشاهده دورهها» / «درباره مرکز»
|
||||
- بنر کمپین بالای صفحه
|
||||
- بخشهای: چرا امیرکبیر، رویکرد آموزشی، رویدادها، حوزههای موضوعی، کارousel برنامهها، آمار، فوتر
|
||||
- مقالهٔ ویژه در هیرو لینک شده («سه اصل برای تبدیل داده…»)
|
||||
|
||||
### لندینگ حرفهای (`/professional`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
- هیرو دورههای کوتاه
|
||||
- جستجو + فیلتر دسته + کارت دورهها با پوستر
|
||||
- آمار، testimonials، فوتر
|
||||
- مسیر اصلی کاتالوگ دوره برای کاربران حرفهای
|
||||
|
||||
### درباره ما (`/about`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
### ارزشها (`/values`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
### تماس (`/contact`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
- فرم تماس / اعلام علاقه
|
||||
|
||||
### دانشآموختگان (`/alumni`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
- ۳ کارت داستان با تصویر (فعلاً از URL/مسیر ذخیرهشده؛ آپلود از ادمین برای رکوردهای جدید)
|
||||
|
||||
### رویدادها — فهرست (`/events`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
- ۴ رویداد در شبکهٔ کارت
|
||||
|
||||
### رویداد — جزئیات نمونه (`/events/evt-1`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
- محتوای کم؛ فقط متادیتا + خلاصه
|
||||
|
||||
### بینشها — فهرست (`/insights`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
### بینش — جزئیات نمونه (`/insights/art-1`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
### برنامهها — فهرست (`/programs`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
### برنامه — جزئیات نمونه (`/programs/management-core`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
### موضوع — نمونه (`/topics/ai-organizational-transformation`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
سایر موضوعها در DB: `branding`, `marketing`, `managerial-dialogue` (الگوی صفحه یکسان؛ اسکرین جدا گرفته نشد).
|
||||
|
||||
### ثبتنام / علاقه — نمونه (`/register/ai-fluency`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
- هیرو دوره + بروشور/پوستر + سایدبار «درخواست ثبتنام»
|
||||
- نمونهٔ بقیهٔ slugها: `branding`, `marketing`, `ai-organizational-transformation`, `managerial-dialogue`, …
|
||||
|
||||
### حریم خصوصی (`/privacy`)
|
||||
وضعیت: **۴۰۴ — باگ**
|
||||

|
||||
|
||||
داده در `legal_pages` هست؛ whitelist کد آن را حذف میکند. توضیح کامل در بخش یافتهها.
|
||||
|
||||
### دسترسیپذیری (`/accessibility`)
|
||||
وضعیت: **۴۰۴ — باگ**
|
||||

|
||||
|
||||
همان علت `/privacy`.
|
||||
|
||||
### روابط عمومی (`/press`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
### همکاری با ما (`/careers`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
### اساتید (`/faculty`)
|
||||
وضعیت: ریدایرکت خارجی — اسکرین مقصد کامل نیست
|
||||

|
||||
|
||||
**توضیح کامل:**
|
||||
- داخل اپ صفحهٔ اساتید نداریم؛ `redirects()` در Next به سایت دانشکده میرود.
|
||||
- مرورگر اتوماسیون به مقصد رسید ولی WAF دانشگاه پاسخ «درخواست شما مسدود گردید» با شماره پیگیری داد.
|
||||
- برای بررسی بصری شبکهٔ اساتید باید دستی در مرورگر عادی باز شود:
|
||||
https://mst.aut.ac.ir/content/31094/شبکه-اساتید
|
||||
|
||||
---
|
||||
|
||||
## پنل ادمین
|
||||
|
||||
### ورود (`/admin/login`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
### داشبورد (`/admin`)
|
||||
وضعیت: OK (پس از لاگین API)
|
||||

|
||||
|
||||
- شمارندهها: ۷ دوره، ۱۰ برنامه، ۴ رویداد، ۴ مقاله، ۱۰ استاد، ۳ alumni
|
||||
- جدول لیدهای اخیر دیده میشود
|
||||
|
||||
### دورهها — لیست (`/admin/courses`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
### دوره — ایجاد (`/admin/courses/new`)
|
||||
وضعیت: OK — **آپلود تصویر فعال**
|
||||

|
||||
|
||||
- دو باکس «انتخاب و بارگذاری تصویر» برای پوستر و بروشور
|
||||
|
||||
### مقالات — لیست (`/admin/articles`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
### مقاله — ایجاد (`/admin/articles/new`)
|
||||
وضعیت: OK — **آپلود تصویر فعال**
|
||||

|
||||
|
||||
### ثبتنامها (`/admin/registrations`)
|
||||
وضعیت: OK
|
||||

|
||||
|
||||
### صفحات ادمین که اسکرین جدا نگرفتیم (الگوی یکسان GenericForm/Table)
|
||||
این مسیرها از همان رجیستری `entities` ساخته میشوند؛ UI مشابه articles است:
|
||||
|
||||
| مسیر | توضیح |
|
||||
|---|---|
|
||||
| `/admin/programs` و `.../new` و `.../[id]/edit` | CRUD برنامه |
|
||||
| `/admin/events` و new/edit | CRUD رویداد |
|
||||
| `/admin/topics` و new/edit | CRUD موضوع (+ آپلود تصویر) |
|
||||
| `/admin/faculty` و new/edit | CRUD استاد (+ آپلود تصویر اختیاری) |
|
||||
| `/admin/alumni` و new/edit | CRUD alumni (+ آپلود تصویر) |
|
||||
| `/admin/banners` | بنر کمپین (بدون تصویر) |
|
||||
| `/admin/stats` | آمار |
|
||||
| `/admin/testimonials` | نظرات |
|
||||
| `/admin/legal` | صفحات قانونی |
|
||||
| `/admin/courses/[id]/edit` | ویرایش دوره (همان فرم new با دادهٔ اولیه) |
|
||||
|
||||
اگر اسکرین جدا برای یکی از اینها لازم است بگویید تا همان را هم بگیرم.
|
||||
|
||||
---
|
||||
|
||||
## صفحات عمومی که اسکرین تکراری نگرفتیم
|
||||
|
||||
| نوع | نمونه گرفتهشده | بقیه در DB (اسکرین نشد) |
|
||||
|---|---|---|
|
||||
| دوره/ثبتنام | `/register/ai-fluency` | branding, marketing, branding-marketing-in-practice, ai-organizational-transformation, hr-prompt-engineering, managerial-dialogue |
|
||||
| برنامه | `/programs/management-core` | bridge, business-analytics, leadership-fellows, finance, executive, systems-management, evening-management, research-track, short-executive |
|
||||
| رویداد | `/events/evt-1` | evt-2, evt-3, evt-4 |
|
||||
| مقاله | `/insights/art-1` | art-2, art-3, art-4 |
|
||||
| موضوع | یک topic | branding, marketing, managerial-dialogue |
|
||||
|
||||
الگوی قالب یکی است؛ تفاوت عمدتاً محتوا/تصویر است.
|
||||
|
||||
---
|
||||
|
||||
## پیشنهاد اقدام بعدی (اولویت)
|
||||
|
||||
1. whitelist قانونی را به `privacy` و `accessibility` گسترش دهید (یا از DB بخوانید).
|
||||
2. برای دورهها در ادمین تگ بگذارید تا منوی «دورهها» پر شود.
|
||||
3. جزئیات رویداد را در صورت نیاز غنیتر کنید (تصویر/CTA).
|
||||
4. صفحهٔ اساتید خارجی را دستی در مرورگر چک کنید (WAF محیط اتوماسیون را بسته).
|
||||
|
After Width: | Height: | Size: 1.2 MiB |
|
After Width: | Height: | Size: 2.1 MiB |
|
After Width: | Height: | Size: 420 KiB |
|
After Width: | Height: | Size: 374 KiB |
|
After Width: | Height: | Size: 302 KiB |
|
After Width: | Height: | Size: 597 KiB |
|
After Width: | Height: | Size: 285 KiB |
|
After Width: | Height: | Size: 283 KiB |
|
After Width: | Height: | Size: 702 KiB |
|
After Width: | Height: | Size: 507 KiB |
|
After Width: | Height: | Size: 445 KiB |
|
After Width: | Height: | Size: 352 KiB |
|
After Width: | Height: | Size: 370 KiB |
|
After Width: | Height: | Size: 981 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 252 KiB |
|
After Width: | Height: | Size: 252 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 86 KiB |
|
After Width: | Height: | Size: 137 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 112 KiB |
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 84 KiB |
@@ -0,0 +1,262 @@
|
||||
[
|
||||
{
|
||||
"id": "01-home",
|
||||
"title": "صفحه اصلی (/)",
|
||||
"url": "/",
|
||||
"finalUrl": "http://localhost:3000/",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "01-home.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "02-professional",
|
||||
"title": "لندینگ حرفهای (/professional)",
|
||||
"url": "/professional",
|
||||
"finalUrl": "http://localhost:3000/professional",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "02-professional.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "03-about",
|
||||
"title": "درباره ما (/about)",
|
||||
"url": "/about",
|
||||
"finalUrl": "http://localhost:3000/about",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "03-about.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "04-values",
|
||||
"title": "ارزشها (/values)",
|
||||
"url": "/values",
|
||||
"finalUrl": "http://localhost:3000/values",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "04-values.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "05-contact",
|
||||
"title": "تماس (/contact)",
|
||||
"url": "/contact",
|
||||
"finalUrl": "http://localhost:3000/contact",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "05-contact.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "06-alumni",
|
||||
"title": "دانشآموختگان (/alumni)",
|
||||
"url": "/alumni",
|
||||
"finalUrl": "http://localhost:3000/alumni",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "06-alumni.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "07-events",
|
||||
"title": "فهرست رویدادها (/events)",
|
||||
"url": "/events",
|
||||
"finalUrl": "http://localhost:3000/events",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "07-events.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "08-event-detail",
|
||||
"title": "جزئیات رویداد (/events/evt-1)",
|
||||
"url": "/events/evt-1",
|
||||
"finalUrl": "http://localhost:3000/events/evt-1",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "08-event-detail.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "09-insights",
|
||||
"title": "فهرست بینشها (/insights)",
|
||||
"url": "/insights",
|
||||
"finalUrl": "http://localhost:3000/insights",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "09-insights.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "10-insight-detail",
|
||||
"title": "جزئیات مقاله (/insights/art-1)",
|
||||
"url": "/insights/art-1",
|
||||
"finalUrl": "http://localhost:3000/insights/art-1",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "10-insight-detail.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "11-programs",
|
||||
"title": "فهرست برنامهها (/programs)",
|
||||
"url": "/programs",
|
||||
"finalUrl": "http://localhost:3000/programs",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "11-programs.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "12-program-detail",
|
||||
"title": "جزئیات برنامه (/programs/management-core)",
|
||||
"url": "/programs/management-core",
|
||||
"finalUrl": "http://localhost:3000/programs/management-core",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "12-program-detail.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "13-topic-detail",
|
||||
"title": "موضوع (/topics/ai-organizational-transformation)",
|
||||
"url": "/topics/ai-organizational-transformation",
|
||||
"finalUrl": "http://localhost:3000/topics/ai-organizational-transformation",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "13-topic-detail.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "14-register",
|
||||
"title": "ثبتنام/علاقه (/register/ai-fluency)",
|
||||
"url": "/register/ai-fluency",
|
||||
"finalUrl": "http://localhost:3000/register/ai-fluency",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "14-register.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "15-privacy",
|
||||
"title": "حریم خصوصی (/privacy)",
|
||||
"url": "/privacy",
|
||||
"finalUrl": "http://localhost:3000/privacy",
|
||||
"status": "http-error",
|
||||
"note": "HTTP 404",
|
||||
"file": "15-privacy.png",
|
||||
"httpStatus": 404
|
||||
},
|
||||
{
|
||||
"id": "16-accessibility",
|
||||
"title": "دسترسیپذیری (/accessibility)",
|
||||
"url": "/accessibility",
|
||||
"finalUrl": "http://localhost:3000/accessibility",
|
||||
"status": "http-error",
|
||||
"note": "HTTP 404",
|
||||
"file": "16-accessibility.png",
|
||||
"httpStatus": 404
|
||||
},
|
||||
{
|
||||
"id": "17-press",
|
||||
"title": "روابط عمومی (/press)",
|
||||
"url": "/press",
|
||||
"finalUrl": "http://localhost:3000/press",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "17-press.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "18-careers",
|
||||
"title": "همکاری با ما (/careers)",
|
||||
"url": "/careers",
|
||||
"finalUrl": "http://localhost:3000/careers",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "18-careers.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "19-faculty-redirect",
|
||||
"title": "اساتید (/faculty → ریدایرکت خارجی)",
|
||||
"url": "/faculty",
|
||||
"finalUrl": "https://mst.aut.ac.ir/content/31094/%D8%B4%D8%A8%DA%A9%D9%87-%D8%A7%D8%B3%D8%A7%D8%AA%DB%8C%D8%AF",
|
||||
"status": "http-error",
|
||||
"note": "HTTP 500",
|
||||
"file": "19-faculty-redirect.png",
|
||||
"httpStatus": 500
|
||||
},
|
||||
{
|
||||
"id": "20-admin-login",
|
||||
"title": "ورود ادمین (/admin/login)",
|
||||
"url": "/admin/login",
|
||||
"finalUrl": "http://localhost:3000/admin/login",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "20-admin-login.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "21-admin-dashboard",
|
||||
"title": "داشبورد ادمین (/admin)",
|
||||
"url": "/admin",
|
||||
"finalUrl": "http://localhost:3000/admin",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "21-admin-dashboard.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "22-admin-courses",
|
||||
"title": "لیست دورهها (/admin/courses)",
|
||||
"url": "/admin/courses",
|
||||
"finalUrl": "http://localhost:3000/admin/courses",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "22-admin-courses.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "23-admin-course-new",
|
||||
"title": "ایجاد دوره — فیلد آپلود تصویر (/admin/courses/new)",
|
||||
"url": "/admin/courses/new",
|
||||
"finalUrl": "http://localhost:3000/admin/courses/new",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "23-admin-course-new.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "24-admin-articles",
|
||||
"title": "لیست مقالات (/admin/articles)",
|
||||
"url": "/admin/articles",
|
||||
"finalUrl": "http://localhost:3000/admin/articles",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "24-admin-articles.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "25-admin-articles-new",
|
||||
"title": "ایجاد مقاله — فیلد آپلود (/admin/articles/new)",
|
||||
"url": "/admin/articles/new",
|
||||
"finalUrl": "http://localhost:3000/admin/articles/new",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "25-admin-articles-new.png",
|
||||
"httpStatus": 200
|
||||
},
|
||||
{
|
||||
"id": "26-admin-registrations",
|
||||
"title": "ثبتنامها (/admin/registrations)",
|
||||
"url": "/admin/registrations",
|
||||
"finalUrl": "http://localhost:3000/admin/registrations",
|
||||
"status": "ok",
|
||||
"note": "",
|
||||
"file": "26-admin-registrations.png",
|
||||
"httpStatus": 200
|
||||
}
|
||||
]
|
||||
@@ -1,26 +1,17 @@
|
||||
# Active Context
|
||||
|
||||
## Current Goal
|
||||
منوی صفحهٔ اصلی: یک دراپداون دوره از تگها (`courseNavParentTag` + `docs/LINKS.md`). در انتظار تأیید لیبل تگ پدر (ابهام 01).
|
||||
تاکسونومی دوره (دسته + تگ ادمینمحور) پیاده شد (D25). لیبل ریشهٔ منو همچنان `courseNavParentTag` = «دورهها».
|
||||
|
||||
## Current Work
|
||||
کار ساختاری به پایان رسید و همهٔ چکهای نهایی سبزند (2026-09-24):
|
||||
|
||||
- **حذف وابستگی runtime به mock**: همهٔ importهای `@/lib/mock` از runtime حذف شد. هویت/ناو استاتیک که تیبل ندارند → `src/lib/site-config.ts` (siteName، siteShortName، siteFaculty، siteUniversity، siteMission، siteAddress، homeNav، professionalNav، aboutFocusAreas، valuesContent، courseCategories). `src/lib/mock/site.ts` فقط برای seed (`db/seed.mjs`) باقی ماند (هدر کامنت دارد).
|
||||
- **محتوا از DB**: `src/lib/data/site.ts` + `getSiteStats()`/`getTestimonials()` (مپرهای `rowToSiteStat`/`rowToTestimonial` موجود بودند)؛ هوم (`intersections` → `getTopics()` + `stats`) و `/professional` (stats/testimonials) از DB میخوانند. `HomeRest` prop جدید `stats: SiteStat[]` گرفت (Page آن را پاس میدهد).
|
||||
- **ایندکسها**: `db/migrations/002_indexes.sql` اعمال شد (`registration_leads(created_at DESC)`، `articles(published, published_at DESC)`، `events(published, start_date)`، `programs/courses(published, title)`). slugها و `articles_one_featured` از 001 موجودند.
|
||||
- **tests**: tsc/lint/build سبز؛ `scripts/smoke.mjs` با `SMOKE_OK` زنده پاس شد (۴ API عمومی + login + create stat + delete stat؛ لید باقینماند)؛ `/` و `/professional` با خروجی 200؛ ایندکس بهصورت idempotent اجرا شد.
|
||||
- **docs**: `00-brief.md` (ادمین دیگر out نیست)، `01-architecture.md` (پستگرس + ادمین همان اپ + الگوی registry)، `03-database.md` (بینقص: جداول + migrate/seed + ایندکس ۰۰۲)، `04-development-plan.md` (چکلیست H کامل)، `README.md` (دستورات dev/migrate/seed/admin/smoke) بهروز شدند.
|
||||
- جداول `course_categories` / `course_tags` + junction؛ migration `007_course_taxonomy.sql`
|
||||
- ادمین: `/admin/course-categories`، `/admin/course-tags`؛ فرم دوره چندانتخابی
|
||||
- عمومی: منو از تگهای `show_in_nav`؛ فیلتر `/professional?tag=` و `?category=` با slug
|
||||
- مستند: `docs/LINKS.md`، domain-rules، D25
|
||||
|
||||
## Current Blockers
|
||||
بدون مانع. تصمیمهای باز (حذف vs unpublish؛ ORM؛ محتوای واقعی) در بخش ۱۵ پلن برای پرسش هنگام نیاز آمدهاند.
|
||||
بدون مانع.
|
||||
|
||||
## Next Steps
|
||||
1. محتوای واقعی از پنل ادمین (طبق دستور کاربر بعداً — فعلاً چیزی بقای ساختاری نمانده).
|
||||
2. (اختیاری، بخش ۱۰ پلن) rate limit روی `POST /api/registrations`.
|
||||
|
||||
## آپلود تصویر (D24 — 2026-10-11)
|
||||
ادمین فایل را از UI بارگذاری میکند (`ImageUploadField` + `POST /api/admin/upload`). مسیر در DB بهصورت `/uploads/...` ذخیره میشود. در Docker volume `uploads_data` را نگه دارید.
|
||||
|
||||
## نکته برای ادامهٔ کار
|
||||
صفحات جدید داخل `src/app/admin/(guard)/` و کامپوننتهای رابط در `src/components/organisms/admin/*`. افزودن primitive shadcn جدید فقط با `npx shadcn@latest add <name>` (بدون دستنویسی). **انتقال spec به Client Component نباید تابع داشته باشد** (list/get/preview → فقط `GenericFormSpec` serialize میشود؛ `GenericTable` سرور است و spec کامل مجاز است). Select بیس UI مقدار `null` هم میفرستد (`(v) => v ?? "all"`). در PowerShell مسیرهای حاوی `[id]` به `-LiteralPath` نیاز دارند؛ `Start-Process cmd` باید با `-ArgumentList @('/c', 'npm run start -- -p 3100 > server.log 2>&1')` ساخته شود. تست زنده: `npm run build` سپس سرور روی `-p 3100` و لاگین با `admin@aut.ac.ir/admin123` (cookie دارای Secure است؛ روی http باید دستی ارسال شود). smoke: `SMOKE_ADMIN_EMAIL/PASSWORD` بگذار و `node scripts/smoke.mjs` بزن.
|
||||
1. `node db/migrate.mjs` سپس در صورت نیاز `node db/seed.mjs` روی محیطهای موجود
|
||||
2. محتوای واقعی دسته/تگ/دوره از پنل ادمین
|
||||
@@ -37,7 +37,8 @@
|
||||
|
||||
## Doing
|
||||
|
||||
- [x] منوی هوم: حذف دکمههای جدا «دورههای کوتاه/صنعتی» → یک دراپداون از تگها؛ تگ پدر در `courseNavParentTag`؛ لینک پایدار `?tag=`؛ مستند `docs/LINKS.md`
|
||||
- [x] منوی هوم: یک دراپداون از تگها؛ `courseNavParentTag`؛ لینک پایدار
|
||||
- [x] D25 تاکسونومی ادمینمحور: دسته + تگ many-to-many؛ migration 007؛ CRUD ادمین؛ فیلتر `?tag=`/`?category=` با slug
|
||||
|
||||
## Next
|
||||
- [x] فاز H باقیمانده — ایندکسها، docs/README نهایی، حذف وابستگی runtime به mock، smoke script
|
||||
|
||||
@@ -6,7 +6,11 @@
|
||||
"dev": "next dev",
|
||||
"build": "next build --webpack",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
"lint": "eslint",
|
||||
"db:migrate": "node db/migrate.mjs",
|
||||
"db:seed": "node db/seed.mjs",
|
||||
"db:test": "node scripts/test-db-connection.mjs",
|
||||
"db:seed-admin": "node scripts/seed-admin.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.8.0",
|
||||
|
||||
@@ -16,6 +16,19 @@ if not exist "node_modules\" (
|
||||
)
|
||||
)
|
||||
|
||||
if not exist ".env.local" (
|
||||
echo.
|
||||
echo [خطا] فایل .env.local وجود ندارد.
|
||||
echo ابتدا .env.example را کپی کنید و DATABASE_URL دیتابیس تست را بگذارید:
|
||||
echo copy .env.example .env.local
|
||||
echo سپس:
|
||||
echo npm run db:test
|
||||
echo npm run db:migrate
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo در حال اجرای سرور توسعه...
|
||||
echo آدرسها:
|
||||
echo هوم: http://localhost:3000
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
/**
|
||||
* Capture full-page screenshots of public + admin routes for visual review.
|
||||
* Usage: node scripts/capture-page-screenshots.mjs
|
||||
* Requires: local next dev on BASE_URL, and npx playwright chromium installed.
|
||||
*/
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { chromium } from "playwright";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const root = path.resolve(__dirname, "..");
|
||||
const outDir = path.join(root, "docs", "review", "screenshots");
|
||||
const BASE = process.env.BASE_URL || "http://localhost:3000";
|
||||
const ADMIN_EMAIL = process.env.SMOKE_ADMIN_EMAIL || "admin@aut.ac.ir";
|
||||
const ADMIN_PASSWORD = process.env.SMOKE_ADMIN_PASSWORD || "admin123";
|
||||
|
||||
const publicPages = [
|
||||
{ id: "01-home", url: "/", title: "صفحه اصلی (/)" },
|
||||
{ id: "02-professional", url: "/professional", title: "لندینگ حرفهای (/professional)" },
|
||||
{ id: "03-about", url: "/about", title: "درباره ما (/about)" },
|
||||
{ id: "04-values", url: "/values", title: "ارزشها (/values)" },
|
||||
{ id: "05-contact", url: "/contact", title: "تماس (/contact)" },
|
||||
{ id: "06-alumni", url: "/alumni", title: "دانشآموختگان (/alumni)" },
|
||||
{ id: "07-events", url: "/events", title: "فهرست رویدادها (/events)" },
|
||||
{ id: "08-event-detail", url: "/events/evt-1", title: "جزئیات رویداد (/events/evt-1)" },
|
||||
{ id: "09-insights", url: "/insights", title: "فهرست بینشها (/insights)" },
|
||||
{ id: "10-insight-detail", url: "/insights/art-1", title: "جزئیات مقاله (/insights/art-1)" },
|
||||
{ id: "11-programs", url: "/programs", title: "فهرست برنامهها (/programs)" },
|
||||
{
|
||||
id: "12-program-detail",
|
||||
url: "/programs/management-core",
|
||||
title: "جزئیات برنامه (/programs/management-core)",
|
||||
},
|
||||
{
|
||||
id: "13-topic-detail",
|
||||
url: "/topics/ai-organizational-transformation",
|
||||
title: "موضوع (/topics/ai-organizational-transformation)",
|
||||
},
|
||||
{
|
||||
id: "14-register",
|
||||
url: "/register/ai-fluency",
|
||||
title: "ثبتنام/علاقه (/register/ai-fluency)",
|
||||
},
|
||||
{ id: "15-privacy", url: "/privacy", title: "حریم خصوصی (/privacy)" },
|
||||
{ id: "16-accessibility", url: "/accessibility", title: "دسترسیپذیری (/accessibility)" },
|
||||
{ id: "17-press", url: "/press", title: "روابط عمومی (/press)" },
|
||||
{ id: "18-careers", url: "/careers", title: "همکاری با ما (/careers)" },
|
||||
{ id: "19-faculty-redirect", url: "/faculty", title: "اساتید (/faculty → ریدایرکت خارجی)" },
|
||||
];
|
||||
|
||||
const adminPages = [
|
||||
{ id: "20-admin-login", url: "/admin/login", title: "ورود ادمین (/admin/login)", login: false },
|
||||
{ id: "21-admin-dashboard", url: "/admin", title: "داشبورد ادمین (/admin)", login: true },
|
||||
{ id: "22-admin-courses", url: "/admin/courses", title: "لیست دورهها (/admin/courses)", login: true },
|
||||
{
|
||||
id: "23-admin-course-new",
|
||||
url: "/admin/courses/new",
|
||||
title: "ایجاد دوره — فیلد آپلود تصویر (/admin/courses/new)",
|
||||
login: true,
|
||||
},
|
||||
{
|
||||
id: "24-admin-articles",
|
||||
url: "/admin/articles",
|
||||
title: "لیست مقالات (/admin/articles)",
|
||||
login: true,
|
||||
},
|
||||
{
|
||||
id: "25-admin-articles-new",
|
||||
url: "/admin/articles/new",
|
||||
title: "ایجاد مقاله — فیلد آپلود (/admin/articles/new)",
|
||||
login: true,
|
||||
},
|
||||
{
|
||||
id: "26-admin-registrations",
|
||||
url: "/admin/registrations",
|
||||
title: "ثبتنامها (/admin/registrations)",
|
||||
login: true,
|
||||
},
|
||||
];
|
||||
|
||||
async function capture(page, item) {
|
||||
const result = {
|
||||
id: item.id,
|
||||
title: item.title,
|
||||
url: item.url,
|
||||
finalUrl: "",
|
||||
status: "ok",
|
||||
note: "",
|
||||
file: `${item.id}.png`,
|
||||
};
|
||||
try {
|
||||
const response = await page.goto(new URL(item.url, BASE).toString(), {
|
||||
waitUntil: "domcontentloaded",
|
||||
timeout: 60000,
|
||||
});
|
||||
await page.waitForTimeout(1200);
|
||||
result.finalUrl = page.url();
|
||||
result.httpStatus = response?.status() ?? null;
|
||||
if (item.id === "19-faculty-redirect") {
|
||||
result.note =
|
||||
"این مسیر در next.config به سایت خارجی mst.aut.ac.ir ریدایرکت دائمی میشود؛ صفحه داخلی ندارد.";
|
||||
if (!result.finalUrl.includes("localhost")) {
|
||||
result.status = "redirect-external";
|
||||
}
|
||||
}
|
||||
const dest = path.join(outDir, result.file);
|
||||
await page.screenshot({ path: dest, fullPage: true });
|
||||
if (result.httpStatus && result.httpStatus >= 400) {
|
||||
result.status = "http-error";
|
||||
result.note = `HTTP ${result.httpStatus}`;
|
||||
}
|
||||
} catch (err) {
|
||||
result.status = "failed";
|
||||
result.note = err instanceof Error ? err.message : String(err);
|
||||
try {
|
||||
await page.screenshot({
|
||||
path: path.join(outDir, result.file),
|
||||
fullPage: true,
|
||||
});
|
||||
} catch {
|
||||
result.file = "";
|
||||
}
|
||||
}
|
||||
console.log(`${result.status.padEnd(18)} ${item.id} → ${result.finalUrl || item.url}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
async function loginAdmin(page, context) {
|
||||
// Prefer API login so cookie is set reliably (UI uses client fetch + router.push).
|
||||
const res = await page.request.post(new URL("/api/admin/login", BASE).toString(), {
|
||||
data: { email: ADMIN_EMAIL, password: ADMIN_PASSWORD },
|
||||
});
|
||||
if (!res.ok()) {
|
||||
throw new Error(`admin login API ${res.status()}: ${await res.text()}`);
|
||||
}
|
||||
await page.goto(new URL("/admin", BASE).toString(), {
|
||||
waitUntil: "domcontentloaded",
|
||||
timeout: 60000,
|
||||
});
|
||||
await page.waitForTimeout(800);
|
||||
return page.url();
|
||||
}
|
||||
|
||||
const report = [];
|
||||
await mkdir(outDir, { recursive: true });
|
||||
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: 1440, height: 900 },
|
||||
locale: "fa-IR",
|
||||
});
|
||||
const page = await context.newPage();
|
||||
|
||||
for (const item of publicPages) {
|
||||
report.push(await capture(page, item));
|
||||
}
|
||||
|
||||
let loggedIn = false;
|
||||
for (const item of adminPages) {
|
||||
if (item.login && !loggedIn) {
|
||||
try {
|
||||
const after = await loginAdmin(page, context);
|
||||
loggedIn = after.includes("/admin") && !after.includes("/login");
|
||||
if (!loggedIn) {
|
||||
report.push({
|
||||
id: "login-blocker",
|
||||
title: "ورود ادمین",
|
||||
url: "/admin/login",
|
||||
finalUrl: after,
|
||||
status: "blocked",
|
||||
note: "لاگین ادمین موفق نشد؛ صفحات محافظتشده اسکرین نشدند. احتمالاً cookie Secure روی http یا رمز اشتباه.",
|
||||
file: "",
|
||||
});
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
report.push({
|
||||
id: "login-blocker",
|
||||
title: "ورود ادمین",
|
||||
url: "/admin/login",
|
||||
finalUrl: "",
|
||||
status: "blocked",
|
||||
note: err instanceof Error ? err.message : String(err),
|
||||
file: "",
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
report.push(await capture(page, item));
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
|
||||
const md = [];
|
||||
md.push("# بازبینی صفحات سایت — اسکرینشات");
|
||||
md.push("");
|
||||
md.push(`تاریخ: ${new Date().toISOString()}`);
|
||||
md.push(`پایه: \`${BASE}\``);
|
||||
md.push("");
|
||||
md.push("هر ردیف یک مسیر واقعی است. تصویر full-page در پوشهٔ `screenshots/` است.");
|
||||
md.push("");
|
||||
|
||||
for (const r of report) {
|
||||
md.push(`## ${r.title}`);
|
||||
md.push("");
|
||||
md.push(`- مسیر: \`${r.url}\``);
|
||||
if (r.finalUrl) md.push(`- URL نهایی: \`${r.finalUrl}\``);
|
||||
if (r.httpStatus != null) md.push(`- HTTP: ${r.httpStatus}`);
|
||||
md.push(`- وضعیت: **${r.status}**`);
|
||||
if (r.note) md.push(`- توضیح: ${r.note}`);
|
||||
if (r.file) {
|
||||
md.push("");
|
||||
md.push(``);
|
||||
}
|
||||
md.push("");
|
||||
}
|
||||
|
||||
md.push("## نکات کلی برای بررسی");
|
||||
md.push("");
|
||||
md.push("- viewport دسکتاپ ۱۴۴۰×۹۰۰؛ اسکرین full-page است.");
|
||||
md.push("- `/faculty` عمداً ریدایرکت خارجی است (صفحهٔ داخلی ندارد).");
|
||||
md.push("- جزئیات همهٔ دورهها/برنامهها/رویدادها تکرار نشد؛ از هر نوع یک نمونه گرفته شد.");
|
||||
md.push("- صفحات ادمین edit برای همهٔ entityها تکراریاند؛ نمونهٔ دوره و مقاله کافی است.");
|
||||
md.push("");
|
||||
|
||||
const reportPath = path.join(root, "docs", "review", "PAGE-AUDIT.md");
|
||||
await writeFile(reportPath, md.join("\n"), "utf8");
|
||||
await writeFile(path.join(outDir, "report.json"), JSON.stringify(report, null, 2), "utf8");
|
||||
console.log("Wrote", reportPath);
|
||||
console.log("Screenshots:", outDir);
|
||||
@@ -8,17 +8,20 @@ flock 9
|
||||
ENV_FILE=/etc/edu-production.env
|
||||
CONTAINER=aut-management-faculty
|
||||
NETWORK=shared_web_network
|
||||
UPLOAD_VOLUME=edu-uploads
|
||||
REVISION=$(git rev-parse HEAD)
|
||||
IMAGE="aut-management-faculty:$REVISION"
|
||||
|
||||
test -s "$ENV_FILE" || { echo "Missing protected production environment: $ENV_FILE" >&2; exit 1; }
|
||||
docker network inspect "$NETWORK" >/dev/null
|
||||
docker inspect insaight-postgres --format '{{json .NetworkSettings.Networks}}' | grep -q '"shared_web_network"'
|
||||
docker volume create "$UPLOAD_VOLUME" >/dev/null
|
||||
|
||||
# Keep the current app running throughout the build.
|
||||
docker build --build-arg NEXT_PUBLIC_SITE_URL=https://edu.mstaut.ir -t "$IMAGE" .
|
||||
|
||||
# Back up before applying the repository's transactional, versioned migrations.
|
||||
# Migrations are forward-only and idempotent (schema_migrations); dump is the safety net.
|
||||
install -d -m 700 /opt/backups/edu
|
||||
BACKUP="/opt/backups/edu/database-$(date -u +%Y%m%dT%H%M%SZ).dump"
|
||||
docker exec insaight-postgres sh -c 'pg_dump -U "$POSTGRES_USER" -d ManagmentWebSite_Db -Fc' > "$BACKUP"
|
||||
@@ -29,7 +32,10 @@ docker run --rm --network "$NETWORK" --env-file "$ENV_FILE" \
|
||||
|
||||
# Check the database and rendered pages before switching the public upstream.
|
||||
CANDIDATE="edu-candidate-${REVISION:0:12}"
|
||||
docker run -d --name "$CANDIDATE" --network "$NETWORK" --env-file "$ENV_FILE" "$IMAGE"
|
||||
docker run -d --name "$CANDIDATE" --network "$NETWORK" --env-file "$ENV_FILE" \
|
||||
-e UPLOAD_DIR=/app/public/uploads \
|
||||
-v "$UPLOAD_VOLUME:/app/public/uploads" \
|
||||
"$IMAGE"
|
||||
cleanup_candidate() { docker rm -f "$CANDIDATE" >/dev/null 2>&1 || true; }
|
||||
trap cleanup_candidate EXIT
|
||||
READY=false
|
||||
@@ -73,7 +79,10 @@ rollback() {
|
||||
}
|
||||
trap rollback ERR
|
||||
docker run -d --name "$CONTAINER" --restart unless-stopped \
|
||||
--network "$NETWORK" --env-file "$ENV_FILE" -p 127.0.0.1:3000:3000 "$IMAGE"
|
||||
--network "$NETWORK" --env-file "$ENV_FILE" \
|
||||
-e UPLOAD_DIR=/app/public/uploads \
|
||||
-v "$UPLOAD_VOLUME:/app/public/uploads" \
|
||||
-p 127.0.0.1:3000:3000 "$IMAGE"
|
||||
READY=false
|
||||
for attempt in $(seq 1 30); do
|
||||
if curl -fsS --max-time 5 --resolve edu.mstaut.ir:443:127.0.0.1 https://edu.mstaut.ir/ >/dev/null; then
|
||||
|
||||
@@ -1,15 +1,38 @@
|
||||
// Usage: node scripts/test-db-connection.mjs
|
||||
// Reads DATABASE_URL from the environment or .env.local (never hardcode hosts/passwords).
|
||||
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import pg from "pg";
|
||||
|
||||
const { Client } = pg;
|
||||
|
||||
const client = new Client({
|
||||
host: "185.36.145.12",
|
||||
port: 5432,
|
||||
database: "ManagmentWebSite_Db",
|
||||
user: "managment_web",
|
||||
password: process.env.DB_PASSWORD,
|
||||
if (!process.env.DATABASE_URL) {
|
||||
const envPath = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
"..",
|
||||
".env.local",
|
||||
);
|
||||
if (existsSync(envPath)) {
|
||||
for (const line of readFileSync(envPath, "utf8").split(/\r?\n/)) {
|
||||
const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);
|
||||
if (match && !(match[1] in process.env)) {
|
||||
process.env[match[1]] = match[2];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
connectionTimeoutMillis: 20000,
|
||||
if (!process.env.DATABASE_URL) {
|
||||
console.error("CONNECTION_FAIL");
|
||||
console.error("DATABASE_URL is not set. Copy .env.example → .env.local and fill it in.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new Client({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
connectionTimeoutMillis: 10000,
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -26,6 +49,14 @@ try {
|
||||
console.log("CONNECTION_OK");
|
||||
console.log(JSON.stringify(info.rows[0], null, 2));
|
||||
|
||||
const migrations = await client.query(
|
||||
"SELECT version, applied_at FROM schema_migrations ORDER BY version",
|
||||
).catch(() => ({ rows: [] }));
|
||||
console.log("migrations_applied:", migrations.rows.length);
|
||||
if (migrations.rows.length) {
|
||||
console.log(JSON.stringify(migrations.rows.map((r) => r.version), null, 2));
|
||||
}
|
||||
|
||||
const tables = await client.query(`
|
||||
SELECT table_schema, table_name
|
||||
FROM information_schema.tables
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import pg from "pg";
|
||||
import { readFileSync, existsSync } from "fs";
|
||||
|
||||
if (existsSync(".env.local")) {
|
||||
for (const line of readFileSync(".env.local", "utf8").split(/\r?\n/)) {
|
||||
const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);
|
||||
if (m && !(m[1] in process.env)) process.env[m[1]] = m[2];
|
||||
}
|
||||
}
|
||||
|
||||
const c = new pg.Client({ connectionString: process.env.DATABASE_URL });
|
||||
await c.connect();
|
||||
const r = await c.query(`
|
||||
SELECT c.slug,
|
||||
(SELECT json_agg(json_build_object('id',cat.id,'slug',cat.slug,'label',cat.label)
|
||||
ORDER BY cat.sort_order)
|
||||
FROM course_category_links l
|
||||
JOIN course_categories cat ON cat.id=l.category_id
|
||||
WHERE l.course_id=c.id) AS categories,
|
||||
(SELECT json_agg(json_build_object('id',t.id,'slug',t.slug,'label',t.label)
|
||||
ORDER BY t.sort_order)
|
||||
FROM course_tag_links l
|
||||
JOIN course_tags t ON t.id=l.tag_id
|
||||
WHERE l.course_id=c.id) AS tags
|
||||
FROM courses c
|
||||
LIMIT 2
|
||||
`);
|
||||
console.log(JSON.stringify(r.rows, null, 2));
|
||||
await c.end();
|
||||
@@ -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();
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 *`,
|
||||
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);
|
||||
const row = res.rows[0];
|
||||
} 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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
|
||||
@@ -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,15 +27,19 @@ 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([
|
||||
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,22 +125,44 @@ export function CategoryCourseExplorer({
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{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="دستهبندی دورهها"
|
||||
aria-label={categoriesLabel}
|
||||
>
|
||||
{courseCategories.map((item) => (
|
||||
<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={category === item.id ? "default" : "ghost"}
|
||||
aria-selected={category === item.id}
|
||||
onClick={() => setCategory(item.id)}
|
||||
variant={categorySlug === item.slug ? "default" : "ghost"}
|
||||
aria-selected={categorySlug === item.slug}
|
||||
onClick={() => selectCategory(item.slug)}
|
||||
className={cn(
|
||||
category !== item.id &&
|
||||
categorySlug !== item.slug &&
|
||||
"bg-background/10 text-background/85 hover:bg-background/20 hover:text-background",
|
||||
)}
|
||||
>
|
||||
@@ -127,8 +170,10 @@ export function CategoryCourseExplorer({
|
||||
</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,63 +182,74 @@ 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>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{(tag !== "" || category !== "all") && (
|
||||
{(tagSlug !== "" || categorySlug !== "") && (
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-background/60">
|
||||
<span>فیلترهای فعال:</span>
|
||||
{category !== "all" && (
|
||||
{activeCategory ? (
|
||||
<Badge variant="secondary" className="gap-1 py-0.5 pe-1">
|
||||
{courseCategories.find((c) => c.id === category)?.label ?? category}
|
||||
{activeCategory.label}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCategory("all")}
|
||||
onClick={() => {
|
||||
setCategorySlug("");
|
||||
syncUrl(tagSlug, "");
|
||||
}}
|
||||
className="rounded-full p-0.5 hover:bg-foreground/10"
|
||||
aria-label="حذف فیلتر دستهبندی"
|
||||
aria-label="حذف فیلتر دسته"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</Badge>
|
||||
)}
|
||||
{tag !== "" && (
|
||||
) : null}
|
||||
{activeTag ? (
|
||||
<Badge variant="secondary" className="gap-1 py-0.5 pe-1">
|
||||
{tag}
|
||||
{activeTag.label}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => selectTag("")}
|
||||
onClick={() => {
|
||||
setTagSlug("");
|
||||
syncUrl("", categorySlug);
|
||||
}}
|
||||
className="rounded-full p-0.5 hover:bg-foreground/10"
|
||||
aria-label="حذف فیلتر تگ"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</Badge>
|
||||
)}
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
onClick={resetFilters}
|
||||
@@ -201,10 +257,24 @@ export function CategoryCourseExplorer({
|
||||
>
|
||||
پاککردن همه
|
||||
</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>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,12 +130,19 @@ export function AdminSidebar({ userName }: { userName: string }) {
|
||||
</SidebarHeader>
|
||||
|
||||
<SidebarContent>
|
||||
{NAV_GROUPS.map((group) => (
|
||||
{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>
|
||||
{group.items.map((item) => {
|
||||
{items.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const active = isActive(
|
||||
pathname,
|
||||
@@ -145,7 +165,8 @@ export function AdminSidebar({ userName }: { userName: string }) {
|
||||
</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,52 +131,48 @@ 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>
|
||||
<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>
|
||||
<Label htmlFor="slug">اسلاگ *</Label>
|
||||
<Input
|
||||
id="slug"
|
||||
value={form.slug}
|
||||
onChange={(e) => set("slug", e.target.value)}
|
||||
placeholder="ai-for-managers"
|
||||
required
|
||||
placeholder="ai-fluency"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="title">عنوان</Label>
|
||||
<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)}
|
||||
placeholder="هوش مصنوعی برای مدیران"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5 sm:col-span-2">
|
||||
<Label htmlFor="summary">خلاصه</Label>
|
||||
<Label htmlFor="summary">خلاصه *</Label>
|
||||
<Textarea
|
||||
id="summary"
|
||||
value={form.summary}
|
||||
onChange={(e) => set("summary", e.target.value)}
|
||||
rows={3}
|
||||
required
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -209,24 +184,10 @@ export function CourseForm({ initial }: CourseFormProps) {
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-foreground">برگزاری و قیمت</h2>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">
|
||||
دسته، قالب، مدت و هزینهٔ اختیاری
|
||||
قالب، مدت و هزینهٔ اختیاری
|
||||
</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)}>
|
||||
@@ -249,10 +210,7 @@ export function CourseForm({ initial }: CourseFormProps) {
|
||||
value={form.durationHours ?? ""}
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value;
|
||||
set(
|
||||
"durationHours",
|
||||
raw === "" ? null : Number(raw),
|
||||
);
|
||||
set("durationHours", raw === "" ? null : Number(raw));
|
||||
}}
|
||||
placeholder="اختیاری"
|
||||
/>
|
||||
@@ -268,9 +226,6 @@ export function CourseForm({ initial }: CourseFormProps) {
|
||||
onChange={(e) => onPriceChange(e.target.value)}
|
||||
placeholder="خالی = بدون نمایش قیمت"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
اگر خالی بماند، قیمت در سایت نمایش داده نمیشود.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -279,87 +234,116 @@ export function CourseForm({ initial }: CourseFormProps) {
|
||||
|
||||
<section className="space-y-4">
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-foreground">تگها و دستهبندی</h2>
|
||||
<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);
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>دستهبندیها</Label>
|
||||
{categories.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
هنوز دستهای تعریف نشده. از «دستهبندی دورهها» اضافه کنید.
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{categories.map((item) => {
|
||||
const active = form.categoryIds.includes(item.id);
|
||||
return (
|
||||
<Button
|
||||
key={tag}
|
||||
key={item.id}
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={active ? "default" : "outline"}
|
||||
aria-pressed={active}
|
||||
onClick={() => toggleTag(tag)}
|
||||
onClick={() => set("categoryIds", toggleId(form.categoryIds, item.id))}
|
||||
className="h-8 px-3 text-xs"
|
||||
>
|
||||
{tag}
|
||||
{item.label}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</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}
|
||||
)}
|
||||
{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"
|
||||
onClick={() => removeTag(tag)}
|
||||
className="rounded-full p-0.5 transition-colors hover:bg-foreground/10"
|
||||
aria-label={`حذف تگ ${tag}`}
|
||||
onClick={() =>
|
||||
set(
|
||||
"categoryIds",
|
||||
form.categoryIds.filter((x) => x !== id),
|
||||
)
|
||||
}
|
||||
className="rounded-full p-0.5 hover:bg-foreground/10"
|
||||
aria-label="حذف دسته"
|
||||
>
|
||||
<X className="size-3" />
|
||||
×
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<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>
|
||||
|
||||
@@ -379,27 +363,25 @@ export function CourseForm({ initial }: CourseFormProps) {
|
||||
id="registrationUrl"
|
||||
value={form.registrationUrl}
|
||||
onChange={(e) => set("registrationUrl", e.target.value)}
|
||||
placeholder="/register/ai-for-managers"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5 sm:col-span-2">
|
||||
<Label htmlFor="posterImageUrl">پوستر (نمایش در لیست دورهها)</Label>
|
||||
<Label>پوستر</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>
|
||||
<Label>بروشور</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">
|
||||
@@ -408,14 +390,14 @@ export function CourseForm({ initial }: CourseFormProps) {
|
||||
id="seoDescription"
|
||||
value={form.seoDescription}
|
||||
onChange={(e) => set("seoDescription", e.target.value)}
|
||||
rows={2}
|
||||
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") === "true")}
|
||||
onValueChange={(v) => set("published", v === "true")}
|
||||
>
|
||||
<SelectTrigger id="published" className="w-full">
|
||||
<SelectValue />
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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 }));
|
||||
}
|
||||
@@ -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],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
`;
|
||||
@@ -1,29 +1,22 @@
|
||||
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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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) });
|
||||
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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: "همه برنامهها" },
|
||||
];
|
||||
@@ -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: "همه برنامهها" },
|
||||
];
|
||||
@@ -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;
|
||||
@@ -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";
|
||||
|
||||
@@ -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(""),
|
||||
|
||||