Merge pull request 'fix/module-builder-disease-select-and-export-path' (#37) from fix/module-builder-disease-select-and-export-path into main

Reviewed-on: https://git.zedobject.local/AcuPedia/acupedia-api/pulls/37
This commit is contained in:
Amit Salunke 2026-11-25 05:11:29 +00:00
commit 2fa448379f
4 changed files with 126 additions and 70 deletions

View File

@ -10,13 +10,15 @@ from collections.abc import AsyncIterator
from app.core.config import settings from app.core.config import settings
engine = create_async_engine(settings.database_url, pool_pre_ping=True, future=True) engine = create_async_engine(
# AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession) settings.database_url,
pool_size=settings.database_pool_size,
# async def get_db_session() -> AsyncGenerator[AsyncSession, None]: max_overflow=settings.database_max_overflow,
# async with AsyncSessionLocal() as session: pool_timeout=settings.database_pool_timeout_seconds,
# yield session pool_pre_ping=True,
pool_recycle=1800,
future=True,
)
SessionFactory = async_sessionmaker( SessionFactory = async_sessionmaker(
bind=engine, bind=engine,
@ -27,4 +29,10 @@ SessionFactory = async_sessionmaker(
async def get_db_session() -> AsyncIterator[AsyncSession]: async def get_db_session() -> AsyncIterator[AsyncSession]:
async with SessionFactory() as session: async with SessionFactory() as session:
yield session try:
yield session
except Exception:
await session.rollback()
raise
finally:
await session.close()

View File

@ -50,8 +50,7 @@ class ModuleBuilderService:
if legacy_mod: if legacy_mod:
legacy_meta = legacy_mod.metadata_json or {} legacy_meta = legacy_mod.metadata_json or {}
legacy_kind = legacy_meta.get("kind") or "legacy" legacy_kind = legacy_meta.get("kind") or "legacy"
legacy_managed = legacy_meta.get("managed_by") if legacy_kind != "therapeutic":
if legacy_kind != "therapeutic" or legacy_managed != "module_builder":
raise HTTPException( raise HTTPException(
status_code=403, status_code=403,
detail=( detail=(
@ -345,8 +344,7 @@ class ModuleBuilderService:
if legacy_mod: if legacy_mod:
legacy_meta = legacy_mod.metadata_json or {} legacy_meta = legacy_mod.metadata_json or {}
legacy_kind = legacy_meta.get("kind") or "legacy" legacy_kind = legacy_meta.get("kind") or "legacy"
legacy_managed = legacy_meta.get("managed_by") if legacy_kind != "therapeutic":
if legacy_kind != "therapeutic" or legacy_managed != "module_builder":
raise HTTPException( raise HTTPException(
status_code=403, status_code=403,
detail=( detail=(
@ -469,7 +467,6 @@ class ModuleBuilderService:
) )
res = await self.session.execute(stmt) res = await self.session.execute(stmt)
cat = res.scalar_one() cat = res.scalar_one()
await self.session.commit()
# Count diseases # Count diseases
count_stmt = select(func.count(BuilderDisease.id)).where( count_stmt = select(func.count(BuilderDisease.id)).where(
@ -478,6 +475,7 @@ class ModuleBuilderService:
) )
count_res = await self.session.execute(count_stmt) count_res = await self.session.execute(count_stmt)
count = count_res.scalar_one() or 0 count = count_res.scalar_one() or 0
await self.session.commit()
return BuilderCategorySummary( return BuilderCategorySummary(
id=cat.id, id=cat.id,
@ -491,28 +489,7 @@ class ModuleBuilderService:
async def delete_category(self, module_code: str, category_code: str) -> bool: async def delete_category(self, module_code: str, category_code: str) -> bool:
clean_code = module_code.strip().lower() clean_code = module_code.strip().lower()
await self._verify_module_editable(clean_code)
# 1. Block if legacy module
legacy_stmt = select(Module).where(Module.code == clean_code)
legacy_res = await self.session.execute(legacy_stmt)
legacy_mod = legacy_res.scalar_one_or_none()
if legacy_mod:
legacy_meta = legacy_mod.metadata_json or {}
legacy_kind = legacy_meta.get("kind") or "legacy"
legacy_managed = legacy_meta.get("managed_by")
if legacy_kind != "therapeutic" or legacy_managed != "module_builder":
raise HTTPException(
status_code=403,
detail=(
f"Module '{clean_code}' is a legacy '{legacy_kind}' module "
"and cannot be modified via Module Builder."
),
)
stmt = select(BuilderModule).where(BuilderModule.code == clean_code)
mod = (await self.session.execute(stmt)).scalar_one_or_none()
if not mod:
return False
del_stmt = delete(BuilderCategory).where( del_stmt = delete(BuilderCategory).where(
BuilderCategory.module_code == clean_code, BuilderCategory.module_code == clean_code,
@ -671,7 +648,6 @@ class ModuleBuilderService:
) )
res = await self.session.execute(stmt) res = await self.session.execute(stmt)
dis = res.scalar_one() dis = res.scalar_one()
await self.session.commit()
count_stmt = select(func.count(BuilderPattern.id)).where( count_stmt = select(func.count(BuilderPattern.id)).where(
BuilderPattern.module_code == module_code, BuilderPattern.module_code == module_code,
@ -701,9 +677,10 @@ class ModuleBuilderService:
updated_at=now, updated_at=now,
) )
await self.session.execute(init_pat) await self.session.execute(init_pat)
await self.session.commit()
count = 1 count = 1
await self.session.commit()
return BuilderDiseaseSummary( return BuilderDiseaseSummary(
id=dis.id, id=dis.id,
module_code=dis.module_code, module_code=dis.module_code,
@ -719,28 +696,7 @@ class ModuleBuilderService:
self, module_code: str, category_code: str, disease_code: str self, module_code: str, category_code: str, disease_code: str
) -> bool: ) -> bool:
clean_code = module_code.strip().lower() clean_code = module_code.strip().lower()
await self._verify_module_editable(clean_code)
# 1. Block if legacy module
legacy_stmt = select(Module).where(Module.code == clean_code)
legacy_res = await self.session.execute(legacy_stmt)
legacy_mod = legacy_res.scalar_one_or_none()
if legacy_mod:
legacy_meta = legacy_mod.metadata_json or {}
legacy_kind = legacy_meta.get("kind") or "legacy"
legacy_managed = legacy_meta.get("managed_by")
if legacy_kind != "therapeutic" or legacy_managed != "module_builder":
raise HTTPException(
status_code=403,
detail=(
f"Module '{clean_code}' is a legacy '{legacy_kind}' module "
"and cannot be modified via Module Builder."
),
)
stmt = select(BuilderModule).where(BuilderModule.code == clean_code)
mod = (await self.session.execute(stmt)).scalar_one_or_none()
if not mod:
return False
stmt = delete(BuilderDisease).where( stmt = delete(BuilderDisease).where(
BuilderDisease.module_code == clean_code, BuilderDisease.module_code == clean_code,

View File

@ -4,6 +4,7 @@ import copy
import io import io
import json import json
import logging import logging
import os
import re import re
import zipfile import zipfile
from datetime import datetime, timezone from datetime import datetime, timezone
@ -18,9 +19,54 @@ from app.db.models import BuilderCategory, BuilderDisease, BuilderModule, Builde
logger = logging.getLogger("acupedia.builder.compiler") logger = logging.getLogger("acupedia.builder.compiler")
DEFAULT_CONTENT_REPO_PATH = Path(
"/home/cspl/urvish/CSPL/Panacea/acupedia_content/acupedia-content" def get_default_content_repo_path() -> Path:
) """Dynamically resolves the content repository path without machine-specific hardcoded paths."""
# 1. Environment variables
for env_var in ("ACUPEDIA_CONTENT_PATH", "CONTENT_PATH", "MODULES_ROOT"):
val = os.getenv(env_var)
if val:
p = Path(val).resolve()
if p.exists() and p.is_dir():
return p
# 2. Docker container standard mount (/app/content)
container_mount = Path("/app/content")
if container_mount.exists() and container_mount.is_dir():
return container_mount
# 3. Dynamic search relative to this source file repository
current_file = Path(__file__).resolve()
for parent in current_file.parents:
candidates = [
parent / "acupedia_content" / "acupedia-content",
parent / "acupedia-content",
parent / "acupedia_content",
parent / "content",
]
for candidate in candidates:
if candidate.exists() and (candidate / "config.json").exists():
return candidate
if candidate.exists() and candidate.is_dir() and (candidate / "modules").exists():
return candidate
# 4. Search relative to current working directory
cwd = Path.cwd().resolve()
for candidate in [
cwd / "acupedia_content" / "acupedia-content",
cwd.parent / "acupedia_content" / "acupedia-content",
cwd / "acupedia-content",
cwd.parent / "acupedia-content",
cwd / "content",
]:
if candidate.exists() and candidate.is_dir():
return candidate
# Fallback relative to project structure
try:
return current_file.parents[5] / "acupedia_content" / "acupedia-content"
except IndexError:
return cwd / "content"
class ModuleContentCompiler: class ModuleContentCompiler:
@ -474,11 +520,15 @@ class ModuleContentCompiler:
repo_root: Path | None = None, repo_root: Path | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
module, files = await self.compile_module(module_code) module, files = await self.compile_module(module_code)
target_root = repo_root or DEFAULT_CONTENT_REPO_PATH target_root = repo_root or get_default_content_repo_path()
if not target_root.exists(): if not target_root.exists():
raise HTTPException( raise HTTPException(
status_code=500, status_code=400,
detail=f"Content repository directory not found at: {target_root}", detail=(
f"Content repository directory not found on server (checked: {target_root}). "
"Please configure the CONTENT_PATH environment variable, or use 'Download Acupedia (.zip)' "
"from the Export menu to download the production bundle directly to your computer."
),
) )
module_folder_name = f"{module.code}-{module.slug}" module_folder_name = f"{module.code}-{module.slug}"

View File

@ -39,11 +39,18 @@ With the clean Acupedia naming conventions:
- **Database**: `acupedia_db` - **Database**: `acupedia_db`
- **User**: `db_admin` / Password: `C1234spl` - **User**: `db_admin` / Password: `C1234spl`
- **Volumes**: `acupedia-postgres-data`, `acupedia-minio-data` - **Volumes**: `acupedia-postgres-data`, `acupedia-minio-data`
- **MinIO Bucket**: `accupedia-media` - **MinIO Bucket**: `acupedia-media`
### Step 2.1: Generate Container Git Info Metadata (Recommended)
Before building, run the script to capture the branch and commit of `api`, `store`, and `admin`:
### Start the containers:
```bash ```bash
cd ~/acupedia/acupedia_ops cd ~/acupedia/acupedia_ops
./scripts/generate-git-info.sh
```
### Step 2.2: Start the Containers
```bash
docker compose -f docker-compose.dev.yml up -d --build docker compose -f docker-compose.dev.yml up -d --build
``` ```
@ -63,7 +70,20 @@ docker compose -f docker-compose.dev.yml exec backend \
--- ---
### Step 3.2: Seed Authentication & Super Admin User ### Step 3.2: Run Alembic Migrations (Module Builder & Dynamic Content)
Stamps the baseline DDL (schema v5 includes migrations up to `0003`) and applies new migrations (such as Module Builder tables `content.builder_modules`, `content.builder_categories`, etc.):
```bash
docker compose -f docker-compose.dev.yml exec backend \
alembic stamp 0003_monthly_invoice_seq
docker compose -f docker-compose.dev.yml exec backend \
alembic upgrade head
```
---
### Step 3.3: Seed Authentication & Super Admin User
Seeds default roles (`super_admin`, `admin`, `finance_admin`, `practitioner`), permissions, and creates the super admin account: Seeds default roles (`super_admin`, `admin`, `finance_admin`, `practitioner`), permissions, and creates the super admin account:
```bash ```bash
@ -75,7 +95,7 @@ docker compose -f docker-compose.dev.yml exec -e ACCUPEDIA_BOOTSTRAP_ADMIN_PASSW
--- ---
### Step 3.3: Seed Content & Modules ### Step 3.4: Seed Content & Modules
Reads the mounted `/app/content` folder, parses templates, and seeds and publishes all 16 clinical modules (`m0001` through `m0042`): Reads the mounted `/app/content` folder, parses templates, and seeds and publishes all 16 clinical modules (`m0001` through `m0042`):
```bash ```bash
@ -89,7 +109,7 @@ docker compose -f docker-compose.dev.yml exec backend \
--- ---
### Step 3.4: Seed Clinical Media Assets (Images to MinIO) ### Step 3.4: Seed Clinical Media Assets (Images to MinIO)
Seeds all 787 anatomical images, channel pathways, and charts across the 4 visual modules into MinIO object storage (`accupedia-media` bucket) and links them to their respective content items in PostgreSQL: Seeds all 787 anatomical images, channel pathways, and charts across the 4 visual modules into MinIO object storage (`acupedia-media` bucket) and links them to their respective content items in PostgreSQL:
**Option A (Recommended — Automated 1-line loop for all 4 modules):** **Option A (Recommended — Automated 1-line loop for all 4 modules):**
```bash ```bash
@ -186,3 +206,25 @@ After running the manual steps above, test your endpoints:
| **Admin Portal** | `3001` | `http://<IP_OR_DOMAIN>:3001/admin/` | | **Admin Portal** | `3001` | `http://<IP_OR_DOMAIN>:3001/admin/` |
| **MinIO Console** | `9001` | `http://<IP_OR_DOMAIN>:9001` (`minioadmin` / `minioadmin`) | | **MinIO Console** | `9001` | `http://<IP_OR_DOMAIN>:9001` (`minioadmin` / `minioadmin`) |
| **MailHog UI** | `8025` | `http://<IP_OR_DOMAIN>:8025` | | **MailHog UI** | `8025` | `http://<IP_OR_DOMAIN>:8025` |
### Git Identity Verification (Inspect Container Branch & Commit)
To verify which branch and commit are running inside each container:
```bash
# 1. API Backend
docker compose -f docker-compose.dev.yml exec backend cat /app/.git_api_info
# 2. Storefront
docker compose -f docker-compose.dev.yml exec store cat /app/.git_store_info
# 3. Admin Portal
docker compose -f docker-compose.dev.yml exec admin cat /app/.git_admin_info
```
Example output:
```text
Branch: main
Commit: 29279bfd72a6fa296d1aa05a825bd88ca1f36c91
```