Compare commits

..
49 Commits
Author SHA1 Message Date
Radmehr 85dc7fc1c9 Merge branch 'master' into feat/rag 2026-12-01 08:40:40 +03:30
Radmehr a202e65692 fix: fix some changes 2026-12-01 08:36:29 +03:30
Radmehr e32995c70f feat: add trust proxy 2026-11-28 16:50:42 +03:30
Radmehr 9c7f1340b6 tmp: add logging to npm ci 2026-11-28 15:45:58 +03:30
Radmehr 8a1e61b0f7 feat: add rag by codex 2026-11-27 20:46:29 +03:30
Radmehr 155cb09c22 fix: fix create-admin:prod 2026-11-25 13:57:04 +03:30
Radmehr 8bc3c24a7a fix: fix datasource 2026-11-25 12:54:09 +03:30
Radmehr 5238dd872c feat: change admin panel content 2026-11-25 11:42:29 +03:30
Radmehr 4086209241 fix: fix create admin command 2026-11-25 11:17:00 +03:30
Radmehr 7611033c44 feat: add create admin script 2026-11-22 15:08:23 +03:30
Radmehr 302d06b44f feat: add reset password 2026-11-22 09:25:21 +03:30
Radmehr 88b4a99908 feat: add get chatbot conversation by id endpoint 2026-11-14 23:58:34 +03:30
Radmehr d572f6b7a2 feat: add chatbot conversations endpoint 2026-11-14 23:24:10 +03:30
Radmehr 8d6834f44c feat: add admin panel dto & validation 2026-11-14 22:43:12 +03:30
Radmehr 2d32e2679b fix: fix refresh token race condition 2026-11-06 20:58:45 +03:30
Radmehr 48e9ab5531 fix: fix otp security issue and race condition 2026-11-06 19:00:37 +03:30
Radmehr 2051090d3d feat: add throttler 2026-11-06 18:32:48 +03:30
Radmehr 71ce020803 feat: add join columns 2026-11-02 14:51:55 +03:30
Radmehr a0801be463 feat: add some admin translations 2026-11-01 16:43:40 +03:30
Radmehr e48b6c5460 fix: remove undici fetch function 2026-10-23 19:47:03 +03:30
Radmehr 97b1e48cfd feat: add development openrouter and fix changes 2026-10-23 19:19:40 +03:30
Radmehr ce17808543 feat: add open router proxy 2026-10-21 17:00:17 +03:30
Radmehr 5ac99d1772 feat: submission analyze sse 2026-10-10 13:46:44 +03:30
Radmehr f6075ba146 feat: add submission anaylize 2026-10-10 09:15:55 +03:30
Radmehr ace4342870 feat: add admin js 2026-10-07 16:34:11 +03:30
Radmehr 195eca1015 feat: add logout functionality 2026-10-07 15:36:44 +03:30
Radmehr f3fe1f55e4 fix: fix some changes 2026-10-05 17:27:37 +03:30
Radmehr 5c4e9df341 feat: connect chatbot to conversation database 2026-10-05 13:59:03 +03:30
Radmehr 9842f4db31 feat: add conversation module 2026-09-30 17:55:21 +03:30
Radmehr 13ba11f951 fix: fix some change 2026-09-28 17:32:27 +03:30
Radmehr 76f6c97a9e feat: add chatbot module and service 2026-09-27 17:45:11 +03:30
Radmehr 17b47ffd91 feat: add records deletion before seeding 2026-09-27 16:49:06 +03:30
Radmehr fbce16ef60 feat: add seedResultRange and organize other seeds 2026-09-20 18:11:09 +03:30
Radmehr f660a6b7a7 feat: change minmax probability to minmax score 2026-09-20 16:05:16 +03:30
Radmehr 7658ba805d fix: fix some changes 2026-09-14 15:55:18 +03:30
Radmehr bc333b8289 feat: change result range check field 2026-09-09 18:22:06 +03:30
Radmehr f3c86da09b feat: add user submission list logic 2026-09-09 13:22:41 +03:30
Radmehr f0bf186b6c feat: add user submission history preparations 2026-09-08 17:44:47 +03:30
Radmehr f90b802419 feat: init logging system 2026-09-05 16:50:15 +03:30
Radmehr 287091724d feat: add redis authentication 2026-09-05 14:20:23 +03:30
Radmehr 0961b8f11d feat: complete auth and submission's swagger docs 2026-09-02 16:37:47 +03:30
Radmehr 8fced148b7 Merge branch 'master' of https://git.healahealth.app/Radmehr/heala-backend 2026-09-01 17:38:57 +03:30
Radmehr d1324eb960 feat: add login swagger fields 2026-09-01 17:38:29 +03:30
Radmehr 9ecc9647b5 feat: add database seed script 2026-08-29 23:00:27 +03:30
Radmehr dd9a31278e test: testing system and fix bugs 2026-08-28 13:58:51 +03:30
Radmehr 7dd9206ca6 feat: add debug flag 2026-08-26 08:53:25 +03:30
Radmehr f75e33a7dc Merge branch 'master' of https://git.healahealth.app/Radmehr/heala-backend 2026-08-25 23:39:01 +03:30
Radmehr 73e8fc71bb debug server 2026-08-25 23:38:24 +03:30
Radmehr 195ace097c fix: fix migration 2026-08-23 11:52:35 +03:30
226 changed files with 16198 additions and 452 deletions
+1
View File
@@ -0,0 +1 @@
AdminJS.UserComponents = {}
+9 -1
View File
@@ -3,4 +3,12 @@ dist
.git
.gitignore
Dockerfile
docker-compose.yml
docker-compose.yml
.env*
private-articles
embedding-service
.tmp
.temp
.venv
.pytest_cache
coverage
+43
View File
@@ -0,0 +1,43 @@
NODE_ENV=development
PORT=8000
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_USER=heala
DATABASE_PASS=replace-me
DATABASE_NAME=heala
DATABASE_AUTOLOAD=true
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=replace-me
JWT_ACCESS_SECRET=replace-me
JWT_ACCESS_TTL=900
JWT_REFRESH_SECRET=replace-me
JWT_REFRESH_TTL=604800
JWT_ISSUER=heala
JWT_AUDIENCE=heala
CORS_ORIGINS=http://localhost:3000
CORS_SUBDOMAIN=localhost
SWAGGER_SERVERS=http://localhost:8000
OPENROUTER_API_KEY=replace-me
OPENROUTER_MODEL=replace-with-a-model-id
# OPENROUTER_PROXY_URL=
# OPENROUTER_PROXY_USERNAME=
# OPENROUTER_PROXY_PASSWORD=
ADMIN_PANEL_ENABLED=false
RAG_ENABLED=false
RAG_EMBEDDING_URL=http://localhost:8080
RAG_EMBEDDING_MODEL=intfloat/multilingual-e5-small
RAG_EMBEDDING_REVISION=62ff60abe92eb88c1b297fabaad28f7ac77b5875
RAG_EMBEDDING_TIMEOUT_MS=30000
RAG_BATCH_SIZE=8
RAG_CHUNK_SIZE=440
RAG_CHUNK_OVERLAP=88
RAG_TOP_K=5
RAG_SIMILARITY_THRESHOLD=0.78
RAG_CONTEXT_BYTES=10000
RAG_PROMPT_BYTES=14000
RAG_INGESTION_CONCURRENCY=1
RAG_UPLOAD_MAX_BYTES=10485760
RAG_UPLOAD_MIME_TYPES=application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain
RAG_STORAGE_DIR=./private-articles
+3
View File
@@ -41,6 +41,9 @@ lerna-debug.log*
.env.test
.env.production
.env.local
/private-articles/
__pycache__/
.venv/
# temp directory
.temp
+7 -3
View File
@@ -16,11 +16,15 @@ WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
RUN npm ci --omit=dev --verbose \
--fetch-retries=5 \
--fetch-timeout=600000 \
--maxsockets=2 \
--no-audit \
--no-fund \
|| (cat /root/.npm/_logs/*debug-0.log; exit 1)
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY .env.production .env
EXPOSE 8000
+2
View File
@@ -27,6 +27,8 @@
## Project setup
See the [article RAG runbook](docs/rag.md) for configuration, migrations, testing, and deployment.
```bash
$ npm install
```
+51 -22
View File
@@ -1,54 +1,83 @@
version: "3.9"
services:
postgres:
image: postgres:17
image: pgvector/pgvector:0.8.7-pg17
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${DATABASE_USER}"]
test: ["CMD-SHELL", "pg_isready -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\""]
interval: 10s
timeout: 5s
retries: 5
container_name: postgres
restart: unless-stopped
env_file:
- .env.production
environment:
POSTGRES_USER: ${DATABASE_USER}
POSTGRES_PASSWORD: ${DATABASE_PASS}
POSTGRES_DB: ${DATABASE_NAME}
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:8-alpine
restart: unless-stopped
environment:
REDISCLI_AUTH: ${REDIS_PASSWORD}
command: ["sh", "-c", "exec redis-server --appendonly yes --requirepass \"$$REDISCLI_AUTH\""]
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
volumes:
- redis_data:/data
embedding:
profiles: ["rag"]
build: ./embedding-service
restart: unless-stopped
environment:
RAG_EMBEDDING_MODEL: ${RAG_EMBEDDING_MODEL:-intfloat/multilingual-e5-small}
RAG_EMBEDDING_REVISION: ${RAG_EMBEDDING_REVISION:-62ff60abe92eb88c1b297fabaad28f7ac77b5875}
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health', timeout=3)"]
interval: 15s
timeout: 5s
retries: 4
start_period: 3m
volumes:
- embedding_cache:/cache
networks:
- embedding_network
cpus: 2
mem_limit: 2g
app:
build: .
container_name: nest-app
restart: unless-stopped
stop_grace_period: 2m
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
environment:
NODE_ENV: production
RAG_EMBEDDING_URL: http://embedding:8080
RAG_STORAGE_DIR: /var/lib/heala/articles
env_file:
- .env.production
- ${APP_ENV_FILE:-.env.production}
ports:
- "8000:8000"
volumes:
- article_files:/var/lib/heala/articles
networks:
- default
- embedding_network
networks:
embedding_network:
volumes:
postgres_data:
postgres_data:
redis_data:
embedding_cache:
article_files:
+413
View File
@@ -0,0 +1,413 @@
# مستند فارسی اصلاح امنیت و یکپارچگی داده در AdminJS
تاریخ تهیه: ۹ نوامبر ۲۰۲۶
## دامنهٔ این مستند
این سند تغییرات مرحلهٔ اخیر اصلاح AdminJS را توضیح می‌دهد: ۱۰ فایل موجود ویرایش شد و ۶ فایل کد و تست اضافه شد. تغییرات قبلی گفتگو در زمینهٔ محدودسازی درخواست‌ها، OTP و refresh token در این مرحله تغییر نکرده‌اند و موضوع این سند نیستند.
برای هر فایل، وظیفهٔ آن، مشکل قبلی، تغییر انجام‌شده و اثر تغییر توضیح داده شده است. پیوندهای فایل‌ها نسبت به محل همین سند هستند.
## ۱. مشکل اولیه چه بود؟
در مسیر عادی API، درخواست ابتدا وارد Controller می‌شود، DTO اعتبارسنجی می‌شود و سپس Service و Provider قوانین کسب‌وکار را اجرا می‌کنند.
اما پنل قبلی Entityها را به‌صورت خودکار به AdminJS معرفی می‌کرد. آداپتر TypeORM پنل می‌توانست مستقیماً روی Entity بنویسد. بنابراین اجرای قواعدی مثل بررسی انتشار آزمون، بررسی مسیرها، جلوگیری از هم‌پوشانی بازه‌ها، افزایش شمارندهٔ سؤال و هش‌کردن رمز تضمین نمی‌شد.
مخفی‌کردن یک فیلد در رابط کاربری هم به‌تنهایی محافظت سمت سرور نیست؛ هم باید جلوی نوشتن نامجاز گرفته شود و هم دادهٔ حساس از پاسخ واقعی حذف شود.
مسیر جدید برای عملیات ساخت و ویرایش کاتالوگ:
```text
درخواست AdminJS
→ بررسی نقش فعلی کاربر در دیتابیس
→ کنترل دسترسی اکشن
→ AdminPanelResource
→ کنترل هم‌زمانی نوشتن‌های پنل
→ بررسی فیلدهای مجاز و تبدیل داده‌های فرم
→ کنترل قفل ساختار و وابستگی‌ها
→ اعتبارسنجی DTO
→ Service موجود
→ Command Provider و Validatorهای موجود
→ ذخیره در دیتابیس
→ حذف اطلاعات حساس از پاسخ
```
حذف، DTO ساخت را اجرا نمی‌کند؛ پس از بررسی مجوز، قفل ساختار و وابستگی‌ها، به متد حذف Service مربوطه واگذار می‌شود.
## ۲. فهرست تمام فایل‌های کد و تست این تغییر
| ردیف | فایل | وضعیت | مسئولیت اصلی |
|---|---|---|---|
| ۱ | [admin-panel.setup.ts](../src/modules/admin-panel/admin-panel.setup.ts) | ویرایش | اتصال تنظیمات جدید به پنل |
| ۲ | [admin-panel.resource.ts](../src/modules/admin-panel/admin-panel.resource.ts) | جدید | جلوگیری از نوشتن مستقیم آداپتر |
| ۳ | [admin-panel.validation.ts](../src/modules/admin-panel/admin-panel.validation.ts) | جدید | تبدیل فرم، اعتبارسنجی و حذف اطلاعات حساس |
| ۴ | [admin-panel.resources.ts](../src/modules/admin-panel/admin-panel.resources.ts) | جدید | تعریف منابع، مجوزها و مسیر نوشتن |
| ۵ | [validate-metadata.helper.ts](../src/modules/questions/helpers/validate-metadata.helper.ts) | ویرایش | اعتبارسنجی metadata سؤال |
| ۶ | [questions-command.provider.ts](../src/modules/questions/providers/questions-command.provider.ts) | ویرایش | عملیات نوشتن سؤال |
| ۷ | [choices-command.provider.ts](../src/modules/questions/providers/choices/choices-command.provider.ts) | ویرایش | عملیات نوشتن گزینه |
| ۸ | [question-range-rule-command.provider.ts](../src/modules/questions/providers/range-rule/question-range-rule-command.provider.ts) | ویرایش | قوانین بازه‌ای سؤال |
| ۹ | [question-transition-command.provider.ts](../src/modules/questions/providers/transition/question-transition-command.provider.ts) | ویرایش | مسیرهای بین سؤال‌ها |
| ۱۰ | [question-transition-type.validator.ts](../src/modules/questions/validators/question-transition-type.validator.ts) | ویرایش | بررسی سازگاری نوع مسیر و شرط آن |
| ۱۱ | [result-range-command.provider.ts](../src/modules/scoring/providers/result-range-command.provider.ts) | ویرایش | بازه‌های نتیجهٔ آزمون |
| ۱۲ | [test.entity.ts](../src/modules/tests/entities/test.entity.ts) | ویرایش | تعریف ستون قفل ساختار آزمون |
| ۱۳ | [tests-command.provider.ts](../src/modules/tests/providers/tests-command.provider.ts) | ویرایش | ذخیره و انتشار آزمون |
| ۱۴ | [LockPublishedTestStructure](../src/migrations/1794182400000-LockPublishedTestStructure.ts) | جدید | migration ستون جدید |
| ۱۵ | [admin-panel.resources.spec.ts](../src/modules/admin-panel/admin-panel.resources.spec.ts) | جدید | تست منابع، امنیت و مجوزهای پنل |
| ۱۶ | [admin-panel.ranges.spec.ts](../src/modules/admin-panel/admin-panel.ranges.spec.ts) | جدید | تست اصلاح بازه‌ها و روابط |
## ۳. توضیح فایل‌به‌فایل
### فایل ۱: `src/modules/admin-panel/admin-panel.setup.ts`
**وظیفه:** راه‌اندازی AdminJS روی Express، معرفی آداپتر TypeORM، تنظیم زبان و ظاهر، اتصال احراز هویت و Session Store مبتنی بر Redis.
**قبل:** تمام Entityهای واقعی دیتابیس به‌صورت خودکار وارد پنل می‌شدند. علاوه بر آن، `User` جداگانه نیز معرفی می‌شد و امکان معرفی تکراری آن وجود داشت. تنظیم رمز در این محل عمدتاً مربوط به نمایش ستون بود.
**تغییر:** ساخت منابع به `buildAdminPanelResources(app)` سپرده شد و ثبت خودکار Entityها حذف شد.
**اثر:** منابع پنل اکنون فهرست مشخص دارند. افزودن یک Entity جدید به پروژه، آن را خودکار در پنل قابل مشاهده یا قابل تغییر نمی‌کند. `User` فقط یک بار ثبت می‌شود. نحوهٔ ورود، Redis Session Store و محل نصب Router در این تغییر بازنویسی نشده‌اند.
### فایل ۲: `src/modules/admin-panel/admin-panel.resource.ts`
**وظیفه:** آداپتر محافظت‌شدهٔ پنل است؛ از `Resource` آداپتر TypeORM ارث‌بری می‌کند.
**اجزای مهم:**
- `PanelWrite`: قرارداد تابعی است که یک عملیات `new`، `edit` یا `delete` را اجرا می‌کند.
- `persist`: ورودی مشترک نوشتن است؛ شناسه را بررسی می‌کند، مسیرهای فیلد شامل `__proto__`، `prototype` و `constructor` را رد می‌کند و دادهٔ تخت AdminJS را باز می‌کند.
- `create`، `update` و `delete`: به تابع `write` واگذار می‌شوند؛ به متد نوشتن آداپتر اصلی برنمی‌گردند.
- اگر منبع تابع `write` نداشته باشد، عملیات نوشتن حتی در صورت فراخوانی مستقیم متد Resource هم رد می‌شود.
- `findOne`، `find` و `findMany`: پس از خواندن، هش `password` را از پارامترهای رکورد حذف می‌کنند.
- `redact`: علاوه بر حذف هش رمز، `metadata` و `condition` شیئی را به متن JSON مناسب فرم تبدیل می‌کند.
**مثال بازکردن فیلد تخت:**
```ts
// ورودی AdminJS
{ 'test.id': '2' }
// پس از بازکردن ساختار
{ test: { id: '2' } }
```
**اثر:** بستن دکمه در UI تنها لایهٔ دفاعی نیست؛ خود مسیر ذخیره نیز محافظت می‌شود. حذف رمز از خواندن‌های چندرکوردی برای جست‌وجو و پرکردن روابط هم اهمیت دارد.
### فایل ۳: `src/modules/admin-panel/admin-panel.validation.ts`
**وظیفه:** ابزارهای مشترک تبدیل و اعتبارسنجی ورودی پنل را فراهم می‌کند.
**`panelValues`:**
- فقط فیلدهای معرفی‌شده در `PanelField` را قابل تغییر می‌داند.
- فیلد خارج از فهرست را رد می‌کند؛ اگر فیلد موجودی مثل شناسه یا تاریخ بدون تغییر همراه فرم برگشته باشد، آن را نادیده می‌گیرد.
- مقدار عددی را به عدد صحیح امن تبدیل می‌کند؛ مقدار اعشاری، نامتناهی یا خارج از محدودهٔ امن JavaScript رد می‌شود.
- مرجع عددی `{ id: '2' }` را نیز می‌شناسد.
- ورودی خالی مرجع عددی را به `null` تبدیل می‌کند؛ DTO و Provider تصمیم می‌گیرند این مقدار مجاز است یا نه.
- فقط `true`، `false`، `'true'` و `'false'` را برای فیلد بولی می‌پذیرد. بنابراین رشتهٔ `'false'` اشتباهاً به `true` تبدیل نمی‌شود.
- متن JSON را تجزیه می‌کند و JSON نامعتبر را رد می‌کند.
- نام فرم را به نام DTO نگاشت می‌کند؛ مثلاً `questionId` به `question`.
**`validatePanelDto`:**
- با `plainToInstance` از ورودی، DTO می‌سازد.
- `class-validator` را با `whitelist`، `forbidNonWhitelisted` و `forbidUnknownValues` اجرا می‌کند.
- خطاهای تودرتو را به خطاهای فیلدی AdminJS تبدیل می‌کند.
- نام فیلد خطا را به نام فرم برمی‌گرداند؛ مثلاً خطای `password` روی `newPassword` نمایش داده می‌شود.
- پیام‌های i18n را به فارسی ترجمه می‌کند. پیام خام i18n شامل JSON و مقدار ورودی است؛ مقدار ورودی حذف می‌شود و متن خام به مرورگر برنمی‌گردد.
**`redactPanelSecrets`:** پاسخ‌ها و روابط تودرتو را پیمایش می‌کند و `password`، `newPassword` و `confirmPassword` را حذف می‌کند. بخش `errors` نگه داشته می‌شود چون خطاها پیش‌تر به پیام‌های امن تبدیل شده‌اند و برای نمایش خطای فرم لازم‌اند.
### فایل ۴: `src/modules/admin-panel/admin-panel.resources.ts`
**وظیفه:** مرکز سیاست‌گذاری و اتصال منابع پنل به Serviceهای پروژه است.
**`authorize`:** قبل از اکشن، کاربر جاری را از دیتابیس می‌خواند. نقش داخل Session به‌تنهایی ملاک نیست. اگر حساب حذف شده یا نقش فعلی دیگر `ADMIN` یا `SUPERUSER` نباشد، درخواست رد می‌شود. کنترل‌های دسترسی بعدی از نقش تازه استفاده می‌کنند.
**`resource`:** برای هر Entity، فیلدهای قابل ویرایش، کنترل دسترسی اکشن‌ها، Hookهای بررسی نقش و حذف اطلاعات حساس را تعریف می‌کند. `bulkDelete` برای تمام منابع غیرفعال است.
**`protectTest`:** برای تغییر ساختار یا حذف، وضعیت آزمون را بررسی می‌کند. آزمون منتشرشده، آزمون دارای `structureLocked` یا آزمون دارای هر Submission پایدار از این عملیات محافظت می‌شود.
**`serialize`:** نوشتن‌های پنل را بین نمونه‌های برنامه با قفل مشورتی PostgreSQL هماهنگ می‌کند:
```sql
SELECT pg_try_advisory_lock(724091, 1) AS acquired;
```
این قفل به‌صورت غیرمنتظر عمل می‌کند. اگر نوشتن دیگری از پنل در حال اجرا باشد، درخواست جدید پیام تلاش مجدد می‌گیرد. پس از اتمام یا خطا، قفل در `finally` آزاد و اتصال QueryRunner رها می‌شود.
قفل روی یک Session دیتابیس نگه داشته می‌شود؛ Providerها همچنان Repositoryها و Transactionهای قبلی خود را استفاده می‌کنند. این طراحی نوشتن‌های پنل را پشت سر هم انجام می‌دهد، اما تمام فراخوانی‌های Provider را در یک Transaction جدید قرار نمی‌دهد و عملیات مستقیم SQL یا APIهای دیگر را قفل نمی‌کند.
**`catalog`:** منطق مشترک سؤال، گزینه، قوانین بازه، مسیرها و بازهٔ نتیجه است:
1. رکورد فعلی را هنگام ویرایش یا حذف می‌خواند.
2. دادهٔ فرم را تبدیل و فیلدهای مجاز را بررسی می‌کند.
3. در ویرایش، دادهٔ فعلی را با تغییرات ترکیب می‌کند.
4. جابه‌جایی رکورد به والد دیگر را رد می‌کند.
5. آزمون والد و قفل ساختار را بررسی می‌کند.
6. قواعد اضافی وابستگی را اجرا می‌کند.
7. برای ساخت و ویرایش، دادهٔ کامل را با DTO ساخت اعتبارسنجی می‌کند و به Service موجود می‌دهد.
8. برای حذف، به متد `deleteOne` همان Service مراجعه می‌کند.
**قواعد اضافی وابستگی:**
- گزینه فقط برای سؤال تک‌انتخابی یا چندانتخابی قابل تعریف است.
- قانون بازه فقط برای سؤال عددی قابل تعریف است.
- نوع سؤال دارای گزینه، قانون بازه یا مسیر ورودی/خروجی قابل تغییر نیست.
- گزینه‌ای که شناسه‌اش در شرط مسیر استفاده شده، قبل از اصلاح مسیر قابل حذف نیست؛ چون شناسه داخل JSON الزاماً با Foreign Key محافظت نمی‌شود.
**منبع آزمون:** ساخت از `CreateTestDTO` و ویرایش از دادهٔ کامل و سپس `UpdateTestDTO` عبور می‌کند. آزمون جدید باید پیش‌نویس باشد. فعال‌بودن برای آزمون منتشرنشده رد می‌شود. مبلغ عددی فرم به رشته تبدیل می‌شود و سقف `bigint` دیتابیس بررسی می‌شود. انتشار از `TestsService` و اعتبارسنج گراف موجود عبور می‌کند.
**منبع کاربر:** فقط نام، نام خانوادگی، رمز جدید و تأیید آن قابل تغییر است. رمز خالی به معنی عدم تغییر است. رمز و تأیید باید با هم وارد شوند. محدودیت ۷۲ بایت UTF-8 برای جلوگیری از قطع‌شدن ورودی bcrypt بررسی می‌شود. سپس `UpdateProfileDTO` و `UsersService.updateProfile` اجرا می‌شوند؛ هش‌کردن را همان `UserProfileProvider` انجام می‌دهد.
**فهرست منابع:** شش منبع کاتالوگ، یک منبع کاربر و پنج منبع فقط‌خواندنی سوابق ثبت می‌شوند. OTP در فهرست وجود ندارد.
**مدیریت خطا:** خطای اعتبارسنجی قابل نمایش نگه داشته می‌شود؛ خطاهای معمول HTTP ترجمه می‌شوند؛ خطاهای داخلی ذخیره‌سازی به پیام عمومی تبدیل می‌شوند تا جزئیات SQL و داده‌های داخلی وارد پاسخ پنل نشوند.
### فایل ۵: `src/modules/questions/helpers/validate-metadata.helper.ts`
**وظیفه:** براساس نوع سؤال، DTO مناسب metadata را انتخاب و اعتبارسنجی می‌کند؛ مثلاً `NumericMetadataDTO` برای سؤال عددی.
**تغییر:** نوع پارامتر `metadata` اکنون `null` و `undefined` را هم می‌پذیرد. تابع از قبل در نبود metadata آرایهٔ خطای خالی برمی‌گرداند؛ امضای TypeScript با این رفتار هماهنگ شد.
**اثر:** فراخوانی جدید Provider ساخت سؤال با metadata خالی بدون ناسازگاری نوع انجام می‌شود. این تغییر به‌تنهایی metadata را اجباری نمی‌کند و قاعدهٔ جدیدی برای حداقل، حداکثر یا گام عددی اضافه نکرده است.
### فایل ۶: `src/modules/questions/providers/questions-command.provider.ts`
**وظیفه:** ساخت، ویرایش و حذف سؤال و هماهنگی شمارندهٔ سؤال‌های آزمون.
**تغییر اول:** `createOne` مستقیماً `validateMetadata` را اجرا می‌کند. اگر نوع مشخص نشده باشد، نوع پیش‌فرض تک‌انتخابی در این بررسی لحاظ می‌شود. metadata نامعتبر قبل از ذخیره رد می‌شود.
**تغییر دوم:** تغییر آزمون والد در `updateOne` رد می‌شود. صرف معتبر بودن شناسهٔ آزمون مقصد کافی نبود؛ انتقال می‌توانست شمارنده‌ها و مسیرهای قبلی را ناسازگار کند.
**تغییر سوم:** فیلد DTO به نام `test` قبل از `Object.assign` کنار گذاشته می‌شود؛ شناسهٔ عددی نباید به‌عنوان شیء رابطه روی Entity نوشته شود.
**اثر:** پنل از Transaction موجود ساخت/حذف سؤال و افزایش/کاهش شمارنده استفاده می‌کند. قواعد جدید داخل همین Provider برای فراخوان‌های غیرپنلی آن نیز اجرا می‌شوند؛ اما قفل انتشار پنل داخل این Provider منتقل نشده است.
### فایل ۷: `src/modules/questions/providers/choices/choices-command.provider.ts`
**وظیفه:** ساخت، ویرایش و حذف گزینه و بررسی وجود سؤال و محدودیت ترتیب گزینه‌ها.
**قبل:** `Object.assign(choice, updateChoiceDto)` ممکن بود مقدار عددی `question` در DTO را مستقیماً روی رابطهٔ `choice.question` بگذارد، در حالی که Entity ستون صریح `questionId` هم دارد.
**تغییر:** فیلد `question` جدا می‌شود؛ سایر تغییرات اعمال می‌شوند و در صورت وجود شناسهٔ والد، هر دو مقدار زیر هماهنگ تنظیم می‌شوند:
```ts
choice.questionId = questionId;
choice.question = { id: questionId } as Question;
```
**اثر:** رابطه و Foreign Key هنگام ذخیره با یکدیگر سازگار می‌مانند. خود Provider همچنان انتقال به یک سؤال معتبر را پشتیبانی می‌کند؛ ممنوعیت جابه‌جایی در این مرحله، سیاست لایهٔ AdminJS است.
### فایل ۸: `src/modules/questions/providers/range-rule/question-range-rule-command.provider.ts`
**وظیفه:** مدیریت بازه‌های عددی و امتیاز مربوط به آن‌ها برای سؤال.
**مشکل قبلی:** هنگام ویرایش، منطق قدیمی فرض می‌کرد یکی از بازه‌های هم‌پوشان همان رکورد جاری است و یک هم‌پوشانی را مجاز می‌دانست. اگر بازه به جای دیگری منتقل می‌شد، تنها نتیجهٔ Query می‌توانست رکورد دیگری باشد و به‌اشتباه پذیرفته شود.
**تغییر:** پارامتر بولی `excludeSelf` به شناسهٔ دقیق `excludeId` تبدیل شد. Query رکورد جاری را با شرط `rule.id != :excludeId` کنار می‌گذارد؛ هر نتیجهٔ باقی‌مانده به معنی تداخل است.
همچنین در ذخیرهٔ ویرایش، `question` به شکل `{ id: questionId }` و ستون `questionId` به همان مقدار تنظیم می‌شوند.
**مثال:** اگر بازهٔ رکورد ۷ از `[0, 5]` به `[20, 30]` تغییر کند و رکورد ۹۹ از قبل `[25, 35]` باشد، ویرایش رد می‌شود؛ حتی اگر فقط همین یک هم‌پوشانی پیدا شود.
### فایل ۹: `src/modules/questions/providers/transition/question-transition-command.provider.ts`
**وظیفه:** ذخیرهٔ مسیرهای سؤال‌ها پس از اجرای `QuestionTransitionValidatorProvider` و مدیریت خطاهای محدودیت‌های دیتابیس.
**قبل:** شناسه‌های گزینه‌ها در شرط مسیر چندانتخابی هنگام ساخت مرتب می‌شدند، اما هنگام ویرایش این رفتار وجود نداشت.
**تغییر:** در `updateOne` نیز برای نوع `MULTI_CHOICE`، یک کپی از `choiceIds` ساخته و به صورت عددی مرتب می‌شود. در ساخت نیز نوع شیء شرط برای TypeScript صریح‌تر شده است.
**اثر:** ترتیب ذخیرهٔ یک مجموعهٔ یکسان در ساخت و ویرایش هماهنگ می‌شود؛ مثلاً `[8, 2, 5]` به `[2, 5, 8]` تبدیل می‌شود. بررسی تعلق گزینه‌ها به سؤال، نوع مسیر و سایر قواعد همچنان به Validator موجود سپرده می‌شود.
### فایل ۱۰: `src/modules/questions/validators/question-transition-type.validator.ts`
**وظیفه:** بررسی شکل معتبر هر نوع مسیر، مانند START، END، تک‌انتخابی، چندانتخابی و بازهٔ عددی.
**قبل:** در مسیر تک‌انتخابی، خواندن مستقیم `conditionValue.choiceId` در نبود شرط می‌توانست `TypeError` ایجاد کند و به‌جای خطای ورودی، خطای داخلی بدهد.
**تغییر:** خواندن `choiceId` با optional chaining انجام می‌شود. نبود شرط به `undefined` می‌رسد و همان بررسی نوع موجود، خطای اعتبارسنجی مناسب می‌دهد.
**اثر:** ورودی ناقص به‌صورت کنترل‌شده رد می‌شود؛ معتبر بودن گزینه یا تعلق آن به سؤال همچنان جداگانه بررسی می‌شود.
### فایل ۱۱: `src/modules/scoring/providers/result-range-command.provider.ts`
**وظیفه:** مدیریت بازه‌های امتیازی که عنوان و توضیح نتیجهٔ آزمون را تعیین می‌کنند.
**تغییر اول:** مشابه قوانین بازهٔ سؤال، رکورد ویرایش‌شده با شناسه از بررسی هم‌پوشانی خارج می‌شود؛ وجود یک رکورد متداخل دیگر هم برای رد عملیات کافی است.
**تغییر دوم:** شرط هم‌پوشانی ساده و گروه‌بندی شد:
```text
existing.minScore <= new.maxScore
AND
existing.maxScore >= new.minScore
```
این شرط زیر فیلتر آزمون قرار دارد. عبارت OR قبلی بدون گروه‌بندی کامل می‌توانست به‌علت تقدم AND و OR، بخشی از شرط‌ها را خارج از فیلتر آزمون اعمال کند.
**تغییر سوم:** رابطهٔ `test` و ستون `testId` با هم تنظیم می‌شوند.
**نکته:** دو بازه با مرز مشترک، مثل `[0, 10]` و `[10, 20]`، همچنان متداخل محسوب می‌شوند. معنی مرزهای بسته در این اصلاح عوض نشده است.
### فایل ۱۲: `src/modules/tests/entities/test.entity.ts`
**وظیفه:** تعریف ساختار Entity آزمون در TypeORM.
**تغییر:** ستون بولی زیر با پیش‌فرض `false` اضافه شده است:
```ts
@Column({ type: 'boolean', default: false })
structureLocked!: boolean;
```
**اثر:** قفل ساختار مستقل از وضعیت فعلی انتشار ذخیره می‌شود. اگر آزمونی منتشر و بعد دوباره پیش‌نویس شود، سابقهٔ قفل از بین نمی‌رود.
**علت:** پروژه Snapshot یا نسخهٔ جداگانه برای ساختار هر نوبت پاسخ ندارد. جلسه‌های مهمان نیز در Redis هستند و الزاماً Submission دیتابیسی ندارند. بازکردن ساختار صرفاً با تغییر وضعیت، می‌توانست جلسهٔ جاری یا تفسیر سوابق را خراب کند.
**محدودیت:** این ستون به‌تنهایی یک محدودیت یا Trigger دیتابیس برای جلوگیری از تغییر سؤال‌ها نیست؛ تصمیم جلوگیری از تغییر را لایهٔ پنل می‌گیرد.
### فایل ۱۳: `src/modules/tests/providers/tests-command.provider.ts`
**وظیفه:** ساخت، ویرایش، حذف و انتشار آزمون.
**قیمت:** تفاوت بین `undefined` و `null` حفظ شد. `undefined` یعنی قیمت ارسال نشده و مقدار قبلی بماند؛ `null` یعنی حذف صریح قیمت. استفادهٔ قبلی از `??` این دو را یکسان می‌کرد.
**سازگاری قیمت و نوع دسترسی:** بررسی اکنون بر نبود/وجود مقدار استوار است، نه صرف truthy بودن مقدار. آزمون پولی باید قیمت داشته باشد و آزمون غیرپولی نباید قیمت داشته باشد. این تغییر به‌خودی‌خود شرط «قیمت حتماً بزرگ‌تر از صفر باشد» اضافه نمی‌کند.
**انتشار:** پس از ترکیب تغییرات، اگر وضعیت حاصل `PUBLISHED` باشد، اعتبارسنج انتشار اجرا می‌شود؛ حتی وقتی فیلد `status` در درخواست جدید ارسال نشده باشد.
**قفل:** پس از موفقیت اعتبارسنج انتشار، `structureLocked = true` همراه آزمون ذخیره می‌شود. مسیر عادی ویرایش، آن را هنگام پیش‌نویس‌شدن دوباره `false` نمی‌کند.
**اثر:** انتشار همچنان از اعتبارسنج گراف موجود استفاده می‌کند؛ شامل قواعد START، دسترسی‌پذیری سؤال‌ها، چرخه‌ها، رسیدن مسیرها به پایان و قواعد مسیرهای چندانتخابی.
### فایل ۱۴: `src/migrations/1794182400000-LockPublishedTestStructure.ts`
**وظیفه:** هماهنگ‌کردن Schema واقعی PostgreSQL با ستون جدید Entity.
**`up`:**
1. ستون `structureLocked` را با `NOT NULL DEFAULT false` اضافه می‌کند.
2. برای آزمون‌های فعلاً منتشرشده، مقدار را `true` می‌کند.
3. برای آزمون‌هایی که هر Submission دیتابیسی دارند نیز مقدار را `true` می‌کند.
**`down`:** ستون را حذف می‌کند؛ این کار سابقهٔ قفل ذخیره‌شده را نیز از بین می‌برد.
**محدودیت تشخیص گذشته:** اگر آزمونی قبلاً منتشر شده ولی اکنون پیش‌نویس است، Submission پایدار ندارد و هیچ سابقهٔ انتشار دیگری ذخیره نشده است، migration نمی‌تواند انتشار گذشته را حدس بزند. در صورت وجود چنین آزمون‌هایی باید وضعیت حفظ ساختارشان پیش از اجازهٔ ویرایش تعیین شود.
**وضعیت اجرا:** این migration در جریان اصلاحات به‌صورت خودکار روی دیتابیس اجرا نشده است.
### فایل ۱۵: `src/modules/admin-panel/admin-panel.resources.spec.ts`
**وظیفه:** ۱۵ تست برای مسیر منابع و سیاست‌های پنل.
تست‌ها Metadata واقعی TypeORM را بدون اتصال دیتابیس می‌سازند و یک AdminJS واقعی با منابع جدید ایجاد می‌کنند. فراخوانی‌های دیتابیس و Serviceها Mock هستند.
پوشش تست‌ها:
- نبود منبع تکراری و نبود OTP در پنل؛
- تبدیل عدد، بولی و JSON و ارجاع به Provider؛
- رد DTO نامعتبر و جعل فیلد سیستمی؛
- رد نوشتن هم‌زمان در صورت اشغال قفل؛
- تبدیل مرجع `test.id` و انتهای خالی مسیر؛
- قفل آزمون منتشرشده و حفظ قفل پس از خروج از انتشار؛
- حفاظت آزمون دارای Submission و جلوگیری از حذف آبشاری از پنل؛
- رد انتقال سؤال بین آزمون‌ها؛
- فقط‌خواندنی بودن سوابق و رد ساخت/حذف کاربر؛
- عبور تغییر رمز از مسیر پروفایل؛
- بررسی نقش فعلی دیتابیس به‌جای نقش Session؛
- حذف رمز از پاسخ تودرتو و خطای فرم؛
- جلوگیری از افشای رمز در پیام خام i18n؛
- تبدیل صحیح `'false'` و رد اعداد نامناسب.
تست تغییر رمز، فراخوانی مسیر پروفایل را بررسی می‌کند؛ اجرای واقعی bcrypt یا ابطال همهٔ Sessionها را اثبات نمی‌کند. تست قفل نیز نتیجهٔ Mock را بررسی می‌کند، نه زمان‌بندی واقعی PostgreSQL.
### فایل ۱۶: `src/modules/admin-panel/admin-panel.ranges.spec.ts`
**وظیفه:** تست مشترک برای Provider بازهٔ نتیجه و Provider قانون بازهٔ سؤال.
دو سناریو برای هر Provider اجرا می‌شود؛ در مجموع ۴ تست:
1. پس از جابه‌جایی بازه، حتی یک رکورد دیگر با هم‌پوشانی باید موجب خطا شود؛ شناسهٔ جاری نیز باید صریحاً از Query کنار گذاشته شود.
2. ویرایش بدون هم‌پوشانی باید ذخیره شود و شیء رابطه و Foreign Key با هم سازگار بمانند.
این تست‌ها Provider واقعی را با Repository و QueryBuilder شبیه‌سازی‌شده اجرا می‌کنند؛ اجرای SQL روی PostgreSQL واقعی نیستند.
## ۴. کدام قواعد بازاستفاده شدند و کدام‌ها جدیدند؟
| قاعده | محل اجرا | منشأ |
|---|---|---|
| شکل و نوع فیلدهای DTO | `validatePanelDto` و DTOهای موجود | بازاستفاده |
| اعتبارسنجی انتشار و گراف آزمون | `TestsService` و Provider انتشار | بازاستفاده |
| اعتبارسنجی metadata سؤال | Helper و DTOهای metadata | بازاستفاده؛ فراخوانی در ساخت Provider اضافه شد |
| شمارندهٔ سؤال در ساخت/حذف | Transactionهای QuestionsCommandProvider | بازاستفاده |
| وجود والد و محدودیت‌های ترتیب | Providerهای موجود | بازاستفاده |
| نوع مسیر، تعلق گزینه و محدودیت START/END | Providerها و Validatorهای مسیر | بازاستفاده |
| هم‌پوشانی بازه‌ها | دو Command Provider بازه | بازاستفاده همراه اصلاح خطا |
| سیاست رمز و هش‌کردن | UpdateProfileDTO و UserProfileProvider | بازاستفاده |
| قفل دائمی ساختار پس از انتشار | Entity، Provider آزمون و پنل | جدید |
| محدودیت نقش و محافظت از سوابق در پنل | `admin-panel.resources.ts` | جدید |
| هماهنگی هم‌زمانی نوشتن‌های پنل | قفل مشورتی PostgreSQL | جدید |
| حذف رازها از پاسخ و خطای فرم | Resource و Validation helper | جدید |
## ۵. مجوزهای نهایی پنل
| منبع/عملیات | ADMIN | SUPERUSER |
|---|---|---|
| مشاهدهٔ کاتالوگ آزمون و اجزای آن | مجاز | مجاز |
| ساخت/ویرایش/حذف اجزای پیش‌نویس بدون سابقه و قفل | با اعتبارسنجی | با اعتبارسنجی |
| تغییر ساختار یا حذف آزمون قفل‌شده/دارای سابقه | ممنوع | ممنوع |
| تغییر اطلاعات عمومی، وضعیت و فعال‌بودن آزمون | با اعتبارسنجی | با اعتبارسنجی |
| مشاهدهٔ کاربران | ممنوع | مجاز |
| تغییر نام و رمز کاربران | ممنوع | با اعتبارسنجی |
| تغییر شماره تلفن یا نقش از پنل | ممنوع | ممنوع |
| ساخت و حذف مستقیم حساب | ممنوع | ممنوع |
| مشاهدهٔ پاسخ‌ها، نتایج و مکالمه‌ها | ممنوع | مجاز |
| ویرایش/حذف پاسخ‌ها، نتایج و مکالمه‌ها | ممنوع | ممنوع |
| حذف گروهی | ممنوع | ممنوع |
| دسترسی به OTP از منابع پنل | منبع ثبت نشده | منبع ثبت نشده |
## ۶. محدودهٔ تضمین‌ها و محدودیت‌ها
- کنترل قفل ساختار و کنترل هم‌زمانی فعلاً متعلق به مسیر AdminJS هستند؛ تمام Command Providerها این سیاست را مستقلاً اجرا نمی‌کنند.
- قفل مشورتی همهٔ نوشتن‌های پنل را هماهنگ می‌کند، حتی اگر روی دو آزمون متفاوت باشند. درخواست دوم باید دوباره تلاش کند.
- نوشتن مستقیم SQL، ابزارهای دیتابیس یا مسیر API مستقل، خودکار تحت این قفل نیستند.
- اگر `AdminModule` فعلاً غیرفعال بعداً فعال شود، باید سیاست حفاظت ساختار و هم‌زمانی به مسیرهای آن هم اعمال شود.
- اصلاح Query هم‌پوشانی، به‌تنهایی جای محدودیت دیتابیسی برای رقابت تمام نویسنده‌های ممکن را نمی‌گیرد.
- قفل انتشار Snapshot نمی‌سازد. عنوان و توضیح عمومی آزمون همچنان قابل تغییرند؛ این تغییر نسخه‌بندی کامل تاریخچه نیست.
- تغییر رمز از رفتار فعلی پروفایل استفاده می‌کند و ابطال سراسری access token، refresh token و Sessionهای قبلی به این مرحله اضافه نشده است.
- وجود ساختار خراب در داده‌های قدیمی به‌صورت خودکار اصلاح نشده است. ذخیرهٔ بعدی ممکن است به‌درستی با خطای اعتبارسنجی متوقف شود.
- هیچ پاسخ، نتیجه یا مکالمهٔ موجود در این اصلاح به‌صورت خودکار حذف یا بازنویسی نشده است.
## ۷. نصب، استقرار و بررسی
برای محیط توسعه، پیش از اجرای برنامه با Schema جدید:
```bash
npm run migration:run:dev
```
برای تولید، ابتدا خروجی نسخهٔ جدید را بسازید و سپس migration را روی دیتابیس مقصد اجرا کنید؛ پیش از سرویس‌دهی نسخهٔ جدید باید ستون وجود داشته باشد:
```bash
npm run build
npm run migration:run:prod
```
ساخت برنامه به‌تنهایی migration را اجرا نمی‌کند.
فرمان‌های بررسی کد و تست:
```bash
npx tsc --noEmit --incremental false
npm test -- --runInBand
```
در آخرین بررسی اجرای اصلاحات، TypeScript و ESLint فایل‌های تغییرکرده موفق بودند. ۴ مجموعه تست و مجموعاً ۲۹ تست موفق شدند: ۱۹ تست جدید این مرحله و ۱۰ تست قبلی OTP و refresh token.
بررسی‌های انجام‌نشده شامل اجرای migration روی دیتابیس زنده، رفتار واقعی قفل در PostgreSQL، تست بار و بررسی رابط پنل در مرورگر است. پس از استقرار، ساخت پیش‌نویس، تعریف سؤال و مسیر، انتشار، تغییر رمز و رد ویرایش ساختار قفل‌شده باید در محیط مقصد بررسی شوند.
## ۸. فایل‌های مستندات
`docs/admin-panel-integrity.md` خلاصهٔ انگلیسی معماری، مجوزها، محدودیت‌ها و استقرار را نگه می‌دارد. فایل حاضر، `docs/admin-panel-integrity.fa.md`، توضیح فارسی فایل‌به‌فایل همین تغییرات است. این دو فایل در رفتار اجرایی برنامه نقشی ندارند.
+89
View File
@@ -0,0 +1,89 @@
# AdminJS data integrity
مستند دقیق فارسی و توضیح فایل‌به‌فایل: [admin-panel-integrity.fa.md](admin-panel-integrity.fa.md).
## Write path
AdminJS uses an explicit resource list in `admin-panel.resources.ts`. Every resource
uses `AdminPanelResource`; its create/update/delete methods never call the raw
TypeORM adapter. Catalog writes are normalized, validated with the existing create
DTO (merged with the current record on edit), then delegated to the existing
TestsService, QuestionsService, ChoicesService, QuestionRangeRuleService,
QuestionTransitionService or ResultRangeService. Their command/query/validation
providers remain responsible for business rules and persistence.
The panel converts numeric references and booleans explicitly (`"false"` remains
false), parses JSON fields, rejects unexpected fields, checks integer bounds and
retains the TypeORM-generated `test.id` reference for transitions. Read-only values
sent back unchanged by an edit form are accepted; attempts to change them fail.
## Permissions and sensitive records
- ADMIN and SUPERUSER can manage draft catalog records.
- User accounts are visible/editable only to SUPERUSER. The panel can change
first/last name and an explicitly confirmed new password through UsersService
and UserProfileProvider. Password policy is reused and bcrypt input is capped at
72 UTF-8 bytes. Phone and role cannot be changed here. Account creation/deletion
requires a separate workflow and is disabled in this panel.
- Submissions, answers, results, conversations and messages are read-only and
visible only to SUPERUSER. Bulk deletion is disabled for every resource.
- OTP is not registered. New entity classes are not automatically exposed.
- The actor's role is reloaded from the database before every resource action;
a role stored in an old admin session does not retain revoked privileges.
- Password hashes are removed from adapter reads and response payloads, including
populated references. New-password/confirmation values are scrubbed from form
responses. i18n validation messages are rendered without returning their raw
JSON payload, which otherwise contains the submitted value.
## Published structure and history
Question/choice/range/transition writes and catalog deletions are refused once the
test is published, permanently structure-locked, or has any persisted submission.
Publishing sets `Test.structureLocked`; unpublishing does not clear it. This also
protects guest sessions that do not have a persisted Submission row. To change
structure, create a new test. Normal test metadata/status/activation changes remain
available, with publication validation reused; only published tests may be active.
The migration marks currently published tests and tests with submissions as locked.
Previously published tests that are already drafts, have no persisted submissions,
and have no stored publication history cannot be identified retrospectively. If
such tests exist and must be preserved, lock them before allowing panel edits.
Moving child records between parents is blocked. Changing question type while it
has choices, range rules or transitions is blocked. Deleting a choice referenced
by a transition condition is blocked. This avoids dangling references inside JSON.
Panel writes across instances use one PostgreSQL session advisory lock. Acquisition
is nonblocking: a simultaneous panel write is rejected with a retry message instead
of filling the connection pool with lock waiters. Providers keep their existing
transactions. This is serialization, not a new transaction around all providers;
it does not serialize direct SQL or other API write paths. If the currently disabled
AdminModule is enabled later, apply the same structure/locking policy there too.
## Shared provider fixes
- Range-overlap updates exclude the edited ID explicitly instead of allowing one
overlap. Scoring overlap SQL is grouped under the test filter.
- Relationship updates persist proper relation objects and FK columns. Question
movement between tests is rejected so counts/transitions cannot silently drift.
- Question creation also runs metadata validation in its command provider.
- Single-choice transition validation rejects missing conditions cleanly;
multi-choice IDs are sorted on update as well as creation.
- Test updates preserve an explicit null price and validate the resulting published
state. The existing publication graph validator is reused.
No existing history is deleted or rewritten. Password changes follow the existing
profile behavior; this change does not add global token/session revocation.
## Deployment and verification
Build the new application and run `npm run migration:run:prod` before serving it
(development: `npm run migration:run:dev`). The migration is
`1794182400000-LockPublishedTestStructure.ts`. It has not been run automatically.
Tests build real TypeORM metadata and real AdminJS resource configuration without
database connections. Provider calls and database operations are mocked. They cover
DTO conversion/validation, permission refresh, immutable records, secret redaction,
generated references, lock contention and range-update regressions. Browser UI,
live PostgreSQL advisory-lock behavior and migration execution still require a
deployment smoke test.
+26
View File
@@ -0,0 +1,26 @@
# RAG implementation milestones
| Milestone | Main files | Verification |
| --- | --- | --- |
| 1. Audit | Existing NestJS, Redis, JWT, TypeORM, OpenRouter and chat modules | Reused the existing API, response envelope, roles and provider client |
| 2. Vector storage | `src/migrations`, article entities, `vector.repository.ts` | Created the schema and HNSW index, wrote TypeORM vectors and checked cosine search and model filtering against pgvector via a disposable PGlite socket |
| 3. CPU service | `embedding-service`, `embedding.provider.ts` | Verified API validation, E5 prefixes, batch encoding and 384-dimensional normalized output with the pinned CPU model |
| 4. Ingestion | `articles.controller.ts`, document parser, ingestion worker | Verified HTTP role checks and file validation, PDF pages, DOCX headings, TXT normalization, queue options, retry transitions and stale worker fencing |
| 5. Retrieval | `rag-retrieval.service.ts`, `rag-context.service.ts`, `rag-generation.service.ts` | Verified thresholds, deduplication, prompt budgets, missing-evidence handling, untrusted excerpts and citation validation |
| 6. Chatbot | Existing chatbot and conversation modules, citation migration | Verified the legacy response, grounded SSE event, history and citation snapshots, with OpenRouter mocked |
| 7. Operations | Compose, Dockerfiles, `.env.example`, [runbook](rag.md) | Verified build, lint, typecheck, Jest, Python and Compose configuration. Docker Hub returned HTTP 403 for the required images |
The existing Compose deployment uses PostgreSQL major 17. TypeORM has native vector support. The old HTTP test targeted a root route absent from the application and lacked path alias configuration. A multipart upload test now exercises the real JWT guard and application response envelope.
## Verification commands
- `npm test -- --runInBand` passed 53 tests. The optional integration case passed separately with `PGVECTOR_TEST_URL` and `npm test -- --runInBand pgvector.spec`.
- `npm run test:e2e -- --runInBand` passed three HTTP tests.
- `npx tsc --noEmit --incremental false`, `npx eslint "src/**/*.ts" "test/**/*.ts"` and `npm run build` passed.
- `python -m pytest -q embedding-service` passed four cases with `RAG_REAL_MODEL_TEST=1`, including CPU inference using the pinned E5 weights.
- `docker compose --env-file .env.example --profile rag config --quiet` passed with `APP_ENV_FILE=.env.example`.
Before rollout, run the full Compose stack on a host with registry access and smoke-test upload, Redis processing, grounded chat and fallback on an approved corpus. The local checks used a disposable vector database and mocked the generation provider.
`npm audit --omit=dev` reported the same production advisory counts for both lockfiles. Review the existing 14 high and one critical advisories before deployment.
+127
View File
@@ -0,0 +1,127 @@
# Article-grounded answers
RAG is off by default. The existing chatbot remains at `/v1/chatbot/chat` and `/v1/chatbot/stream`. Set `RAG_ENABLED=true` after applying both RAG migrations and starting the embedding service.
## Architecture
NestJS owns article metadata, private files, ingestion, vector retrieval and conversation history. The FastAPI service owns the tokenizer and CPU inference. OpenRouter generates the final text through the existing SDK client and configured `OPENROUTER_MODEL`. Redis runs BullMQ and never receives articles, questions or embeddings.
1. An administrator uploads a PDF, DOCX or UTF-8 TXT file. NestJS stores the file under a generated UUID and records a pending article.
2. A recurring dispatcher reconciles PostgreSQL status with deterministic BullMQ job IDs. The worker extracts text, normalizes Unicode and asks the Python service to split it into token windows. It embeds chunks in batches and publishes the new index and ready status in a single transaction.
3. Chat embeds the latest question locally. PostgreSQL searches ready chunks with the matching model and revision. NestJS filters repetitive excerpts, caps sources and builds the model prompt with the original medical safety policy.
4. NestJS validates the citation IDs returned by OpenRouter and persists the answer and source metadata in the existing conversation. It returns a localized fallback if there is insufficient evidence or the completion cannot be validated.
The worker uses a generation number and a per-attempt token to fence stale workers. Transient failures retry up to four attempts with exponential backoff starting at five seconds. Document errors such as unreadable files or PDFs requiring OCR fail immediately. Redis recovery redispatches pending work. Reprocessing makes the old chunks ineligible for retrieval until the new generation is ready.
## Storage
- `rag_article` stores metadata, private storage key, status, generation, model identity and a sanitized failure code.
- `rag_article_chunk` stores text, zero-based chunk index, optional source location and `vector(384)`. It has a unique article/chunk key, cascading article foreign key and HNSW cosine index.
- `message.sources` is a nullable JSONB citation snapshot. Existing messages retain their original response shape.
- Source URLs are stored as metadata. The backend never fetches them.
TypeORM uses its native vector column type and synchronization stays off. The migration installs the vector extension and creates the index explicitly. A rollback of the RAG schema discards indexed article metadata and citations. It leaves the shared vector extension and private files in place. Prefer disabling the flag and reverting the app release when troubleshooting a rollout.
## Local development
Use Node 22.13 or newer in the 22.x line, PostgreSQL 17 with pgvector 0.8 or newer, Redis and Python 3.12. Prepare the existing development environment using `.env.example` as a reference. The existing database, Redis and OpenRouter variables still apply.
From the repository root:
```sh
npm ci
npm run migration:run:dev
npm run start:dev
```
Run the embedding service in a dedicated Python virtual environment:
```sh
cd embedding-service
python -m venv .venv
# Activate the venv using your shell's activation script.
python -m pip install torch==2.9.1 --index-url https://download.pytorch.org/whl/cpu
python -m pip install -r requirements.txt
python -m uvicorn main:app --host 127.0.0.1 --port 8080 --no-access-log
```
The first startup downloads the pinned Hugging Face snapshot. `HF_HOME` controls the cache directory. Compose mounts a persistent cache at `/cache`. Prewarm that cache before restricting egress. Set `HF_HUB_OFFLINE=1` in the embedding runtime once the exact snapshot is cached if the deployment must operate offline. The runtime loads model weights once, on CPU, using safetensors. `GET /health` checks readiness and `GET /model` reports the model identity, token limit, dimensions and device. The service accepts at most 32 inputs per request and validates the token limit before encoding. [E5 model card](https://huggingface.co/intfloat/multilingual-e5-small)
## Configuration
| Variable | Default and behavior |
| --- | --- |
| `RAG_ENABLED` | `false`. Enables article routes, ingestion and grounded chatbot answers |
| `RAG_EMBEDDING_URL` | `http://localhost:8080`. Compose uses `http://embedding:8080` |
| `RAG_EMBEDDING_MODEL`, `RAG_EMBEDDING_REVISION` | The model repository and pinned 40-character revision in `.env.example`. Both runtimes must agree |
| `RAG_EMBEDDING_TIMEOUT_MS`, `RAG_BATCH_SIZE` | 30,000 ms and 8 texts. The latter accepts up to 32 |
| `RAG_CHUNK_SIZE`, `RAG_CHUNK_OVERLAP` | 440 and 88 E5 tokens. E5 supports up to 512 including prefix and special tokens |
| `RAG_TOP_K`, `RAG_SIMILARITY_THRESHOLD` | 5 and 0.78. Calibrate the threshold on representative Persian questions |
| `RAG_CONTEXT_BYTES`, `RAG_PROMPT_BYTES` | 10,000 and 14,000 UTF-8 bytes. Includes a conservative budget for prompt, references and recent history. Set the prompt budget below the selected model's input window after reserving 768 output tokens and provider formatting overhead |
| `OPENROUTER_MODEL` | Existing required model ID. Use a model that follows the grounded JSON answer instructions and supports the configured context budget |
| `RAG_INGESTION_CONCURRENCY` | 1 worker job per app replica, configurable up to 4 |
| `RAG_UPLOAD_MAX_BYTES`, `RAG_UPLOAD_MIME_TYPES` | 10 MiB and PDF, DOCX, TXT. The multipart parser has a 20 MiB hard ceiling |
| `RAG_STORAGE_DIR` | `./private-articles`. Compose mounts the private volume at `/var/lib/heala/articles` |
## Article and chat APIs
Use an access token for a user with the existing `admin` or `superuser` role.
```sh
curl -f -H "Authorization: Bearer $ADMIN_ACCESS_TOKEN" \
-F "title=Patient education article" \
-F "file=@article.pdf;type=application/pdf" \
"$API_BASE/v1/articles"
curl -f -H "Authorization: Bearer $ADMIN_ACCESS_TOKEN" \
"$API_BASE/v1/articles/$ARTICLE_ID"
```
Upload returns HTTP 202 and the existing `success`/`data` envelope. An optional `sourceUrl` field accepts HTTP or HTTPS. Ingestion status progresses through `pending`, `processing`, and `ready` or `failed`. Use `GET /v1/articles?page=1&limit=20` to enumerate articles. `PUT /v1/articles/:id` accepts the same multipart fields and replaces the original file. It returns 409 during active ingestion. `POST /v1/articles/:id/reprocess` queues the stored file and returns the active status if ingestion is already underway.
Ordinary authenticated users keep using the current chatbot request, with `message` and optional `conversationId`. When RAG is enabled, the response adds `data.sources` with cited IDs such as `S1`, article ID, chunk ID, title, filename, source URL, similarity and page or section when indexed. The SSE route uses the existing event envelope and emits one validated answer event with its citations. The conversation-details route returns saved citation snapshots. Query rewriting is omitted, so users should restate the topic on ambiguous follow-ups.
The app bounds extraction to 400 PDF pages, 500,000 characters and 4,000 indexed chunks per article. Document parsing does not run OCR. PDF page numbers are available for extractable text. Styled DOCX headings are retained as sections. DOCX page numbers require document rendering. Verify representative right-to-left PDFs before loading a full corpus.
## Production rollout
1. Take a PostgreSQL backup and verify restore, existing volume identity and PostgreSQL major 17. Check that the migration role can install pgvector or ask a database administrator to provision the extension first. The Compose image preserves major 17 and the existing data mount. [pgvector installation and image tags](https://github.com/pgvector/pgvector)
2. Set the production environment values with your deployment secret store. Inside Compose use `DATABASE_HOST=postgres` and `REDIS_HOST=redis`, align `REDIS_PASSWORD` across app and Redis, and provide the existing production OpenRouter proxy settings. Keep RAG disabled for the initial migration. Compose's env file path defaults to `.env.production` and can be set with `APP_ENV_FILE`. Preserve your Compose project name so the existing database volume is reused.
3. Build the app and prepare the services. PostgreSQL, Redis and the embedding service use internal container networking with no host ports. Only the existing app port is published.
```sh
docker compose --env-file .env.production --profile rag config --quiet
docker compose --env-file .env.production --profile rag build app embedding
docker compose --env-file .env.production --profile rag up -d --wait postgres redis embedding
docker compose --env-file .env.production run --rm --no-deps app \
node node_modules/typeorm/cli.js -d dist/database/data-source.js migration:run
docker compose --env-file .env.production --profile rag up -d app
```
4. Enable `RAG_ENABLED=true` in the deployment environment and recreate the app. Upload a small approved article. Poll until ready, ask a question it supports and check the cited excerpt against the original. Ask an unrelated question to verify the fallback. Test an urgent symptom and a personalized dosage request. Review backup, restore and volume permissions. Multiple app replicas need shared private storage and should use the same embedding model and Redis queue.
The feature sends selected excerpts and bounded conversation text to the configured OpenRouter provider. Use publications approved for that processing. Citation validation checks IDs and format. Factual attribution and clinical behavior still need evaluation against your corpus before rollout.
## Model replacement
Choose a compatible 384-dimensional model with a fast tokenizer and E5-style `query:` and `passage:` prefixes. Set model and revision in both runtimes, redeploy and verify `/model` from the app network. Enumerate articles and call `POST /v1/articles/:id/reprocess` for each, then wait for ready status. Queries ignore vectors from older revisions. A change of dimension or embedding protocol requires a schema or provider change. If using a rolling deployment, coordinate the cutover so ingestion workers do not process with different model identities.
## Verification and troubleshooting
```sh
npm test -- --runInBand
npm run test:e2e -- --runInBand
npx tsc --noEmit --incremental false
npm run build
npx eslint "src/**/*.ts" "test/**/*.ts"
```
Set `PGVECTOR_TEST_URL` to a disposable PostgreSQL instance with pgvector and run `npm test -- --runInBand pgvector.spec`. This test uses a temporary schema inside a rolled-back transaction. It never needs an OpenRouter key. For the Python API tests, install `-r requirements.txt`, `httpx` and `pytest` in the Python environment and run `python -m pytest -q embedding-service` from the repository root. Those tests use a fake CPU model.
Set `RAG_REAL_MODEL_TEST=1` and run `python -m pytest -q embedding-service -k real_model` to load the pinned model and check normalization, dimensions and CPU execution with Persian and English input.
- Pending for an extended period. Check the NestJS worker log, Redis health, password, queue and model readiness.
- `pdf_no_text_ocr_required`. Upload a text-exported PDF, DOCX or UTF-8 TXT version.
- `ingestion_dependency_failure`. Check model identity, timeouts, disk and database permissions, then reprocess.
- No sources available. Confirm the article is ready and indexed with the active model revision. Test the configured threshold on the corpus.
- Storage failure. Check the private mount across app replicas and compare its objects with `rag_article.storageKey`. A process failure between storing a file and committing metadata can leave an unreferenced file. Review such files offline before cleanup.
+4
View File
@@ -0,0 +1,4 @@
.venv/
__pycache__/
.pytest_cache/
test_main.py
+14
View File
@@ -0,0 +1,14 @@
FROM python:3.12-slim
WORKDIR /app
ENV HF_HOME=/cache PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
COPY requirements.txt .
RUN pip install --no-cache-dir torch==2.9.1 --index-url https://download.pytorch.org/whl/cpu \
&& pip install --no-cache-dir -r requirements.txt \
&& mkdir -p /cache && chown 65532:65532 /cache
COPY main.py .
USER 65532:65532
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--limit-concurrency", "32", "--timeout-graceful-shutdown", "30", "--no-access-log"]
+143
View File
@@ -0,0 +1,143 @@
import logging
import os
from contextlib import asynccontextmanager
from threading import Lock
from typing import Annotated, Literal
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field, StringConstraints
MODEL = os.getenv("RAG_EMBEDDING_MODEL", "intfloat/multilingual-e5-small")
REVISION = os.getenv("RAG_EMBEDDING_REVISION", "62ff60abe92eb88c1b297fabaad28f7ac77b5875")
MODEL_ID = f"{MODEL}@{REVISION}"
MAX_BATCH = 32
MAX_TOKENS = 512
logger = logging.getLogger("embedding")
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False
inference_lock = Lock()
def load_model():
import torch
from sentence_transformers import SentenceTransformer
torch.set_num_threads(2)
return SentenceTransformer(
MODEL, revision=REVISION, device="cpu", trust_remote_code=False,
model_kwargs={"use_safetensors": True},
)
@asynccontextmanager
async def lifespan(app: FastAPI):
model = load_model()
if model.get_sentence_embedding_dimension() != 384 or not model.tokenizer.is_fast:
raise RuntimeError("Expected 384 dimensions and a fast tokenizer")
model.max_seq_length = min(MAX_TOKENS, model.max_seq_length)
app.state.model = model
logger.info('{"event":"embedding_model_ready","device":"cpu"}')
try:
yield
finally:
del app.state.model
logger.info('{"event":"embedding_model_stopped"}')
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
Text = Annotated[str, StringConstraints(strict=True, strip_whitespace=True, min_length=1)]
class EmbedInput(BaseModel):
input_type: Literal["query", "passage"]
texts: list[Annotated[Text, Field(max_length=8192)]] = Field(min_length=1, max_length=MAX_BATCH)
class ChunkInput(BaseModel):
text: Annotated[Text, Field(max_length=32000)]
size: int = Field(ge=64, le=480, strict=True)
overlap: int = Field(ge=0, le=160, strict=True)
@app.exception_handler(RequestValidationError)
async def validation_error(_request: Request, exc: RequestValidationError):
return JSONResponse(status_code=422, content={
"detail": [{"loc": item["loc"], "type": item["type"]} for item in exc.errors()]
})
@app.get("/health")
def health():
return {"status": "ready"}
@app.get("/model")
def model_info(request: Request):
return {"model": MODEL_ID, "dimensions": 384, "max_batch": MAX_BATCH,
"max_tokens": request.app.state.model.max_seq_length, "device": "cpu"}
@app.post("/embed")
def embed(body: EmbedInput, request: Request):
model = request.app.state.model
texts = [f"{body.input_type}: {text}" for text in body.texts]
try:
with inference_lock:
if any(len(ids) > model.max_seq_length for ids in model.tokenizer(texts, verbose=False)["input_ids"]):
raise HTTPException(422, "Input exceeds the tokenizer limit")
vectors = model.encode(texts, batch_size=min(8, len(texts)),
normalize_embeddings=True, show_progress_bar=False)
except HTTPException:
raise
except Exception:
logger.error('{"event":"embedding_inference_failed"}')
raise HTTPException(503, "Embedding inference failed") from None
if vectors.shape != (len(texts), 384):
raise HTTPException(503, "Unexpected model output")
return {"model": MODEL_ID, "embeddings": vectors.tolist()}
def split_text(text, tokenizer, size, overlap, max_tokens):
offsets = tokenizer(text, add_special_tokens=False, verbose=False,
return_offsets_mapping=True)["offset_mapping"]
start = 0
while start < len(offsets):
end = min(start + size, len(offsets))
floor = start + max(overlap + 1, size * 3 // 4)
if end < len(offsets):
for boundary in range(end, floor - 1, -1):
if text[offsets[boundary - 1][1]:offsets[boundary][0]].strip(" \n\t") == "" and (
text[offsets[boundary - 1][1]:offsets[boundary][0]].count("\n")
or text[offsets[boundary - 1][1] - 1:offsets[boundary - 1][1]] in ".؟!?؛"
):
end = boundary
break
while end > start:
content = text[offsets[start][0]:offsets[end - 1][1]].strip()
if 0 < len(content) <= 4096 and len(tokenizer(f"passage: {content}", verbose=False)["input_ids"]) <= max_tokens:
yield content
break
end -= 1
if end == len(offsets):
break
start = max(start + 1, end - overlap)
@app.post("/chunks")
def chunks(body: ChunkInput, request: Request):
if body.overlap >= body.size:
raise HTTPException(422, "Overlap must be smaller than size")
model = request.app.state.model
try:
with inference_lock:
parts = list(split_text(body.text, model.tokenizer, body.size, body.overlap, model.max_seq_length))
except Exception:
logger.error('{"event":"embedding_tokenization_failed"}')
raise HTTPException(503, "Embedding tokenization failed") from None
return {"model": MODEL_ID, "chunks": parts}
+5
View File
@@ -0,0 +1,5 @@
fastapi==0.121.3
uvicorn==0.38.0
sentence-transformers==5.1.2
transformers==4.57.6
+104
View File
@@ -0,0 +1,104 @@
import math
import os
import re
from unittest.mock import Mock
import pytest
from fastapi.testclient import TestClient
import main
class Tokenizer:
is_fast = True
def __call__(self, texts, add_special_tokens=True, **_kwargs):
if isinstance(texts, list):
return {"input_ids": [self(text)["input_ids"] for text in texts]}
offsets = [match.span() for match in re.finditer(r"\S+", texts)]
return {"input_ids": [1] * (len(offsets) + 2 * add_special_tokens),
"offset_mapping": offsets}
@pytest.fixture
def model(monkeypatch):
model = Mock(max_seq_length=512, tokenizer=Tokenizer())
model.get_sentence_embedding_dimension.return_value = 384
def encode(texts, **_kwargs):
array = Mock(shape=(len(texts), 384))
array.tolist.return_value = [[1.0] + [0.0] * 383 for _ in texts]
return array
model.encode.side_effect = encode
monkeypatch.setattr(main, "load_model", lambda: model)
return model
def test_prefixes_batch_and_metadata(model):
with TestClient(main.app) as client:
assert client.get("/health").status_code == 200
assert client.get("/model").json()["dimensions"] == 384
for kind in ("query", "passage"):
result = client.post("/embed", json={"input_type": kind, "texts": ["سلام", "text"]})
assert result.status_code == 200
assert len(result.json()["embeddings"]) == 2
assert len(result.json()["embeddings"][0]) == 384
assert model.encode.call_args.args[0] == [f"{kind}: سلام", f"{kind}: text"]
assert model.encode.call_args.kwargs["normalize_embeddings"]
def test_limits_and_validation_does_not_echo_content(model):
with TestClient(main.app) as client:
for payload in (
{"input_type": "secret-invalid", "texts": ["hello"]},
{"input_type": "query", "texts": []},
{"input_type": "query", "texts": [" "]},
{"input_type": "query", "texts": [123]},
{"input_type": "query", "texts": ["x"] * 33},
{"input_type": "query", "texts": ["x " * 513]},
{"input_type": "query", "texts": ["x" * 8193]},
):
response = client.post("/embed", json=payload)
assert response.status_code == 422
assert "secret-invalid" not in response.text
model.encode.assert_not_called()
def test_token_chunks_overlap_and_fit(model):
words = [f"واژه{i}" for i in range(150)]
with TestClient(main.app) as client:
response = client.post("/chunks", json={"text": " ".join(words), "size": 64, "overlap": 12})
assert response.status_code == 200
first, second, last = [chunk.split() for chunk in response.json()["chunks"]]
assert len(first) == 64
assert first[-12:] == second[:12]
assert last[-1] == words[-1]
assert client.post("/chunks", json={"text": "سلام", "size": 64, "overlap": 64}).status_code == 422
@pytest.mark.skipif(os.getenv("RAG_REAL_MODEL_TEST") != "1", reason="requires CPU model weights")
def test_real_model_contract():
with TestClient(main.app) as client:
assert main.app.state.model.device.type == "cpu"
response = client.post("/embed", json={
"input_type": "query",
"texts": ["فشار خون چیست؟", "What is blood pressure?"],
})
assert response.status_code == 200
assert response.json()["model"] == main.MODEL_ID
embeddings = response.json()["embeddings"]
assert len(embeddings) == 2
for embedding in embeddings:
assert len(embedding) == 384
assert math.isclose(sum(value * value for value in embedding), 1, abs_tol=1e-3)
text = "این بخش درباره فشار خون است. " * 240
chunk_response = client.post("/chunks", json={"text": text, "size": 440, "overlap": 88})
assert chunk_response.status_code == 200
passages = chunk_response.json()["chunks"]
assert 1 < len(passages) <= main.MAX_BATCH
passage_response = client.post("/embed", json={"input_type": "passage", "texts": passages})
assert passage_response.status_code == 200
assert len(passage_response.json()["embeddings"]) == len(passages)
+2 -2
View File
@@ -1,11 +1,11 @@
{
"local": {
"baseUrl": "http://localhost:3000/v1"
"baseUrl": "http://localhost:8000/v1"
},
"dev": {
"baseUrl": "http://localhost:3000"
},
"prod": {
"baseUrl": "http://localhost:3000"
"baseUrl": "https://api-dev.healahealth.app/v1"
}
}
+4
View File
@@ -8,6 +8,10 @@
{
"include": "i18n/**/*",
"outDir": "dist"
},
{
"include": "modules/rag/*.cjs",
"outDir": "dist"
}
]
}
+6097 -140
View File
File diff suppressed because it is too large Load Diff
+30 -2
View File
@@ -25,9 +25,17 @@
"migration:run:dev": "npm run typeorm:dev -- migration:run",
"migration:run:prod": "npm run typeorm:prod -- migration:run",
"migration:revert:dev": "npm run typeorm:dev -- migration:revert",
"migration:revert:prod": "npm run typeorm:prod -- migration:revert"
"migration:revert:prod": "npm run typeorm:prod -- migration:revert",
"seed": "cross-env NODE_ENV=development tsx src/database/seeds/seed.ts",
"seed:prod": "cross-env NODE_ENV=production node dist/database/seeds/seed.js",
"create-admin:dev": "npm run build && cross-env NODE_ENV=development node dist/cli/create-admin.js",
"create-admin:prod": "cross-env NODE_ENV=production node dist/cli/create-admin.js"
},
"dependencies": {
"@adminjs/express": "^5.1.0",
"@adminjs/nestjs": "^5.1.1",
"@adminjs/typeorm": "^4.0.0",
"@inquirer/prompts": "^8.8.1",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.3",
"@nestjs/core": "^11.0.1",
@@ -38,20 +46,33 @@
"@nestjs/swagger": "^11.2.6",
"@nestjs/throttler": "^6.5.0",
"@nestjs/typeorm": "^11.0.0",
"@openrouter/sdk": "^1.3.33",
"adminjs": "^6.8.7",
"bcrypt": "^6.0.0",
"bullmq": "6.7.10",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.3",
"dotenv": "^17.4.2",
"express-formidable": "^1.2.0",
"express-session": "^1.19.0",
"helmet": "^8.2.0",
"htmlparser2": "12.0.0",
"ioredis": "^5.10.1",
"joi": "^18.0.2",
"mammoth": "1.13.0",
"nestjs-i18n": "^10.6.0",
"nestjs-pino": "^5.1.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"pdfjs-dist": "6.5.438",
"pg": "^8.18.0",
"pino": "^10.3.1",
"pino-http": "^11.0.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"typeorm": "^0.3.28"
"typeorm": "^0.3.28",
"undici": "^6.29.1",
"yauzl": "3.4.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
@@ -61,16 +82,19 @@
"@nestjs/testing": "^11.0.1",
"@types/bcrypt": "^6.0.0",
"@types/express": "^5.0.0",
"@types/express-session": "^1.19.0",
"@types/jest": "^29.5.14",
"@types/node": "^22.10.7",
"@types/passport-jwt": "^4.0.1",
"@types/supertest": "^6.0.2",
"@types/yauzl": "3.4.0",
"cross-env": "^10.1.0",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^16.0.0",
"jest": "^29.7.0",
"pino-pretty": "^13.1.3",
"prettier": "^3.4.2",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
@@ -78,6 +102,7 @@
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"tsx": "^4.23.15",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
},
@@ -88,6 +113,9 @@
"ts"
],
"rootDir": "src",
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/$1"
},
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
+30 -11
View File
@@ -20,9 +20,15 @@ import { TestsModule } from './modules/tests/tests.module';
import { QuestionsModule } from './modules/questions/questions.module';
import { SubmissionsModule } from './modules/submissions/submissions.module';
import { ScoringModule } from './modules/scoring/scoring.module';
import { AdminModule } from './modules/admin/admin.module';
import { AppThrottlerGuard } from './common/guards/app-throttler.guard';
import { ThrottlerModule } from '@nestjs/throttler';
import { LoggingModule } from './common/modules/logging/logging.module';
import { ChatbotModule } from './modules/chatbot/chatbot.module';
import { ConversationModule } from './modules/conversation/conversation.module';
import { AdminPanelModule } from './modules/admin-panel/admin-panel.module';
import openRouterConfig from './config/open-router.config';
import adminConfig from './config/admin.config';
import { OpenRouterModule } from './common/modules/open-router/open-router.module';
const ENV = process.env.NODE_ENV;
@@ -47,7 +53,14 @@ const ENV = process.env.NODE_ENV;
ConfigModule.forRoot({
isGlobal: true,
envFilePath: !ENV ? '.env' : `.env.${ENV}`,
load: [appConfig, databaseConfig, jwtConfig, redisConfig],
load: [
appConfig,
databaseConfig,
jwtConfig,
redisConfig,
openRouterConfig,
adminConfig,
],
validationSchema: environmentValidation,
}),
@@ -64,20 +77,21 @@ const ENV = process.env.NODE_ENV;
database: configService.get('database.name'),
autoLoadEntities: configService.get<boolean>('database.autoLoad'),
synchronize: false,
installExtensions: false,
migrationsRun: false,
migrationsTableName: 'migrations',
}),
}),
// Schedule
ScheduleModule.forRoot(),
// Throttler
// ThrottlerModule.forRoot([
// { name: 'default', limit: 100, ttl: 60_000 },
// { name: 'login', limit: 5, ttl: 60_000 },
// { name: 'otp', limit: 3, ttl: 300_000 },
// { name: 'admin', limit: 30, ttl: 60_000 },
// ]),
ThrottlerModule.forRoot([]),
// Generous per-IP, per-endpoint limits for the MVP. Sensitive routes
// override this same bucket so their limits do not affect other routes.
ThrottlerModule.forRoot([{ name: 'default', limit: 300, ttl: 60_000 }]),
// Logging
LoggingModule,
/**
* Local Modules
@@ -91,7 +105,12 @@ const ENV = process.env.NODE_ENV;
QuestionsModule,
SubmissionsModule,
ScoringModule,
AdminModule,
// AdminModule,
AdminPanelModule,
LoggingModule,
OpenRouterModule,
ChatbotModule,
ConversationModule,
],
providers: [
{
+92
View File
@@ -0,0 +1,92 @@
import { NestFactory } from '@nestjs/core';
import { UsersService } from '@/modules/users/providers/users.service';
import { Role } from '@/common/enums/roles.enum';
import { password, input, select } from '@inquirer/prompts';
import { AppModule } from '@/app.module';
import { ConfigService } from '@nestjs/config';
import { CreatePrivilegedUserDTO } from '@/modules/users/dtos/create-privileged-user.dto';
import { plainToInstance } from 'class-transformer';
import { validateOrReject } from 'class-validator';
async function bootstrap() {
const app = await NestFactory.createApplicationContext(AppModule);
try {
const configService = app.get(ConfigService);
if (!configService.get<boolean>('app.enablePrivilegedUserCli')) {
throw new Error('Privileged user creation is disabled.');
}
const usersService = app.get(UsersService);
const phone = await input({
message: 'Enter phone:',
});
const firstName = await input({
message: 'Enter First Name:',
});
const lastName = await input({
message: 'Enter Last Name:',
});
const role = await select({
message: 'Select role:',
choices: [
{ name: 'Admin', value: Role.ADMIN },
{ name: 'Superuser', value: Role.SUPERUSER },
],
});
const userPassword = await password({
message: 'Enter Password:',
mask: '*',
});
const userConfirmPassword = await password({
message: 'Enter Password Confirmation:',
mask: '*',
});
if (userPassword !== userConfirmPassword) {
throw new Error('Passwords should match!');
}
const confirmation = await input({
message: `Type "${role}" to confirm:`,
});
if ((confirmation as Role) !== role) {
throw new Error('Confirmation failed.');
}
const rawData: CreatePrivilegedUserDTO = {
phone,
firstName,
lastName,
password: userPassword,
confirmPassword: userConfirmPassword,
role,
};
const dto = plainToInstance(CreatePrivilegedUserDTO, rawData);
await validateOrReject(dto, {
whitelist: true,
forbidNonWhitelisted: true,
});
const user = await usersService.createPrivilegedUser(dto);
console.log(`Successfully created ${role}: ${user.phone}`);
} catch (error) {
console.error('Error:', error);
process.exitCode = 1;
} finally {
await app.close();
}
}
bootstrap();
@@ -1,10 +1,14 @@
import { User } from '@/modules/users/entities/user.entity';
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import type { Request } from 'express';
import type { BaseEntity } from 'typeorm';
import { REQUEST_USER_KEY } from '../constants/request-headers.constants';
export const ActiveUser = createParamDecorator(
(field: keyof User | undefined, ctx: ExecutionContext) => {
(
field: Exclude<keyof User, keyof BaseEntity> | undefined,
ctx: ExecutionContext,
) => {
const request: Request = ctx.switchToHttp().getRequest();
const user = request[REQUEST_USER_KEY] as User;
@@ -0,0 +1,100 @@
import { applyDecorators, Type } from '@nestjs/common';
import { ApiExtraModels, ApiResponse, getSchemaPath } from '@nestjs/swagger';
import { AppResponse } from '../responses';
interface ApiAppResponseVariant<T = any> {
model?: Type<T>;
isArray?: boolean;
summary?: string;
example?: AppResponse<T>;
messageExample?: string;
}
interface ApiAppResponseStatus {
status: number;
description?: string;
variants: ApiAppResponseVariant[];
}
export function ApiAppResponse(
options: ApiAppResponseStatus[],
): MethodDecorator {
const models = options.flatMap((status) =>
status.variants
.filter((variant) => variant.model)
.map((variant) => variant.model!),
);
return applyDecorators(
ApiExtraModels(AppResponse, ...models),
...options.map((status) => {
const variants = status.variants;
const schemas = variants.map((variant) => ({
allOf: [
{
$ref: getSchemaPath(AppResponse),
},
{
type: 'object',
properties: {
data: variant.model
? variant.isArray
? {
type: 'array',
items: {
$ref: getSchemaPath(variant.model),
},
}
: {
$ref: getSchemaPath(variant.model),
}
: {
nullable: true,
},
message: {
type: 'string',
example:
variant.messageExample ?? 'Operation completed successfully',
},
},
},
],
}));
return ApiResponse({
status: status.status,
description: status.description,
content: {
'application/json': {
schema:
variants.length > 1
? {
oneOf: schemas,
}
: schemas[0],
...(variants.some((variant) => variant.example)
? {
examples: Object.fromEntries(
variants
.filter((variant) => variant.example)
.map((variant, index) => [
`response${index + 1}`,
{
summary: variant.summary ?? `Response ${index + 1}`,
value: variant.example,
},
]),
),
}
: {}),
},
},
});
}),
);
}
@@ -8,6 +8,7 @@ import {
} from '@nestjs/common';
import type { Request, Response } from 'express';
import { I18nService } from 'nestjs-i18n';
import { PinoLogger } from 'nestjs-pino';
@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
@@ -16,6 +17,11 @@ export class GlobalExceptionFilter implements ExceptionFilter {
* Inject I18n Service
*/
private readonly i18nService: I18nService,
/**
* Inject Pino Logger
*/
private readonly logger: PinoLogger,
) {}
catch(exception: any, host: ArgumentsHost) {
@@ -40,6 +46,8 @@ export class GlobalExceptionFilter implements ExceptionFilter {
args: (exceptionResponse as any).params,
});
this.logException(request, status, exception);
response.status(status).json({
success: false,
statusCode: status,
@@ -52,4 +60,28 @@ export class GlobalExceptionFilter implements ExceptionFilter {
}),
});
}
logException(request: Request, status: number, exception?: any) {
if (status >= 500) {
this.logger.error(
{
err: exception,
stack: exception instanceof Error ? exception.stack : undefined,
method: request.method,
url: request.url,
statusCode: status,
},
'Unhandled server exception',
);
} else {
this.logger.warn(
{
method: request.method,
url: request.url,
statusCode: status,
},
'HTTP exception',
);
}
}
}
@@ -0,0 +1,81 @@
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { LoggerModule } from 'nestjs-pino';
@Module({
imports: [
LoggerModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
pinoHttp: {
level: configService.get<string>('app.logLevel') ?? 'info',
genReqId: (req) => {
const requestId = req.headers['x-request-id'];
if (typeof requestId === 'string' && requestId.length > 0) {
return requestId;
}
return crypto.randomUUID();
},
redact: {
paths: [
'req.headers.authorization',
'req.headers.cookie',
'req.headers["set-cookie"]',
'password',
'accessToken',
'refreshToken',
'otp',
],
censor: '[REDACTED]',
},
// serializers: {
// req: (req) => ({
// method: req.method,
// url: req.url,
// remoteAddress: req.remoteAddress,
// }),
// res: (res) => ({
// statusCode: res.statusCode,
// }),
// },
customProps: (req) => ({
requestId: req.id,
}),
customLogLevel: (req, res, error) => {
if (error || res.statusCode >= 500) {
return 'error';
}
if (res.statusCode >= 400) {
return 'warn';
}
return 'info';
},
transport:
configService.get<string>('app.environment') !== 'production'
? {
target: 'pino-pretty',
options: {
colorize: true,
singleLine: true,
translateTime: 'SYS:standard',
ignore: 'pid,hostname',
},
}
: undefined,
},
}),
}),
],
exports: [LoggerModule],
})
export class LoggingModule {}
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { OpenRouterService } from './providers/open-router.service';
@Module({
providers: [OpenRouterService],
exports: [OpenRouterService],
})
export class OpenRouterModule {}
@@ -0,0 +1,93 @@
import { Injectable, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class OpenRouterService implements OnModuleDestroy {
private proxyAgent?: import('undici').ProxyAgent;
private openRouterPromise?: Promise<
InstanceType<(typeof import('@openrouter/sdk'))['OpenRouter']>
>;
constructor(private readonly configService: ConfigService) {}
public getOpenRouter() {
if (!this.openRouterPromise) {
this.openRouterPromise = this.createOpenRouter().catch(
(error: unknown) => {
this.openRouterPromise = undefined;
throw error;
},
);
}
return this.openRouterPromise;
}
private async createOpenRouter() {
const { ProxyAgent } = await import('undici');
const { HTTPClient, OpenRouter } = await import('@openrouter/sdk');
const env = this.configService.get<string>('app.environment');
const apiKey = this.configService.getOrThrow<string>('openRouter.apiKey');
if (env !== 'production') {
return new OpenRouter({ apiKey });
}
const proxyUrl = this.configService.getOrThrow<string>(
'openRouter.proxyUrl',
);
const proxyUser = this.configService.getOrThrow<string>(
'openRouter.proxyUser',
);
const proxyPassword = this.configService.getOrThrow<string>(
'openRouter.proxyPassword',
);
const proxyAgent = new ProxyAgent({
uri: proxyUrl,
token:
'Basic ' +
Buffer.from(`${proxyUser}:${proxyPassword}`).toString('base64'),
});
this.proxyAgent = proxyAgent;
try {
const httpClient = new HTTPClient({
fetcher: async (input, init) => {
const response = await globalThis.fetch(input, {
...init,
dispatcher: proxyAgent,
} as RequestInit & {
dispatcher: typeof proxyAgent;
});
return response;
},
});
return new OpenRouter({
apiKey,
httpClient,
});
} catch (error) {
this.proxyAgent = undefined;
await proxyAgent.close();
throw error;
}
}
public async onModuleDestroy(): Promise<void> {
const agent = this.proxyAgent;
this.proxyAgent = undefined;
this.openRouterPromise = undefined;
if (agent) {
await agent.close();
}
}
}
+1 -2
View File
@@ -1,5 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-unsafe-call */
import { Module } from '@nestjs/common';
import { RedisService } from './providers/redis.service';
import { REDIS } from './constants/redis.constants';
@@ -15,6 +13,7 @@ import Redis from 'ioredis';
return new Redis({
host: configService.get<string>('redis.host'),
port: configService.get<number>('redis.port'),
password: configService.get<string>('redis.password'),
});
},
},
+21
View File
@@ -7,3 +7,24 @@ export const normalizePhone = (phone: string): string => {
return phone;
};
type GenerateCodeOptions = {
prefix?: string;
length?: number;
};
export const generateCode = (options?: GenerateCodeOptions) => {
const prefix = options?.prefix || '';
const length = options?.length || 5;
const characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let random = '';
for (let i = 0; i < length; i++) {
random += characters.charAt(Math.floor(Math.random() * characters.length));
}
return `${prefix}${random}`;
};
+10
View File
@@ -0,0 +1,10 @@
import { registerAs } from '@nestjs/config';
export default registerAs('admin', () => ({
enabled: process.env.ADMIN_PANEL_ENABLED !== 'false',
rootPath: process.env.ADMIN_ROOT_PATH || '/admin',
cookiePassword: process.env.ADMIN_COOKIE_PASSWORD,
cookieName: 'heala.admin.sid',
sessionTtlMinutes: parseInt(process.env.ADMIN_SESSION_TTL_MINUTES || '120'),
secureCookies: process.env.NODE_ENV === 'production',
}));
+3
View File
@@ -9,4 +9,7 @@ export default registerAs('app', () => ({
swaggerServers: process.env.SWAGGER_SERVERS?.split(',').map((origin) =>
origin.trim(),
),
logLevel: process.env.LOG_LEVEL,
enablePrivilegedUserCli:
process.env.ENABLE_PRIVILEGED_USER_CLI === 'true' ? true : false,
}));
+34 -1
View File
@@ -1,24 +1,57 @@
import Joi from 'joi';
import { ragValidation, validateRagLimits } from './rag.config';
export default Joi.object({
...ragValidation,
NODE_ENV: Joi.string()
.valid('development', 'test', 'production', 'staging')
.default('development'),
// Database
DATABASE_HOST: Joi.string().required(),
DATABASE_PORT: Joi.number().port().default(5432),
DATABASE_USER: Joi.string().required(),
DATABASE_PASS: Joi.string().required(),
DATABASE_NAME: Joi.string().required(),
DATABASE_AUTOLOAD: Joi.boolean().default('true'),
// JWT
JWT_ACCESS_SECRET: Joi.string().required(),
JWT_ACCESS_TTL: Joi.number().required(),
JWT_REFRESH_SECRET: Joi.string().required(),
JWT_REFRESH_TTL: Joi.number().required(),
JWT_ISSUER: Joi.string().required(),
JWT_AUDIENCE: Joi.string().required(),
// Redis
REDIS_HOST: Joi.string().required(),
REDIS_PORT: Joi.number().port().default(6379),
REDIS_PASSWORD: Joi.string().required(),
// CORS
CORS_ORIGINS: Joi.string().required(),
CORS_SUBDOMAIN: Joi.string().required(),
// Swagger
SWAGGER_SERVERS: Joi.string().required(),
});
// Logging
LOG_LEVEL: Joi.string().default('info'),
// OpenRouter
OPENROUTER_API_KEY: Joi.string().required(),
OPENROUTER_MODEL: Joi.string().required(),
OPENROUTER_PROXY_URL: Joi.string().optional(),
OPENROUTER_PROXY_USERNAME: Joi.string().optional(),
OPENROUTER_PROXY_PASSWORD: Joi.string().optional(),
// Admin Panel (AdminJS)
ADMIN_PANEL_ENABLED: Joi.string().valid('true', 'false').default('true'),
// Required at runtime when the panel is enabled (validated in AdminPanelSetup)
ADMIN_COOKIE_PASSWORD: Joi.string().allow('').default(''),
ADMIN_ROOT_PATH: Joi.string().default('/admin'),
ADMIN_SESSION_TTL_MINUTES: Joi.number().integer().min(5).default(120),
// CLI
ENABLE_PRIVILEGED_USER_CLI: Joi.boolean().default('true'),
}).custom(validateRagLimits);
+9
View File
@@ -0,0 +1,9 @@
import { registerAs } from '@nestjs/config';
export default registerAs('openRouter', () => ({
apiKey: process.env.OPENROUTER_API_KEY,
model: process.env.OPENROUTER_MODEL,
proxyUrl: process.env.OPENROUTER_PROXY_URL,
proxyUser: process.env.OPENROUTER_PROXY_USERNAME,
proxyPassword: process.env.OPENROUTER_PROXY_PASSWORD,
}));
+73
View File
@@ -0,0 +1,73 @@
import Joi, { type CustomHelpers } from 'joi';
export const documentMimeTypes = [
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'text/plain',
];
export const maxUploadBytes = 20 * 1024 * 1024;
interface RagLimits {
RAG_CHUNK_SIZE: number;
RAG_CHUNK_OVERLAP: number;
RAG_CONTEXT_BYTES: number;
RAG_PROMPT_BYTES: number;
}
export function validateRagLimits<T extends RagLimits>(
value: T,
helpers: CustomHelpers,
) {
if (value.RAG_CHUNK_OVERLAP >= value.RAG_CHUNK_SIZE) {
return helpers.message({
custom: 'RAG_CHUNK_OVERLAP must be smaller than RAG_CHUNK_SIZE',
});
}
if (value.RAG_CONTEXT_BYTES >= value.RAG_PROMPT_BYTES) {
return helpers.message({
custom: 'RAG_CONTEXT_BYTES must be smaller than RAG_PROMPT_BYTES',
});
}
return value;
}
export const ragValidation = {
RAG_ENABLED: Joi.boolean().default(false),
RAG_EMBEDDING_URL: Joi.string()
.uri({ scheme: ['http', 'https'] })
.default('http://localhost:8080'),
RAG_EMBEDDING_MODEL: Joi.string()
.max(240)
.default('intfloat/multilingual-e5-small'),
RAG_EMBEDDING_REVISION: Joi.string()
.hex()
.length(40)
.default('62ff60abe92eb88c1b297fabaad28f7ac77b5875'),
RAG_EMBEDDING_TIMEOUT_MS: Joi.number()
.integer()
.min(1000)
.max(120000)
.default(30000),
RAG_BATCH_SIZE: Joi.number().integer().min(1).max(32).default(8),
RAG_CHUNK_SIZE: Joi.number().integer().min(64).max(480).default(440),
RAG_CHUNK_OVERLAP: Joi.number().integer().min(0).max(160).default(88),
RAG_TOP_K: Joi.number().integer().min(1).max(12).default(5),
RAG_SIMILARITY_THRESHOLD: Joi.number().min(0).max(1).default(0.78),
RAG_CONTEXT_BYTES: Joi.number().integer().min(1024).max(64000).default(10000),
RAG_PROMPT_BYTES: Joi.number().integer().min(6000).max(128000).default(14000),
RAG_INGESTION_CONCURRENCY: Joi.number().integer().min(1).max(4).default(1),
RAG_UPLOAD_MAX_BYTES: Joi.number()
.integer()
.min(1)
.max(maxUploadBytes)
.default(10 * 1024 * 1024),
RAG_UPLOAD_MIME_TYPES: Joi.string()
.custom((value: string, helpers) =>
value.split(',').every((mime) => documentMimeTypes.includes(mime.trim()))
? value
: helpers.error('any.invalid'),
)
.default(documentMimeTypes.join(',')),
RAG_STORAGE_DIR: Joi.string().trim().min(1).default('./private-articles'),
};
+1
View File
@@ -3,4 +3,5 @@ import { registerAs } from '@nestjs/config';
export default registerAs('redis', () => ({
host: process.env.REDIS_HOST || 'localhost',
port: parseInt(process.env.REDIS_PORT || '6379', 10),
password: process.env.REDIS_PASSWORD,
}));
+3
View File
@@ -18,6 +18,9 @@ export default new DataSource({
password: process.env.DATABASE_PASS,
database: process.env.DATABASE_NAME,
synchronize: false,
installExtensions: false,
migrationsRun: false,
migrationsTableName: 'migrations',
entities: [path.join(__dirname, `../**/*.entity.${extension}`)],
migrations: [path.join(__dirname, `../migrations/*.${extension}`)],
});
+306
View File
@@ -0,0 +1,306 @@
import { Choice } from '@/modules/questions/entities/choice.entity';
import { Question } from '@/modules/questions/entities/question.entity';
import { EntityManager } from 'typeorm';
export async function seedChoices(
manager: EntityManager,
questions: Record<string, Question>,
) {
const choiceRepository = manager.getRepository(Choice);
const { q1, q2, q3, q4, q5, q6, q7, q8, q10, q12 } = questions;
/*
* ---------------------------------------------------------
* QUESTION 1 CHOICES
* ---------------------------------------------------------
*/
const q1Yes = choiceRepository.create({
question: q1,
text: 'بله',
order: 1,
score: 1,
});
const q1No = choiceRepository.create({
question: q1,
text: 'خیر',
order: 2,
score: 0,
});
const q1Choices = [q1Yes, q1No];
await choiceRepository.save(q1Choices);
/*
* ---------------------------------------------------------
* QUESTION 2 CHOICES
* ---------------------------------------------------------
*/
const q2Yes = choiceRepository.create({
question: q2,
text: 'بله',
order: 1,
score: 1,
});
const q2No = choiceRepository.create({
question: q2,
text: 'خیر',
order: 2,
score: 0,
});
const q2NotSure = choiceRepository.create({
question: q2,
text: 'مطمئن نیستم',
order: 3,
score: 1,
});
const q2Choices = [q2Yes, q2No, q2NotSure];
await choiceRepository.save(q2Choices);
/*
* ---------------------------------------------------------
* QUESTION 3 CHOICES
* ---------------------------------------------------------
*/
const q3Texts = [
'اچ‌آی‌وی (HIV)',
'سیفلیس',
'سوزاک',
'عفونت غیراختصاصی مجرای ادرار',
'هپاتیت B',
'هپاتیت C',
'کلامیدیا',
'زگیل تناسلی',
// 'سایر',
// 'مطمئن نیستم',
// 'هیچ کدام',
];
const q3Choices = q3Texts.map((text, index) =>
choiceRepository.create({
question: q3,
text,
order: index + 1,
score: 2,
}),
);
await choiceRepository.save(q3Choices);
/*
* ---------------------------------------------------------
* QUESTION 4 CHOICES
* ---------------------------------------------------------
*/
const q4Texts = [
'سیفلیس',
'سوزاک',
'عفونت غیراختصاصی مجرای ادرار',
'هپاتیت B',
'هپاتیت C',
'کلامیدیا',
'زگیل تناسلی',
// 'سایر',
// 'مطمئن نیستم',
// 'هیچ کدام',
];
const q4Choices = q4Texts.map((text, index) =>
choiceRepository.create({
question: q4,
text,
order: index + 1,
score: 1,
}),
);
await choiceRepository.save(q4Choices);
/*
* ---------------------------------------------------------
* QUESTION 5 CHOICES
* ---------------------------------------------------------
*/
const q5Yes = choiceRepository.create({
question: q5,
text: 'بله',
order: 1,
score: 1,
});
const q5No = choiceRepository.create({
question: q5,
text: 'خیر',
order: 2,
score: 0,
});
const q5NotSure = choiceRepository.create({
question: q5,
text: 'مطمئن نیستم',
order: 3,
score: 1,
});
const q5Choices = [q5Yes, q5No, q5NotSure];
await choiceRepository.save(q5Choices);
/*
* ---------------------------------------------------------
* QUESTION 6 CHOICES
* ---------------------------------------------------------
*/
const q6Yes = choiceRepository.create({
question: q6,
text: 'بله',
order: 1,
score: 1,
});
const q6No = choiceRepository.create({
question: q6,
text: 'خیر',
order: 2,
score: 0,
});
const q6NotSure = choiceRepository.create({
question: q6,
text: 'مطمئن نیستم',
order: 3,
score: 1,
});
const q6Choices = [q6Yes, q6No, q6NotSure];
await choiceRepository.save(q6Choices);
/*
* ---------------------------------------------------------
* QUESTION 7 CHOICES
* ---------------------------------------------------------
*/
const q7Yes = choiceRepository.create({
question: q7,
text: 'بله',
order: 1,
score: 2,
});
const q7No = choiceRepository.create({
question: q7,
text: 'خیر',
order: 2,
score: 0,
});
const q7Choices = [q7Yes, q7No];
await choiceRepository.save(q7Choices);
/*
* ---------------------------------------------------------
* QUESTION 8 CHOICES
* ---------------------------------------------------------
*/
const q8Yes = choiceRepository.create({
question: q8,
text: 'بله',
order: 1,
score: 2,
});
const q8No = choiceRepository.create({
question: q8,
text: 'خیر',
order: 2,
score: 0,
});
const q8Choices = [q8Yes, q8No];
await choiceRepository.save(q8Choices);
/*
* ---------------------------------------------------------
* QUESTION 10 CHOICES
* ---------------------------------------------------------
*/
const q10Yes = choiceRepository.create({
question: q10,
text: 'بله',
order: 1,
score: 1,
});
const q10No = choiceRepository.create({
question: q10,
text: 'خیر',
order: 2,
score: 0,
});
const q10Choices = [q10Yes, q10No];
await choiceRepository.save(q10Choices);
/*
* ---------------------------------------------------------
* QUESTION 12 CHOICES
* ---------------------------------------------------------
*/
const q12Always = choiceRepository.create({
question: q12,
text: 'همیشه با همهٔ شرکای جنسی‌ام از کاندوم استفاده کرده‌ام.',
order: 1,
score: 0,
});
const q12Sometimes = choiceRepository.create({
question: q12,
text: 'گاهی با شرکای جنسی‌ام از کاندوم استفاده کرده‌ام.',
order: 2,
score: 2,
});
const q12Never = choiceRepository.create({
question: q12,
text: 'هیچ‌وقت با هیچ‌کدام از شرکای جنسی‌ام از کاندوم استفاده نکرده‌ام.',
order: 3,
score: 5,
});
const q12NotApplicable = choiceRepository.create({
question: q12,
text: 'سؤال در مورد من صحت ندارد؛ چون که رابطهٔ واژنی یا مقعدی نداشته‌ام.',
order: 4,
score: 1,
});
const q12NotSure = choiceRepository.create({
question: q12,
text: 'مطمئن نیستم.',
order: 5,
score: 2,
});
const q12Choices = [
q12Always,
q12Sometimes,
q12Never,
q12NotApplicable,
q12NotSure,
];
await choiceRepository.save(q12Choices);
return { q8Yes, q10Yes };
}
@@ -0,0 +1,77 @@
import { QuestionRangeRule } from '@/modules/questions/entities/question-range-rule.entity';
import { Question } from '@/modules/questions/entities/question.entity';
import { EntityManager } from 'typeorm';
export async function seedQuestionRangeRules(
manager: EntityManager,
questions: Record<string, Question>,
) {
const rangeRuleRepository = manager.getRepository(QuestionRangeRule);
const { q9, q11 } = questions;
/*
* ---------------------------------------------------------
* QUESTION 9 RANGE RULES
* ---------------------------------------------------------
*
* 1 person => 2
* 2 people => 3
* 3 or more => 5
*/
await rangeRuleRepository.save([
rangeRuleRepository.create({
question: q9,
min: 1,
max: 1,
score: 2,
}),
rangeRuleRepository.create({
question: q9,
min: 2,
max: 2,
score: 3,
}),
rangeRuleRepository.create({
question: q9,
min: 3,
max: 2147483647,
score: 5,
}),
]);
/*
* ---------------------------------------------------------
* QUESTION 11 RANGE RULES
* ---------------------------------------------------------
*
* 1 person => 1
* 2 people => 2
* 3 or more => 3
*/
await rangeRuleRepository.save([
rangeRuleRepository.create({
question: q11,
min: 1,
max: 1,
score: 1,
}),
rangeRuleRepository.create({
question: q11,
min: 2,
max: 2,
score: 2,
}),
rangeRuleRepository.create({
question: q11,
min: 3,
max: 2147483647,
score: 3,
}),
]);
}
+149
View File
@@ -0,0 +1,149 @@
import { Question } from '@/modules/questions/entities/question.entity';
import { QuestionType } from '@/modules/questions/enums/question-type.enum';
import { Test } from '@/modules/tests/entities/test.entity';
import { EntityManager } from 'typeorm';
export async function seedQuestions(manager: EntityManager, savedTest: Test) {
const questionRepository = manager.getRepository(Question);
/*
* ---------------------------------------------------------
* QUESTIONS
* ---------------------------------------------------------
*/
const q1 = questionRepository.create({
test: savedTest,
type: QuestionType.SINGLE_CHOICE,
weight: 1,
required: true,
content:
'آیا اخیراً علائمی داشته‌اید که فکر می‌کنید ممکن است ناشی از عفونت‌های منتقله از راه جنسی باشند؟',
metadata: {},
});
const q2 = questionRepository.create({
test: savedTest,
type: QuestionType.SINGLE_CHOICE,
weight: 1,
required: true,
content:
'آیا تا به حال پزشک یا یکی از کادر درمان به شما گفته است که به یک یا چند بیماری مقاربتی مبتلا شده‌اید؟',
metadata: {},
});
const q3 = questionRepository.create({
test: savedTest,
type: QuestionType.MULTI_CHOICE,
weight: 1,
required: true,
content:
'تاکنون به کدام‌یک از بیماری‌های مقاربتی مبتلا بوده‌اید؟ (می‌توانید بیش از یک گزینه را انتخاب کنید.)',
metadata: {},
});
const q4 = questionRepository.create({
test: savedTest,
type: QuestionType.MULTI_CHOICE,
weight: 1,
required: true,
content:
'آیا اخیراً با فردی که به یکی از بیماری‌های زیر مبتلا بوده، رابطهٔ جنسی داشته‌اید؟',
metadata: {},
});
const q5 = questionRepository.create({
test: savedTest,
type: QuestionType.SINGLE_CHOICE,
weight: 1,
required: true,
content: 'آیا تاکنون ماده‌ای غیرقانونی را به صورت تزریقی مصرف کرده‌اید؟',
metadata: {},
});
const q6 = questionRepository.create({
test: savedTest,
type: QuestionType.SINGLE_CHOICE,
weight: 1,
required: true,
content:
'در ۱۲ ماه گذشته، آیا با فردی با تابعیت غیر ایرانی رابطهٔ جنسی داشته‌اید؟ (مثلاً هنگام سفر به خارج از کشور رابطهٔ جنسی داشته‌اید، یا در ایران با فردی از کشور دیگری رابطه داشته‌اید؟)',
metadata: {},
});
const q7 = questionRepository.create({
test: savedTest,
type: QuestionType.SINGLE_CHOICE,
weight: 1,
required: true,
content: 'آیا در حال حاضر به عنوان کارگر جنسی فعالیت می‌کنید؟',
metadata: {},
});
const q8 = questionRepository.create({
test: savedTest,
type: QuestionType.SINGLE_CHOICE,
weight: 1,
required: true,
content:
'در ۱۲ ماه گذشته، آیا با یک فرد همجنس رابطهٔ جنسی داشته‌اید؟ (مثلاً مرد با مرد)',
metadata: {},
});
const q9 = questionRepository.create({
test: savedTest,
type: QuestionType.NUMERIC,
weight: 1,
required: true,
content: 'در ۱۲ ماه گذشته، با چند فرد از همجنس خود رابطهٔ جنسی داشته‌اید؟',
metadata: {},
});
const q10 = questionRepository.create({
test: savedTest,
type: QuestionType.SINGLE_CHOICE,
weight: 1,
required: true,
content:
'در ۱۲ ماه گذشته، آیا با یک فرد از جنس مخالف رابطهٔ جنسی داشته‌اید؟',
metadata: {},
});
const q11 = questionRepository.create({
test: savedTest,
type: QuestionType.NUMERIC,
weight: 1,
required: true,
content: 'در ۱۲ ماه گذشته، با چند نفر از جنس مخالف رابطهٔ جنسی داشته‌اید؟',
metadata: {},
});
const q12 = questionRepository.create({
test: savedTest,
type: QuestionType.SINGLE_CHOICE,
weight: 1,
required: true,
content:
'در ۱۲ ماه گذشته، آیا هنگام رابطهٔ واژنی یا مقعدی از کاندوم استفاده کرده‌اید؟',
metadata: {},
});
const questions = {
q1,
q2,
q3,
q4,
q5,
q6,
q7,
q8,
q9,
q10,
q11,
q12,
};
await questionRepository.save(Object.values(questions));
return questions;
}
+41
View File
@@ -0,0 +1,41 @@
import { ResultRange } from '@/modules/scoring/entities/result-range.entity';
import { Test } from '@/modules/tests/entities/test.entity';
import { EntityManager } from 'typeorm';
export async function seedResultRange(manager: EntityManager, savedTest: Test) {
const resultRangeRepository = manager.getRepository(ResultRange);
await resultRangeRepository.save([
resultRangeRepository.create({
test: savedTest,
minScore: 0,
maxScore: 1,
title: 'خطر پایین',
description: 'امتیاز شما در محدوده خطر پایین قرار دارد.',
}),
resultRangeRepository.create({
test: savedTest,
minScore: 2,
maxScore: 4,
title: 'خطر متوسط',
description: 'امتیاز شما در محدوده خطر متوسط قرار دارد.',
}),
resultRangeRepository.create({
test: savedTest,
minScore: 5,
maxScore: 7,
title: 'خطر بالا',
description: 'امتیاز شما در محدوده خطر بالا قرار دارد.',
}),
resultRangeRepository.create({
test: savedTest,
minScore: 8,
maxScore: 60,
title: 'خطر بسیار بالا',
description: 'امتیاز شما در محدوده خطر بسیار بالا قرار دارد.',
}),
]);
}
+89
View File
@@ -0,0 +1,89 @@
import dataSource from '../data-source';
import { Test } from '../../modules/tests/entities/test.entity';
import { seedSuperuser } from './superuser.seed';
import { seedTests } from './tests.seed';
import { seedQuestions } from './questions.seed';
import { seedChoices } from './choices.seed';
import { seedQuestionRangeRules } from './question-range-rules.seed';
import { seedTransitions } from './transitions.seed';
import { seedResultRange } from './result-range.seed';
async function prepareTests() {
const result = await dataSource.transaction(async (manager) => {
const seedTestResult = await seedTests(manager);
let savedTest: Test;
if (seedTestResult instanceof Test) {
savedTest = seedTestResult;
} else {
return seedTestResult;
}
const questions = await seedQuestions(manager, savedTest);
const choices = await seedChoices(manager, questions);
await seedQuestionRangeRules(manager, questions);
await seedTransitions(manager, savedTest, questions, choices);
await seedResultRange(manager, savedTest);
return {
created: true,
testId: savedTest.id,
};
});
if (result.created) {
console.log(`Test created successfully. ID: ${result.testId}`);
} else {
console.log(
`Test already exists. ID: ${result.testId}. Nothing was created.`,
);
}
}
export async function clearDatabase() {
await dataSource.query(`
DO $$
DECLARE
r RECORD;
BEGIN
FOR r IN (
SELECT tablename
FROM pg_tables
WHERE schemaname = 'public'
)
LOOP
EXECUTE 'TRUNCATE TABLE "' || r.tablename || '" RESTART IDENTITY CASCADE';
END LOOP;
END $$;
`);
}
async function seed() {
try {
await dataSource.initialize();
console.log('Database connection initialized.');
await clearDatabase();
await seedSuperuser();
await prepareTests();
console.log('Seed completed successfully.');
} catch (error) {
console.error('Seed failed:', error);
process.exitCode = 1;
} finally {
if (dataSource.isInitialized) {
await dataSource.destroy();
}
}
}
void seed();
+50
View File
@@ -0,0 +1,50 @@
import * as bcrypt from 'bcrypt';
import { User } from '../../modules/users/entities/user.entity';
import { Role } from '@/common/enums/roles.enum';
import dataSource from '../data-source';
const SUPERUSER_PHONE = process.env.SUPERUSER_PHONE;
const SUPERUSER_PASSWORD = process.env.SUPERUSER_PASSWORD;
export async function seedSuperuser() {
if (!SUPERUSER_PHONE || !SUPERUSER_PASSWORD) {
console.log(
'SUPERUSER_PHONE or SUPERUSER_PASSWORD is not defined. Skipping superuser seed.',
);
return;
}
const userRepository = dataSource.getRepository(User);
const existingUser = await userRepository.findOne({
where: {
phone: SUPERUSER_PHONE,
},
});
if (existingUser) {
if (existingUser.role !== Role.SUPERUSER) {
existingUser.role = Role.SUPERUSER;
await userRepository.save(existingUser);
console.log(`User ${SUPERUSER_PHONE} promoted to SUPERUSER.`);
} else {
console.log(`Superuser ${SUPERUSER_PHONE} already exists.`);
}
return;
}
const passwordHash = await bcrypt.hash(SUPERUSER_PASSWORD, 12);
const superuser = userRepository.create({
phone: SUPERUSER_PHONE,
password: passwordHash,
role: Role.SUPERUSER,
});
await userRepository.save(superuser);
console.log(`Superuser ${SUPERUSER_PHONE} created successfully.`);
}
+43
View File
@@ -0,0 +1,43 @@
import { Test } from '@/modules/tests/entities/test.entity';
import { AccessType } from '@/modules/tests/enums/access-types.enum';
import { TestStatus } from '@/modules/tests/enums/test-status.enum';
import { EntityManager } from 'typeorm';
const TEST_TITLE = 'تست ارزیابی خطر ابتلا به عفونت‌های منتقله از راه جنسی';
export async function seedTests(manager: EntityManager) {
const testRepository = manager.getRepository(Test);
const existingTest = await testRepository.findOne({
where: {
title: TEST_TITLE,
},
});
if (existingTest) {
return {
created: false,
testId: existingTest.id,
};
}
/*
* ---------------------------------------------------------
* TEST
* ---------------------------------------------------------
*/
const test = testRepository.create({
title: TEST_TITLE,
description:
'این تست برای ارزیابی عوامل مرتبط با خطر ابتلا به عفونت‌های منتقله از راه جنسی طراحی شده است.',
status: TestStatus.PUBLISHED,
accessType: AccessType.FREE,
isActive: true,
questionsCount: 12,
});
const savedTest = await testRepository.save(test);
return savedTest;
}
+239
View File
@@ -0,0 +1,239 @@
import { Choice } from '@/modules/questions/entities/choice.entity';
import { QuestionTransition } from '@/modules/questions/entities/question-transition.entity';
import { Question } from '@/modules/questions/entities/question.entity';
import { QuestionTransitionType } from '@/modules/questions/enums/question-transition-type.enum';
import { Test } from '@/modules/tests/entities/test.entity';
import { EntityManager } from 'typeorm';
export async function seedTransitions(
manager: EntityManager,
savedTest: Test,
questions: Record<string, Question>,
choices: Record<string, Choice>,
) {
const transitionRepository = manager.getRepository(QuestionTransition);
const { q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12 } = questions;
const { q8Yes, q10Yes } = choices;
/*
* ---------------------------------------------------------
* QUESTION TRANSITIONS
* ---------------------------------------------------------
*/
/*
* START -> Q1
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: null,
toQuestion: q1,
type: QuestionTransitionType.START,
condition: null,
}),
);
/*
* Q1 -> Q2
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q1,
toQuestion: q2,
type: QuestionTransitionType.DEFAULT,
condition: null,
}),
);
/*
* Q2 -> Q3
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q2,
toQuestion: q3,
type: QuestionTransitionType.DEFAULT,
condition: null,
}),
);
/*
* Q3 -> Q4
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q3,
toQuestion: q4,
type: QuestionTransitionType.DEFAULT,
condition: null,
}),
);
/*
* Q4 -> Q5
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q4,
toQuestion: q5,
type: QuestionTransitionType.DEFAULT,
condition: null,
}),
);
/*
* Q5 -> Q6
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q5,
toQuestion: q6,
type: QuestionTransitionType.DEFAULT,
condition: null,
}),
);
/*
* Q6 -> Q7
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q6,
toQuestion: q7,
type: QuestionTransitionType.DEFAULT,
condition: null,
}),
);
/*
* Q7 -> Q8
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q7,
toQuestion: q8,
type: QuestionTransitionType.DEFAULT,
condition: null,
}),
);
/*
* ---------------------------------------------------------
* Q8 BRANCH
* ---------------------------------------------------------
*
* YES -> Q9
* NO -> Q10
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q8,
toQuestion: q9,
type: QuestionTransitionType.CHOICE,
condition: {
choiceId: q8Yes.id,
},
}),
);
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q8,
toQuestion: q10,
type: QuestionTransitionType.DEFAULT,
condition: null,
}),
);
/*
* Q9 -> Q10
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q9,
toQuestion: q10,
type: QuestionTransitionType.DEFAULT,
condition: null,
}),
);
/*
* ---------------------------------------------------------
* Q10 BRANCH
* ---------------------------------------------------------
*
* YES -> Q11
* NO -> Q12
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q10,
toQuestion: q11,
type: QuestionTransitionType.CHOICE,
condition: {
choiceId: q10Yes.id,
},
}),
);
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q10,
toQuestion: q12,
type: QuestionTransitionType.DEFAULT,
condition: null,
}),
);
/*
* Q11 -> Q12
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q11,
toQuestion: q12,
type: QuestionTransitionType.DEFAULT,
condition: null,
}),
);
/*
* Q12 -> END
*/
await transitionRepository.save(
transitionRepository.create({
test: savedTest,
fromQuestion: q12,
toQuestion: null,
type: QuestionTransitionType.END,
condition: null,
}),
);
}
+4 -1
View File
@@ -5,14 +5,17 @@
"otp": "Otp"
},
"errors": {
"otpAlreadySent": "OTP already sent. Please try again in 1 minute.",
"wrongPhoneOrPass": "Entered phone number or password is wrong.",
"unauthorized": "Unauthorized access",
"tokenReuse": "Token reuse detected.",
"invalidOTP": "OTP is invalid or expired.",
"accountNotFound": "Account not found.",
"accessDenied": "Access denied. You do not have the required permissions to perform this action."
},
"messages": {
"otpSent": "OTP sent to {phone}.",
"sendPass": "Please send password."
"sendPass": "Please send password.",
"loggedOut": "Logged out successfully."
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"fields": {
"conversationId": "Conversation Id",
"message": "Message"
}
}
+5
View File
@@ -0,0 +1,5 @@
{
"fields": {
"conversation": "Conversation"
}
}
-1
View File
@@ -9,7 +9,6 @@
"question": "Question",
"text": "Text",
"value": "Value",
"choice": "Choice",
"score": "Score",
"weight": "Weight",
"rangeRule": "Range Rule",
+5 -2
View File
@@ -9,12 +9,15 @@
},
"errors": {
"alreadyTookTest": "You already took this test.",
"choiceNumericConstraint": "You must send either choiceId or numericValue.",
"choiceNumericConstraint": "You must send either choiceId, choiceIds or numericValue.",
"emptyNumericValue": "A numeric value should be provided as answer.",
"numericValueRange": "Numeric value is out of specified range.",
"emptyChoiceId": "Choice Id should be provided as answer.",
"emptyChoiceIds": "Choice Ids should be provided as answer.",
"transitionNotFound": "No transition found for the test",
"uniqueSubmissionQuestion": "Question's Answer already exists."
"uniqueSubmissionQuestion": "Question's Answer already exists.",
"submissionNotCompleted": "This submission is not completed yet.",
"noAnswers": "No answers found to analyze.",
"analysisFailed": "The analysis failed. Please try again."
}
}
+4 -1
View File
@@ -5,14 +5,17 @@
"otp": "کد تایید"
},
"errors": {
"otpAlreadySent": "کد تایید قبلا ارسال شده. لطفا دقایقی دیگر مجددا امتحان کنید.",
"wrongPhoneOrPass": "شماره موبایل یا رمز عبور اشتباه است.",
"unauthorized": "دسترسی غیر مجاز",
"tokenReuse": "توکن قبلا استفاده شده.",
"invalidOTP": "کد تایید اشتباه است یا منقضی شده.",
"accountNotFound": "حساب کاربری یافت نشد.",
"accessDenied": "دسترسی غیرمجاز. شما مجوزهای لازم برای انجام این عملیات را ندارید."
},
"messages": {
"otpSent": "کد تایید به شماره {phone} ارسال شد.",
"sendPass": "لطفا رمز عبور را ارسال کنید."
"sendPass": "لطفا رمز عبور را ارسال کنید.",
"loggedOut": "با موفقیت خارج شدید."
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"fields": {
"conversationId": "شناسه مکالمه",
"message": "پیام"
}
}
+5
View File
@@ -0,0 +1,5 @@
{
"fields": {
"conversation": "مکالمه"
}
}
-1
View File
@@ -8,7 +8,6 @@
"metadata": "تنظیمات",
"question": "سوال",
"text": "متن",
"value": "مقدار",
"choice": "گزینه",
"score": "نمره",
"weight": "وزن",
+4 -1
View File
@@ -15,6 +15,9 @@
"emptyChoiceId": "شناسه گزینه باید به عنوان پاسخ مشخص شود.",
"emptyChoiceIds": "لیستی از شناسه گزینه ها باید به عنوان پاسخ مشخص شود.",
"transitionNotFound": "مسیری برای تست پیدا نشد.",
"uniqueSubmissionQuestion": "این سوال قبلا پاسخ داده شده است."
"uniqueSubmissionQuestion": "این سوال قبلا پاسخ داده شده است.",
"submissionNotCompleted": "این Submission هنوز تکمیل نشده است.",
"noAnswers": "هیچ پاسخی برای تحلیل یافت نشد.",
"analysisFailed": "تحلیل با خطا مواجه شد. لطفا دوباره تلاش کنید."
}
}
+18 -2
View File
@@ -5,11 +5,23 @@ import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
import helmet from 'helmet';
import { ConfigService } from '@nestjs/config';
import { Logger } from 'nestjs-pino';
import { AdminPanelSetup } from './modules/admin-panel/admin-panel.setup';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const app = await NestFactory.create(AppModule, { bufferLogs: true });
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
app.getHttpAdapter().getInstance().set('trust proxy', 1);
app.useLogger(app.get(Logger));
app.setGlobalPrefix('v1');
app.enableShutdownHooks();
// Mount the admin panel before Nest registers its body parsers; the setup
// itself is deferred until the DI container is ready (after app.init)
AdminPanelSetup.mount(app);
app.useGlobalPipes(
new I18nValidationPipe({
@@ -91,6 +103,10 @@ async function bootstrap() {
SwaggerModule.setup('v1/docs', app, document);
await app.init();
AdminPanelSetup.setup(app);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
void bootstrap();
@@ -2,8 +2,8 @@ import { UNIQUE_QUESTION_MULTI_CHOICE } from '@/modules/questions/constants';
import { QuestionTransitionType } from '@/modules/questions/enums/question-transition-type.enum';
import { MigrationInterface, QueryRunner } from 'typeorm';
export class MultiChoiceTransitionUniqueIndex1786856474000 implements MigrationInterface {
name = 'AddMultiChoiceTransitionUniqueIndex1750000000000';
export class MultiChoiceTransitionUniqueIndex1787294625900 implements MigrationInterface {
name = 'MultiChoiceTransitionUniqueIndex1787294625900';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
@@ -0,0 +1,35 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class PrepUserSubmissionHistory1788876455659 implements MigrationInterface {
name = 'PrepUserSubmissionHistory1788876455659';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP INDEX "public"."unq_question_multi_choice"`);
await queryRunner.query(`ALTER TABLE "choice" DROP COLUMN "value"`);
await queryRunner.query(
`ALTER TABLE "submission_answer" ADD "createdAt" TIMESTAMP NOT NULL DEFAULT now()`,
);
await queryRunner.query(
`ALTER TABLE "submission" ADD "code" character varying`,
);
await queryRunner.query(
`ALTER TABLE "submission" ADD "completedAt" TIMESTAMP WITH TIME ZONE`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "submission" DROP COLUMN "completedAt"`,
);
await queryRunner.query(`ALTER TABLE "submission" DROP COLUMN "code"`);
await queryRunner.query(
`ALTER TABLE "submission_answer" DROP COLUMN "createdAt"`,
);
await queryRunner.query(
`ALTER TABLE "choice" ADD "value" integer NOT NULL`,
);
await queryRunner.query(
`CREATE UNIQUE INDEX "unq_question_multi_choice" ON "question_transition" ("type", "fromQuestionId") WHERE (type = 'multi-choice'::question_transition_type_enum)`,
);
}
}
@@ -0,0 +1,35 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class ChangeResultRangeFields1788950646073 implements MigrationInterface {
name = 'ChangeResultRangeFields1788950646073';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "result_range" DROP COLUMN "minScore"`,
);
await queryRunner.query(
`ALTER TABLE "result_range" DROP COLUMN "maxScore"`,
);
await queryRunner.query(
`ALTER TABLE "result_range" ADD "minProbability" integer NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "result_range" ADD "maxProbability" integer NOT NULL`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "result_range" DROP COLUMN "maxProbability"`,
);
await queryRunner.query(
`ALTER TABLE "result_range" DROP COLUMN "minProbability"`,
);
await queryRunner.query(
`ALTER TABLE "result_range" ADD "maxScore" integer NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "result_range" ADD "minScore" integer NOT NULL`,
);
}
}
@@ -0,0 +1,35 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class CalculateByScore1789906979798 implements MigrationInterface {
name = 'CalculateByScore1789906979798';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "result_range" DROP COLUMN "minProbability"`,
);
await queryRunner.query(
`ALTER TABLE "result_range" DROP COLUMN "maxProbability"`,
);
await queryRunner.query(
`ALTER TABLE "result_range" ADD "minScore" integer NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "result_range" ADD "maxScore" integer NOT NULL`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "result_range" DROP COLUMN "maxScore"`,
);
await queryRunner.query(
`ALTER TABLE "result_range" DROP COLUMN "minScore"`,
);
await queryRunner.query(
`ALTER TABLE "result_range" ADD "maxProbability" integer NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "result_range" ADD "minProbability" integer NOT NULL`,
);
}
}
@@ -0,0 +1,35 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class Conversation1791194400675 implements MigrationInterface {
name = 'Conversation1791194400675';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "conversation" ("id" SERIAL NOT NULL, "title" character varying, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), "userId" integer, CONSTRAINT "PK_864528ec4274360a40f66c29845" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE TYPE "public"."message_role_enum" AS ENUM('user', 'assistant', 'doctor')`,
);
await queryRunner.query(
`CREATE TABLE "message" ("id" SERIAL NOT NULL, "role" "public"."message_role_enum" NOT NULL, "content" text NOT NULL, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "conversationId" integer, CONSTRAINT "PK_ba01f0a3e0123651915008bc578" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`ALTER TABLE "conversation" ADD CONSTRAINT "FK_c308b1cd542522bb66430fa860a" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "message" ADD CONSTRAINT "FK_7cf4a4df1f2627f72bf6231635f" FOREIGN KEY ("conversationId") REFERENCES "conversation"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "message" DROP CONSTRAINT "FK_7cf4a4df1f2627f72bf6231635f"`,
);
await queryRunner.query(
`ALTER TABLE "conversation" DROP CONSTRAINT "FK_c308b1cd542522bb66430fa860a"`,
);
await queryRunner.query(`DROP TABLE "message"`);
await queryRunner.query(`DROP TYPE "public"."message_role_enum"`);
await queryRunner.query(`DROP TABLE "conversation"`);
}
}
@@ -0,0 +1,37 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class QuestionTestId1793536838991 implements MigrationInterface {
name = 'QuestionTestId1793536838991';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "question" DROP CONSTRAINT "FK_2c8f911efa2fb5b0fe1abe92020"`,
);
await queryRunner.query(`DROP INDEX "public"."UNQ_TEST_ORDER_IDX"`);
await queryRunner.query(
`ALTER TABLE "question" ALTER COLUMN "testId" SET NOT NULL`,
);
await queryRunner.query(
`CREATE UNIQUE INDEX "UNQ_TEST_ORDER_IDX" ON "question" ("testId", "order") `,
);
await queryRunner.query(
`ALTER TABLE "question" ADD CONSTRAINT "FK_2c8f911efa2fb5b0fe1abe92020" FOREIGN KEY ("testId") REFERENCES "test"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "question" DROP CONSTRAINT "FK_2c8f911efa2fb5b0fe1abe92020"`,
);
await queryRunner.query(`DROP INDEX "public"."UNQ_TEST_ORDER_IDX"`);
await queryRunner.query(
`ALTER TABLE "question" ALTER COLUMN "testId" DROP NOT NULL`,
);
await queryRunner.query(
`CREATE UNIQUE INDEX "UNQ_TEST_ORDER_IDX" ON "question" ("order", "testId") `,
);
await queryRunner.query(
`ALTER TABLE "question" ADD CONSTRAINT "FK_2c8f911efa2fb5b0fe1abe92020" FOREIGN KEY ("testId") REFERENCES "test"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}
}
@@ -0,0 +1,225 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddJoinColumns1793618352591 implements MigrationInterface {
name = 'AddJoinColumns1793618352591';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`DROP INDEX "public"."IDX_275b917b91392b9a2d6ab7ccee"`,
);
await queryRunner.query(`DROP INDEX "public"."UNQ_TEST_ORDER_IDX"`);
await queryRunner.query(`ALTER TABLE "question" DROP COLUMN "order"`);
await queryRunner.query(
`ALTER TABLE "message" DROP CONSTRAINT "FK_7cf4a4df1f2627f72bf6231635f"`,
);
await queryRunner.query(
`ALTER TABLE "message" ALTER COLUMN "conversationId" SET NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "conversation" DROP CONSTRAINT "FK_c308b1cd542522bb66430fa860a"`,
);
await queryRunner.query(
`ALTER TABLE "conversation" ALTER COLUMN "userId" SET NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "choice" DROP CONSTRAINT "FK_5cc8f4862acc8b7b956be1be204"`,
);
await queryRunner.query(`DROP INDEX "public"."UNQ_QUESTION_ORDER_IDX"`);
await queryRunner.query(
`ALTER TABLE "choice" ALTER COLUMN "questionId" SET NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "question_range_rule" DROP CONSTRAINT "FK_d7c902bf4e3c214ad80cb9b6e8a"`,
);
await queryRunner.query(
`ALTER TABLE "question_range_rule" ALTER COLUMN "questionId" SET NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "result_range" DROP CONSTRAINT "FK_af2d7b64263e469098d234ce3d0"`,
);
await queryRunner.query(
`ALTER TABLE "result_range" ALTER COLUMN "testId" SET NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "submission_answer" DROP CONSTRAINT "FK_d52d9c3efb0e1aa66d2e27155ac"`,
);
await queryRunner.query(
`ALTER TABLE "submission_answer" DROP CONSTRAINT "FK_1da4a54a983fd01227d9fad225c"`,
);
await queryRunner.query(
`DROP INDEX "public"."UNQ_SUBMISSION_QUESTION_IDX"`,
);
await queryRunner.query(
`ALTER TABLE "submission_answer" ALTER COLUMN "submissionId" SET NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "submission_answer" ALTER COLUMN "questionId" SET NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "submission" DROP CONSTRAINT "FK_7bd626272858ef6464aa2579094"`,
);
await queryRunner.query(
`ALTER TABLE "submission" DROP CONSTRAINT "FK_53685d02371670b4495ff181aec"`,
);
await queryRunner.query(
`ALTER TABLE "submission" ALTER COLUMN "userId" SET NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "submission" ALTER COLUMN "testId" SET NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "submission_result" DROP CONSTRAINT "FK_3ff0186775dd04fd7a209b6dca9"`,
);
await queryRunner.query(
`ALTER TABLE "submission_result" ALTER COLUMN "submissionId" SET NOT NULL`,
);
await queryRunner.query(
`CREATE UNIQUE INDEX "UNQ_QUESTION_ORDER_IDX" ON "choice" ("questionId", "order") `,
);
await queryRunner.query(
`CREATE UNIQUE INDEX "UNQ_SUBMISSION_QUESTION_IDX" ON "submission_answer" ("submissionId", "questionId") `,
);
await queryRunner.query(
`ALTER TABLE "message" ADD CONSTRAINT "FK_7cf4a4df1f2627f72bf6231635f" FOREIGN KEY ("conversationId") REFERENCES "conversation"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "conversation" ADD CONSTRAINT "FK_c308b1cd542522bb66430fa860a" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "choice" ADD CONSTRAINT "FK_5cc8f4862acc8b7b956be1be204" FOREIGN KEY ("questionId") REFERENCES "question"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "question_range_rule" ADD CONSTRAINT "FK_d7c902bf4e3c214ad80cb9b6e8a" FOREIGN KEY ("questionId") REFERENCES "question"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "result_range" ADD CONSTRAINT "FK_af2d7b64263e469098d234ce3d0" FOREIGN KEY ("testId") REFERENCES "test"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "submission_answer" ADD CONSTRAINT "FK_d52d9c3efb0e1aa66d2e27155ac" FOREIGN KEY ("submissionId") REFERENCES "submission"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "submission_answer" ADD CONSTRAINT "FK_1da4a54a983fd01227d9fad225c" FOREIGN KEY ("questionId") REFERENCES "question"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "submission" ADD CONSTRAINT "FK_7bd626272858ef6464aa2579094" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "submission" ADD CONSTRAINT "FK_53685d02371670b4495ff181aec" FOREIGN KEY ("testId") REFERENCES "test"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "submission_result" ADD CONSTRAINT "FK_3ff0186775dd04fd7a209b6dca9" FOREIGN KEY ("submissionId") REFERENCES "submission"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "submission_result" DROP CONSTRAINT "FK_3ff0186775dd04fd7a209b6dca9"`,
);
await queryRunner.query(
`ALTER TABLE "submission" DROP CONSTRAINT "FK_53685d02371670b4495ff181aec"`,
);
await queryRunner.query(
`ALTER TABLE "submission" DROP CONSTRAINT "FK_7bd626272858ef6464aa2579094"`,
);
await queryRunner.query(
`ALTER TABLE "submission_answer" DROP CONSTRAINT "FK_1da4a54a983fd01227d9fad225c"`,
);
await queryRunner.query(
`ALTER TABLE "submission_answer" DROP CONSTRAINT "FK_d52d9c3efb0e1aa66d2e27155ac"`,
);
await queryRunner.query(
`ALTER TABLE "result_range" DROP CONSTRAINT "FK_af2d7b64263e469098d234ce3d0"`,
);
await queryRunner.query(
`ALTER TABLE "question_range_rule" DROP CONSTRAINT "FK_d7c902bf4e3c214ad80cb9b6e8a"`,
);
await queryRunner.query(
`ALTER TABLE "choice" DROP CONSTRAINT "FK_5cc8f4862acc8b7b956be1be204"`,
);
await queryRunner.query(
`ALTER TABLE "conversation" DROP CONSTRAINT "FK_c308b1cd542522bb66430fa860a"`,
);
await queryRunner.query(
`ALTER TABLE "message" DROP CONSTRAINT "FK_7cf4a4df1f2627f72bf6231635f"`,
);
await queryRunner.query(
`DROP INDEX "public"."UNQ_SUBMISSION_QUESTION_IDX"`,
);
await queryRunner.query(`DROP INDEX "public"."UNQ_QUESTION_ORDER_IDX"`);
await queryRunner.query(
`ALTER TABLE "submission_result" ALTER COLUMN "submissionId" DROP NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "submission_result" ADD CONSTRAINT "FK_3ff0186775dd04fd7a209b6dca9" FOREIGN KEY ("submissionId") REFERENCES "submission"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "submission" ALTER COLUMN "testId" DROP NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "submission" ALTER COLUMN "userId" DROP NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "submission" ADD CONSTRAINT "FK_53685d02371670b4495ff181aec" FOREIGN KEY ("testId") REFERENCES "test"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "submission" ADD CONSTRAINT "FK_7bd626272858ef6464aa2579094" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "submission_answer" ALTER COLUMN "questionId" DROP NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "submission_answer" ALTER COLUMN "submissionId" DROP NOT NULL`,
);
await queryRunner.query(
`CREATE UNIQUE INDEX "UNQ_SUBMISSION_QUESTION_IDX" ON "submission_answer" ("submissionId", "questionId") `,
);
await queryRunner.query(
`ALTER TABLE "submission_answer" ADD CONSTRAINT "FK_1da4a54a983fd01227d9fad225c" FOREIGN KEY ("questionId") REFERENCES "question"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "submission_answer" ADD CONSTRAINT "FK_d52d9c3efb0e1aa66d2e27155ac" FOREIGN KEY ("submissionId") REFERENCES "submission"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "result_range" ALTER COLUMN "testId" DROP NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "result_range" ADD CONSTRAINT "FK_af2d7b64263e469098d234ce3d0" FOREIGN KEY ("testId") REFERENCES "test"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "question_range_rule" ALTER COLUMN "questionId" DROP NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "question_range_rule" ADD CONSTRAINT "FK_d7c902bf4e3c214ad80cb9b6e8a" FOREIGN KEY ("questionId") REFERENCES "question"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "choice" ALTER COLUMN "questionId" DROP NOT NULL`,
);
await queryRunner.query(
`CREATE UNIQUE INDEX "UNQ_QUESTION_ORDER_IDX" ON "choice" ("order", "questionId") `,
);
await queryRunner.query(
`ALTER TABLE "choice" ADD CONSTRAINT "FK_5cc8f4862acc8b7b956be1be204" FOREIGN KEY ("questionId") REFERENCES "question"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "conversation" ALTER COLUMN "userId" DROP NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "conversation" ADD CONSTRAINT "FK_c308b1cd542522bb66430fa860a" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "message" ALTER COLUMN "conversationId" DROP NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "message" ADD CONSTRAINT "FK_7cf4a4df1f2627f72bf6231635f" FOREIGN KEY ("conversationId") REFERENCES "conversation"("id") ON DELETE CASCADE ON UPDATE NO ACTION`,
);
await queryRunner.query(
`ALTER TABLE "question" ADD "order" integer NOT NULL`,
);
await queryRunner.query(
`CREATE UNIQUE INDEX "UNQ_TEST_ORDER_IDX" ON "question" ("order", "testId") `,
);
await queryRunner.query(
`CREATE INDEX "IDX_275b917b91392b9a2d6ab7ccee" ON "question" ("order") `,
);
}
}
@@ -0,0 +1,13 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class OtpFailedAttempts1793923200000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "otp" ADD "failedAttempts" integer NOT NULL DEFAULT 0`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "otp" DROP COLUMN "failedAttempts"`);
}
}
@@ -0,0 +1,17 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class LockPublishedTestStructure1794182400000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "test" ADD "structureLocked" boolean NOT NULL DEFAULT false`,
);
await queryRunner.query(`UPDATE "test" SET "structureLocked" = true
WHERE "status" = 'published' OR EXISTS (
SELECT 1 FROM "submission" WHERE "submission"."testId" = "test"."id"
)`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "test" DROP COLUMN "structureLocked"`);
}
}
@@ -0,0 +1,13 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class OtpPurpose1795305600000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "otp" ADD "purpose" varchar NOT NULL DEFAULT 'signup'`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "otp" DROP COLUMN "purpose"`);
}
}
@@ -0,0 +1,42 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class ArticleRag1795737600000 implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('CREATE EXTENSION IF NOT EXISTS vector');
await queryRunner.query(`
CREATE TABLE rag_article (
id uuid PRIMARY KEY,
"storageKey" uuid NOT NULL,
"runToken" uuid,
title varchar(240) NOT NULL,
"fileName" varchar(255) NOT NULL,
"mimeType" varchar(120) NOT NULL,
"byteSize" integer NOT NULL,
"sourceUrl" varchar(2048),
status varchar(16) NOT NULL CHECK (status IN ('pending','processing','ready','failed')),
generation integer NOT NULL DEFAULT 1,
"embeddingModel" varchar(300),
"errorCode" varchar(80),
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX rag_article_dispatch_idx ON rag_article (status, "createdAt", id);
CREATE TABLE rag_article_chunk (
id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"articleId" uuid NOT NULL CONSTRAINT rag_chunk_article_fkey REFERENCES rag_article(id) ON DELETE CASCADE,
"chunkIndex" integer NOT NULL,
content text NOT NULL,
embedding vector(384) NOT NULL,
metadata jsonb NOT NULL,
"createdAt" timestamptz NOT NULL DEFAULT now(),
"updatedAt" timestamptz NOT NULL DEFAULT now(),
CONSTRAINT rag_chunk_article_index_key UNIQUE ("articleId", "chunkIndex")
);
CREATE INDEX rag_chunk_cosine_idx ON rag_article_chunk USING hnsw (embedding vector_cosine_ops);
`);
}
async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('DROP TABLE rag_article_chunk, rag_article');
}
}
@@ -0,0 +1,11 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class MessageSources1795737600001 implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('ALTER TABLE "message" ADD COLUMN "sources" jsonb');
}
async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('ALTER TABLE "message" DROP COLUMN "sources"');
}
}
@@ -0,0 +1,67 @@
import type { SessionData } from 'express-session';
import { Store } from 'express-session';
import { RedisService } from '@/common/modules/redis/providers/redis.service';
/**
* express-session store backed by the application Redis, so admin sessions
* survive restarts and expire server-side together with the cookie.
*/
export class AdminPanelSessionStore extends Store {
constructor(
/**
* Inject Redis Service
*/
private readonly redisService: RedisService,
) {
super();
}
private key(sessionId: string) {
return `admin:panel:sess:${sessionId}`;
}
private ttlSeconds(session: SessionData) {
const maxAgeMs = session.cookie?.maxAge;
return typeof maxAgeMs === 'number'
? Math.floor(maxAgeMs / 1000)
: undefined;
}
override get(
sessionId: string,
callback: (err: unknown, session?: SessionData | null) => void,
) {
this.redisService
.get<SessionData>(this.key(sessionId))
.then((session) => callback(null, session ?? null))
.catch(callback);
}
override set(
sessionId: string,
session: SessionData,
callback: (err?: unknown) => void,
) {
this.redisService
.set(this.key(sessionId), session, this.ttlSeconds(session))
.then(() => callback())
.catch(callback);
}
override destroy(sessionId: string, callback: (err?: unknown) => void) {
this.redisService
.del(this.key(sessionId))
.then(() => callback())
.catch(callback);
}
override touch(
sessionId: string,
session: SessionData,
callback: (err?: unknown) => void,
) {
// Rolling sessions: refresh the server-side TTL on every request
this.set(sessionId, session, callback);
}
}
@@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { UsersModule } from '../users/users.module';
import { HashingModule } from '@/common/modules/hashing/hashing.module';
import { RedisModule } from '@/common/modules/redis/redis.module';
import { AdminPanelAuthenticator } from './providers/admin-panel-auth.provider';
/**
* Wires the dependencies AdminPanelSetup resolves after bootstrap.
* The panel itself is mounted on the express instance (see admin-panel.setup.ts
* and main.ts), not through Nest controllers.
*/
@Module({
imports: [UsersModule, HashingModule, RedisModule],
providers: [AdminPanelAuthenticator],
exports: [AdminPanelAuthenticator],
})
export class AdminPanelModule {}
@@ -0,0 +1,76 @@
import { describe, expect, it, jest } from '@jest/globals';
import { Repository } from 'typeorm';
import { I18nService } from 'nestjs-i18n';
import { TestsService } from '@/modules/tests/providers/tests.service';
import { ResultRange } from '@/modules/scoring/entities/result-range.entity';
import { ResultRangeCommandProvider } from '@/modules/scoring/providers/result-range-command.provider';
import { Question } from '@/modules/questions/entities/question.entity';
import { QuestionRangeRule } from '@/modules/questions/entities/question-range-rule.entity';
import { QuestionRangeRuleCommandProvider } from '@/modules/questions/providers/range-rule/question-range-rule-command.provider';
describe.each(['result', 'question'] as const)('%s range updates', (kind) => {
function setup(overlaps: unknown[]) {
const andWhere = jest.fn<(...args: unknown[]) => unknown>();
const builder = {
where: jest.fn<(...args: unknown[]) => unknown>(),
andWhere,
getMany: jest.fn<() => Promise<unknown[]>>().mockResolvedValue(overlaps),
};
builder.where.mockReturnValue(builder);
andWhere.mockReturnValue(builder);
const save = jest
.fn<(value: unknown) => Promise<unknown>>()
.mockImplementation((value) => Promise.resolve(value));
const repository = {
createQueryBuilder: () => builder,
findOne: () =>
Promise.resolve({
id: 7,
test: { id: 2 },
question: { id: 3 },
minScore: 0,
maxScore: 5,
min: 0,
max: 5,
}),
save,
};
const update =
kind === 'result'
? () =>
new ResultRangeCommandProvider(
repository as unknown as Repository<ResultRange>,
{} as TestsService,
{} as I18nService,
).updateOne(7, { minScore: 20, maxScore: 30 })
: () =>
new QuestionRangeRuleCommandProvider(
repository as unknown as Repository<QuestionRangeRule>,
{} as Repository<Question>,
{} as I18nService,
).updateOne(7, { min: 20, max: 30 });
return { update, andWhere, save };
}
it('rejects even one overlapping different record after moving a range', async () => {
const { update, andWhere, save } = setup([{ id: 99 }]);
await expect(update()).rejects.toThrow();
expect(andWhere).toHaveBeenCalledWith(
expect.stringContaining('id != :excludeId'),
{ excludeId: 7 },
);
expect(save).not.toHaveBeenCalled();
});
it('allows non-overlapping edits and preserves entity relations', async () => {
const { update, save } = setup([]);
await update();
expect(save).toHaveBeenCalledWith(
expect.objectContaining(
kind === 'result'
? { test: { id: 2 }, testId: 2, minScore: 20, maxScore: 30 }
: { question: { id: 3 }, questionId: 3, min: 20, max: 30 },
),
);
});
});
@@ -0,0 +1,103 @@
import { Resource } from '@adminjs/typeorm';
import { BaseRecord, Filter, ValidationError, flat } from 'adminjs';
import { BaseEntity } from 'typeorm';
export type PanelWrite = (
operation: 'new' | 'edit' | 'delete',
params: Record<string, unknown>,
id?: number,
) => Promise<Record<string, unknown>>;
/** No AdminJS write is allowed to fall back to the raw TypeORM adapter. */
export class AdminPanelResource extends Resource {
constructor(
model: typeof BaseEntity,
private readonly write?: PanelWrite,
) {
super(model);
}
private async persist(
operation: 'new' | 'edit' | 'delete',
params: Record<string, unknown>,
id?: string | number,
) {
if (!this.write)
throw new ValidationError({}, { message: 'این منبع فقط خواندنی است.' });
if (
id !== undefined &&
(!Number.isSafeInteger(Number(id)) || Number(id) < 1)
) {
throw new ValidationError({}, { message: 'شناسه نامعتبر است.' });
}
if (
Object.keys(params).some((key) =>
key
.split('.')
.some((part) =>
['__proto__', 'prototype', 'constructor'].includes(part),
),
)
) {
throw new ValidationError({}, { message: 'فیلد نامعتبر است.' });
}
const unflatten = (
flat as unknown as {
unflatten: (input: Record<string, unknown>) => Record<string, unknown>;
}
).unflatten;
return this.write(
operation,
unflatten(params),
id === undefined ? undefined : Number(id),
);
}
override create(params: Record<string, unknown>) {
return this.persist('new', params);
}
override update(id: string | number, params: Record<string, unknown> = {}) {
return this.persist('edit', params, id);
}
override delete(id: string | number) {
return this.persist('delete', {}, id);
}
// Visibility settings only affect the UI. Remove credentials from the
// actual records too, including reference-population and search responses.
private redact(record: BaseRecord | null) {
if (record) {
delete record.params.password;
for (const key of ['metadata', 'condition']) {
const value: unknown = record.get(key);
if (value && typeof value === 'object') {
Object.keys(record.params)
.filter((path) => path === key || path.startsWith(`${key}.`))
.forEach((path) => {
delete record.params[path];
});
record.params[key] = JSON.stringify(value);
}
}
}
return record;
}
override async findOne(id: string | number) {
return this.redact(await super.findOne(id));
}
override async find(filter: Filter, params: unknown) {
const records = await super.find(filter, params);
records.forEach((record) => this.redact(record));
return records;
}
override async findMany(ids: Array<string | number>) {
const records = await super.findMany(ids);
records.forEach((record) => this.redact(record));
return records;
}
}
@@ -0,0 +1,371 @@
import {
beforeAll,
beforeEach,
describe,
expect,
it,
jest,
} from '@jest/globals';
import AdminJS, {
ActionContext,
ActionRequest,
ResourceWithOptions,
} from 'adminjs';
import { INestApplication } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { I18nService } from 'nestjs-i18n';
import { Role } from '@/common/enums/roles.enum';
import { User } from '@/modules/users/entities/user.entity';
import { UsersService } from '@/modules/users/providers/users.service';
import { Test } from '@/modules/tests/entities/test.entity';
import { TestStatus } from '@/modules/tests/enums/test-status.enum';
import { Question } from '@/modules/questions/entities/question.entity';
import { QuestionType } from '@/modules/questions/enums/question-type.enum';
import { Choice } from '@/modules/questions/entities/choice.entity';
import { QuestionRangeRule } from '@/modules/questions/entities/question-range-rule.entity';
import { QuestionTransition } from '@/modules/questions/entities/question-transition.entity';
import { ResultRange } from '@/modules/scoring/entities/result-range.entity';
import { Submission } from '@/modules/submissions/entities/submission.entity';
import { SubmissionAnswer } from '@/modules/submissions/entities/submission-answer.entity';
import { SubmissionResult } from '@/modules/submissions/entities/submission-result.entity';
import { Conversation } from '@/modules/conversation/entities/conversation.entity';
import { Message } from '@/modules/conversation/entities/message.entity';
import { buildAdminPanelResources } from './admin-panel.resources';
import { AdminPanelResource } from './admin-panel.resource';
import { panelValues, redactPanelSecrets } from './admin-panel.validation';
describe('AdminJS validated resources', () => {
const database = new DataSource({
type: 'postgres',
entities: [
User,
Test,
Question,
Choice,
QuestionRangeRule,
QuestionTransition,
ResultRange,
Submission,
SubmissionAnswer,
SubmissionResult,
Conversation,
Message,
],
});
let definitions: ResourceWithOptions[];
let query: jest.Mock<(...args: unknown[]) => Promise<unknown>>;
let commands: {
createOne: jest.Mock<(...args: unknown[]) => Promise<unknown>>;
updateOne: jest.Mock<(...args: unknown[]) => Promise<unknown>>;
deleteOne: jest.Mock<(...args: unknown[]) => Promise<unknown>>;
};
let users: {
findOneById: jest.Mock<UsersService['findOneById']>;
updateProfile: jest.Mock<UsersService['updateProfile']>;
};
const resource = (name: string) =>
definitions.find(
({ resource: entry }) => (entry as AdminPanelResource).id() === name,
)!.resource as AdminPanelResource;
beforeAll(async () => {
// Build real TypeORM relation metadata without connecting to a database.
await (
database as unknown as { buildMetadatas(): Promise<void> }
).buildMetadatas();
});
beforeEach(() => {
jest.restoreAllMocks();
commands = {
createOne: jest
.fn<(...args: unknown[]) => Promise<unknown>>()
.mockResolvedValue({ data: { id: 11 } }),
updateOne: jest
.fn<(...args: unknown[]) => Promise<unknown>>()
.mockResolvedValue({ id: 11 }),
deleteOne: jest
.fn<(...args: unknown[]) => Promise<unknown>>()
.mockResolvedValue(undefined),
};
users = {
findOneById: jest.fn<UsersService['findOneById']>().mockResolvedValue(
Object.assign(new User(), {
id: 1,
phone: '09121111111',
role: Role.USER,
password: 'secret-hash',
}),
),
updateProfile: jest
.fn<UsersService['updateProfile']>()
.mockResolvedValue({ message: 'updated' }),
};
query = jest
.fn<(...args: unknown[]) => Promise<unknown>>()
.mockResolvedValue([{ acquired: true }]);
jest.spyOn(database, 'createQueryRunner').mockReturnValue({
connect: () => Promise.resolve(undefined),
query,
release: () => Promise.resolve(undefined),
} as unknown as ReturnType<DataSource['createQueryRunner']>);
jest
.spyOn(database.getRepository(Test), 'findOneByOrFail')
.mockResolvedValue(
Object.assign(new Test(), { id: 2, status: TestStatus.IN_PROGRESS }),
);
jest
.spyOn(database.getRepository(Submission), 'existsBy')
.mockResolvedValue(false);
jest
.spyOn(database.getRepository(Question), 'findOneByOrFail')
.mockResolvedValue(
Object.assign(new Question(), {
id: 11,
testId: 2,
type: QuestionType.SINGLE_CHOICE,
content: 'Question',
weight: 1,
required: true,
metadata: null,
}),
);
const app = {
get: (token: unknown) =>
token === DataSource
? database
: token === UsersService
? users
: token === I18nService
? { translate: (message: string) => message }
: commands,
} as unknown as INestApplication;
definitions = buildAdminPanelResources(app);
});
it('builds the real AdminJS schema without duplicates or an OTP resource', () => {
const admin = new AdminJS({ resources: definitions });
const ids = admin.resources.map((entry) => entry.id());
expect(new Set(ids).size).toBe(ids.length);
expect(ids).not.toContain('OTP');
expect(
resource('QuestionTransition')
.properties()
.map((property) => property.path()),
).toContain('test.id');
});
it('validates and converts form values before using the question provider', async () => {
await resource('Question').create({
testId: '2',
content: 'New question',
type: QuestionType.SINGLE_CHOICE,
required: 'false',
weight: '2',
metadata: '{"allowOther":false}',
});
expect(commands.createOne).toHaveBeenCalledWith(
expect.objectContaining({
test: 2,
required: false,
weight: 2,
metadata: { allowOther: false },
}),
);
expect(query.mock.calls.map(([sql]) => sql)).toEqual([
'SELECT pg_try_advisory_lock(724091, 1) AS acquired',
'SELECT pg_advisory_unlock(724091, 1)',
]);
});
it('rejects invalid DTOs and forged system fields without calling providers', async () => {
await expect(
resource('Question').create({ testId: 2, content: '' }),
).rejects.toThrow();
await expect(
resource('Test').create({
title: 'Test',
description: 'Description',
questionsCount: 999,
}),
).rejects.toThrow();
expect(commands.createOne).not.toHaveBeenCalled();
});
it('rejects concurrent panel writes without waiting and holding the connection pool', async () => {
query.mockResolvedValue([{ acquired: false }]);
await expect(
resource('Question').create({ testId: 2, content: 'Question' }),
).rejects.toThrow();
expect(commands.createOne).not.toHaveBeenCalled();
expect(query).toHaveBeenCalledTimes(1);
});
it('converts the generated test.id reference and null transition endpoints', async () => {
await resource('QuestionTransition').create({
'test.id': '2',
fromQuestionId: '',
toQuestionId: '11',
type: 'start',
condition: '',
});
expect(commands.createOne).toHaveBeenCalledWith(
expect.objectContaining({
test: 2,
fromQuestion: null,
toQuestion: 11,
conditionValue: null,
}),
);
});
it('blocks structural changes to published tests', async () => {
jest
.spyOn(database.getRepository(Test), 'findOneByOrFail')
.mockResolvedValue(
Object.assign(new Test(), { id: 2, status: TestStatus.PUBLISHED }),
);
await expect(
resource('Question').update(11, { content: 'Changed' }),
).rejects.toThrow();
expect(commands.updateOne).not.toHaveBeenCalled();
});
it('keeps previously published structure locked even after unpublishing', async () => {
jest
.spyOn(database.getRepository(Test), 'findOneByOrFail')
.mockResolvedValue(
Object.assign(new Test(), {
id: 2,
status: TestStatus.IN_PROGRESS,
structureLocked: true,
}),
);
await expect(
resource('Question').update(11, { content: 'Changed' }),
).rejects.toThrow();
expect(commands.updateOne).not.toHaveBeenCalled();
});
it('blocks structural changes and cascaded deletion when a test has submissions', async () => {
jest
.spyOn(database.getRepository(Submission), 'existsBy')
.mockResolvedValue(true);
await expect(
resource('Question').update(11, { content: 'Changed' }),
).rejects.toThrow();
await expect(resource('Test').delete(2)).rejects.toThrow();
expect(commands.updateOne).not.toHaveBeenCalled();
expect(commands.deleteOne).not.toHaveBeenCalled();
});
it('rejects moving questions between tests', async () => {
await expect(
resource('Question').update(11, { testId: 3 }),
).rejects.toThrow();
expect(commands.updateOne).not.toHaveBeenCalled();
});
it('disables direct writes to history, conversations and users creation/deletion', async () => {
for (const name of [
'Submission',
'SubmissionAnswer',
'SubmissionResult',
'Conversation',
'Message',
]) {
await expect(resource(name).update(1, {})).rejects.toThrow();
await expect(resource(name).delete(1)).rejects.toThrow();
}
await expect(resource('User').create({})).rejects.toThrow();
await expect(resource('User').delete(1)).rejects.toThrow();
});
it('routes password changes through profile validation and hashing provider path', async () => {
const result = await resource('User').update(1, {
newPassword: 'StrongPass1!',
confirmPassword: 'StrongPass1!',
});
expect(users.updateProfile).toHaveBeenCalledWith(
expect.objectContaining({ id: 1 }),
expect.objectContaining({
password: 'StrongPass1!',
confirmPassword: 'StrongPass1!',
}),
);
expect(result).not.toHaveProperty('password');
await expect(
resource('User').update(1, { role: Role.SUPERUSER }),
).rejects.toThrow();
await expect(
resource('User').update(1, { newPassword: 'StrongPass1!' }),
).rejects.toThrow();
});
it('rechecks the current database role instead of trusting the session', async () => {
jest
.spyOn(database.getRepository(User), 'findOneBy')
.mockResolvedValue(Object.assign(new User(), { id: 1, role: Role.USER }));
const action = definitions.find(
({ resource: entry }) => (entry as AdminPanelResource).id() === 'Test',
)!.options.actions!.list!;
const context = {
currentAdmin: { id: '1', role: Role.SUPERUSER },
} as unknown as ActionContext;
const before = action.before as (
request: ActionRequest,
context: ActionContext,
) => Promise<ActionRequest>;
await expect(
before(
{ method: 'get', params: { resourceId: 'Test', action: 'list' } },
context,
),
).rejects.toThrow();
});
it('does not leak secrets through nested or failed-form responses', () => {
const response = {
record: {
params: {
password: 'hash',
newPassword: 'plain',
confirmPassword: 'plain',
firstName: 'Name',
},
populated: { user: { params: { password: 'hash' } } },
},
};
redactPanelSecrets(response);
expect(JSON.stringify(response)).not.toMatch(/hash|plain/);
expect(response.record.params.firstName).toBe('Name');
});
it('does not leak submitted passwords through i18n validation errors', async () => {
try {
await resource('User').update(1, {
newPassword: 'secret',
confirmPassword: 'secret',
});
throw new Error('Expected validation failure');
} catch (error) {
expect(error).toHaveProperty('propertyErrors.newPassword');
expect(JSON.stringify(error)).not.toContain('secret');
}
expect(users.updateProfile).not.toHaveBeenCalled();
});
it('rejects false-like boolean coercion and unsafe numeric values', () => {
expect(
panelValues([{ name: 'required', kind: 'boolean' }], {
required: 'false',
}),
).toEqual({ required: false });
expect(() =>
panelValues([{ name: 'weight', kind: 'number' }], { weight: '1.5' }),
).toThrow();
expect(() =>
panelValues([{ name: 'required', kind: 'boolean' }], { required: 'no' }),
).toThrow();
});
});
@@ -0,0 +1,553 @@
import { HttpException, INestApplication } from '@nestjs/common';
import { BaseEntity, DataSource } from 'typeorm';
import { ClassConstructor } from 'class-transformer';
import {
ActionContext,
ActionRequest,
ActionResponse,
ForbiddenError,
ResourceWithOptions,
ValidationError,
} from 'adminjs';
import { I18nService } from 'nestjs-i18n';
import { Role } from '@/common/enums/roles.enum';
import { User } from '@/modules/users/entities/user.entity';
import { UsersService } from '@/modules/users/providers/users.service';
import { UpdateProfileDTO } from '@/modules/users/dtos/update-profile.dto';
import { Test } from '@/modules/tests/entities/test.entity';
import { TestStatus } from '@/modules/tests/enums/test-status.enum';
import { TestsService } from '@/modules/tests/providers/tests.service';
import { CreateTestDTO } from '@/modules/tests/dtos/create-test.dto';
import { UpdateTestDTO } from '@/modules/tests/dtos/update-test.dto';
import { Question } from '@/modules/questions/entities/question.entity';
import { QuestionType } from '@/modules/questions/enums/question-type.enum';
import { Choice } from '@/modules/questions/entities/choice.entity';
import { QuestionRangeRule } from '@/modules/questions/entities/question-range-rule.entity';
import { QuestionTransition } from '@/modules/questions/entities/question-transition.entity';
import { QuestionsService } from '@/modules/questions/providers/questions.service';
import { ChoicesService } from '@/modules/questions/providers/choices/choices.service';
import { QuestionRangeRuleService } from '@/modules/questions/providers/range-rule/question-range-rule.service';
import { QuestionTransitionService } from '@/modules/questions/providers/transition/question-transition.service';
import { CreateQuestionDTO } from '@/modules/questions/dtos/create-question.dto';
import { CreateChoiceDTO } from '@/modules/questions/dtos/create-choice.dto';
import { CreateQuestionRangeRuleDTO } from '@/modules/questions/dtos/create-question-range-rule.dto';
import { CreateQuestionTransitionDTO } from '@/modules/questions/dtos/create-question-transition.dto';
import { ResultRange } from '@/modules/scoring/entities/result-range.entity';
import { ResultRangeService } from '@/modules/scoring/providers/result-range.service';
import { CreateResultRangeDTO } from '@/modules/scoring/dtos/create-result-range.dto';
import { Submission } from '@/modules/submissions/entities/submission.entity';
import { SubmissionAnswer } from '@/modules/submissions/entities/submission-answer.entity';
import { SubmissionResult } from '@/modules/submissions/entities/submission-result.entity';
import { Conversation } from '@/modules/conversation/entities/conversation.entity';
import { Message } from '@/modules/conversation/entities/message.entity';
import { AdminPanelResource, PanelWrite } from './admin-panel.resource';
import {
panelValues,
PanelField,
redactPanelSecrets,
validatePanelDto,
} from './admin-panel.validation';
const field = (
name: string,
kind?: PanelField['kind'],
dto?: string,
): PanelField => ({ name, kind, dto });
const reject = (message: string): never => {
throw new ValidationError({}, { message });
};
export function buildAdminPanelResources(
app: INestApplication,
): ResourceWithOptions[] {
const database = app.get(DataSource);
const users = app.get(UsersService);
const i18n: I18nService = app.get(I18nService);
const authorize = async (request: ActionRequest, context: ActionContext) => {
const id = Number(context.currentAdmin?.id);
const actor = Number.isSafeInteger(id)
? await database.getRepository(User).findOneBy({ id })
: null;
if (!actor || ![Role.ADMIN, Role.SUPERUSER].includes(actor.role))
throw new ForbiddenError('دسترسی مدیریت ندارید.');
// Refresh authorization on every request rather than trusting a stale session.
context.currentAdmin = { ...context.currentAdmin!, role: actor.role };
return request;
};
const staff = ({ currentAdmin }: ActionContext) =>
[Role.ADMIN, Role.SUPERUSER].includes(currentAdmin?.role as Role);
const superuser = ({ currentAdmin }: ActionContext) =>
currentAdmin?.role === Role.SUPERUSER;
const redact = (response: ActionResponse) => {
redactPanelSecrets(response);
return response;
};
const protectTest = async (id: number, structure: boolean) => {
const test = await database.getRepository(Test).findOneByOrFail({ id });
if (
structure &&
(test.structureLocked || test.status === TestStatus.PUBLISHED)
)
reject(
'ساختار آزمونی که منتشر شده قابل تغییر یا حذف نیست؛ آزمون جدید بسازید.',
);
if (await database.getRepository(Submission).existsBy({ testId: id }))
reject(
'این آزمون سابقه پاسخ دارد؛ برای تغییر ساختار یا حذف، آزمون جدید بسازید.',
);
};
// Providers use their own repositories. A shared session-level advisory lock
// serializes all panel writes across app instances without bypassing providers.
const serialize =
(write: PanelWrite): PanelWrite =>
async (...args) => {
const runner = database.createQueryRunner();
await runner.connect();
let locked = false;
try {
const locks = (await runner.query(
'SELECT pg_try_advisory_lock(724091, 1) AS acquired',
)) as Array<{ acquired: boolean }>;
if (!locks[0]?.acquired)
reject(
'درخواست مدیریتی دیگری در حال ذخیره‌سازی است؛ دوباره تلاش کنید.',
);
locked = true;
return await write(...args);
} catch (error) {
if (error instanceof ValidationError) throw error;
if (error instanceof HttpException && error.getStatus() < 500) {
const response = error.getResponse();
const details =
typeof response === 'string'
? { message: response }
: (response as {
message?: string;
params?: Record<string, unknown>;
});
const message = i18n.translate(details.message ?? error.message, {
lang: 'fa',
args: details.params,
});
return reject(String(message));
}
// Do not expose SQL, password hashes or database internals to the browser.
return reject(
'ذخیره‌سازی انجام نشد؛ داده‌ها و وابستگی‌های رکورد را بررسی کنید.',
);
} finally {
try {
if (locked)
await runner.query('SELECT pg_advisory_unlock(724091, 1)');
} finally {
await runner.release();
}
}
};
function resource(
model: typeof BaseEntity,
fields: PanelField[],
write?: PanelWrite,
sensitive = false,
): ResourceWithOptions {
const canRead = sensitive ? superuser : staff;
return {
resource: new AdminPanelResource(model, write && serialize(write)),
options: {
editProperties: fields.map(({ name }) =>
name === 'test' ? 'test.id' : name,
),
properties: {
password: { isVisible: false },
newPassword: {
type: 'password',
isVisible: {
list: false,
filter: false,
show: false,
edit: model === User,
},
},
confirmPassword: {
type: 'password',
isVisible: {
list: false,
filter: false,
show: false,
edit: model === User,
},
},
...(model === QuestionTransition
? { condition: { type: 'textarea' } }
: {}),
...(model === Question ? { metadata: { type: 'textarea' } } : {}),
},
actions: {
list: { before: authorize, after: redact, isAccessible: canRead },
show: { before: authorize, after: redact, isAccessible: canRead },
search: { before: authorize, after: redact, isAccessible: canRead },
new: {
before: authorize,
after: redact,
isAccessible: write && model !== User ? staff : false,
},
edit: {
before: authorize,
after: redact,
isAccessible: write ? (model === User ? superuser : staff) : false,
},
// Destructive cascades and account removal need a dedicated workflow.
delete: {
before: authorize,
after: redact,
isAccessible: write && model !== User ? staff : false,
},
bulkDelete: { isAccessible: false, isVisible: false },
},
},
};
}
function catalog<T extends object>(
model: typeof BaseEntity,
fields: PanelField[],
dto: ClassConstructor<T>,
commands: {
createOne: (values: T) => Promise<unknown>;
updateOne: (id: number, values: T) => Promise<unknown>;
deleteOne: (id: number) => Promise<unknown>;
},
) {
return resource(model, fields, async (operation, params, id) => {
const repository = database.getRepository(model);
const existing =
id === undefined
? undefined
: await repository.findOneByOrFail({ id } as never);
const current = (existing ?? {}) as unknown as Record<string, unknown>;
const input = panelValues(fields, params, current);
const original = panelValues(
fields,
Object.fromEntries(
fields
.filter(({ name }) => Object.hasOwn(current, name))
.map(({ name }) => [name, current[name]]),
),
);
// The generated transition FK is named test.id by TypeORM.
if (model === QuestionTransition && existing) {
const transition = await database
.getRepository(QuestionTransition)
.findOneOrFail({ where: { id }, relations: { test: true } });
original.test = transition.test.id;
}
const merged = { ...original, ...input };
const parent =
model === Question ||
model === ResultRange ||
model === QuestionTransition
? 'test'
: 'question';
if (
existing &&
input[parent] !== undefined &&
merged[parent] !== undefined
) {
const previous = original[parent];
if (Number(input[parent]) !== Number(previous))
reject(
'جابجایی این رکورد به آزمون یا سؤال دیگر مجاز نیست؛ رکورد جدید بسازید.',
);
}
const parentId = Number(merged[parent]);
const testId =
parent === 'test'
? parentId
: (
await database
.getRepository(Question)
.findOneByOrFail({ id: parentId })
).testId;
await protectTest(testId, true);
if (model === Choice || model === QuestionRangeRule) {
const question = await database
.getRepository(Question)
.findOneByOrFail({ id: parentId });
if (
model === Choice &&
![QuestionType.SINGLE_CHOICE, QuestionType.MULTI_CHOICE].includes(
question.type,
)
)
reject('گزینه فقط برای سؤال انتخابی قابل تعریف است.');
if (
model === QuestionRangeRule &&
question.type !== QuestionType.NUMERIC
)
reject('قانون بازه فقط برای سؤال عددی قابل تعریف است.');
}
if (model === Question && existing && merged.type !== current.type) {
const question = await database.getRepository(Question).findOneOrFail({
where: { id },
relations: {
choices: true,
rangeRules: true,
outgoingTransitions: true,
incomingTransitions: true,
},
});
if (
question.choices.length ||
question.rangeRules?.length ||
question.outgoingTransitions.length ||
question.incomingTransitions.length
)
reject(
'قبل از تغییر نوع سؤال، گزینه‌ها، قوانین و مسیرهای وابسته را تعیین تکلیف کنید.',
);
}
if (operation === 'delete') {
if (model === Choice) {
const transitions = await database
.getRepository(QuestionTransition)
.findBy({ fromQuestionId: parentId });
if (
transitions.some(
({ condition }) =>
condition &&
(('choiceId' in condition && condition.choiceId === id) ||
('choiceIds' in condition &&
condition.choiceIds.includes(id!))),
)
)
reject(
'این گزینه در شرط یک مسیر استفاده شده است؛ ابتدا مسیر را اصلاح کنید.',
);
}
await commands.deleteOne(id!);
return {};
}
const validated = await validatePanelDto(
dto,
merged,
i18n,
Object.fromEntries(
fields.map(({ name, dto: dtoName }) => [
dtoName ?? name,
name === 'test' ? 'test.id' : name,
]),
),
);
const result =
operation === 'new'
? await commands.createOne(validated)
: await commands.updateOne(id!, validated);
if (operation === 'edit')
return (await repository.findOneByOrFail({
id,
} as never)) as unknown as Record<string, unknown>;
const entity =
result && typeof result === 'object' && 'data' in result
? result.data
: result;
return entity as Record<string, unknown>;
});
}
const tests = app.get(TestsService);
const testFields = [
field('title'),
field('description'),
field('accessType'),
field('price'),
field('isActive', 'boolean'),
field('status'),
];
const testResource = resource(
Test,
testFields,
async (operation, params, id) => {
const existing =
id === undefined
? undefined
: await database.getRepository(Test).findOneByOrFail({ id });
const values = panelValues(
testFields,
params,
existing as unknown as Record<string, unknown>,
);
if (typeof values.price === 'number') {
if (!Number.isSafeInteger(values.price))
reject('مبلغ را به صورت عدد صحیح وارد کنید.');
values.price = values.price.toString();
}
if (operation === 'delete') {
await protectTest(id!, true);
await tests.deleteOne(id!);
return {};
}
const complete = {
...(existing &&
panelValues(
testFields,
Object.fromEntries(
testFields.map(({ name }) => [
name,
(existing as unknown as Record<string, unknown>)[name],
]),
),
)),
...values,
};
const status = complete.status;
delete complete.status;
const validated = await validatePanelDto(CreateTestDTO, complete, i18n);
if (
validated.price != null &&
BigInt(validated.price) > 9223372036854775807n
)
reject('مبلغ خارج از محدوده مجاز است.');
if (
validated.isActive &&
(status ?? TestStatus.IN_PROGRESS) !== TestStatus.PUBLISHED
)
reject('فقط آزمون منتشرشده می‌تواند فعال باشد.');
if (operation === 'new') {
if (status !== undefined && status !== TestStatus.IN_PROGRESS)
reject('آزمون جدید باید ابتدا پیش‌نویس باشد.');
return (await tests.createOne(validated)).data as unknown as Record<
string,
unknown
>;
}
const update = await validatePanelDto(
UpdateTestDTO,
{
...validated,
status,
},
i18n,
);
return (await tests.updateOne(id!, update)) as unknown as Record<
string,
unknown
>;
},
);
const userFields = [
field('firstName'),
field('lastName'),
field('newPassword', undefined, 'password'),
field('confirmPassword'),
];
const userResource = resource(
User,
userFields,
async (operation, params, id) => {
if (operation !== 'edit')
reject('ساخت و حذف مستقیم حساب کاربری مجاز نیست.');
const user = await users.findOneById(id!);
const input = panelValues(
userFields,
params,
user as unknown as Record<string, unknown>,
);
if (input.password === '') delete input.password;
if (input.confirmPassword === '') delete input.confirmPassword;
if (input.password !== undefined && input.confirmPassword === undefined)
reject('تکرار رمز عبور الزامی است.');
if (input.password === undefined && input.confirmPassword !== undefined)
reject('رمز عبور جدید را هم وارد کنید.');
if (
typeof input.password === 'string' &&
Buffer.byteLength(input.password, 'utf8') > 72
)
reject('رمز عبور نباید بیشتر از ۷۲ بایت باشد.');
const validated = await validatePanelDto(UpdateProfileDTO, input, i18n, {
password: 'newPassword',
});
if (Object.keys(input).length) await users.updateProfile(user, validated);
const updated = await users.findOneById(id!);
const safe = { ...updated };
delete safe.password;
return safe;
},
true,
);
return [
testResource,
catalog(
Question,
[
field('testId', 'number', 'test'),
field('type'),
field('content'),
field('weight', 'number'),
field('required', 'boolean'),
field('metadata', 'json'),
],
CreateQuestionDTO,
app.get(QuestionsService),
),
catalog(
Choice,
[
field('questionId', 'number', 'question'),
field('text'),
field('order', 'number'),
field('score', 'number'),
],
CreateChoiceDTO,
app.get(ChoicesService),
),
catalog(
QuestionRangeRule,
[
field('questionId', 'number', 'question'),
field('min', 'number'),
field('max', 'number'),
field('score', 'number'),
],
CreateQuestionRangeRuleDTO,
app.get(QuestionRangeRuleService),
),
catalog(
QuestionTransition,
[
field('test', 'number'),
field('fromQuestionId', 'number', 'fromQuestion'),
field('toQuestionId', 'number', 'toQuestion'),
field('type'),
field('condition', 'json', 'conditionValue'),
],
CreateQuestionTransitionDTO,
app.get(QuestionTransitionService),
),
catalog(
ResultRange,
[
field('testId', 'number', 'test'),
field('minScore', 'number'),
field('maxScore', 'number'),
field('title'),
field('description'),
],
CreateResultRangeDTO,
app.get(ResultRangeService),
),
userResource,
...[
Submission,
SubmissionAnswer,
SubmissionResult,
Conversation,
Message,
].map((model) => resource(model, [], undefined, true)),
];
}
@@ -0,0 +1,120 @@
import { INestApplication } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { DataSource } from 'typeorm';
import type { Express, Request, Response, NextFunction } from 'express';
import AdminJS from 'adminjs';
import AdminJSExpress from '@adminjs/express';
import { Database, Resource } from '@adminjs/typeorm';
import { buildAdminPanelResources } from './admin-panel.resources';
import { RedisService } from '@/common/modules/redis/providers/redis.service';
import { AdminPanelAuthenticator } from './providers/admin-panel-auth.provider';
import { AdminPanelSessionStore } from './admin-panel-session.store';
import fa from './locales/fa';
/**
* AdminJS panel bootstrap.
*
* The router must be registered on the express instance BEFORE NestJS body
* parsers (they would otherwise consume request bodies and trip AdminJS's
* OldBodyParserUsedError guard). @adminjs/nestjs reorders express layers for
* this, but its reorder relies on app._router which no longer exists in
* Express 5, so we mount a lazy placeholder early and swap in the real
* AdminJS router once the DI container is initialized.
*/
export class AdminPanelSetup {
private static handler: (
req: Request,
res: Response,
next: NextFunction,
) => void;
static mount(app: INestApplication): void {
if (process.env.ADMIN_PANEL_ENABLED === 'false') {
return;
}
const expressApp = app.getHttpAdapter().getInstance() as Express;
const rootPath = process.env.ADMIN_ROOT_PATH || '/admin';
// Placeholder stands in until setup() replaces it with the real router
expressApp.use(rootPath, (req, res, next) => {
if (AdminPanelSetup.handler) {
return AdminPanelSetup.handler(req, res, next);
}
next();
});
}
static setup(app: INestApplication): void {
const configService = app.get(ConfigService);
if (!configService.get<boolean>('admin.enabled')) {
return;
}
const cookiePassword = configService.get<string>('admin.cookiePassword');
if (!cookiePassword || cookiePassword.length < 32) {
throw new Error(
'ADMIN_COOKIE_PASSWORD must be set to a random string of at least 32 characters when the admin panel is enabled',
);
}
AdminJS.registerAdapter({ Database, Resource });
// Entities extend ActiveRecord's BaseEntity, which resolves its repository
// through this static DataSource reference (the adapter relies on it)
const dataSource = app.get(DataSource);
for (const entity of dataSource.entityMetadatas.map((m) => m.target)) {
const baseEntity = entity as { useDataSource?: (ds: DataSource) => void };
baseEntity.useDataSource?.(dataSource);
}
const adminJs = new AdminJS({
rootPath: configService.get<string>('admin.rootPath'),
locale: {
language: 'fa',
translations: fa,
},
branding: {
companyName: 'پنل ادمین هیلا',
withMadeWithLove: false,
logo: false,
},
resources: buildAdminPanelResources(app),
});
const authenticator = app.get(AdminPanelAuthenticator);
const redisService = app.get(RedisService);
AdminPanelSetup.handler = AdminJSExpress.buildAuthenticatedRouter(
adminJs,
{
authenticate: (phone: string, password: string) =>
authenticator.authenticate(phone, password),
cookieName: configService.get<string>('admin.cookieName'),
cookiePassword,
},
undefined,
{
// AdminJS overrides `secret` and `name` from the auth options; both
// are repeated here only to satisfy the newer express-session typings
secret: cookiePassword,
store: new AdminPanelSessionStore(redisService),
resave: false,
saveUninitialized: false,
rolling: true,
cookie: {
httpOnly: true,
sameSite: 'lax',
secure: configService.get<boolean>('admin.secureCookies'),
maxAge:
(configService.get<number>('admin.sessionTtlMinutes') ?? 120) *
60_000,
},
},
);
}
}
@@ -0,0 +1,136 @@
import { plainToInstance, ClassConstructor } from 'class-transformer';
import { validate, ValidationError as DtoError } from 'class-validator';
import { ValidationError } from 'adminjs';
import { I18nService } from 'nestjs-i18n';
export async function validatePanelDto<T extends object>(
type: ClassConstructor<T>,
values: Record<string, unknown>,
i18n?: I18nService,
aliases: Record<string, string> = {},
): Promise<T> {
const dto = plainToInstance(type, values);
const errors = await validate(dto, {
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
});
if (errors.length) {
const fields: Record<string, { message: string }> = {};
const collect = (items: DtoError[], prefix = '') => {
for (const error of items) {
const key = prefix + (aliases[error.property] ?? error.property);
if (error.constraints)
fields[key] = {
message: Object.values(error.constraints)
.map((message) => {
const separator = message.indexOf('|');
if (separator < 0) return message;
const translationKey = message.slice(0, separator);
// i18nValidationMessage embeds the submitted value in JSON.
// Never return that raw payload (especially for passwords).
const args = JSON.parse(message.slice(separator + 1)) as Record<
string,
unknown
>;
delete args.value;
return i18n
? String(i18n.translate(translationKey, { lang: 'fa', args }))
: 'مقدار این فیلد معتبر نیست.';
})
.join('؛ '),
};
collect(error.children ?? [], `${key}.`);
}
};
collect(errors);
throw new ValidationError(fields, {
message: 'اطلاعات فرم معتبر نیست؛ فیلدهای مشخص‌شده را بررسی کنید.',
});
}
return dto;
}
export type PanelField = {
name: string;
dto?: string;
kind?: 'number' | 'boolean' | 'json';
};
export function redactPanelSecrets(value: unknown): void {
if (!value || typeof value !== 'object') return;
for (const [key, nested] of Object.entries(value)) {
// Validation errors contain safe, rendered messages, not submitted values.
if (key === 'errors') continue;
if (
['password', 'newPassword', 'confirmPassword'].includes(key.split('.')[0])
)
delete (value as Record<string, unknown>)[key];
else redactPanelSecrets(nested);
}
}
/** Convert only declared editable fields; reject mass assignment server-side. */
export function panelValues(
fields: PanelField[],
params: Record<string, unknown>,
existing: Record<string, unknown> = {},
) {
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(params)) {
const field = fields.find((item) => item.name === key);
if (!field) {
const previous = existing[key];
const comparable = (input: unknown) =>
input instanceof Date ? input.toISOString() : String(input);
if (
Object.hasOwn(existing, key) &&
comparable(previous) === comparable(value)
)
continue;
throw new ValidationError({
[key]: { message: 'تغییر این فیلد مجاز نیست.' },
});
}
if (value === undefined) continue;
let converted: unknown = value;
if (field.kind === 'number' && value !== null && value !== '') {
const numeric =
value &&
typeof value === 'object' &&
Object.keys(value).length === 1 &&
'id' in value
? value.id
: value;
converted =
typeof numeric === 'number'
? numeric
: typeof numeric === 'string'
? Number(numeric)
: NaN;
if (!Number.isFinite(converted) || !Number.isSafeInteger(converted))
throw new ValidationError({
[key]: { message: 'عدد صحیح معتبر وارد کنید.' },
});
}
if (field.kind === 'number' && value === '') converted = null;
if (field.kind === 'boolean') {
if (![true, false, 'true', 'false'].includes(value as boolean))
throw new ValidationError({
[key]: { message: 'مقدار بولی معتبر وارد کنید.' },
});
converted = value === true || value === 'true';
}
if (field.kind === 'json' && typeof value === 'string') {
try {
converted = value === '' ? null : (JSON.parse(value) as unknown);
} catch {
throw new ValidationError({
[key]: { message: 'JSON معتبر وارد کنید.' },
});
}
}
result[field.dto ?? key] = converted;
}
return result;
}
@@ -0,0 +1,4 @@
export const MAX_FAILED_ATTEMPTS = 5;
export const ATTEMPT_WINDOW_SECONDS = 15 * 60;
export const DUMMY_BCRYPT_HASH =
'$2b$10$ZFUmcSvMhrye2p.Dt1J7rOcfEdi.NcDLk3Bf55taT3ed57cAcpiNS';
+146
View File
@@ -0,0 +1,146 @@
const fa = {
actions: {
new: 'ایجاد',
edit: 'ویرایش',
show: 'مشاهده',
delete: 'حذف',
bulkDelete: 'حذف گروهی',
list: 'فهرست',
search: 'جستجو',
filter: 'فیلتر',
},
buttons: {
save: 'ذخیره',
addNewItem: 'افزودن مورد جدید',
filter: 'فیلتر',
applyChanges: 'اعمال تغییرات',
resetFilter: 'پاک کردن فیلترها',
confirmRemovalMany: 'حذف موارد انتخاب‌شده',
logout: 'خروج',
login: 'ورود',
},
labels: {
navigation: 'منوی اصلی',
pages: 'صفحات',
selectedRecords: 'موارد انتخاب‌شده',
filters: 'فیلترها',
dashboard: 'داشبورد',
loginWelcome: 'به پنل مدیریت خوش آمدید',
},
messages: {
successfullyCreated: 'مورد جدید با موفقیت ایجاد شد.',
successfullyUpdated: 'تغییرات با موفقیت ذخیره شد.',
successfullyDeleted: 'مورد با موفقیت حذف شد.',
successfullyBulkDeleted: 'موارد انتخاب‌شده با موفقیت حذف شدند.',
thereWereValidationErrors: 'لطفاً خطاهای فرم را برطرف کنید.',
noRecords: 'هیچ موردی یافت نشد.',
noRecordsInResource: 'هیچ موردی برای نمایش وجود ندارد.',
confirmDelete: 'آیا از حذف این مورد مطمئن هستید؟',
loginWelcome: 'برای ورود به پنل مدیریت، اطلاعات خود را وارد کنید.',
loginFailed: 'شماره موبایل یا رمز عبور اشتباه است.',
},
properties: {
email: 'شماره موبایل',
password: 'رمز عبور',
},
resources: {
User: {
labels: {
User: 'کاربران',
},
properties: {
id: 'شناسه',
firstName: 'نام',
lastName: 'نام خانوادگی',
phone: 'شماره تلفن',
role: 'نقش',
createdAt: 'تاریخ ایجاد',
updatedAt: 'تاریخ به‌روزرسانی',
password: 'رمز عبور',
},
},
OTP: {
labels: {
OTP: 'کد‌های تایید',
},
properties: {
id: 'شناسه',
phone: 'شماره تلفن',
code: 'کد',
expiresAt: 'تاریخ انقضا',
used: 'استفاده شده',
},
},
Choice: {
labels: {
Choice: 'گزینه ها',
},
properties: {
id: 'شناسه',
text: 'متن',
order: 'ترتیب',
score: 'امتیاز',
questionId: 'شناسه پرسش',
},
},
QuestionRangeRule: {
labels: {
QuestionRangeRule: 'قوانین بازه‌ای پرسش‌ها',
},
},
QuestionTransition: {
labels: {
QuestionTransition: 'مسیر‌ پرسش‌ها',
},
},
Question: {
labels: {
Question: 'پرسش‌ها',
},
},
ResultRange: {
labels: {
ResultRange: 'بازه نتایج آزمایش',
},
},
Test: {
labels: {
Test: 'آزمایش‌ها',
},
},
SubmissionAnswer: {
labels: {
SubmissionAnswer: 'پاسخ‌های ارسالی',
},
},
SubmissionResult: {
labels: {
SubmissionResult: 'نتایج آزمایش‌های ارسالی',
},
},
Submission: {
labels: {
Submission: 'آزمایش‌های ارسالی',
},
},
Message: {
labels: {
Message: 'پیام‌ها',
},
},
Conversation: {
labels: {
Conversation: 'مکالمه‌ها',
},
},
},
components: {},
pages: {},
};
export default fa;
@@ -0,0 +1,81 @@
import { Injectable } from '@nestjs/common';
import type { CurrentAdmin } from 'adminjs';
import { Role } from '@/common/enums/roles.enum';
import { UsersService } from '@/modules/users/providers/users.service';
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
import { RedisService } from '@/common/modules/redis/providers/redis.service';
import {
ATTEMPT_WINDOW_SECONDS,
DUMMY_BCRYPT_HASH,
MAX_FAILED_ATTEMPTS,
} from '../constants';
@Injectable()
export class AdminPanelAuthenticator {
constructor(
/**
* Inject Users Service
*/
private readonly usersService: UsersService,
/**
* Inject Hashing Provider
*/
private readonly hashingProvider: HashingProvider,
/**
* Inject Redis Service
*/
private readonly redisService: RedisService,
) {}
public async authenticate(
phone: string,
password: string,
): Promise<CurrentAdmin | null> {
const normalizedPhone = phone?.trim();
if (!normalizedPhone || !password) {
return null;
}
const attemptsKey = `admin:panel:login:${normalizedPhone}`;
const failedAttempts =
(await this.redisService.get<number>(attemptsKey)) ?? 0;
if (failedAttempts >= MAX_FAILED_ATTEMPTS) {
return null;
}
const user = await this.usersService.findOneByPhone(normalizedPhone);
const isSuperuser =
!!user && (user.role === Role.SUPERUSER || user.role === Role.ADMIN);
const passwordMatches = await this.hashingProvider.compare(
password,
isSuperuser && user.password ? user.password : DUMMY_BCRYPT_HASH,
);
if (!isSuperuser || !user.password || !passwordMatches) {
await this.redisService.set(
attemptsKey,
failedAttempts + 1,
ATTEMPT_WINDOW_SECONDS,
);
return null;
}
await this.redisService.del(attemptsKey);
return {
id: user.id.toString(),
firstName: user.firstName,
lastName: user.lastName,
phone: user.phone,
role: user.role,
// AdminJS requires an email on CurrentAdmin for the UI
email: user.phone,
};
}
}
@@ -5,7 +5,7 @@ import { Public } from '@/modules/auth/decorators/public.decorator';
import { Throttle } from '@nestjs/throttler';
@Controller('admin/auth')
@Throttle({ login: {} })
@Throttle({ default: { limit: 30, ttl: 60_000 } })
export class AdminAuthController {
constructor(
/**
@@ -21,7 +21,7 @@ import { Throttle } from '@nestjs/throttler';
@Controller('admin/choices')
@Roles(Role.SUPERUSER, Role.ADMIN)
@Throttle({ admin: {} })
@Throttle({ default: { limit: 120, ttl: 60_000 } })
export class AdminChoicesController {
constructor(
/**
@@ -3,9 +3,8 @@ Authorization: Bearer {{$global.accessToken}}
Content-Type: application/json
{
"question": 6,
"text": "Option 2",
"value": 1,
"order": 2,
"score": 8
"question": 13,
"text": "Option 4",
"order": 4,
"score": 10
}
@@ -19,7 +19,7 @@ import { Throttle } from '@nestjs/throttler';
@Controller('admin/question-transitions')
@Roles(Role.SUPERUSER, Role.ADMIN)
@Throttle({ admin: {} })
@Throttle({ default: { limit: 120, ttl: 60_000 } })
export class AdminQuestionTransitionsController {
constructor(
/**
@@ -0,0 +1,3 @@
DELETE {{baseUrl}}/admin/question-transitions/26
Authorization: Bearer {{$global.accessToken}}
Content-Type: application/json
@@ -0,0 +1,7 @@
PATCH {{baseUrl}}/admin/question-transitions/26
Authorization: Bearer {{$global.accessToken}}
Content-Type: application/json
{
"toQuestion": 13
}
@@ -3,10 +3,11 @@ Authorization: Bearer {{$global.accessToken}}
Content-Type: application/json
{
"test": 1,
"test": 2,
"type": "end",
"fromQuestion": 7
// "toQuestion": 7
// "conditionValue": {"min": 51, "max": 100}
// "conditionValue": {"choiceId": 5}
"fromQuestion": 13
// "toQuestion": 13
// "conditionValue": {"min": 11, "max": 20}
// "conditionValue": {"choiceId": 16 }
// "conditionValue": {"choiceIds": [13, 14, 15], "operator": "all"}
}
@@ -25,7 +25,7 @@ import { Throttle } from '@nestjs/throttler';
@Controller('admin/questions')
@Roles(Role.SUPERUSER, Role.ADMIN)
@Throttle({ admin: {} })
@Throttle({ default: { limit: 120, ttl: 60_000 } })
export class AdminQuestionsController {
constructor(
/**
@@ -3,11 +3,11 @@ Authorization: Bearer {{$global.accessToken}}
Content-Type: application/json
{
"test": 1,
"content": "سوال هفتم",
"test": 2,
"content": "Q6",
"required": true,
"type": "numeric"
// "metadata": { "min": -10, "max": 10 }
"type": "multi-choice"
// "metadata": { "min": 0, "max": 100 }
}
POST {{baseUrl}}/admin/questions/range-rules
@@ -15,8 +15,8 @@ Authorization: Bearer {{$global.accessToken}}
Content-Type: application/json
{
"question": 5,
"min": 1,
"max": 10,
"score": 8
"question": 11,
"min": 51,
"max": 100,
"score": 5
}
@@ -19,7 +19,7 @@ import { Throttle } from '@nestjs/throttler';
@Controller('admin/scoring')
@Roles(Role.SUPERUSER, Role.ADMIN)
@Throttle({ admin: {} })
@Throttle({ default: { limit: 120, ttl: 60_000 } })
export class AdminScoringController {
constructor(
/**
@@ -21,7 +21,7 @@ import { Throttle } from '@nestjs/throttler';
@Controller('admin/tests')
@Roles(Role.SUPERUSER, Role.ADMIN)
@Throttle({ admin: {} })
@Throttle({ default: { limit: 120, ttl: 60_000 } })
export class AdminTestsController {
constructor(
/**
@@ -1,5 +1,5 @@
GET {{baseUrl}}/admin/tests?title=test&isActive=true&accessType=paid&sortBy=title&order=DSC&page=2&limit=1
Authorization: Bearer {{$global.accessToken}}
GET {{baseUrl}}/admin/tests/4
GET {{baseUrl}}/admin/tests/1
Authorization: Bearer {{$global.accessToken}}
@@ -1,8 +1,9 @@
PATCH {{baseUrl}}/admin/tests/4
PATCH {{baseUrl}}/admin/tests/2
Authorization: Bearer {{$global.accessToken}}
Content-Type: application/json
{
"accessType": "login",
"isActive": false
"accessType": "free"
// "isActive": false
// "status": "published"
}
@@ -3,8 +3,8 @@ Content-Type: application/json
Authorization: Bearer {{$global.accessToken}}
{
"title": "Test One",
"description": "Description One",
"title": "Test Two",
"description": "Description Two",
"accessType": "login",
"isActive": true
}
+163 -4
View File
@@ -1,10 +1,27 @@
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
import {
Body,
Controller,
Header,
HttpCode,
HttpStatus,
Post,
} from '@nestjs/common';
import { LoginDTO } from './dtos/login.dto';
import { AuthService } from './providers/auth.service';
import { VerifyOtpDTO } from './dtos/verify-otp.dto';
import { Public } from './decorators/public.decorator';
import { RefreshTokenDTO } from './dtos/refresh-token.dto';
import { Throttle } from '@nestjs/throttler';
import { ApiAppResponse } from '@/common/decorators/api-app-response.decorator';
import { NewUserLoginResponseDTO } from './dtos/responses/new-user-login.dto';
import { RequirePasswordDTO } from './dtos/responses/require-password.dto';
import { TokensResponseDTO } from './dtos/responses/tokens.dto';
import { LogoutDTO } from './dtos/logout.dto';
import { ActiveUser } from '@/common/decorators/active-user.decorator';
import { AccessToken } from './decorators/access-token.decorator';
import { User } from '@/modules/users/entities/user.entity';
import { ResetPasswordDTO } from './dtos/reset-password.dto';
import { ResetPasswordOtpResponseDTO } from './dtos/responses/reset-password-otp.dto';
@Controller('auth')
export class AuthController {
@@ -18,7 +35,59 @@ export class AuthController {
@Public()
@Post('login')
@HttpCode(HttpStatus.OK)
@Throttle({ login: {} })
@Throttle({ default: { limit: 30, ttl: 60_000 } })
@ApiAppResponse([
{
status: HttpStatus.OK,
variants: [
{
model: TokensResponseDTO,
example: {
data: {
access: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
refresh: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
},
},
},
{
model: NewUserLoginResponseDTO,
example: {
data: {
newUser: true,
otpExpiresAt: '2026-09-01T09:24:34.894Z',
},
message: 'کد تایید به شماره 09121111111 فرستاده شد.',
},
},
{
model: RequirePasswordDTO,
example: {
data: {
newUser: false,
},
message: 'لطفا رمز عبور را ارسال کنید.',
},
},
],
},
{
status: HttpStatus.UNAUTHORIZED,
variants: [
{
messageExample: 'شماره موبایل یا رمز عبور اشتباه است.',
},
],
},
{
status: HttpStatus.TOO_MANY_REQUESTS,
variants: [
{
messageExample:
'تعداد درخواست ها بیشتر از حد مجاز است! لطفا بعد از 1 دقیقه دوباره امتحان کنید.',
},
],
},
])
public async logIn(@Body() loginDto: LoginDTO) {
return await this.authService.logIn(loginDto);
}
@@ -26,16 +95,106 @@ export class AuthController {
@Public()
@Post('verify-otp')
@HttpCode(HttpStatus.OK)
@Throttle({ otp: {} })
@Throttle({ default: { limit: 30, ttl: 60_000 } })
@ApiAppResponse([
{
status: HttpStatus.OK,
variants: [
{
model: TokensResponseDTO,
},
],
},
{
status: HttpStatus.UNAUTHORIZED,
variants: [
{
messageExample: 'کد تایید اشتباه است یا منقضی شده.',
},
],
},
])
public async verifyOTP(@Body() verifyOtpDto: VerifyOtpDTO) {
return await this.authService.verifyOTP(verifyOtpDto);
}
@Public()
@Post('reset-password')
@HttpCode(HttpStatus.OK)
@Header('Cache-Control', 'no-store')
@Throttle({ default: { limit: 30, ttl: 60_000 } })
@ApiAppResponse([
{
status: HttpStatus.OK,
variants: [
{ model: ResetPasswordOtpResponseDTO },
{ model: TokensResponseDTO },
],
},
{
status: HttpStatus.UNAUTHORIZED,
variants: [{ messageExample: 'کد تایید اشتباه است یا منقضی شده.' }],
},
{
status: HttpStatus.NOT_FOUND,
variants: [{ messageExample: 'حساب کاربری یافت نشد.' }],
},
{
status: HttpStatus.TOO_MANY_REQUESTS,
variants: [{ messageExample: 'لطفا بعد از ۱ دقیقه دوباره امتحان کنید.' }],
},
])
public async resetPassword(@Body() dto: ResetPasswordDTO) {
return this.authService.resetPassword(dto);
}
@Public()
@Post('refresh')
@HttpCode(HttpStatus.OK)
@Throttle({ login: {} })
@Throttle({ default: { limit: 60, ttl: 60_000 } })
@ApiAppResponse([
{
status: HttpStatus.OK,
variants: [
{
model: TokensResponseDTO,
},
],
},
{
status: HttpStatus.UNAUTHORIZED,
variants: [{ messageExample: 'توکن قبلا استفاده شده.' }],
},
])
public async refreshToken(@Body() refreshTokenDto: RefreshTokenDTO) {
return await this.authService.refreshToken(refreshTokenDto);
}
@Post('logout')
@HttpCode(HttpStatus.OK)
@ApiAppResponse([
{
status: HttpStatus.OK,
variants: [
{
messageExample: 'با موفقیت خارج شدید.',
},
],
},
{
status: HttpStatus.UNAUTHORIZED,
variants: [
{
messageExample: 'دسترسی غیر مجاز',
},
],
},
])
public async logout(
@ActiveUser() user: User,
@Body() logoutDto: LogoutDTO,
@AccessToken() accessToken: string,
) {
return await this.authService.logout(user.id, logoutDto, accessToken);
}
}
+4
View File
@@ -15,6 +15,8 @@ import { GlobalAuthGuard } from './guards/global-auth.guard';
import { RefreshTokensProvider } from './providers/refresh-tokens.provider';
import { RedisModule } from '@/common/modules/redis/redis.module';
import { AuthRedisProvider } from './providers/auth-redis.provider';
import { LogoutProvider } from './providers/logout.provider';
import { ResetPasswordProvider } from './providers/reset-password.provider';
@Module({
imports: [
@@ -43,6 +45,8 @@ import { AuthRedisProvider } from './providers/auth-redis.provider';
JwtStrategy,
RefreshTokensProvider,
AuthRedisProvider,
LogoutProvider,
ResetPasswordProvider,
{
provide: APP_GUARD,
useClass: GlobalAuthGuard,
@@ -0,0 +1,11 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { ExtractJwt } from 'passport-jwt';
import type { Request } from 'express';
export const AccessToken = createParamDecorator(
(_: unknown, ctx: ExecutionContext): string | undefined => {
const request: Request = ctx.switchToHttp().getRequest();
return ExtractJwt.fromAuthHeaderAsBearerToken()(request) ?? undefined;
},
);
+3 -1
View File
@@ -22,7 +22,9 @@ export class PhoneDTO {
field: '$t(auth.fields.phone)',
}),
})
@Transform(({ value }) => Utils.StringUtils.normalizePhone(value as string))
@Transform(({ value }: { value: unknown }) =>
typeof value === 'string' ? Utils.StringUtils.normalizePhone(value) : value,
)
phone!: string;
}
+13
View File
@@ -0,0 +1,13 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';
export class LogoutDTO {
@IsNotEmpty()
@IsString()
@ApiProperty({
type: 'string',
description: "User's Refresh Token",
required: true,
})
refreshToken!: string;
}
@@ -1,7 +1,13 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString } from 'class-validator';
export class RefreshTokenDTO {
@IsNotEmpty()
@IsString()
@ApiProperty({
type: 'string',
description: "User's Refresh Token",
required: true,
})
refreshToken!: string;
}
@@ -0,0 +1,14 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsString, Matches, ValidateIf } from 'class-validator';
import { i18nValidationMessage as t } from 'nestjs-i18n';
import { PhoneDTO } from './login.dto';
export class ResetPasswordDTO extends PhoneDTO {
@ApiPropertyOptional({ description: '5-digit OTP code', example: '12345' })
@ValidateIf((_object, value) => value !== undefined)
@IsString()
@Matches(/^[0-9]{5}$/, {
message: t('validation.wrongFieldFormat', { field: '$t(auth.fields.otp)' }),
})
otp?: string;
}

Some files were not shown because too many files have changed in this diff Show More