From 8cb459747f5a3daeff98afbd31d940aa5ca07d65 Mon Sep 17 00:00:00 2001 From: Urvish Date: Fri, 13 Nov 2026 15:21:28 +0530 Subject: [PATCH] feat(module-builder): add multi-module management, compiler, and therapeutics safety guards --- .../versions/0005_builder_modules_table.py | 175 +++ app/db/models/__init__.py | 5 + app/db/models/content.py | 44 + app/features/admin/api.py | 108 ++ app/features/admin/builder_schema.py | 58 +- .../admin/services/module_builder_service.py | 428 ++++++- .../admin/services/module_compiler.py | 1039 +++++++++++++++++ tests/test_module_builder.py | 646 ++++++++++ 8 files changed, 2497 insertions(+), 6 deletions(-) create mode 100644 alembic/versions/0005_builder_modules_table.py create mode 100644 app/features/admin/services/module_compiler.py diff --git a/alembic/versions/0005_builder_modules_table.py b/alembic/versions/0005_builder_modules_table.py new file mode 100644 index 0000000..52e7149 --- /dev/null +++ b/alembic/versions/0005_builder_modules_table.py @@ -0,0 +1,175 @@ +"""create builder_modules table and link builder_categories + +Revision ID: 0005_builder_modules_table +Revises: 0004_module_builder_tables +Create Date: 2026-11-13 +""" + +from __future__ import annotations + +from collections.abc import Sequence + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +revision: str = "0005_builder_modules_table" +down_revision: str | None = "0004_module_builder_tables" +branch_labels: Sequence[str] | None = None +depends_on: Sequence[str] | None = None + +CONTENT_SCHEMA = "content" + + +def upgrade() -> None: + bind = op.get_bind() + inspector = sa.inspect(bind) + tables = inspector.get_table_names(schema=CONTENT_SCHEMA) + + if "builder_modules" not in tables: + op.create_table( + "builder_modules", + sa.Column( + "id", + postgresql.UUID(as_uuid=True), + primary_key=True, + server_default=sa.text("gen_random_uuid()"), + ), + sa.Column("code", sa.String(length=32), nullable=False, unique=True), + sa.Column("name", sa.String(length=255), nullable=False), + sa.Column("slug", sa.String(length=255), nullable=False), + sa.Column("description", sa.Text(), nullable=True), + sa.Column("short_description", sa.String(length=500), nullable=True), + sa.Column( + "kind", + sa.String(length=64), + nullable=False, + server_default="therapeutic", + ), + sa.Column( + "managed_by", + sa.String(length=64), + nullable=False, + server_default="module_builder", + ), + sa.Column("default_template_code", sa.String(length=64), nullable=True), + sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"), + sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + nullable=False, + server_default=sa.text("now()"), + ), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + nullable=False, + server_default=sa.text("now()"), + ), + schema=CONTENT_SCHEMA, + ) + op.create_index( + "idx_builder_modules_code", + "builder_modules", + ["code"], + unique=True, + schema=CONTENT_SCHEMA, + ) + + # Seed therapeutics modules (m0041, m0042) + bind.execute( + sa.text( + f""" + INSERT INTO {CONTENT_SCHEMA}.builder_modules + (code, name, slug, description, short_description, kind, default_template_code, sort_order, managed_by, is_active) + VALUES + ( + 'm0041', + 'Auriculotherapy', + 'auriculotherapy', + 'Auriculotherapy protocols and treatment points for musculoskeletal and clinical disorders.', + 'Ear reflexology and clinical auriculotherapy protocols.', + 'therapeutic', + 'm0041_ct0001', + 40001, + 'module_builder', + TRUE + ), + ( + 'm0042', + 'Gynecological Disorders', + 'gynecological-disorders', + 'TCM therapeutics and pattern differentiation for women''s health and gynecological disorders.', + 'TCM gynecology and women''s health therapeutics.', + 'therapeutic', + 'm0042_ct0001', + 42000, + 'module_builder', + TRUE + ) + ON CONFLICT (code) DO NOTHING + """ + ) + ) + + # Ensure any orphan module_codes in builder_categories have a parent row + bind.execute( + sa.text( + f""" + INSERT INTO {CONTENT_SCHEMA}.builder_modules (code, name, slug, kind, sort_order, managed_by, is_active) + SELECT DISTINCT bc.module_code, + INITCAP(REPLACE(bc.module_code, '_', ' ')), + LOWER(REPLACE(bc.module_code, '_', '-')), + 'therapeutic', + 40000, + 'module_builder', + TRUE + FROM {CONTENT_SCHEMA}.builder_categories bc + WHERE NOT EXISTS ( + SELECT 1 FROM {CONTENT_SCHEMA}.builder_modules bm WHERE bm.code = bc.module_code + ) + ON CONFLICT (code) DO NOTHING + """ + ) + ) + + # Add foreign key constraint if not present + existing_fks = [ + fk["name"] + for fk in inspector.get_foreign_keys( + "builder_categories", schema=CONTENT_SCHEMA + ) + ] + if "fk_builder_categories_module" not in existing_fks: + op.create_foreign_key( + "fk_builder_categories_module", + "builder_categories", + "builder_modules", + ["module_code"], + ["code"], + source_schema=CONTENT_SCHEMA, + referent_schema=CONTENT_SCHEMA, + ondelete="CASCADE", + onupdate="CASCADE", + ) + + +def downgrade() -> None: + bind = op.get_bind() + inspector = sa.inspect(bind) + existing_fks = [ + fk["name"] + for fk in inspector.get_foreign_keys( + "builder_categories", schema=CONTENT_SCHEMA + ) + ] + if "fk_builder_categories_module" in existing_fks: + op.drop_constraint( + "fk_builder_categories_module", + "builder_categories", + schema=CONTENT_SCHEMA, + type_="foreignkey", + ) + op.drop_table("builder_modules", schema=CONTENT_SCHEMA) + diff --git a/app/db/models/__init__.py b/app/db/models/__init__.py index d3b039f..4126dbc 100644 --- a/app/db/models/__init__.py +++ b/app/db/models/__init__.py @@ -30,6 +30,7 @@ from .content import ( SearchFacetMapping, ContentSearchDocument, ContentSearchFacet, + BuilderModule, BuilderCategory, BuilderDisease, BuilderPattern, @@ -91,6 +92,10 @@ __all__ = [ "SearchFacetMapping", "ContentSearchDocument", "ContentSearchFacet", + "BuilderModule", + "BuilderCategory", + "BuilderDisease", + "BuilderPattern", "UserBillingProfile", "AccessPlan", "AccessPlanModule", diff --git a/app/db/models/content.py b/app/db/models/content.py index ffac419..f5998bc 100644 --- a/app/db/models/content.py +++ b/app/db/models/content.py @@ -893,10 +893,53 @@ class ContentSearchFacet(Base): # ============================================================================= +class BuilderModule(Base): + __tablename__ = "builder_modules" + __table_args__ = ( + UniqueConstraint("code", name="uq_builder_modules_code"), + Index("idx_builder_modules_code", "code", unique=True), + {"schema": CONTENT_SCHEMA}, + ) + + id: Mapped[UUID] = mapped_column( + PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()") + ) + code: Mapped[str] = mapped_column(String(32), unique=True, nullable=False) + name: Mapped[str] = mapped_column(String(255), nullable=False) + slug: Mapped[str] = mapped_column(String(255), nullable=False) + description: Mapped[str | None] = mapped_column(Text) + short_description: Mapped[str | None] = mapped_column(String(500)) + kind: Mapped[str] = mapped_column(String(64), nullable=False, server_default=text("'therapeutic'")) + managed_by: Mapped[str] = mapped_column(String(64), nullable=False, server_default=text("'module_builder'")) + default_template_code: Mapped[str | None] = mapped_column(String(64)) + sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0")) + is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true")) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), nullable=False, server_default=text("now()") + ) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), nullable=False, server_default=text("now()") + ) + + categories: Mapped[list["BuilderCategory"]] = relationship( + back_populates="module", + cascade="all, delete-orphan", + passive_deletes=True, + order_by="BuilderCategory.sort_order", + ) + + class BuilderCategory(Base): __tablename__ = "builder_categories" __table_args__ = ( UniqueConstraint("module_code", "category_code", name="uq_builder_categories_code"), + ForeignKeyConstraint( + ["module_code"], + [f"{CONTENT_SCHEMA}.builder_modules.code"], + ondelete="CASCADE", + onupdate="CASCADE", + name="fk_builder_categories_module", + ), Index("idx_builder_categories_module", "module_code"), {"schema": CONTENT_SCHEMA}, ) @@ -916,6 +959,7 @@ class BuilderCategory(Base): DateTime(timezone=True), nullable=False, server_default=text("now()") ) + module: Mapped["BuilderModule"] = relationship(back_populates="categories") diseases: Mapped[list["BuilderDisease"]] = relationship( back_populates="category", cascade="all, delete-orphan", diff --git a/app/features/admin/api.py b/app/features/admin/api.py index 5d42a31..69af3d4 100644 --- a/app/features/admin/api.py +++ b/app/features/admin/api.py @@ -1,4 +1,5 @@ from __future__ import annotations +import io from fastapi import APIRouter, Depends, HTTPException, Query, status from fastapi.responses import HTMLResponse, StreamingResponse from app.db.models import AppUser @@ -21,6 +22,9 @@ from .schema import ( UpdateCouponRequest, ) from .builder_schema import ( + BuilderModuleSummary, + CreateBuilderModuleRequest, + UpdateBuilderModuleRequest, BuilderCategorySummary, BuilderDiseaseDetailResponse, BuilderDiseaseSummary, @@ -539,6 +543,74 @@ async def export_report_csv( # MODULE BUILDER ENDPOINTS # ============================================================================= +@router.get("/module-builder/modules", response_model=list[BuilderModuleSummary]) +async def list_builder_modules( + admin: AppUser = Depends(get_current_admin), + service: AdminService = Depends(get_admin_service), +): + try: + return await service.builder.get_modules() + except Exception as exc: + raise HTTPException(500, detail=f"Failed to fetch module builder modules: {exc}") from exc + + +@router.post("/module-builder/modules", response_model=BuilderModuleSummary, status_code=status.HTTP_201_CREATED) +async def create_builder_module( + payload: CreateBuilderModuleRequest, + admin: AppUser = Depends(get_current_admin), + service: AdminService = Depends(get_admin_service), +): + try: + return await service.builder.create_module(payload) + except HTTPException: + raise + except Exception as exc: + raise HTTPException(500, detail=f"Failed to create builder module: {exc}") from exc + + +@router.get("/module-builder/modules/{module_code}", response_model=BuilderModuleSummary) +async def get_builder_module( + module_code: str, + admin: AppUser = Depends(get_current_admin), + service: AdminService = Depends(get_admin_service), +): + try: + return await service.builder.get_module(module_code) + except HTTPException: + raise + except Exception as exc: + raise HTTPException(500, detail=f"Failed to fetch builder module: {exc}") from exc + + +@router.patch("/module-builder/modules/{module_code}", response_model=BuilderModuleSummary) +async def update_builder_module( + module_code: str, + payload: UpdateBuilderModuleRequest, + admin: AppUser = Depends(get_current_admin), + service: AdminService = Depends(get_admin_service), +): + try: + return await service.builder.update_module(module_code, payload) + except HTTPException: + raise + except Exception as exc: + raise HTTPException(500, detail=f"Failed to update builder module: {exc}") from exc + + +@router.delete("/module-builder/modules/{module_code}") +async def delete_builder_module( + module_code: str, + admin: AppUser = Depends(get_current_admin), + service: AdminService = Depends(get_admin_service), +): + try: + return await service.builder.delete_module(module_code) + except HTTPException: + raise + except Exception as exc: + raise HTTPException(500, detail=f"Failed to delete builder module: {exc}") from exc + + @router.get("/module-builder/{module_code}/categories", response_model=list[BuilderCategorySummary]) async def get_builder_categories( module_code: str, @@ -683,6 +755,42 @@ async def export_module_json( raise HTTPException(500, detail=f"Failed to export module JSON: {exc}") from exc +@router.get("/module-builder/{module_code}/export-bundle") +async def export_builder_module_bundle( + module_code: str, + admin: AppUser = Depends(get_current_admin), + service: AdminService = Depends(get_admin_service), +): + try: + filename, zip_bytes = await service.builder.export_bundle_zip(module_code) + return StreamingResponse( + io.BytesIO(zip_bytes), + media_type="application/zip", + headers={ + "Content-Disposition": f'attachment; filename="{filename}"', + "Access-Control-Expose-Headers": "Content-Disposition", + }, + ) + except HTTPException: + raise + except Exception as exc: + raise HTTPException(500, detail=f"Failed to generate module package: {exc}") from exc + + +@router.post("/module-builder/{module_code}/sync-content-repo") +async def sync_builder_module_to_repo( + module_code: str, + admin: AppUser = Depends(get_current_admin), + service: AdminService = Depends(get_admin_service), +): + try: + return await service.builder.sync_content_repo(module_code) + except HTTPException: + raise + except Exception as exc: + raise HTTPException(500, detail=f"Failed to sync module to content repository: {exc}") from exc + + @router.post("/module-builder/{module_code}/import-json", response_model=ModuleBuilderImportResponse) async def import_module_json( module_code: str, diff --git a/app/features/admin/builder_schema.py b/app/features/admin/builder_schema.py index e9afd5b..3a91207 100644 --- a/app/features/admin/builder_schema.py +++ b/app/features/admin/builder_schema.py @@ -1,8 +1,64 @@ from __future__ import annotations +import re from typing import Any from uuid import UUID -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, field_validator + + +# ============================================================================= +# MODULE SCHEMAS +# ============================================================================= + + +class CreateBuilderModuleRequest(BaseModel): + name: str = Field(..., min_length=2, max_length=255) + code: str | None = Field(default=None, max_length=32) + slug: str | None = Field(default=None, max_length=255) + short_description: str | None = Field(default=None, max_length=500) + description: str | None = None + kind: str = Field(default="therapeutic", max_length=64) + managed_by: str = Field(default="module_builder", max_length=64) + sort_order: int | None = None + + @field_validator("code") + @classmethod + def validate_code(cls, v: str | None) -> str | None: + if v is None: + return None + cleaned = v.strip().lower() + if not re.match(r"^m[0-9]{4}$", cleaned): + raise ValueError( + "Module code must start with 'm' followed by exactly 4 digits (e.g. 'm0043')" + ) + return cleaned + + +class UpdateBuilderModuleRequest(BaseModel): + name: str | None = Field(default=None, min_length=2, max_length=255) + short_description: str | None = Field(default=None, max_length=500) + description: str | None = None + sort_order: int | None = None + is_active: bool | None = None + + +class BuilderModuleSummary(BaseModel): + id: UUID | None = None + code: str + name: str + slug: str + short_description: str | None = None + description: str | None = None + kind: str = "therapeutic" + managed_by: str = "module_builder" + default_template_code: str | None = None + sort_order: int = 0 + is_active: bool = True + category_count: int = 0 + disease_count: int = 0 + pattern_count: int = 0 + created_at: Any = None + updated_at: Any = None # ============================================================================= diff --git a/app/features/admin/services/module_builder_service.py b/app/features/admin/services/module_builder_service.py index c6bd70c..6c796f6 100644 --- a/app/features/admin/services/module_builder_service.py +++ b/app/features/admin/services/module_builder_service.py @@ -1,5 +1,6 @@ from __future__ import annotations +import re from datetime import datetime, timezone from typing import Any from fastapi import HTTPException @@ -7,8 +8,12 @@ from sqlalchemy import delete, func, select from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession -from app.db.models import BuilderCategory, BuilderDisease, BuilderPattern +from app.db.models import BuilderModule, BuilderCategory, BuilderDisease, BuilderPattern, Module +from .module_compiler import ModuleContentCompiler from app.features.admin.builder_schema import ( + BuilderModuleSummary, + CreateBuilderModuleRequest, + UpdateBuilderModuleRequest, BuilderCategorySummary, BuilderDiseaseDetailResponse, BuilderDiseaseSummary, @@ -28,6 +33,363 @@ from app.features.admin.builder_schema import ( class ModuleBuilderService: def __init__(self, session: AsyncSession) -> None: self.session = session + self.compiler = ModuleContentCompiler(session) + + async def _verify_module_editable(self, module_code: str) -> BuilderModule: + """Verifies that the target module exists, is of kind 'therapeutic', + + and is managed by 'module_builder'. Core legacy modules (points, patterns, nutrition) + are protected and strictly forbidden from being modified or overwritten. + """ + clean_code = module_code.strip().lower() + + # 1. Check if it's an existing legacy core module in content.modules + 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 or overwritten via Module Builder." + ), + ) + + # 2. Check builder_modules + stmt = select(BuilderModule).where(BuilderModule.code == clean_code) + res = await self.session.execute(stmt) + mod = res.scalar_one_or_none() + + if mod: + if mod.kind != "therapeutic": + raise HTTPException( + status_code=403, + detail=( + f"Module '{clean_code}' is of kind '{mod.kind}'. " + "The Module Builder is restricted to therapeutic modules only." + ), + ) + if mod.managed_by != "module_builder": + raise HTTPException( + status_code=403, + detail=( + f"Module '{clean_code}' has managed_by='{mod.managed_by}' and cannot " + "be modified via Module Builder." + ), + ) + return mod + + # 3. Not found + raise HTTPException( + status_code=404, + detail=f"Module '{clean_code}' not found. Please create it first.", + ) + + # ========================================================================= + # PRODUCTION COMPILER & EXPORT + # ========================================================================= + + async def export_bundle_zip(self, module_code: str) -> tuple[str, bytes]: + await self._verify_module_editable(module_code) + return await self.compiler.generate_zip_bundle(module_code) + + async def sync_content_repo( + self, module_code: str, repo_root: Any = None + ) -> dict[str, Any]: + await self._verify_module_editable(module_code) + return await self.compiler.sync_to_content_repo(module_code, repo_root=repo_root) + + # ========================================================================= + # MODULES + # ========================================================================= + + async def get_modules(self) -> list[BuilderModuleSummary]: + cat_counts = ( + select( + BuilderCategory.module_code, + func.count(BuilderCategory.id).label("count"), + ) + .group_by(BuilderCategory.module_code) + .subquery() + ) + dis_counts = ( + select( + BuilderDisease.module_code, + func.count(BuilderDisease.id).label("count"), + ) + .group_by(BuilderDisease.module_code) + .subquery() + ) + pat_counts = ( + select( + BuilderPattern.module_code, + func.count(BuilderPattern.id).label("count"), + ) + .group_by(BuilderPattern.module_code) + .subquery() + ) + + stmt = ( + select( + BuilderModule, + func.coalesce(cat_counts.c.count, 0).label("cat_count"), + func.coalesce(dis_counts.c.count, 0).label("dis_count"), + func.coalesce(pat_counts.c.count, 0).label("pat_count"), + ) + .outerjoin(cat_counts, BuilderModule.code == cat_counts.c.module_code) + .outerjoin(dis_counts, BuilderModule.code == dis_counts.c.module_code) + .outerjoin(pat_counts, BuilderModule.code == pat_counts.c.module_code) + .where( + BuilderModule.kind == "therapeutic", + BuilderModule.managed_by == "module_builder", + ) + .order_by(BuilderModule.sort_order, BuilderModule.code) + ) + + res = await self.session.execute(stmt) + rows = res.all() + + return [ + BuilderModuleSummary( + id=mod.id, + code=mod.code, + name=mod.name, + slug=mod.slug, + short_description=mod.short_description, + description=mod.description, + kind=mod.kind, + managed_by=mod.managed_by, + default_template_code=mod.default_template_code, + sort_order=mod.sort_order, + is_active=mod.is_active, + category_count=int(cat_c), + disease_count=int(dis_c), + pattern_count=int(pat_c), + created_at=mod.created_at, + updated_at=mod.updated_at, + ) + for mod, cat_c, dis_c, pat_c in rows + ] + + async def get_module(self, module_code: str) -> BuilderModuleSummary: + mod = await self._verify_module_editable(module_code) + + cat_count_stmt = select(func.count(BuilderCategory.id)).where(BuilderCategory.module_code == mod.code) + dis_count_stmt = select(func.count(BuilderDisease.id)).where(BuilderDisease.module_code == mod.code) + pat_count_stmt = select(func.count(BuilderPattern.id)).where(BuilderPattern.module_code == mod.code) + + cat_count = (await self.session.execute(cat_count_stmt)).scalar_one() or 0 + dis_count = (await self.session.execute(dis_count_stmt)).scalar_one() or 0 + pat_count = (await self.session.execute(pat_count_stmt)).scalar_one() or 0 + + return BuilderModuleSummary( + id=mod.id, + code=mod.code, + name=mod.name, + slug=mod.slug, + short_description=mod.short_description, + description=mod.description, + kind=mod.kind, + managed_by=mod.managed_by, + default_template_code=mod.default_template_code, + sort_order=mod.sort_order, + is_active=mod.is_active, + category_count=int(cat_count), + disease_count=int(dis_count), + pattern_count=int(pat_count), + created_at=mod.created_at, + updated_at=mod.updated_at, + ) + + async def create_module(self, payload: CreateBuilderModuleRequest) -> BuilderModuleSummary: + # Enforce kind == "therapeutic" + if payload.kind and payload.kind.strip() != "therapeutic": + raise HTTPException( + status_code=400, + detail=f"Module Builder only allows creating modules of kind 'therapeutic', got '{payload.kind}'." + ) + + code = payload.code + if not code: + # Auto-suggest next module code in therapeutic range (m0043+) + existing_codes_res = await self.session.execute(select(BuilderModule.code)) + legacy_codes_res = await self.session.execute(select(Module.code)) + all_codes = {r[0] for r in existing_codes_res.fetchall()} | {r[0] for r in legacy_codes_res.fetchall()} + numbers = [] + for c in all_codes: + match = re.match(r"^m([0-9]{4})$", c) + if match: + numbers.append(int(match.group(1))) + next_num = max([n for n in numbers if n >= 40], default=42) + 1 + code = f"m{next_num:04d}" + else: + code = code.strip().lower() + + # Check uniqueness against both builder_modules and content.modules + existing = await self.session.execute( + select(BuilderModule).where(BuilderModule.code == code) + ) + if existing.scalar_one_or_none(): + raise HTTPException( + status_code=409, + detail=f"Module with code '{code}' already exists in Module Builder. Please choose a different code." + ) + + existing_legacy = await self.session.execute( + select(Module).where(Module.code == code) + ) + if existing_legacy.scalar_one_or_none(): + raise HTTPException( + status_code=409, + detail=f"Module code '{code}' conflicts with an existing core Acupedia module. Please choose a different code." + ) + + # Derive slug if not supplied + slug = payload.slug + if not slug: + slug = re.sub(r"[^a-z0-9]+", "-", payload.name.lower()).strip("-") + + # Determine sort_order + sort_order = payload.sort_order + if sort_order is None: + max_order_res = await self.session.execute( + select(func.max(BuilderModule.sort_order)).where(BuilderModule.kind == "therapeutic") + ) + max_order = max_order_res.scalar_one() or 40002 + sort_order = max_order + 1 + + default_template_code = f"{code}_ct0001" + + new_module = BuilderModule( + code=code, + name=payload.name.strip(), + slug=slug, + description=payload.description.strip() if payload.description else None, + short_description=payload.short_description.strip() if payload.short_description else None, + kind="therapeutic", + managed_by="module_builder", + default_template_code=default_template_code, + sort_order=sort_order, + is_active=True, + created_at=datetime.now(timezone.utc), + updated_at=datetime.now(timezone.utc), + ) + + self.session.add(new_module) + await self.session.commit() + await self.session.refresh(new_module) + + return BuilderModuleSummary( + id=new_module.id, + code=new_module.code, + name=new_module.name, + slug=new_module.slug, + short_description=new_module.short_description, + description=new_module.description, + kind=new_module.kind, + managed_by=new_module.managed_by, + default_template_code=new_module.default_template_code, + sort_order=new_module.sort_order, + is_active=new_module.is_active, + category_count=0, + disease_count=0, + pattern_count=0, + created_at=new_module.created_at, + updated_at=new_module.updated_at, + ) + + async def update_module(self, module_code: str, payload: UpdateBuilderModuleRequest) -> BuilderModuleSummary: + mod = await self._verify_module_editable(module_code) + + if payload.name is not None: + mod.name = payload.name.strip() + if payload.short_description is not None: + mod.short_description = payload.short_description.strip() or None + if payload.description is not None: + mod.description = payload.description.strip() or None + if payload.sort_order is not None: + mod.sort_order = payload.sort_order + if payload.is_active is not None: + mod.is_active = payload.is_active + + mod.updated_at = datetime.now(timezone.utc) + await self.session.commit() + await self.session.refresh(mod) + + return await self.get_module(module_code) + + async def delete_module(self, module_code: str) -> dict[str, Any]: + mod = await self._verify_module_editable(module_code) + + await self.session.delete(mod) + await self.session.commit() + + return { + "status": "deleted", + "code": module_code, + "message": f"Module '{module_code}' and all associated content were deleted successfully.", + } + + async def _ensure_module(self, module_code: str) -> BuilderModule: + clean_code = module_code.strip().lower() + + # 1. Check if it's an existing legacy core module in content.modules + 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 or overwritten via Module Builder." + ), + ) + + # 2. Check if already exists in builder_modules + stmt = select(BuilderModule).where(BuilderModule.code == clean_code) + res = await self.session.execute(stmt) + mod = res.scalar_one_or_none() + if mod: + if mod.kind != "therapeutic" or mod.managed_by != "module_builder": + raise HTTPException( + status_code=403, + detail=( + f"Module '{clean_code}' has kind='{mod.kind}' / managed_by='{mod.managed_by}' " + "and cannot be modified via Module Builder." + ), + ) + return mod + + # 3. Auto-register as therapeutic module managed by module_builder + slug = re.sub(r"[^a-z0-9]+", "-", clean_code).strip("-") + name = clean_code.replace("_", " ").title() + mod = BuilderModule( + code=clean_code, + name=name, + slug=slug, + description=f"Clinical module {name}", + short_description=f"Clinical module {name}", + kind="therapeutic", + managed_by="module_builder", + default_template_code=f"{clean_code}_ct0001", + sort_order=40000, + is_active=True, + created_at=datetime.now(timezone.utc), + updated_at=datetime.now(timezone.utc), + ) + self.session.add(mod) + await self.session.flush() + return mod # ========================================================================= # CATEGORIES @@ -82,6 +444,7 @@ class ModuleBuilderService: if not payload.category_code or not payload.category_code.strip(): raise HTTPException(400, detail="Category system code cannot be empty.") + await self._ensure_module(module_code) now = datetime.now(timezone.utc) stmt = ( insert(BuilderCategory) @@ -127,11 +490,35 @@ class ModuleBuilderService: ) async def delete_category(self, module_code: str, category_code: str) -> bool: - stmt = delete(BuilderCategory).where( - BuilderCategory.module_code == module_code, + clean_code = module_code.strip().lower() + + # 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( + BuilderCategory.module_code == clean_code, BuilderCategory.category_code == category_code, ) - res = await self.session.execute(stmt) + res = await self.session.execute(del_stmt) await self.session.commit() return res.rowcount > 0 @@ -247,6 +634,8 @@ class ModuleBuilderService: if not payload.category_code or not payload.category_code.strip(): raise HTTPException(400, detail="Category code is required to attach a disease.") + await self._ensure_module(module_code) + # Ensure parent category exists cat_check = await self.session.execute( select(BuilderCategory.id).where( @@ -329,8 +718,32 @@ class ModuleBuilderService: async def delete_disease( self, module_code: str, category_code: str, disease_code: str ) -> bool: + clean_code = module_code.strip().lower() + + # 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( - BuilderDisease.module_code == module_code, + BuilderDisease.module_code == clean_code, BuilderDisease.category_code == category_code, BuilderDisease.disease_code == disease_code, ) @@ -345,6 +758,8 @@ class ModuleBuilderService: async def save_full_disease( self, module_code: str, payload: SaveFullDiseaseRequest ) -> BuilderDiseaseDetailResponse: + await self._ensure_module(module_code) + if not payload.name or not payload.name.strip(): raise HTTPException(400, detail="Disease name cannot be empty.") if not payload.disease_code or not payload.disease_code.strip(): @@ -451,6 +866,8 @@ class ModuleBuilderService: # ========================================================================= async def export_module_json(self, module_code: str) -> ModuleBuilderExportResponse: + await self._verify_module_editable(module_code) + # Fetch categories cat_stmt = ( select(BuilderCategory) @@ -554,6 +971,7 @@ class ModuleBuilderService: async def import_module_json( self, module_code: str, payload: ModuleBuilderImportRequest ) -> ModuleBuilderImportResponse: + await self._verify_module_editable(module_code) now = datetime.now(timezone.utc) cat_count = 0 dis_count = 0 diff --git a/app/features/admin/services/module_compiler.py b/app/features/admin/services/module_compiler.py new file mode 100644 index 0000000..8182adc --- /dev/null +++ b/app/features/admin/services/module_compiler.py @@ -0,0 +1,1039 @@ +from __future__ import annotations + +import copy +import io +import json +import logging +import re +import zipfile +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from fastapi import HTTPException +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.db.models import BuilderCategory, BuilderDisease, BuilderModule, BuilderPattern + +logger = logging.getLogger("acupedia.builder.compiler") + +DEFAULT_CONTENT_REPO_PATH = Path( + "/home/cspl/urvish/CSPL/Panacea/acupedia_content/acupedia-content" +) + + +class ModuleContentCompiler: + """Compiles authored relational module content into the production-grade + + Acupedia multi-file repository structure (module.json, templates/, data/, + search_facets.json). + """ + + def __init__(self, session: AsyncSession) -> None: + self.session = session + + async def compile_module(self, module_code: str) -> tuple[BuilderModule, dict[str, str]]: + # 1. Fetch Module + stmt = select(BuilderModule).where(BuilderModule.code == module_code) + res = await self.session.execute(stmt) + module = res.scalar_one_or_none() + if not module: + raise HTTPException( + status_code=404, + detail=f"Module '{module_code}' not found. Please create it first.", + ) + if module.kind != "therapeutic" or getattr(module, "managed_by", "module_builder") != "module_builder": + raise HTTPException( + status_code=403, + detail=( + f"Module '{module_code}' is not managed by Module Builder " + f"(kind='{module.kind}', managed_by='{getattr(module, 'managed_by', None)}'). Cannot compile." + ), + ) + + # 2. Fetch Categories + cat_stmt = ( + select(BuilderCategory) + .where(BuilderCategory.module_code == module_code) + .order_by(BuilderCategory.sort_order, BuilderCategory.name) + ) + cat_res = await self.session.execute(cat_stmt) + categories = list(cat_res.scalars().all()) + if not categories: + raise HTTPException( + status_code=400, + detail=( + f"Cannot compile module '{module_code}': Please add at least one " + "disease category before exporting or syncing." + ), + ) + + # 3. Fetch Diseases & Patterns per Category + dis_stmt = ( + select(BuilderDisease) + .where(BuilderDisease.module_code == module_code) + .order_by(BuilderDisease.sort_order, BuilderDisease.name) + ) + dis_res = await self.session.execute(dis_stmt) + all_diseases = list(dis_res.scalars().all()) + + pat_stmt = ( + select(BuilderPattern) + .where(BuilderPattern.module_code == module_code) + .order_by(BuilderPattern.sort_order, BuilderPattern.name) + ) + pat_res = await self.session.execute(pat_stmt) + all_patterns = list(pat_res.scalars().all()) + + # Group diseases by category + diseases_by_cat: dict[str, list[BuilderDisease]] = {c.category_code: [] for c in categories} + for d in all_diseases: + if d.category_code in diseases_by_cat: + diseases_by_cat[d.category_code].append(d) + + # Group patterns by (category, disease) + patterns_by_dis: dict[tuple[str, str], list[BuilderPattern]] = {} + for p in all_patterns: + key = (p.category_code, p.disease_code) + if key not in patterns_by_dis: + patterns_by_dis[key] = [] + patterns_by_dis[key].append(p) + + # Validation: check empty diseases or empty categories + for cat in categories: + cat_dis = diseases_by_cat[cat.category_code] + if not cat_dis: + raise HTTPException( + status_code=400, + detail=( + f"Cannot compile module '{module_code}': Category '{cat.name}' " + "has no diseases. Please add at least one disease." + ), + ) + for dis in cat_dis: + dis_pats = patterns_by_dis.get((cat.category_code, dis.disease_code), []) + if not dis_pats: + raise HTTPException( + status_code=400, + detail=( + f"Cannot compile module '{module_code}': Disease '{dis.name}' " + f"(in category '{cat.name}') has no clinical patterns. " + "Please add at least one pattern." + ), + ) + + # 4. Deterministic Template Allocation + root_template_code = f"{module_code}_ct0001" + detail_template_code = f"{module_code}_ct0005" + + cat_template_codes: dict[str, str] = {} + curr_cat_num = 2 + for cat in categories: + if curr_cat_num == 5: + curr_cat_num += 1 + cat_template_codes[cat.category_code] = f"{module_code}_ct{curr_cat_num:04d}" + curr_cat_num += 1 + + dis_template_codes: dict[tuple[str, str], str] = {} + curr_dis_num = 11 + for cat in categories: + for dis in diseases_by_cat[cat.category_code]: + dis_template_codes[(cat.category_code, dis.disease_code)] = f"{module_code}_ct{curr_dis_num:04d}" + curr_dis_num += 1 + + files: dict[str, str] = {} + content_mappings: list[dict[str, Any]] = [] + + # --------------------------------------------------------------------- + # 5. Generate Root Templates & Files (Level 1) + # --------------------------------------------------------------------- + root_template = self._create_list_template( + module_code=module_code, + template_code=root_template_code, + template_name=f"{module.slug.replace('-', '_')}_list_content", + is_searchable=False, + is_filterable=False, + ) + files[f"templates/{root_template_code}.json"] = json.dumps(root_template, indent=2) + + root_list_items = [] + for idx, cat in enumerate(categories): + cat_t_code = cat_template_codes[cat.category_code] + cat_diseases = diseases_by_cat[cat.category_code] + root_list_items.append({ + "name": cat.name, + "code": cat.category_code, + "content_count": len(cat_diseases), + "content_label": "diseases", + "sort_order": idx, + "link": { + "type": "template_ref", + "label": cat.name, + "target": { + "module_code": module_code, + "template_code": cat_t_code, + }, + }, + }) + root_list_doc = {"contents": root_list_items} + files["data/list.json"] = json.dumps(root_list_doc, indent=2) + + content_mappings.append({ + "name": "module_list_content", + "description": "", + "code": root_template_code, + "data_path": "data/list.json", + "template_path": f"templates/{root_template_code}.json", + }) + + # --------------------------------------------------------------------- + # 6. Generate Category Templates & Files (Level 2) + # --------------------------------------------------------------------- + for cat in categories: + cat_t_code = cat_template_codes[cat.category_code] + cat_slug = re.sub(r"[^a-z0-9]+", "_", cat.category_code.lower()).strip("_") + + cat_template = self._create_list_template( + module_code=module_code, + template_code=cat_t_code, + template_name=f"{cat_slug}_list_content", + is_searchable=False, + is_filterable=False, + ) + files[f"templates/{cat_t_code}.json"] = json.dumps(cat_template, indent=2) + + dis_list_items = [] + for d_idx, dis in enumerate(diseases_by_cat[cat.category_code]): + dis_t_code = dis_template_codes[(cat.category_code, dis.disease_code)] + pats = patterns_by_dis[(cat.category_code, dis.disease_code)] + dis_list_items.append({ + "name": dis.name, + "code": dis.disease_code, + "content_count": len(pats), + "content_label": "patterns", + "sort_order": d_idx, + "link": { + "type": "template_ref", + "label": dis.name, + "target": { + "module_code": module_code, + "template_code": dis_t_code, + }, + }, + }) + cat_list_doc = {"contents": dis_list_items} + cat_data_path = f"data/{cat.category_code}/list.json" + files[cat_data_path] = json.dumps(cat_list_doc, indent=2) + + content_mappings.append({ + "name": f"{cat_slug}_list_content", + "description": "", + "code": cat_t_code, + "data_path": cat_data_path, + "template_path": f"templates/{cat_t_code}.json", + }) + + # --------------------------------------------------------------------- + # 7. Generate Master Pattern Detail Template & Master Detail File (Level 4) + # --------------------------------------------------------------------- + detail_template = self._create_detail_template( + module_code=module_code, + template_code=detail_template_code, + ) + files[f"templates/{detail_template_code}.json"] = json.dumps(detail_template, indent=2) + + master_detail_items = [] + global_pattern_sort = 0 + + # --------------------------------------------------------------------- + # 8. Generate Disease Templates, Pattern Lists & data.json (Level 3) + # --------------------------------------------------------------------- + for cat in categories: + for dis in diseases_by_cat[cat.category_code]: + dis_t_code = dis_template_codes[(cat.category_code, dis.disease_code)] + dis_slug = re.sub(r"[^a-z0-9]+", "_", dis.disease_code.lower()).strip("_") + + dis_template = self._create_list_template( + module_code=module_code, + template_code=dis_t_code, + template_name=f"{dis_slug}_list_content", + is_searchable=True, + is_filterable=True, + ) + files[f"templates/{dis_t_code}.json"] = json.dumps(dis_template, indent=2) + + pat_list_items = [] + embedded_patterns = [] + pats = patterns_by_dis[(cat.category_code, dis.disease_code)] + + for p_idx, pat in enumerate(pats): + source_code = f"{dis.disease_code}_{pat.pattern_code}" + c_data = pat.clinical_data or {} + + # Item for disease pattern list + pat_list_items.append({ + "name": pat.name, + "code": source_code, + "sort_order": p_idx, + "link": { + "type": "content_ref", + "label": pat.name, + "target": { + "module_code": module_code, + "template_code": detail_template_code, + "source_code": source_code, + }, + }, + }) + + # Clinical values + raw_manifestations = c_data.get("clinical_manifestations", []) + clean_manifestations = [ + str(m).strip() for m in raw_manifestations if str(m).strip() + ] + tongue = str(c_data.get("tongue", "")).strip() + pulse = str(c_data.get("pulse", "")).strip() + principle = c_data.get("treatment_principle", "") + clean_principles = [ + p.strip() + for p in (principle if isinstance(principle, list) else [str(principle)]) + if p.strip() + ] + + raw_acu = c_data.get("acupuncture", {}) + if isinstance(raw_acu, dict): + acu_points = str(raw_acu.get("points", "")).strip() + acu_method = str(raw_acu.get("method", "")).strip() + else: + acu_points = str(raw_acu).strip() + acu_method = "" + + raw_exp = c_data.get("explanation", []) + clean_exps = [str(e).strip() for e in raw_exp if str(e).strip()] + + # Item for master detail_patterns.json + master_detail_items.append({ + "code": source_code, + "slug": f"{module_code}-ct0005-{source_code}", + "name": pat.name, + "title": f"{dis.name} - {pat.name}", + "pattern_name": pat.name, + "pattern_number": p_idx + 1, + "condition": dis.name, + "clinical_manifestations": clean_manifestations, + "tongue": tongue, + "pulse": pulse, + "treatment_principle": clean_principles, + "sort_order": global_pattern_sort, + "acupuncture": { + "points": acu_points, + "method": acu_method, + }, + "explanation": clean_exps, + }) + global_pattern_sort += 1 + + # Embedded item for data.json + point_list = [p.strip() for p in re.split(r"[,;]\s*", acu_points) if p.strip()] + + # Match points mentioned in each explanation sentence + explanation_items = [] + for exp in clean_exps: + exp_lower = exp.lower() + pts_in_exp = [pt for pt in point_list if pt.lower() in exp_lower] + if not pts_in_exp and point_list: + pts_in_exp = point_list[:1] + explanation_items.append({ + "points": pts_in_exp, + "action": exp, + }) + + embedded_patterns.append({ + "category": cat.name, + "pattern_name": pat.name, + "clinical_manifestations": { + "general": clean_manifestations, + "tongue": tongue, + "pulse": pulse, + }, + "treatment_principle": " ".join(clean_principles), + "acupuncture": { + "points": point_list, + "method": acu_method, + }, + "explanation": explanation_items, + "code": pat.pattern_code, + }) + + dis_list_doc = {"contents": pat_list_items} + dis_data_path = f"data/{cat.category_code}/{dis.disease_code}/list.json" + files[dis_data_path] = json.dumps(dis_list_doc, indent=2) + + dis_full_doc = { + "name": dis.name, + "code": dis.disease_code, + "title": dis.name, + "definition": dis.overview or "", + "contents": embedded_patterns, + } + files[f"data/{cat.category_code}/{dis.disease_code}/data.json"] = json.dumps( + dis_full_doc, indent=2 + ) + + content_mappings.append({ + "name": f"{dis_slug}_list_content", + "description": "", + "code": dis_t_code, + "data_path": dis_data_path, + "template_path": f"templates/{dis_t_code}.json", + }) + + # Insert master detail content mapping right after categories + detail_data_path = "data/detail_patterns.json" + files[detail_data_path] = json.dumps({"contents": master_detail_items}, indent=2) + content_mappings.insert( + len(categories) + 1, + { + "name": f"{module.slug.replace('-', '_')}_detail_content", + "description": f"{module.name} detailed clinical pattern content", + "code": detail_template_code, + "data_path": detail_data_path, + "template_path": f"templates/{detail_template_code}.json", + }, + ) + + # --------------------------------------------------------------------- + # 9. Generate module.json & search_facets.json + # --------------------------------------------------------------------- + managed_by_val = getattr(module, "managed_by", "module_builder") + module_doc = { + "name": module.name, + "description": module.description or f"TCM clinical therapeutics for {module.name}.", + "short_description": module.short_description or module.name, + "code": module.code, + "kind": module.kind or "therapeutic", + "managed_by": managed_by_val, + "default_template_code": root_template_code, + "metadata": { + "version": "0.1", + "status": "active" if module.is_active else "draft", + "entry_template_code": root_template_code, + "managed_by": managed_by_val, + }, + "content_mapping": content_mappings, + } + files["module.json"] = json.dumps(module_doc, indent=2) + + # Facets + search_facets_doc = { + "version": "1.0", + "module_code": module_code, + "facets": [ + { + "code": "category", + "label": "Category", + "category": "TCM Classification", + "description": f"{module.name} category associated with the content", + "control_type": "typeahead_multi", + "allow_multiple_values": True, + "value_source": "projected", + "sort_order": 10, + "mappings": [ + { + "template_code": cat_t_code, + "attribute_key": f"{cat_t_code}.name", + "content_kind": module.kind or "therapeutic", + "mapping_strategy": "multivalue", + } + for cat_t_code in cat_template_codes.values() + ], + } + ], + } + files["search_facets.json"] = json.dumps(search_facets_doc, indent=2) + + return module, files + + async def generate_zip_bundle(self, module_code: str) -> tuple[str, bytes]: + module, files = await self.compile_module(module_code) + folder_prefix = f"{module.code}-{module.slug}" + + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf: + for rel_path, content in files.items(): + archive_path = f"{folder_prefix}/{rel_path}" + zf.writestr(archive_path, content) + + filename = f"{folder_prefix}.zip" + return filename, buf.getvalue() + + async def sync_to_content_repo( + self, + module_code: str, + repo_root: Path | None = None, + ) -> dict[str, Any]: + module, files = await self.compile_module(module_code) + target_root = repo_root or DEFAULT_CONTENT_REPO_PATH + if not target_root.exists(): + raise HTTPException( + status_code=500, + detail=f"Content repository directory not found at: {target_root}", + ) + + module_folder_name = f"{module.code}-{module.slug}" + module_dir = target_root / module_folder_name + + # Safety Check: If folder already exists, verify it is managed by module_builder + existing_module_json = module_dir / "module.json" + if existing_module_json.exists(): + try: + existing_doc = json.loads(existing_module_json.read_text(encoding="utf-8")) + existing_managed_by = existing_doc.get("managed_by") or existing_doc.get("metadata", {}).get("managed_by") + if existing_managed_by != "module_builder": + raise HTTPException( + status_code=403, + detail=( + f"Safety Guard: Destination '{module_folder_name}' has an existing module.json " + f"that is not managed by Module Builder (managed_by={existing_managed_by}). " + "Aborting sync to protect legacy content." + ), + ) + except json.JSONDecodeError: + pass + + module_dir.mkdir(parents=True, exist_ok=True) + + files_written = 0 + for rel_path, content in files.items(): + file_path = module_dir / rel_path + file_path.parent.mkdir(parents=True, exist_ok=True) + file_path.write_text(content, encoding="utf-8") + files_written += 1 + + # Update root config.json + config_path = target_root / "config.json" + config_updated = False + if config_path.exists(): + try: + cfg = json.loads(config_path.read_text(encoding="utf-8")) + modules_list = cfg.get("modules", []) + existing_entry = next((m for m in modules_list if m.get("code") == module.code), None) + + entry_data = { + "name": module.name, + "code": module.code, + "path": module_folder_name, + "status": "active" if module.is_active else "draft", + "sort_order": str(module.sort_order), + } + + if existing_entry: + existing_entry.update(entry_data) + else: + modules_list.append(entry_data) + + # Re-sort modules by integer sort_order + def sort_key(m: dict[str, Any]) -> int: + try: + return int(m.get("sort_order", 99999)) + except (ValueError, TypeError): + return 99999 + + cfg["modules"] = sorted(modules_list, key=sort_key) + config_path.write_text(json.dumps(cfg, indent=4), encoding="utf-8") + config_updated = True + except Exception as exc: + logger.warning("Failed to update root config.json: %s", exc) + + return { + "status": "synced", + "module_code": module.code, + "module_name": module.name, + "target_dir": str(module_dir), + "files_written": files_written, + "config_updated": config_updated, + "message": ( + f"Successfully compiled and synced module '{module.name}' ({module.code}) " + f"to {module_folder_name} ({files_written} files generated)." + ), + } + + # ========================================================================= + # CONTRACT TEMPLATE GENERATORS + # ========================================================================= + + def _create_list_template( + self, + *, + module_code: str, + template_code: str, + template_name: str, + is_searchable: bool = False, + is_filterable: bool = False, + ) -> dict[str, Any]: + return { + "name": template_name, + "description": "", + "code": template_code, + "content_kind": "therapeutic", + "is_searchable": is_searchable, + "is_filterable": is_filterable, + "attribute_prefix_code": template_code, + "attribute_prefix_name": template_name, + "attribute_defs": [ + { + "name": "Name", + "code": "name", + "data_type": "text", + "default": "", + }, + { + "name": "Code", + "code": "code", + "data_type": "text", + "default": "", + }, + { + "name": "Count", + "code": "content_count", + "data_type": "number", + "default": 0, + }, + { + "name": "Label", + "code": "content_label", + "data_type": "text", + "default": "", + }, + { + "name": "Sort Order", + "code": "sort_order", + "data_type": "number", + "default": 0, + }, + { + "name": "Content Link", + "code": "link", + "definition_kind": "object", + "is_multivalue": False, + "is_required": False, + "is_searchable": False, + "is_filterable": False, + "children": [ + { + "name": "Type", + "code": "type", + "data_type": "text", + "definition_kind": "scalar", + "is_required": True, + "default": "template_ref", + "allowed_values": ["template_ref", "content_ref"], + }, + { + "name": "Label", + "code": "label", + "data_type": "text", + "definition_kind": "scalar", + "is_required": False, + }, + { + "name": "Target", + "code": "target", + "definition_kind": "object", + "is_required": True, + "children": [ + { + "name": "Module Code", + "code": "module_code", + "data_type": "text", + "definition_kind": "scalar", + "is_required": True, + }, + { + "name": "Template Code", + "code": "template_code", + "data_type": "text", + "definition_kind": "scalar", + "is_required": True, + }, + { + "name": "Source Code", + "code": "source_code", + "data_type": "text", + "definition_kind": "scalar", + "is_required": False, + }, + { + "name": "Source Key", + "code": "source_key", + "data_type": "text", + "definition_kind": "scalar", + "is_required": False, + }, + { + "name": "Content ID", + "code": "content_id", + "data_type": "text", + "definition_kind": "scalar", + "is_required": False, + }, + ], + }, + ], + }, + ], + "presentation_contracts": [ + { + "client_type": "mobile", + "version_no": 1, + "is_active": True, + "mode": "collection", + "renderers": { + "collection": "module_catalog_collection", + "collection_item": "module_catalog_card", + "detail": f"{template_code}_detail", + }, + "link": {"renderer": "content_link"}, + "attributes": [ + { + "attribute_key": f"{template_code}.name", + "empty_behavior": "hide", + "visibility": "show", + }, + { + "attribute_key": f"{template_code}.code", + "empty_behavior": "hide", + "visibility": "hide", + }, + { + "attribute_key": f"{template_code}.content_count", + "empty_behavior": "hide", + "visibility": "show", + }, + { + "attribute_key": f"{template_code}.content_label", + "empty_behavior": "hide", + "visibility": "show", + }, + { + "attribute_key": f"{template_code}.sort_order", + "empty_behavior": "hide", + "visibility": "hide", + }, + { + "attribute_key": f"{template_code}.link", + "empty_behavior": "hide", + "visibility": "hide", + }, + { + "attribute_key": f"{template_code}.link.type", + "empty_behavior": "hide", + "visibility": "hide", + }, + { + "attribute_key": f"{template_code}.link.label", + "empty_behavior": "hide", + "visibility": "hide", + }, + { + "attribute_key": f"{template_code}.link.target", + "empty_behavior": "hide", + "visibility": "hide", + }, + { + "attribute_key": f"{template_code}.link.target.module_code", + "empty_behavior": "hide", + "visibility": "hide", + }, + { + "attribute_key": f"{template_code}.link.target.template_code", + "empty_behavior": "hide", + "visibility": "hide", + }, + { + "attribute_key": f"{template_code}.link.target.source_code", + "empty_behavior": "hide", + "visibility": "hide", + }, + { + "attribute_key": f"{template_code}.link.target.source_key", + "empty_behavior": "hide", + "visibility": "hide", + }, + { + "attribute_key": f"{template_code}.link.target.content_id", + "empty_behavior": "hide", + "visibility": "hide", + }, + ], + } + ], + "metadata": { + "navigation_reference_policy": { + "contract_version": "1.0", + "default_reference_type": "template_ref", + "allowed_reference_types": ["template_ref", "content_ref"], + } + }, + } + + def _create_detail_template( + self, + *, + module_code: str, + template_code: str, + ) -> dict[str, Any]: + return { + "name": "detail_content", + "description": "", + "code": template_code, + "content_kind": "therapeutic", + "is_searchable": False, + "is_filterable": False, + "attribute_prefix_code": template_code, + "attribute_prefix_name": "detail_content", + "attribute_defs": [ + { + "name": "Pattern Name", + "code": "pattern_name", + "data_type": "text", + "default": "", + }, + { + "name": "Code", + "code": "code", + "data_type": "text", + "default": "", + }, + { + "name": "Pattern Serial No", + "code": "pattern_number", + "data_type": "number", + "default": 0, + }, + { + "name": "Condition", + "code": "condition", + "data_type": "text", + "default": "", + }, + { + "name": "Clinical Manifestations", + "code": "clinical_manifestations", + "data_type": "text", + "is_multivalue": True, + "default": [], + }, + { + "name": "Tongue", + "code": "tongue", + "data_type": "text", + "default": "", + }, + { + "name": "Pulse", + "code": "pulse", + "data_type": "text", + "default": "", + }, + { + "name": "Treatment Principle", + "code": "treatment_principle", + "data_type": "text", + "is_multivalue": True, + "default": [], + }, + { + "name": "Sort Order", + "code": "sort_order", + "data_type": "number", + "default": 0, + }, + { + "name": "Acupuncture", + "code": "acupuncture", + "definition_kind": "object", + "is_multivalue": False, + "is_required": False, + "is_searchable": False, + "is_filterable": False, + "children": [ + { + "name": "Points", + "code": "points", + "data_type": "text", + "definition_kind": "scalar", + "is_required": False, + }, + { + "name": "Method", + "code": "method", + "data_type": "text", + "definition_kind": "scalar", + "is_required": False, + }, + ], + }, + { + "name": "Explanation", + "code": "explanation", + "data_type": "text", + "is_multivalue": True, + "default": [], + }, + { + "name": "Content Link", + "code": "link", + "definition_kind": "object", + "is_multivalue": False, + "is_required": False, + "is_searchable": False, + "is_filterable": False, + "children": [ + { + "name": "Type", + "code": "type", + "data_type": "text", + "definition_kind": "scalar", + "is_required": True, + "default": "template_ref", + "allowed_values": ["template_ref", "content_ref"], + }, + { + "name": "Label", + "code": "label", + "data_type": "text", + "definition_kind": "scalar", + "is_required": False, + }, + { + "name": "Target", + "code": "target", + "definition_kind": "object", + "is_required": True, + "children": [ + { + "name": "Module Code", + "code": "module_code", + "data_type": "text", + "definition_kind": "scalar", + "is_required": True, + }, + { + "name": "Template Code", + "code": "template_code", + "data_type": "text", + "definition_kind": "scalar", + "is_required": True, + }, + { + "name": "Source Code", + "code": "source_code", + "data_type": "text", + "definition_kind": "scalar", + "is_required": False, + }, + { + "name": "Source Key", + "code": "source_key", + "data_type": "text", + "definition_kind": "scalar", + "is_required": False, + }, + { + "name": "Content ID", + "code": "content_id", + "data_type": "text", + "definition_kind": "scalar", + "is_required": False, + }, + ], + }, + ], + }, + ], + "presentation_contracts": [ + { + "client_type": "mobile", + "version_no": 1, + "is_active": True, + "mode": "collection", + "renderers": { + "collection": f"{template_code}_collection", + "collection_item": f"{template_code}_card", + "detail": f"{template_code}_detail", + }, + "link": {"renderer": "content_link"}, + "attributes": [ + { + "attribute_key": f"{template_code}.condition", + "empty_behavior": "hide", + "visibility": "show", + "display_order": 0, + }, + { + "attribute_key": f"{template_code}.name", + "empty_behavior": "hide", + "visibility": "show", + "display_order": 0, + }, + { + "attribute_key": f"{template_code}.clinical_manifestations", + "empty_behavior": "hide", + "visibility": "show", + "display_order": 0, + }, + { + "attribute_key": f"{template_code}.tongue", + "empty_behavior": "hide", + "visibility": "show", + "display_order": 0, + }, + { + "attribute_key": f"{template_code}.pulse", + "empty_behavior": "hide", + "visibility": "show", + "display_order": 0, + }, + { + "attribute_key": f"{template_code}.treatment_principle", + "empty_behavior": "hide", + "visibility": "show", + "display_order": 0, + }, + { + "attribute_key": f"{template_code}.acupuncture", + "empty_behavior": "hide", + "visibility": "show", + "display_order": 0, + }, + { + "attribute_key": f"{template_code}.acupuncture.points", + "empty_behavior": "hide", + "visibility": "show", + "display_order": 0, + }, + { + "attribute_key": f"{template_code}.acupuncture.method", + "empty_behavior": "hide", + "visibility": "show", + "display_order": 0, + }, + { + "attribute_key": f"{template_code}.explanation", + "empty_behavior": "hide", + "visibility": "show", + "display_order": 0, + }, + ], + } + ], + "metadata": { + "navigation_reference_policy": { + "contract_version": "1.0", + "default_reference_type": "template_ref", + "allowed_reference_types": ["template_ref", "content_ref"], + } + }, + } diff --git a/tests/test_module_builder.py b/tests/test_module_builder.py index 2180d7f..df28a04 100644 --- a/tests/test_module_builder.py +++ b/tests/test_module_builder.py @@ -317,3 +317,649 @@ async def test_module_builder_validations(db_session: AsyncSession): assert exc3.value.status_code == 400 assert "at least one clinical pattern" in exc3.value.detail + +@pytest.mark.asyncio +async def test_builder_modules_api_flow(db_session: AsyncSession, admin_headers: dict[str, str], sample_admin): + from app.main import app + from app.db.session import get_db_session + from app.features.admin.deps import get_current_admin + from httpx import ASGITransport, AsyncClient + + async def override_get_db(): + yield db_session + + app.dependency_overrides[get_db_session] = override_get_db + app.dependency_overrides[get_current_admin] = lambda: sample_admin + + try: + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + # 1. List modules - should include at least m0042 + list_res = await client.get("/api/admin/module-builder/modules", headers=admin_headers) + assert list_res.status_code == 200, list_res.text + modules = list_res.json() + codes = [m["code"] for m in modules] + assert "m0042" in codes + + # 2. Create a new module (m0091 Pediatrics Test) + create_res = await client.post( + "/api/admin/module-builder/modules", + headers=admin_headers, + json={ + "name": "Pediatrics Test", + "code": "m0091", + "short_description": "Pediatric disorders test module", + "description": "Comprehensive TCM pediatrics.", + "kind": "therapeutic", + "sort_order": 91000, + }, + ) + assert create_res.status_code == 201, create_res.text + created_mod = create_res.json() + assert created_mod["code"] == "m0091" + assert created_mod["slug"] == "pediatrics-test" + assert created_mod["category_count"] == 0 + + # 3. Duplicate code returns 409 Conflict + dup_res = await client.post( + "/api/admin/module-builder/modules", + headers=admin_headers, + json={"name": "Duplicate Pediatrics", "code": "m0091"}, + ) + assert dup_res.status_code == 409 + assert "already exists" in dup_res.json()["detail"] + + # 4. Invalid code format returns 422 + inv_res = await client.post( + "/api/admin/module-builder/modules", + headers=admin_headers, + json={"name": "Bad Code Module", "code": "invalid_code_123"}, + ) + assert inv_res.status_code == 422 + + # 5. Get created module + get_res = await client.get("/api/admin/module-builder/modules/m0091", headers=admin_headers) + assert get_res.status_code == 200 + assert get_res.json()["name"] == "Pediatrics Test" + + # 6. Update module + patch_res = await client.patch( + "/api/admin/module-builder/modules/m0091", + headers=admin_headers, + json={"name": "Pediatric Disorders Updated", "short_description": "Updated short desc"}, + ) + assert patch_res.status_code == 200 + assert patch_res.json()["name"] == "Pediatric Disorders Updated" + + # 7. Delete created module + del_res = await client.delete("/api/admin/module-builder/modules/m0091", headers=admin_headers) + assert del_res.status_code == 200 + assert del_res.json()["status"] == "deleted" + + # 8. Verify 404 after deletion + not_found_res = await client.get("/api/admin/module-builder/modules/m0091", headers=admin_headers) + assert not_found_res.status_code == 404 + finally: + app.dependency_overrides.pop(get_db_session, None) + app.dependency_overrides.pop(get_current_admin, None) + + +@pytest.mark.asyncio +async def test_module_content_compiler_full_pipeline(db_session: AsyncSession): + import json + import zipfile + import io + from app.features.admin.builder_schema import ( + CreateBuilderModuleRequest, + SaveCategoryRequest, + SaveFullDiseaseRequest, + SavePatternRequest, + ) + from app.features.admin.services.module_builder_service import ModuleBuilderService + from app.bootstrap.seed_content.validators import ( + validate_definition_document, + validate_presentation_contracts, + validate_content_document, + ) + + service = ModuleBuilderService(db_session) + mod_code = "m0088" + + try: + # 1. Create Module + await service.create_module( + CreateBuilderModuleRequest( + name="Compiler Test Pediatrics", + code=mod_code, + short_description="Testing full compiler pipeline", + kind="therapeutic", + sort_order=88000, + ) + ) + + # 2. Add Category + cat_code = "infant_digestion" + await service.save_category( + mod_code, + SaveCategoryRequest(category_code=cat_code, name="Infant Digestion", sort_order=0), + ) + + # 3. Add Disease + Patterns + dis_code = "infantile_colic" + await service.save_full_disease( + mod_code, + SaveFullDiseaseRequest( + category_code=cat_code, + disease_code=dis_code, + name="Infantile Colic", + overview="Colic symptoms in newborn infants.", + patterns=[ + SavePatternRequest( + category_code=cat_code, + disease_code=dis_code, + pattern_code="food_stagnation", + name="Food Stagnation Colic", + clinical_data={ + "clinical_manifestations": ["Inconsolable crying", "Abdominal distension"], + "tongue": "Thick white coating", + "pulse": "Slippery", + "treatment_principle": "Resolve Food Stagnation, Harmonize Middle Burner", + "acupuncture": {"points": "ST-36, SP-4, CV-12", "method": "Even method"}, + "explanation": ["ST-36 harmonizes the stomach and relieves spasms."], + }, + sort_order=0, + ) + ], + ), + ) + + # 4. Compile Module + module_obj, compiled_files = await service.compiler.compile_module(mod_code) + assert module_obj.code == mod_code + assert "module.json" in compiled_files + assert "search_facets.json" in compiled_files + assert "data/list.json" in compiled_files + assert f"data/{cat_code}/list.json" in compiled_files + assert f"data/{cat_code}/{dis_code}/list.json" in compiled_files + assert f"data/{cat_code}/{dis_code}/data.json" in compiled_files + assert "data/detail_patterns.json" in compiled_files + + # 5. Validate Root & Category Templates with Seeder Validators + root_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0001.json"]) + validate_definition_document(root_tpl) + validate_presentation_contracts(root_tpl) + + cat_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0002.json"]) + validate_definition_document(cat_tpl) + validate_presentation_contracts(cat_tpl) + + dis_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0011.json"]) + validate_definition_document(dis_tpl) + validate_presentation_contracts(dis_tpl) + + det_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0005.json"]) + validate_definition_document(det_tpl) + validate_presentation_contracts(det_tpl) + + # 6. Validate Data Documents with Seeder Validators + validate_content_document(json.loads(compiled_files["data/list.json"])) + validate_content_document(json.loads(compiled_files[f"data/{cat_code}/list.json"])) + validate_content_document(json.loads(compiled_files[f"data/{cat_code}/{dis_code}/list.json"])) + validate_content_document(json.loads(compiled_files["data/detail_patterns.json"])) + + # 7. Test In-Memory ZIP Generation + zip_name, zip_bytes = await service.export_bundle_zip(mod_code) + assert zip_name.endswith(".zip") + assert len(zip_bytes) > 0 + + with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf: + namelist = zf.namelist() + assert f"{mod_code}-compiler-test-pediatrics/module.json" in namelist + assert f"{mod_code}-compiler-test-pediatrics/data/list.json" in namelist + assert f"{mod_code}-compiler-test-pediatrics/data/detail_patterns.json" in namelist + finally: + try: + await service.delete_module(mod_code) + except Exception: + pass + + +@pytest.mark.asyncio +async def test_compiler_api_endpoints(db_session: AsyncSession, admin_headers: dict[str, str], sample_admin): + import io + import zipfile + from app.main import app + from app.db.session import get_db_session + from app.features.admin.deps import get_current_admin + from httpx import ASGITransport, AsyncClient + + async def override_get_db(): + yield db_session + + app.dependency_overrides[get_db_session] = override_get_db + app.dependency_overrides[get_current_admin] = lambda: sample_admin + + try: + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + mod = "m0089" + + # 1. Create module + await client.post( + "/api/admin/module-builder/modules", + headers=admin_headers, + json={"name": "API Export Test", "code": mod}, + ) + + # 2. Add Category + await client.post( + f"/api/admin/module-builder/{mod}/categories", + headers=admin_headers, + json={"category_code": "cat_export", "name": "Category Export"}, + ) + + # 3. Add Disease with Pattern + await client.post( + f"/api/admin/module-builder/{mod}/save-full", + headers=admin_headers, + json={ + "category_code": "cat_export", + "disease_code": "dis_export", + "name": "Disease Export", + "patterns": [ + { + "category_code": "cat_export", + "disease_code": "dis_export", + "pattern_code": "pat_export", + "name": "Pattern Export", + "clinical_data": { + "clinical_manifestations": ["Test symptom"], + "tongue": "Red", + "pulse": "Rapid", + "treatment_principle": "Clear heat", + "acupuncture": {"points": "LI-11", "method": "Reducing"}, + "explanation": ["LI-11 clears heat"], + }, + } + ], + }, + ) + + # 4. Export ZIP Bundle + bundle_res = await client.get( + f"/api/admin/module-builder/{mod}/export-bundle", + headers=admin_headers, + ) + assert bundle_res.status_code == 200 + assert bundle_res.headers["content-type"] == "application/zip" + assert "attachment; filename=" in bundle_res.headers["content-disposition"] + + # Inspect zip contents + with zipfile.ZipFile(io.BytesIO(bundle_res.content)) as zf: + files = zf.namelist() + assert any("module.json" in f for f in files) + assert any("detail_patterns.json" in f for f in files) + + # Clean up + await client.delete(f"/api/admin/module-builder/modules/{mod}", headers=admin_headers) + finally: + app.dependency_overrides.pop(get_db_session, None) + app.dependency_overrides.pop(get_current_admin, None) + + +@pytest.mark.asyncio +async def test_compiler_sync_content_repo(db_session: AsyncSession, tmp_path): + import json + from pathlib import Path + from app.features.admin.builder_schema import ( + CreateBuilderModuleRequest, + SaveCategoryRequest, + SaveFullDiseaseRequest, + SavePatternRequest, + ) + from app.features.admin.services.module_builder_service import ModuleBuilderService + + service = ModuleBuilderService(db_session) + mod = "m0087" + + # Setup mock repo root with config.json + mock_config = { + "modules": [ + { + "name": "Acupuncture Points", + "code": "m0001", + "path": "m0001-acupuncture-points", + "status": "active", + "sort_order": "10001", + } + ] + } + config_file = tmp_path / "config.json" + config_file.write_text(json.dumps(mock_config, indent=4), encoding="utf-8") + + try: + # Create module + await service.create_module( + CreateBuilderModuleRequest( + name="Repo Sync Test", + code=mod, + sort_order=87000, + ) + ) + await service.save_category( + mod, + SaveCategoryRequest(category_code="cat_sync", name="Category Sync"), + ) + await service.save_full_disease( + mod, + SaveFullDiseaseRequest( + category_code="cat_sync", + disease_code="dis_sync", + name="Disease Sync", + patterns=[ + SavePatternRequest( + category_code="cat_sync", + disease_code="dis_sync", + pattern_code="pat_sync", + name="Pattern Sync", + clinical_data={ + "clinical_manifestations": ["Sync test symptom"], + "tongue": "Pale", + "pulse": "Weak", + "treatment_principle": "Sync principle", + "acupuncture": {"points": "ST-36", "method": "Even"}, + }, + ) + ], + ), + ) + + # Execute sync to tmp repo root + result = await service.sync_content_repo(mod, repo_root=tmp_path) + assert result["status"] == "synced" + assert result["files_written"] > 0 + assert result["config_updated"] is True + + # Verify files on disk + target_dir = tmp_path / f"{mod}-repo-sync-test" + assert (target_dir / "module.json").exists() + assert (target_dir / "templates" / f"{mod}_ct0001.json").exists() + assert (target_dir / "templates" / f"{mod}_ct0005.json").exists() + assert (target_dir / "data" / "list.json").exists() + assert (target_dir / "data" / "detail_patterns.json").exists() + + # Verify config.json has updated entry + updated_cfg = json.loads(config_file.read_text(encoding="utf-8")) + codes = [m["code"] for m in updated_cfg["modules"]] + assert mod in codes + finally: + try: + await service.delete_module(mod) + except Exception: + pass + + +@pytest.mark.asyncio +async def test_therapeutic_module_builder_lifecycle_and_safety_api( + db_session: AsyncSession, admin_headers: dict[str, str], sample_admin +): + """Thoroughly tests the multi-module lifecycle via FastAPI HTTP endpoints: + + 1. Enforcing 'therapeutic' kind and 'module_builder' ownership. + 2. Preventing modification or creation of non-therapeutic or legacy core modules. + 3. Creating, updating, adding clinical content, exporting, and deleting a test module. + """ + from app.main import app + from app.db.session import get_db_session + from app.features.admin.deps import get_current_admin + from httpx import ASGITransport, AsyncClient + + async def override_get_db(): + yield db_session + + app.dependency_overrides[get_db_session] = override_get_db + app.dependency_overrides[get_current_admin] = lambda: sample_admin + + test_mod_code = "m0049" + + try: + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + # ------------------------------------------------------------- + # 1. SAFETY CHECKS: Legacy Protection + # ------------------------------------------------------------- + # A. Attempting to add a category to legacy points module (m0001) -> 403 + resp = await client.post( + "/api/admin/module-builder/m0001/categories", + headers=admin_headers, + json={"category_code": "illegal_cat", "name": "Illegal Points Category"}, + ) + assert resp.status_code == 403, resp.text + assert "legacy 'point' module and cannot be modified" in resp.json()["detail"] + + # B. Attempting to save disease to legacy nutrition module (m0031) -> 403 + resp = await client.post( + "/api/admin/module-builder/m0031/save-full", + headers=admin_headers, + json={ + "category_code": "nut_cat", + "disease_code": "nut_dis", + "name": "Illegal Nutrition Disease", + "patterns": [ + { + "category_code": "nut_cat", + "disease_code": "nut_dis", + "pattern_code": "nut_pat", + "name": "Nut Pattern", + } + ], + }, + ) + assert resp.status_code == 403, resp.text + assert "legacy 'nutrition' module and cannot be modified" in resp.json()["detail"] + + # C. Attempting to update legacy diagnostics module (m0011) -> 403 + resp = await client.patch( + "/api/admin/module-builder/modules/m0011", + headers=admin_headers, + json={"name": "Hacked Eight Principles"}, + ) + assert resp.status_code == 403, resp.text + + # D. Attempting to create a non-therapeutic module -> 400 + resp = await client.post( + "/api/admin/module-builder/modules", + headers=admin_headers, + json={ + "name": "Invalid Kind Module", + "kind": "point", + }, + ) + assert resp.status_code == 400, resp.text + assert "therapeutic" in resp.json()["detail"] + + # E. Attempting to hijack existing legacy code m0001 -> 409 + resp = await client.post( + "/api/admin/module-builder/modules", + headers=admin_headers, + json={ + "name": "Points Override", + "code": "m0001", + "kind": "therapeutic", + }, + ) + assert resp.status_code == 409, resp.text + assert "conflicts with an existing core Acupedia module" in resp.json()["detail"] + + # ------------------------------------------------------------- + # 2. CREATE NEW THERAPEUTIC TEST MODULE (m0049) + # ------------------------------------------------------------- + # Clean up if existing from a previous interrupted run + await client.delete( + f"/api/admin/module-builder/modules/{test_mod_code}", + headers=admin_headers, + ) + + create_resp = await client.post( + "/api/admin/module-builder/modules", + headers=admin_headers, + json={ + "name": "Pediatric Therapeutics Test", + "code": test_mod_code, + "description": "Comprehensive TCM pediatrics and infantile massage therapeutics.", + "short_description": "Pediatric acupuncture and therapeutics.", + }, + ) + assert create_resp.status_code == 201, create_resp.text + mod_data = create_resp.json() + assert mod_data["code"] == test_mod_code + assert mod_data["name"] == "Pediatric Therapeutics Test" + assert mod_data["kind"] == "therapeutic" + assert mod_data["managed_by"] == "module_builder" + assert mod_data["slug"] == "pediatric-therapeutics-test" + assert mod_data["sort_order"] > 40000 + + # ------------------------------------------------------------- + # 3. GET & LIST MODULES + # ------------------------------------------------------------- + list_resp = await client.get( + "/api/admin/module-builder/modules", + headers=admin_headers, + ) + assert list_resp.status_code == 200 + modules = list_resp.json() + assert any(m["code"] == test_mod_code for m in modules) + for m in modules: + assert m["kind"] == "therapeutic" + assert m["managed_by"] == "module_builder" + + get_resp = await client.get( + f"/api/admin/module-builder/modules/{test_mod_code}", + headers=admin_headers, + ) + assert get_resp.status_code == 200 + assert get_resp.json()["code"] == test_mod_code + + # ------------------------------------------------------------- + # 4. UPDATE MODULE METADATA + # ------------------------------------------------------------- + patch_resp = await client.patch( + f"/api/admin/module-builder/modules/{test_mod_code}", + headers=admin_headers, + json={ + "name": "Pediatric TCM Clinical Therapeutics", + "short_description": "Updated short description", + }, + ) + assert patch_resp.status_code == 200 + updated_mod = patch_resp.json() + assert updated_mod["name"] == "Pediatric TCM Clinical Therapeutics" + assert updated_mod["short_description"] == "Updated short description" + + # ------------------------------------------------------------- + # 5. ADD CATEGORY, DISEASE & PATTERNS TO NEW MODULE + # ------------------------------------------------------------- + cat_resp = await client.post( + f"/api/admin/module-builder/{test_mod_code}/categories", + headers=admin_headers, + json={ + "category_code": "respiratory_disorders", + "name": "Respiratory Disorders", + "overview": "Pediatric respiratory complaints including cough and asthma.", + "sort_order": 1, + }, + ) + assert cat_resp.status_code == 200, cat_resp.text + assert cat_resp.json()["category_code"] == "respiratory_disorders" + + full_dis_resp = await client.post( + f"/api/admin/module-builder/{test_mod_code}/save-full", + headers=admin_headers, + json={ + "category_code": "respiratory_disorders", + "disease_code": "pediatric_cough", + "name": "Pediatric Cough", + "overview": "Overview of pediatric cough and bronchial irritation.", + "patterns": [ + { + "category_code": "respiratory_disorders", + "disease_code": "pediatric_cough", + "pattern_code": "wind_heat_cough", + "name": "Wind-Heat Cough", + "description": "Acute pediatric cough with yellow phlegm and mild fever.", + "clinical_data": { + "clinical_manifestations": ["Barking cough", "Thick yellow sputum", "Thirst"], + "tongue": "Red with thin yellow coating", + "pulse": "Floating and rapid", + "treatment_principle": "Dispel Wind, clear Heat, diffuse Lung Qi.", + "acupuncture": { + "points": "LU-7, LI-4, LU-5, BL-13", + "method": "Reducing or gentle stimulation for pediatric cases", + }, + "explanation": ["LU-7 and LI-4 release the exterior and expel wind."], + }, + "sort_order": 0, + } + ], + }, + ) + assert full_dis_resp.status_code == 200, full_dis_resp.text + dis_data = full_dis_resp.json() + assert dis_data["disease_code"] == "pediatric_cough" + assert len(dis_data["patterns"]) == 1 + assert dis_data["patterns"][0]["name"] == "Wind-Heat Cough" + + # Verify counts in module summary + verify_resp = await client.get( + f"/api/admin/module-builder/modules/{test_mod_code}", + headers=admin_headers, + ) + assert verify_resp.status_code == 200 + summary = verify_resp.json() + assert summary["category_count"] == 1 + assert summary["disease_count"] == 1 + assert summary["pattern_count"] == 1 + + # ------------------------------------------------------------- + # 6. EXPORT ARTIFACTS + # ------------------------------------------------------------- + exp_json_resp = await client.get( + f"/api/admin/module-builder/{test_mod_code}/export-json", + headers=admin_headers, + ) + assert exp_json_resp.status_code == 200 + exp_doc = exp_json_resp.json() + assert len(exp_doc["contents"]) == 1 + assert exp_doc["contents"][0]["code"] == "respiratory_disorders" + + exp_bundle_resp = await client.get( + f"/api/admin/module-builder/{test_mod_code}/export-bundle", + headers=admin_headers, + ) + assert exp_bundle_resp.status_code == 200 + assert exp_bundle_resp.headers["content-type"] == "application/zip" + assert len(exp_bundle_resp.content) > 500 + + # ------------------------------------------------------------- + # 7. DELETE TEST MODULE + # ------------------------------------------------------------- + del_resp = await client.delete( + f"/api/admin/module-builder/modules/{test_mod_code}", + headers=admin_headers, + ) + assert del_resp.status_code == 200 + assert del_resp.json()["status"] == "deleted" + + # Verify 404 after deletion + get_deleted = await client.get( + f"/api/admin/module-builder/modules/{test_mod_code}", + headers=admin_headers, + ) + assert get_deleted.status_code == 404 + finally: + app.dependency_overrides.clear() + + + + +