feat(module-builder): add multi-module management, compiler, and therapeutics safety guards
This commit is contained in:
parent
896ad11fee
commit
8cb459747f
|
|
@ -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)
|
||||||
|
|
||||||
|
|
@ -30,6 +30,7 @@ from .content import (
|
||||||
SearchFacetMapping,
|
SearchFacetMapping,
|
||||||
ContentSearchDocument,
|
ContentSearchDocument,
|
||||||
ContentSearchFacet,
|
ContentSearchFacet,
|
||||||
|
BuilderModule,
|
||||||
BuilderCategory,
|
BuilderCategory,
|
||||||
BuilderDisease,
|
BuilderDisease,
|
||||||
BuilderPattern,
|
BuilderPattern,
|
||||||
|
|
@ -91,6 +92,10 @@ __all__ = [
|
||||||
"SearchFacetMapping",
|
"SearchFacetMapping",
|
||||||
"ContentSearchDocument",
|
"ContentSearchDocument",
|
||||||
"ContentSearchFacet",
|
"ContentSearchFacet",
|
||||||
|
"BuilderModule",
|
||||||
|
"BuilderCategory",
|
||||||
|
"BuilderDisease",
|
||||||
|
"BuilderPattern",
|
||||||
"UserBillingProfile",
|
"UserBillingProfile",
|
||||||
"AccessPlan",
|
"AccessPlan",
|
||||||
"AccessPlanModule",
|
"AccessPlanModule",
|
||||||
|
|
|
||||||
|
|
@ -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):
|
class BuilderCategory(Base):
|
||||||
__tablename__ = "builder_categories"
|
__tablename__ = "builder_categories"
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint("module_code", "category_code", name="uq_builder_categories_code"),
|
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"),
|
Index("idx_builder_categories_module", "module_code"),
|
||||||
{"schema": CONTENT_SCHEMA},
|
{"schema": CONTENT_SCHEMA},
|
||||||
)
|
)
|
||||||
|
|
@ -916,6 +959,7 @@ class BuilderCategory(Base):
|
||||||
DateTime(timezone=True), nullable=False, server_default=text("now()")
|
DateTime(timezone=True), nullable=False, server_default=text("now()")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
module: Mapped["BuilderModule"] = relationship(back_populates="categories")
|
||||||
diseases: Mapped[list["BuilderDisease"]] = relationship(
|
diseases: Mapped[list["BuilderDisease"]] = relationship(
|
||||||
back_populates="category",
|
back_populates="category",
|
||||||
cascade="all, delete-orphan",
|
cascade="all, delete-orphan",
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
import io
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||||
from fastapi.responses import HTMLResponse, StreamingResponse
|
from fastapi.responses import HTMLResponse, StreamingResponse
|
||||||
from app.db.models import AppUser
|
from app.db.models import AppUser
|
||||||
|
|
@ -21,6 +22,9 @@ from .schema import (
|
||||||
UpdateCouponRequest,
|
UpdateCouponRequest,
|
||||||
)
|
)
|
||||||
from .builder_schema import (
|
from .builder_schema import (
|
||||||
|
BuilderModuleSummary,
|
||||||
|
CreateBuilderModuleRequest,
|
||||||
|
UpdateBuilderModuleRequest,
|
||||||
BuilderCategorySummary,
|
BuilderCategorySummary,
|
||||||
BuilderDiseaseDetailResponse,
|
BuilderDiseaseDetailResponse,
|
||||||
BuilderDiseaseSummary,
|
BuilderDiseaseSummary,
|
||||||
|
|
@ -539,6 +543,74 @@ async def export_report_csv(
|
||||||
# MODULE BUILDER ENDPOINTS
|
# 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])
|
@router.get("/module-builder/{module_code}/categories", response_model=list[BuilderCategorySummary])
|
||||||
async def get_builder_categories(
|
async def get_builder_categories(
|
||||||
module_code: str,
|
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
|
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)
|
@router.post("/module-builder/{module_code}/import-json", response_model=ModuleBuilderImportResponse)
|
||||||
async def import_module_json(
|
async def import_module_json(
|
||||||
module_code: str,
|
module_code: str,
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,64 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import UUID
|
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
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
|
|
@ -7,8 +8,12 @@ from sqlalchemy import delete, func, select
|
||||||
from sqlalchemy.dialects.postgresql import insert
|
from sqlalchemy.dialects.postgresql import insert
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
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 (
|
from app.features.admin.builder_schema import (
|
||||||
|
BuilderModuleSummary,
|
||||||
|
CreateBuilderModuleRequest,
|
||||||
|
UpdateBuilderModuleRequest,
|
||||||
BuilderCategorySummary,
|
BuilderCategorySummary,
|
||||||
BuilderDiseaseDetailResponse,
|
BuilderDiseaseDetailResponse,
|
||||||
BuilderDiseaseSummary,
|
BuilderDiseaseSummary,
|
||||||
|
|
@ -28,6 +33,363 @@ from app.features.admin.builder_schema import (
|
||||||
class ModuleBuilderService:
|
class ModuleBuilderService:
|
||||||
def __init__(self, session: AsyncSession) -> None:
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
self.session = session
|
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
|
# CATEGORIES
|
||||||
|
|
@ -82,6 +444,7 @@ class ModuleBuilderService:
|
||||||
if not payload.category_code or not payload.category_code.strip():
|
if not payload.category_code or not payload.category_code.strip():
|
||||||
raise HTTPException(400, detail="Category system code cannot be empty.")
|
raise HTTPException(400, detail="Category system code cannot be empty.")
|
||||||
|
|
||||||
|
await self._ensure_module(module_code)
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
stmt = (
|
stmt = (
|
||||||
insert(BuilderCategory)
|
insert(BuilderCategory)
|
||||||
|
|
@ -127,11 +490,35 @@ 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:
|
||||||
stmt = delete(BuilderCategory).where(
|
clean_code = module_code.strip().lower()
|
||||||
BuilderCategory.module_code == module_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(
|
||||||
|
BuilderCategory.module_code == clean_code,
|
||||||
BuilderCategory.category_code == category_code,
|
BuilderCategory.category_code == category_code,
|
||||||
)
|
)
|
||||||
res = await self.session.execute(stmt)
|
res = await self.session.execute(del_stmt)
|
||||||
await self.session.commit()
|
await self.session.commit()
|
||||||
return res.rowcount > 0
|
return res.rowcount > 0
|
||||||
|
|
||||||
|
|
@ -247,6 +634,8 @@ class ModuleBuilderService:
|
||||||
if not payload.category_code or not payload.category_code.strip():
|
if not payload.category_code or not payload.category_code.strip():
|
||||||
raise HTTPException(400, detail="Category code is required to attach a disease.")
|
raise HTTPException(400, detail="Category code is required to attach a disease.")
|
||||||
|
|
||||||
|
await self._ensure_module(module_code)
|
||||||
|
|
||||||
# Ensure parent category exists
|
# Ensure parent category exists
|
||||||
cat_check = await self.session.execute(
|
cat_check = await self.session.execute(
|
||||||
select(BuilderCategory.id).where(
|
select(BuilderCategory.id).where(
|
||||||
|
|
@ -329,8 +718,32 @@ class ModuleBuilderService:
|
||||||
async def delete_disease(
|
async def delete_disease(
|
||||||
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()
|
||||||
|
|
||||||
|
# 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 == module_code,
|
BuilderDisease.module_code == clean_code,
|
||||||
BuilderDisease.category_code == category_code,
|
BuilderDisease.category_code == category_code,
|
||||||
BuilderDisease.disease_code == disease_code,
|
BuilderDisease.disease_code == disease_code,
|
||||||
)
|
)
|
||||||
|
|
@ -345,6 +758,8 @@ class ModuleBuilderService:
|
||||||
async def save_full_disease(
|
async def save_full_disease(
|
||||||
self, module_code: str, payload: SaveFullDiseaseRequest
|
self, module_code: str, payload: SaveFullDiseaseRequest
|
||||||
) -> BuilderDiseaseDetailResponse:
|
) -> BuilderDiseaseDetailResponse:
|
||||||
|
await self._ensure_module(module_code)
|
||||||
|
|
||||||
if not payload.name or not payload.name.strip():
|
if not payload.name or not payload.name.strip():
|
||||||
raise HTTPException(400, detail="Disease name cannot be empty.")
|
raise HTTPException(400, detail="Disease name cannot be empty.")
|
||||||
if not payload.disease_code or not payload.disease_code.strip():
|
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:
|
async def export_module_json(self, module_code: str) -> ModuleBuilderExportResponse:
|
||||||
|
await self._verify_module_editable(module_code)
|
||||||
|
|
||||||
# Fetch categories
|
# Fetch categories
|
||||||
cat_stmt = (
|
cat_stmt = (
|
||||||
select(BuilderCategory)
|
select(BuilderCategory)
|
||||||
|
|
@ -554,6 +971,7 @@ class ModuleBuilderService:
|
||||||
async def import_module_json(
|
async def import_module_json(
|
||||||
self, module_code: str, payload: ModuleBuilderImportRequest
|
self, module_code: str, payload: ModuleBuilderImportRequest
|
||||||
) -> ModuleBuilderImportResponse:
|
) -> ModuleBuilderImportResponse:
|
||||||
|
await self._verify_module_editable(module_code)
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
cat_count = 0
|
cat_count = 0
|
||||||
dis_count = 0
|
dis_count = 0
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -317,3 +317,649 @@ async def test_module_builder_validations(db_session: AsyncSession):
|
||||||
assert exc3.value.status_code == 400
|
assert exc3.value.status_code == 400
|
||||||
assert "at least one clinical pattern" in exc3.value.detail
|
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()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue