Compare commits

..
Author SHA1 Message Date
smhk1376 a60718aaf9 Merge branch 'master' of https://git.mstaut.ir/smhk1376/Aut.ManagementFaculty
Deploy edu.mstaut.ir / deploy (push) Successful in 22m37s
2026-10-28 14:04:33 +03:30
smhk1376 2858b9c746 Remove unused redirects from the Next.js configuration and update package dependencies to include new Tiptap extensions for enhanced text editing capabilities. Clean up the database seeding script by removing commented-out code and ensuring proper deletion of obsolete entries. Update various pages to handle not found scenarios gracefully, improving user experience across the application. 2026-10-28 14:04:17 +03:30
smhk1376 8cf4490f21 Update docker-compose.yml
Deploy edu.mstaut.ir / deploy (push) Successful in 13m59s
2026-10-22 10:11:30 +00:00
smhk1376 4b84409ed7 Enhance course management by adding 'featured' and 'sort_order' fields to the database schema and related components. Update course filtering and display logic to prioritize featured courses in the catalog. Modify admin interfaces for course creation and editing to include new fields, ensuring proper handling in both the frontend and backend. Update documentation to reflect these changes. 2026-10-22 13:23:43 +03:30
smhk1376 1641edfd01 Refactor image upload handling by moving upload directory outside of public folder for better compatibility with Next.js. Update related Docker configurations and scripts to reflect new upload paths. Replace instances of Next.js Image component with CmsImage for consistent image handling across the application. 2026-10-22 12:51:18 +03:30
smhk1376 0a57ef2b80 Update deployment workflow to enhance VPS build process by removing unsupported Docker cache mount. Improved clarity in deployment documentation.
Deploy edu.mstaut.ir / deploy (push) Successful in 16m57s
2026-10-20 01:22:57 +03:30
smhk1376andCursor 7d7b55f060 Fix VPS build: drop Docker cache mount unsupported on host daemon.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-20 01:22:27 +03:30
smhk1376 fe3d153ef1 Add local database dump directory to .gitignore to prevent accidental commits of backups.
Deploy edu.mstaut.ir / deploy (push) Failing after 34s
2026-10-20 01:21:16 +03:30
smhk1376andCursor 29b71c228e Fix Gitea deploy: restore VPS shell workflow without GitHub Actions.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-20 01:20:36 +03:30
smhk1376 e1b5286946 Refactor deployment workflow to utilize GitHub Actions for improved efficiency. Updated deploy.yml to include actions for checkout and Node.js setup, streamlined build process for Next.js with prebuilt assets, and revised deployment script to eliminate unnecessary steps. Enhanced documentation for clarity on automated deployment process. 2026-10-20 01:17:13 +03:30
smhk1376andCursor bd2cfa5a26 Add rich HTML course lead/body and refresh AI course media from delivery v2.
Deploy edu.mstaut.ir / deploy (push) Has been cancelled
Course detail pages can show sanitized HTML ad copy under the hero and a structured body; posters and brochures are updated for both AI workshops.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-20 00:54:30 +03:30
smhk1376 afd2b3333c Update docs/deployment.md
Deploy edu.mstaut.ir / deploy (push) Successful in 11m1s
2026-10-16 14:17:55 +00:00
smhk1376 05b0a1af72 Update image references to use WebP format for improved performance and remove unused design candidates from the project. Adjusted placeholder image handling in the faculty import script and updated metadata for various pages to reflect the new image paths. 2026-10-16 17:45:55 +03:30
smhk1376 5b0a394216 Refactor BrandLogo component to use native img element for improved loading performance and adjust styling for better responsiveness. Removed fixed width/height attributes to maintain aspect ratio.
Deploy edu.mstaut.ir / deploy (push) Successful in 11m53s
2026-10-16 17:28:12 +03:30
smhk1376andCursor 2709181557 Size horizontal logo to full header height without zoom.
Deploy edu.mstaut.ir / deploy (push) Has been cancelled
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 17:22:48 +03:30
smhk1376andCursor 6745fcdc3f Restore large horizontal logo in header slot without changing header height.
Deploy edu.mstaut.ir / deploy (push) Has been cancelled
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 17:22:01 +03:30
smhk1376andCursor 2f80b96a95 Keep horizontal header logo; fix oversized stretch scaling.
Replace the 235% zoom hack with header-slot height and object-contain so aspect ratio stays correct.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 17:20:48 +03:30
smhk1376andCursor cf29d44ff8 Revert header logo to the agreed seal mark size.
Deploy edu.mstaut.ir / deploy (push) Successful in 12m1s
The temporary horizontal wordmark used 235% height and overpowered the header.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 17:06:25 +03:30
smhk1376andCursor c97498a2ae Fix deploy health check for /mstcontroller and cut ready-loop waste.
Deploy edu.mstaut.ir / deploy (push) Successful in 5m56s
Admin login moved off /admin; old path caused 404 spam for up to two minutes. Slim smoke checks, shorter retries, quieter migrate logs, and npm ci without audit in the image build.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 16:57:31 +03:30
smhk1376andCursor 69bdaf0113 Clear stale git lock files before production checkout fetch.
Deploy edu.mstaut.ir / deploy (push) Has been cancelled
Interrupted shallow fetches leave shallow.lock and block the next deploy.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 16:33:28 +03:30
smhk1376andCursor 8eee3242bf Trigger deploy workflow with a no-op docs probe.
Deploy edu.mstaut.ir / deploy (push) Failing after 12s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 16:32:11 +03:30
smhk1376 4405097f56 Refactor course management features and enhance navigation. Updated course data structure to include new fields for poster and brochure images, improved tag management, and refined admin filters for better usability. Adjusted navigation links to align with the updated course and faculty structure. 2026-10-16 16:27:24 +03:30
233 changed files with 4653 additions and 1235 deletions

No files matched your search

+3
View File
@@ -18,6 +18,9 @@
.claude
skills
# unused design candidates (not referenced by the app)
/public/CandidatesIMages
# project meta / docs
memory-bank
docs
+7 -3
View File
@@ -13,7 +13,7 @@ jobs:
deploy:
runs-on: local-host
steps:
- name: Checkout and deploy on the VPS
- name: Build and deploy on the VPS
env:
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO_ACTOR: ${{ github.actor }}
@@ -27,9 +27,13 @@ jobs:
git -C "$TARGET" init
git -C "$TARGET" remote add origin "http://127.0.0.1:8301/$REPO_NAME.git"
fi
# Supply the job token only for fetch; never store it in .git/config.
rm -f \
"$TARGET/.git/shallow.lock" \
"$TARGET/.git/index.lock" \
"$TARGET/.git/HEAD.lock" \
"$TARGET/.git/config.lock"
AUTH=$(printf '%s:%s' "$REPO_ACTOR" "$REPO_TOKEN" | base64 -w0)
git -C "$TARGET" -c "http.extraHeader=Authorization: Basic $AUTH" fetch --depth=1 origin "$DEPLOY_SHA"
unset AUTH REPO_TOKEN
git -C "$TARGET" checkout --detach --force FETCH_HEAD
bash "$TARGET/scripts/deploy-production.sh"
bash "$TARGET/scripts/vps-autodeploy.sh"
+7 -3
View File
@@ -2,6 +2,7 @@
# dependencies
/node_modules
/.npm-cache
/.pnp
.pnp.*
.yarn/*
@@ -24,9 +25,9 @@
.DS_Store
*.pem
# admin-uploaded images (keep folder via .gitkeep)
/public/uploads/*
!/public/uploads/.gitkeep
# admin-uploaded images (served by GET /uploads/[...path], not public/)
/uploads/
/public/uploads/
# debug
npm-debug.log*
@@ -37,6 +38,9 @@ yarn-error.log*
# env files (can opt-in for committing if needed)
.env*
# local database dumps — never commit
/backups/
# vercel
.vercel
+9 -3
View File
@@ -1,8 +1,11 @@
# syntax=docker/dockerfile:1
# ---- Dependencies ----
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# Skip audit/fund in image builds (saves ~30–60s); keep npm cache across deploys.
RUN --mount=type=cache,target=/root/.npm \
npm ci --no-audit --no-fund
# ---- Builder ----
FROM node:22-alpine AS builder
@@ -33,8 +36,11 @@ COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
# Writable dir for admin image uploads (mount a volume in compose for persistence)
RUN mkdir -p ./public/uploads && chown -R nextjs:nodejs ./public/uploads
# Writable dir for admin image uploads (mount a volume in compose for persistence).
# Keep this outside public/: Next standalone does not serve runtime public files.
RUN rm -rf ./public/uploads \
&& mkdir -p ./uploads \
&& chown -R nextjs:nodejs ./uploads
USER nextjs
+5 -2
View File
@@ -18,8 +18,11 @@ COPY --chown=nextjs:nodejs . ./
# Next warns/breaks if a legacy root-level ./static exists alongside ./public
RUN rm -rf ./static
# Writable dir for admin image uploads (mount a volume in compose for persistence)
RUN mkdir -p ./public/uploads && chown -R nextjs:nodejs ./public/uploads
# Writable dir for admin image uploads (mount a volume in compose for persistence).
# Keep this outside public/: Next standalone does not serve runtime public files.
RUN rm -rf ./public/uploads \
&& mkdir -p ./uploads \
&& chown -R nextjs:nodejs ./uploads
USER nextjs
EXPOSE 3000
+5 -5
View File
@@ -74,16 +74,16 @@ async function main() {
}
const tables = await client.query(`
SELECT table_name
SELECT count(*)::int AS n
FROM information_schema.tables
WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
ORDER BY table_name
`);
console.log(`applied_count: ${appliedCount}`);
console.log(`skipped (already applied): ${skipped.length ? skipped.join(", ") : "none"}`);
console.log(`tables_count: ${tables.rows.length}`);
console.log(JSON.stringify(tables.rows.map((r) => r.table_name)));
if (skipped.length) {
console.log(`skipped_count: ${skipped.length}`);
}
console.log(`tables_count: ${tables.rows[0].n}`);
} finally {
await client.end().catch(() => {});
}
+4
View File
@@ -0,0 +1,4 @@
-- Rich HTML fields for course detail: ad lead under hero title + main body.
ALTER TABLE courses
ADD COLUMN IF NOT EXISTS lead_html TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS body_html TEXT NOT NULL DEFAULT '';
+5
View File
@@ -0,0 +1,5 @@
-- Catalog pin + manual order for current courses.
-- Archive grouping still uses tag-archive; featured never lifts an archive course.
ALTER TABLE courses
ADD COLUMN IF NOT EXISTS featured BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0;
@@ -0,0 +1,8 @@
-- Public sections other than courses are retired.
-- Drop their rows so they cannot be served or listed again.
DELETE FROM articles;
DELETE FROM events;
DELETE FROM programs;
DELETE FROM intersection_topics;
DELETE FROM alumni_stories;
DELETE FROM testimonials;
+4
View File
@@ -0,0 +1,4 @@
-- Optional schedule for a course: when it starts, and when it is held.
ALTER TABLE courses
ADD COLUMN IF NOT EXISTS start_date DATE,
ADD COLUMN IF NOT EXISTS held_date DATE;
+21
View File
@@ -0,0 +1,21 @@
-- News items shown on /news. Separate from articles (long-form insights).
CREATE TABLE IF NOT EXISTS news_items (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
banner_image_url TEXT NOT NULL,
body TEXT NOT NULL,
gallery_images JSONB NOT NULL DEFAULT '[]',
published_at DATE NOT NULL,
published BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_news_items_published_at
ON news_items (published, published_at DESC);
DROP TRIGGER IF EXISTS trg_news_items_set_updated_at ON news_items;
CREATE TRIGGER trg_news_items_set_updated_at
BEFORE UPDATE ON news_items
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
+6
View File
@@ -0,0 +1,6 @@
-- One date per course: when it starts being held.
UPDATE courses
SET start_date = held_date
WHERE start_date IS NULL AND held_date IS NOT NULL;
ALTER TABLE courses DROP COLUMN IF EXISTS held_date;
+14 -34
View File
@@ -8,17 +8,11 @@ import { fileURLToPath } from "node:url";
import pg from "pg";
import { courses } from "../src/lib/mock/courses.ts";
import { programs } from "../src/lib/mock/programs.ts";
import { events } from "../src/lib/mock/events.ts";
import { articles } from "../src/lib/mock/articles.ts";
import {
alumniStories,
campaignBanners,
faculty,
intersections,
legalPages,
stats,
testimonials,
} from "../src/lib/mock/site.ts";
import {
SEED_COURSE_CATEGORIES,
@@ -26,17 +20,11 @@ import {
} from "../src/lib/taxonomy.ts";
import {
alumniStoryToRow,
articleToRow,
campaignBannerToRow,
courseToRow,
eventToRow,
facultyMemberToRow,
intersectionTopicToRow,
legalPageToRow,
programToRow,
siteStatToRow,
testimonialToRow,
} from "../src/lib/db/mappers.ts";
if (!process.env.DATABASE_URL) {
@@ -121,7 +109,9 @@ async function main() {
await upsert("courses", courses.map(courseToRow), [
"id", "slug", "title", "summary", "duration_hours", "format", "price",
"registration_url", "poster_image_url", "brochure_image_url", "image_url", "seo_description", "published",
"registration_url", "poster_image_url", "brochure_image_url", "image_url",
"lead_html", "body_html", "seo_description", "published", "featured",
"sort_order",
]);
const courseIds = courses.map((c) => c.id);
await client.query(
@@ -154,29 +144,22 @@ async function main() {
}
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",
]);
await upsert("events", events.map(eventToRow), [
"id", "title", "start_date", "end_date", "location", "href", "summary", "published",
]);
await upsert("articles", articles.map(articleToRow), [
"id", "title", "category", "excerpt", "image_url", "href", "featured",
"body", "published_at", "author", "published",
]);
await client.query(`DELETE FROM intersection_topics`);
await upsert("intersection_topics", intersections.map(intersectionTopicToRow), [
"id", "slug", "title", "description", "href", "image_url", "body", "highlights", "published",
]);
for (const table of [
"programs",
"events",
"articles",
"intersection_topics",
"alumni_stories",
"testimonials",
]) {
const deleted = await client.query(`DELETE FROM ${table}`);
results.push([`${table}_cleared`, deleted.rowCount]);
}
await upsert("faculty_members", faculty.map(facultyMemberToRow), [
"id", "name", "title", "focus", "bio", "image_url",
"email", "office", "phone", "department", "linkedin_url", "scholar_url",
"published",
]);
await upsert("alumni_stories", alumniStories.map(alumniStoryToRow), [
"id", "title", "excerpt", "name", "program", "image_url", "href", "published",
]);
await upsert("campaign_banners", campaignBanners.map(campaignBannerToRow), [
"id", "version", "text", "href", "cta", "published",
]);
@@ -186,9 +169,6 @@ async function main() {
await upsert("site_stats", stats.map(siteStatToRow), [
"id", "value", "label", "published",
]);
await upsert("testimonials", testimonials.map(testimonialToRow), [
"id", "quote", "name", "role", "course_title", "published",
]);
const counts = await client.query(`
SELECT (SELECT count(*) FROM courses) AS courses,
+4 -2
View File
@@ -13,11 +13,11 @@ services:
- HOSTNAME=0.0.0.0
- NEXT_PUBLIC_SITE_URL=${NEXT_PUBLIC_SITE_URL:-https://edu.mstaut.ir}
- DATABASE_URL=${DATABASE_URL:?Set DATABASE_URL in a protected environment file}
- UPLOAD_DIR=/app/public/uploads
- UPLOAD_DIR=/app/uploads
# Nginx Proxy Manager: edu.mstaut.ir → http://aut-management-faculty:3000
# DB: same Docker network as container `insaight-postgres` (not the public IP).
volumes:
- uploads_data:/app/public/uploads
- uploads_data:/app/uploads
expose:
- "3000"
networks:
@@ -32,3 +32,5 @@ networks:
shared_web_network:
external: true
name: shared_web_network
# TEST
+4
View File
@@ -47,6 +47,8 @@
|---|---|
| `course.categories` | many-to-many با `course_categories` (موضوع؛ ادمین) |
| `course.tags` | many-to-many با `course_tags` (نوع/منو؛ ادمین) |
| `course.featured` | تیک ویژه؛ چند دورهٔ جاری می‌توانند ویژه باشند (محدودیت تک‌ویژهٔ مقاله اینجا نیست) |
| `course.sortOrder` | عدد ترتیب؛ کوچک‌تر جلوتر (مثل دسته/تگ) |
| `program.group` | `standard` یا `executive` برای selector هوم |
| `event.endDate` | اگر null باشد رویداد تک‌روزه است |
| `article.featured` | حداکثر یک مقاله featured در هوم |
@@ -58,6 +60,8 @@
- هیچ مبلغ/ظرفیت واقعی محاسبه نمی‌شود تا DB وصل شود.
- منوی صفحهٔ اصلی فقط **یک** دراپ‌داون دوره دارد؛ لیبل ریشه = `courseNavParentTag`؛ فرزندان = تگ‌های `show_in_nav`. فیلتر پایدار با **slug**: `/professional?tag=` و `/professional?category=` (مستند: `docs/LINKS.md`).
- دسته و تگ فقط از ادمین تعریف می‌شوند (`/admin/course-categories`، `/admin/course-tags`)؛ هر دوره می‌تواند چند دسته و چند تگ داشته باشد.
- ترتیب لیست عمومی دوره: غیرآرشیو، سپس `featured`، سپس `sort_order` صعودی، سپس عنوان. هوم و جستجو همین ترتیب را می‌گیرند؛ هوم آرشیو را نشان نمی‌دهد.
- تگ `archive` (گزیدهٔ برگزارشده) در کتالوگ بلوک جدا و ظاهر ملایم‌تر است؛ `featured` دورهٔ آرشیو را به بلوک جاری بالا نمی‌آورد.
## Locale / Format Rules
- زبان UI: فارسی؛ `dir="rtl"`؛ اعداد نمایشی می‌توانند فارسی‌سازی شوند در لایهٔ UI.
+7 -1
View File
@@ -76,7 +76,7 @@ node scripts/test-db-connection.mjs
| جدول | نکته |
|---|---|
| `courses` | `category`/`format` با CHECK؛ `slug` UNIQUE؛ `price` اختیاری (تومان، NULL = مخفی در UI) |
| `courses` | `format` با CHECK؛ `slug` UNIQUE؛ `price` اختیاری؛ `featured` + `sort_order` (migration 011) |
| `programs` | `group_key` (به‌جای reserve واژهٔ `group`)؛ `highlights` JSONB |
| `events` | `start_date`/`end_date` DATE؛ `end_date` NULL = تک‌روزه |
| `articles` | `featured` + ایندکس جزئی `articles_one_featured` (حداکثر یک مقالهٔ published با `featured=true`) |
@@ -98,6 +98,12 @@ node scripts/test-db-connection.mjs
- `idx_programs_title` / `idx_courses_title` روی `(published, title)`.
- `courses.slug`, `programs.slug`, `intersection_topics.slug` از 001 UNIQUE هستند و ایندکس جزئی `articles_one_featured` از 001 موجود است — تکرار نشده‌اند.
## اولویت کاتالوگ (011)
- Migration: `db/migrations/011_course_priority.sql`.
- `courses.featured BOOLEAN NOT NULL DEFAULT false` و `courses.sort_order INT NOT NULL DEFAULT 0`.
- لیست عمومی: غیرآرشیو (`tag-archive`) سپس ویژه سپس `sort_order` سپس عنوان. آرشیو با تگ جدا می‌شود، نه با ستون جدید.
## Admin (فاز E — 2026-09-22)
- مکانیزم: `admin_users` (رمز با scrypt در `password_hash`، هرگز plaintext) + `admin_sessions` (توکن تصادفی؛ `token_hash` در DB ذخیره می‌شود؛ cookie فقط `admin_session` HttpOnly/SameSite=Lax).
+1
View File
@@ -10,6 +10,7 @@
| فیلتر با تگ | `/professional?tag=<slug>` |
| فیلتر با دسته | `/professional?category=<slug>` |
| هر دو فیلتر | `/professional?tag=<slug>&category=<slug>` |
| گزیدهٔ برگزارشده | `/professional?tag=archive` (در لیست کامل، بلوک جدا زیر دوره‌های جاری) |
### تگ پدر (لیبل منو)
+13
View File
@@ -39,3 +39,16 @@
- [x] 19. سرچ آیکونی؛ با انیمیشن جایگزین دسته/تگ (هدر بدون دسته)
- [x] 20. کل کارت دوره قابل کلیک
- [x] 21. لیبل دسته/تگ روی کارت و جزئیات دوره کلیک‌پذیر (فیلتر)
---
## قفل‌کنندهٔ نسخه‌های بعدی (الان نکن)
منبع: لاگ دیپلوی پروداکشن `69bdaf0` (2026-10-16). وضعیت فعلی دیپلوی سالم است؛ این‌ها بدهی/به‌روزرسانی اختیاری‌اند و نباید وسط فیچر جاری باز شوند.
- [ ] **V-LOCK npm audit** — در `npm ci` داخل Docker: ۱۲ vulnerability (۱۱ high + ۱ critical). در نسخهٔ بعدی: `npm audit` / `npm audit fix` (بدون `--force` مگر بعد از تست)، سپس بیلد+دیپلوی استیجینگ.
- [ ] **V-LOCK ESLint EOL** — هشدار `eslint@9.39.5` deprecated / version-support. در نسخهٔ بعدی: ارتقا به خط پشتیبانی‌شدهٔ ESLint و هم‌تراز کردن config/پلاگین‌ها.
- [ ] **V-LOCK npm toolchain** — notice: npm داخل ایمیج `10.9.9` → پیشنهاد `12.x`. در نسخهٔ بعدی: تصمیم pinned (packageManager / image tag) و تست `npm ci` روی همان نسخه.
- [ ] **V-LOCK deploy checkout noise** — git detach روی `/opt/prod/...` هشدار «leaving 1 commit behind» می‌دهد (طبیعی برای shallow+detach). در نسخهٔ بعدی: در ورک‌فلو `fetch --prune` / پاکسازی refهای یتیم یا ساکت‌کردن هشدار غیرضروری تا لاگ تمیزتر شود.
- [ ] **V-LOCK Docker build context size** — transfer context حدود ۵۵MB در بیلد. در نسخهٔ بعدی: بازبینی `.dockerignore` و دارایی‌های سنگین `public/` تا کش deps کمتر invalidate شود و بیلد سبک‌تر شود.
- [ ] **V-LOCK Docker build wall-time** — بیلد پروداکشن ~۱۵–۲۰ دقیقه (npm ci + copy node_modules + Next webpack/TS با ۱ worker). در نسخهٔ بعدی: کش لایه/registry، کاهش دارایی در context، و در صورت امکان افزایش CPU برای workerهای Next.
+11 -12
View File
@@ -1,10 +1,16 @@
# Production deployment
The production site is https://edu.mstaut.ir. Gitea runs on the same VPS.
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,
**Normal releases are fully automatic:** a push to `master` (or
*workflow_dispatch* in Gitea) runs `.gitea/workflows/deploy.yml` on the
`local-host` runner — checkout, `npm ci` + `next build` on the runner host
(with npm cache), then `scripts/deploy-production.sh` with a prebuilt tree
(`Dockerfile.prebuilt`: no second `npm ci` / compile inside Docker). Backup,
migrations, smoke checks, and container swap need no manual steps.
`scripts/deploy-production.sh` builds the Docker image from `PREBUILT_DIR` in CI
(or from the full root `Dockerfile` only for emergency/local use without CI),
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
@@ -30,15 +36,6 @@ port 443, with `edu.mstaut.ir` as the origin host name. Leave the ACME
challenge path accessible for certificate renewal and bypass caching for
admin pages, API requests, and authenticated traffic.
To deploy manually on the VPS:
```sh
cd /opt/prod/Aut.ManagementFaculty
git fetch origin master
git checkout --detach origin/master
bash scripts/deploy-production.sh
```
To inspect a deployment:
```sh
@@ -46,3 +43,5 @@ docker logs --tail 100 aut-management-faculty
curl --resolve edu.mstaut.ir:443:127.0.0.1 https://edu.mstaut.ir/
certbot renew --cert-name edu.mstaut.ir --dry-run
```
+1
View File
@@ -30,3 +30,4 @@
| 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 می‌مانند |
| 2026-10-22 | D26 — اولویت کاتالوگ: `courses.featured` + `courses.sort_order` (migration 011)؛ ترتیب عمومی غیرآرشیو → ویژه → ترتیب → عنوان؛ تگ `archive` در کتالوگ بلوک جدا با کارت ملایم‌تر است و از هوم حذف می‌ماند | چند دورهٔ جاری باید جلو بیایند و گزیدهٔ برگزارشده از لیست جاری جدا دیده شود |
+5 -5
View File
@@ -1,11 +1,10 @@
# Active Context
## Current Goal
چک‌لیست UI در `docs/Todo.Md` پیاده شد؛ سه آیتم blocked منتظر کاربر.
اولویت نمایش دوره‌ها (ویژه + ترتیب) و جداسازی گزیدهٔ برگزارشده در کتالوگ.
## Current Work
- انجام‌شده: هدر/ناو/فوتر، فونت Vazirmatn، هوم، سرچ/کارت دوره‌ها، اسکیما اساتید (`profile_url` + `course_faculty_links`)
- لوگو دانشکده اعمال شد (`/brand/mst-faculty.png` + favicon)
- انجام‌شده: `featured`/`sort_order` روی `courses`، ادمین، Badge ویژه، بلوک آرشیو جدا در `/professional`
- Blocked: پالت رنگی mst (۱۱)، seed اساتید پس از دسترسی (۱۷c)
## Current Blockers
@@ -13,5 +12,6 @@
- دسترسی به شبکه اساتید mst برای کپی داده
## Next Steps
1. دریافت پالت و به‌روزرسانی توکن‌های `globals.css`
2. پس از دسترسی mst: seed اساتید با `profileUrl`
1. در ادمین، دوره‌های مهم جاری را ویژه/مرتب کنید
2. دریافت پالت و به‌روزرسانی توکن‌های `globals.css`
3. پس از دسترسی mst: seed اساتید با `profileUrl`
+2
View File
@@ -39,10 +39,12 @@
- [x] منوی هوم: یک دراپ‌داون از تگ‌ها؛ `courseNavParentTag`؛ لینک پایدار
- [x] D25 تاکسونومی ادمین‌محور: دسته + تگ many-to-many؛ migration 007؛ CRUD ادمین؛ فیلتر `?tag=`/`?category=` با slug
- [x] D26 اولویت کاتالوگ: `featured` + `sort_order` (migration 011)؛ بلوک جدا برای تگ `archive`
## Next
- [x] فاز H باقی‌مانده — ایندکس‌ها، docs/README نهایی، حذف وابستگی runtime به mock، smoke script
- [x] Todo UI سایت (هدر/هوم/دوره‌ها/فونت/اسکیما اساتید) — جزئیات در `docs/Todo.Md`
- [x] D26 اولویت دوره + جداسازی گزیدهٔ برگزارشده
- [ ] محتوای واقعی از پنل ادمین (طبق دستور کاربر بعداً)
- [x] لوگوی دانشکده (نشان بدون متن کناری + favicon)
- [ ] Todo blocked: پالت mst، seed اساتید از شبکه دانشکده
+4
View File
@@ -41,6 +41,9 @@
"insightsIntro": "نکات کاربردی مدیریت و فناوری برای کار و سازمان.",
"eventsTitle": "رویداد ها",
"eventsIntro": "وبینار ها، بازدیدها و نشست های معرفی برنامه.",
"newsTitle": "اخبار",
"newsIntro": "اطلاعیه ها و خبرهای مرکز آموزش های آزاد.",
"newsEmpty": "هنوز خبری منتشر نشده است.",
"aboutTitle": "درباره مرکز آموزش های آزاد",
"valuesTitle": "ارزش های ما",
"alumniTitle": "دانش آموختگان",
@@ -60,6 +63,7 @@
"courseAboutTitle": "درباره این دوره",
"courseDetailsTitle": "جزئیات برگزاری",
"courseDuration": "مدت",
"courseDate": "تاریخ برگزاری",
"courseFormat": "قالب",
"courseCategory": "دسته بندی",
"coursePrice": "شهریه",
+6 -2
View File
@@ -7,6 +7,10 @@ const nextConfig: NextConfig = {
output: "standalone",
// Babel React Compiler is heavy in Docker/CI; keep it for local `next dev`.
reactCompiler: process.env.DISABLE_REACT_COMPILER !== "1",
// VPS deploy sets SKIP_TYPECHECK=1. `npm run build` locally still typechecks.
typescript: {
ignoreBuildErrors: process.env.SKIP_TYPECHECK === "1",
},
experimental: {
optimizePackageImports: ["lucide-react"],
},
@@ -21,8 +25,8 @@ const nextConfig: NextConfig = {
async redirects() {
return [
{
source: "/faculty",
destination: "https://mst.aut.ac.ir/content/31094/شبکه-اساتید",
source: "/images/faculty/placeholder.png",
destination: "/images/faculty/placeholder.webp",
permanent: true,
},
];
+1163 -4
View File
File diff suppressed because it is too large. Load diff
+10
View File
@@ -14,9 +14,18 @@
},
"dependencies": {
"@base-ui/react": "^1.8.0",
"@tiptap/extension-link": "^3.32.0",
"@tiptap/extension-placeholder": "^3.32.0",
"@tiptap/extension-text-align": "^3.32.0",
"@tiptap/extension-underline": "^3.32.0",
"@tiptap/pm": "^3.32.0",
"@tiptap/react": "^3.32.0",
"@tiptap/starter-kit": "^3.32.0",
"class-variance-authority": "^0.7.1",
"cn": "^0.3.2",
"embla-carousel-react": "^8.6.0",
"isomorphic-dompurify": "^4.6.0",
"jalaali-js": "^2.0.1",
"lucide-react": "^1.47.0",
"next": "16.3.5",
"next-intl": "^4.14.6",
@@ -30,6 +39,7 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/dompurify": "^3.0.5",
"@types/node": "^20",
"@types/pg": "^8.23.1",
"@types/react": "^19",
Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 230 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 430 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 276 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 324 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 296 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 255 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 276 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 230 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 766 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 342 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 223 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 256 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 725 KiB

After

Width:  |  Height:  |  Size: 698 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 541 KiB

After

Width:  |  Height:  |  Size: 769 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

After

Width:  |  Height:  |  Size: 6.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 655 KiB

After

Width:  |  Height:  |  Size: 730 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

After

Width:  |  Height:  |  Size: 4.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 602 KiB

After

Width:  |  Height:  |  Size: 625 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

After

Width:  |  Height:  |  Size: 4.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

View File
Whitespace-only changes.
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# Assemble a Next.js standalone tree ready for Dockerfile.prebuilt (runtime-only image).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUT="${1:-$ROOT/prebuilt}"
test -f "$ROOT/.next/standalone/server.js"
test -f "$ROOT/.next/BUILD_ID"
rm -rf "$OUT"
mkdir -p "$OUT"
cp -a "$ROOT/.next/standalone/." "$OUT/"
rm -rf "$OUT/static" "$OUT/.next/static"
mkdir -p "$OUT/.next"
cp -a "$ROOT/.next/static/." "$OUT/.next/static/"
if [ -d "$ROOT/public" ]; then
rm -rf "$OUT/public"
cp -a "$ROOT/public" "$OUT/public"
else
mkdir -p "$OUT/public"
fi
cp "$ROOT/Dockerfile.prebuilt" "$OUT/Dockerfile"
printf '%s\n' 'Dockerfile' '.dockerignore' > "$OUT/.dockerignore"
test -f "$OUT/server.js"
test -f "$OUT/.next/BUILD_ID"
test -d "$OUT/.next/static"
test -d "$OUT/node_modules"
if [ -e "$OUT/static" ]; then
echo "ERROR: root-level static/ must not exist" >&2
exit 1
fi
echo "Prebuilt tree ready at $OUT"
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
export DISABLE_REACT_COMPILER=1
export NEXT_TELEMETRY_DISABLED=1
export NEXT_PUBLIC_SITE_URL="${NEXT_PUBLIC_SITE_URL:-https://edu.mstaut.ir}"
export NODE_OPTIONS="${NODE_OPTIONS:---max-old-space-size=3072}"
npm ci --no-audit --no-fund
npm run build
test -f .next/standalone/server.js
test -f .next/BUILD_ID
bash scripts/assemble-prebuilt.sh "$(pwd)/prebuilt"
+39 -18
View File
@@ -18,7 +18,18 @@ docker inspect insaight-postgres --format '{{json .NetworkSettings.Networks}}' |
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" .
# PREBUILT_DIR: CI-assembled standalone tree (Dockerfile.prebuilt). Skips npm ci + next build on VPS (~1–2 min).
PREBUILT_DIR="${PREBUILT_DIR:-}"
if [ -n "$PREBUILT_DIR" ]; then
test -f "$PREBUILT_DIR/server.js"
test -f "$PREBUILT_DIR/Dockerfile"
rm -rf "$PREBUILT_DIR/static"
DOCKER_BUILDKIT=1 docker build -t "$IMAGE" "$PREBUILT_DIR"
else
DOCKER_BUILDKIT=1 docker build \
--build-arg NEXT_PUBLIC_SITE_URL=https://edu.mstaut.ir \
-t "$IMAGE" .
fi
# Back up before applying the repository's transactional, versioned migrations.
# Migrations are forward-only and idempotent (schema_migrations); dump is the safety net.
@@ -30,33 +41,43 @@ test -s "$BACKUP"
docker run --rm --network "$NETWORK" --env-file "$ENV_FILE" \
-v "$PWD/db:/app/db:ro" --entrypoint node "$IMAGE" db/migrate.mjs
# Check the database and rendered pages before switching the public upstream.
# Check the database and a minimal page set before switching the public upstream.
CANDIDATE="edu-candidate-${REVISION:0:12}"
docker run -d --name "$CANDIDATE" --network "$NETWORK" --env-file "$ENV_FILE" \
-e UPLOAD_DIR=/app/public/uploads \
-v "$UPLOAD_VOLUME:/app/public/uploads" \
-e UPLOAD_DIR=/app/uploads \
-v "$UPLOAD_VOLUME:/app/uploads" \
"$IMAGE"
cleanup_candidate() { docker rm -f "$CANDIDATE" >/dev/null 2>&1 || true; }
trap cleanup_candidate EXIT
READY=false
for attempt in $(seq 1 60); do
for attempt in $(seq 1 24); do
if docker exec "$CANDIDATE" node -e '
(async () => {
const { Pool } = require("pg");
const pool = new Pool({connectionString: process.env.DATABASE_URL, connectionTimeoutMillis: 5000});
await pool.query("SELECT 1"); await pool.end();
for (const route of ["/", "/programs", "/professional", "/admin/login"]) {
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
connectionTimeoutMillis: 3000,
});
await pool.query("SELECT 1");
await pool.end();
// Minimal smoke: home + admin login (path moved from /admin).
for (const route of ["/", "/mstcontroller/login"]) {
const response = await fetch("http://127.0.0.1:3000" + route);
if (!response.ok) throw new Error(route + ": " + response.status);
}
for (const resource of ["courses", "programs", "events", "articles"]) {
const response = await fetch("http://127.0.0.1:3000/api/" + resource);
const body = await response.json();
if (!response.ok || !Array.isArray(body.data)) throw new Error("API check failed: " + resource);
const api = await fetch("http://127.0.0.1:3000/api/courses");
const body = await api.json();
if (!api.ok || !Array.isArray(body.data)) {
throw new Error("API check failed: courses");
}
})().catch(error => { console.error(error.message); process.exit(1); });
})().catch((error) => {
console.error(error.message || error);
process.exit(1);
});
'; then READY=true; break; fi
sleep 2
sleep 1
done
if [ "$READY" != true ]; then docker logs --tail 50 "$CANDIDATE"; exit 1; fi
cleanup_candidate
@@ -80,15 +101,15 @@ rollback() {
trap rollback ERR
docker run -d --name "$CONTAINER" --restart unless-stopped \
--network "$NETWORK" --env-file "$ENV_FILE" \
-e UPLOAD_DIR=/app/public/uploads \
-v "$UPLOAD_VOLUME:/app/public/uploads" \
-e UPLOAD_DIR=/app/uploads \
-v "$UPLOAD_VOLUME:/app/uploads" \
-p 127.0.0.1:3000:3000 "$IMAGE"
READY=false
for attempt in $(seq 1 30); do
for attempt in $(seq 1 20); do
if curl -fsS --max-time 5 --resolve edu.mstaut.ir:443:127.0.0.1 https://edu.mstaut.ir/ >/dev/null; then
READY=true; break
fi
sleep 2
sleep 1
done
test "$READY" = true
trap - ERR
+198
View File
@@ -0,0 +1,198 @@
// Usage: node scripts/dump-database.mjs
// Reads DATABASE_URL from the environment or .env.local.
// Writes a restorable SQL snapshot under backups/ (gitignored).
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import pg from "pg";
const { Client } = pg;
const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
if (!process.env.DATABASE_URL) {
const envPath = path.join(rootDir, ".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];
}
}
}
}
if (!process.env.DATABASE_URL) {
console.error("DATABASE_URL is not set. Copy .env.example → .env.local and fill it in.");
process.exit(1);
}
function quoteIdent(name) {
return `"${String(name).replaceAll('"', '""')}"`;
}
function topologicalTables(tables, edges) {
const remaining = new Set(tables);
const parentsByChild = new Map(tables.map((table) => [table, new Set()]));
for (const { child, parent } of edges) {
if (remaining.has(child) && remaining.has(parent) && child !== parent) {
parentsByChild.get(child).add(parent);
}
}
const ordered = [];
while (remaining.size > 0) {
const ready = [...remaining].filter((table) => {
const parents = parentsByChild.get(table);
return [...parents].every((parent) => !remaining.has(parent));
});
const batch = ready.length > 0 ? ready.toSorted() : [[...remaining].toSorted()[0]];
for (const table of batch) {
remaining.delete(table);
ordered.push(table);
}
}
return ordered;
}
async function main() {
const client = new Client({
connectionString: process.env.DATABASE_URL,
connectionTimeoutMillis: Number(process.env.DATABASE_CONNECTION_TIMEOUT_MS ?? 20_000),
});
await client.connect();
try {
const info = await client.query(`
SELECT current_database() AS database, current_user AS username, now() AS dumped_at
`);
const { database, username, dumped_at } = info.rows[0];
const tableRows = await client.query(`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
ORDER BY table_name
`);
const tables = tableRows.rows.map((row) => row.table_name);
const fkRows = await client.query(`
SELECT
tc.table_name AS child,
ccu.table_name AS parent
FROM information_schema.table_constraints AS tc
JOIN information_schema.constraint_column_usage AS ccu
ON tc.constraint_name = ccu.constraint_name
AND tc.table_schema = ccu.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY'
AND tc.table_schema = 'public'
`);
const ordered = topologicalTables(tables, fkRows.rows);
const stamp = new Date(dumped_at).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
const outDir = path.join(rootDir, "backups");
mkdirSync(outDir, { recursive: true });
const outFile = path.join(outDir, `${database}-${stamp}.sql`);
const lines = [
`-- Snapshot of ${database} (user ${username})`,
`-- Generated at ${new Date(dumped_at).toISOString()}`,
`-- Restore into an empty DB after migrations, or into a matching schema:`,
`-- psql -v ON_ERROR_STOP=1 -d TARGET_DB -f ${path.basename(outFile)}`,
"BEGIN;",
"SET client_encoding = 'UTF8';",
"SET statement_timeout = 0;",
"SET lock_timeout = 0;",
"",
];
if (ordered.length > 0) {
lines.push(
`TRUNCATE ${ordered.map(quoteIdent).join(", ")} RESTART IDENTITY CASCADE;`,
"",
);
}
const counts = [];
for (const table of ordered) {
const columns = await client.query(
`
SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = $1
ORDER BY ordinal_position
`,
[table],
);
const colNames = columns.rows.map((row) => row.column_name);
if (colNames.length === 0) continue;
const colIdents = colNames.map(quoteIdent).join(", ");
const tupleSql = colNames
.map((name) => `quote_nullable(${quoteIdent(name)}::text)`)
.join(" || ',' || ");
const data = await client.query(
`SELECT ${tupleSql} AS tuple FROM ${quoteIdent(table)}`,
);
counts.push({ table, rows: data.rows.length });
lines.push(`-- ${table}: ${data.rows.length} row(s)`);
if (data.rows.length === 0) {
lines.push("");
continue;
}
const values = data.rows.map((row) => `(${row.tuple})`).join(",\n");
lines.push(
`INSERT INTO ${quoteIdent(table)} (${colIdents}) VALUES`,
`${values};`,
"",
);
}
const sequences = await client.query(`
SELECT sequencename, last_value
FROM pg_sequences
WHERE schemaname = 'public'
ORDER BY sequencename
`);
for (const seq of sequences.rows) {
if (seq.last_value == null) continue;
const seqName = String(seq.sequencename).replaceAll("'", "''");
lines.push(`SELECT setval('${seqName}', ${Number(seq.last_value)}, true);`);
}
lines.push("", "COMMIT;", "");
writeFileSync(outFile, lines.join("\n"), "utf8");
const statsFile = outFile.replace(/\.sql$/, ".tables.json");
writeFileSync(
statsFile,
JSON.stringify(
{
database,
dumpedAt: new Date(dumped_at).toISOString(),
tables: counts,
file: path.basename(outFile),
},
null,
2,
) + "\n",
"utf8",
);
const bytes = Buffer.byteLength(lines.join("\n"), "utf8");
console.log("DUMP_OK");
console.log(outFile);
console.log(`bytes=${bytes} tables=${counts.length} rows=${counts.reduce((sum, item) => sum + item.rows, 0)}`);
for (const item of counts) {
console.log(`${item.table}\t${item.rows}`);
}
} finally {
await client.end().catch(() => {});
}
}
main().catch((error) => {
console.error("DUMP_FAIL");
console.error(error instanceof Error ? error.message : error);
process.exit(1);
});
Loaded 100 of 233 files, more files were not shown because too many files have changed in this diff. Show more