display order fix for m0001

This commit is contained in:
Amit Salunke 2026-09-28 07:47:19 +05:30
parent 92c29dd673
commit 64d5097e1b
5 changed files with 278 additions and 36 deletions

View File

@ -19,6 +19,7 @@ class Settings(BaseSettings):
app_version: str = "0.1.0"
app_env: Literal["local", "dev", "test", "stage", "prod"] = "local"
debug: bool = False
content_preview_enabled: bool = False
api_prefix: str = "/api/v1"
cors_origins: str = "http://localhost:3000,http://localhost:8000"

View File

@ -5,7 +5,7 @@ from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query
from .deps import get_content_service
from .deps import get_content_preview_mode, get_content_service
from .errors import (
AmbiguousTemplateCodeError,
ContentProjectionError,
@ -45,32 +45,47 @@ router = APIRouter(prefix="/contents", tags=["Content"])
@router.get("/modules", response_model=ModuleListResponse)
async def get_modules(service: ContentService = Depends(get_content_service)) -> ModuleListResponse:
return await service.get_modules()
async def get_modules(
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service),
) -> ModuleListResponse:
return await service.get_modules(preview=preview)
@router.post("/module-contents", response_model=ModuleContentListResponse)
async def get_module_contents(
payload: ModuleRequest,
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service),
) -> ModuleContentListResponse:
return await service.get_module_contents(request=payload)
return await service.get_module_contents(
request=payload,
preview=preview,
)
@router.post("/module-template-contents", response_model=ModuleTemplateContentResponse)
async def get_module_template_contents(
payload: ModuleTemplateContentRequest,
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service),
) -> ModuleTemplateContentResponse:
return await service.get_module_contents_by_template(request=payload)
return await service.get_module_contents_by_template(
request=payload,
preview=preview,
)
@router.post("/module-template-content-details", response_model=ModuleTemplateContentDetailResponse)
async def get_module_template_content_details(
payload: ModuleTemplateContentRequest,
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service),
) -> ModuleTemplateContentDetailResponse:
return await service.get_module_content_details_by_template(request=payload)
return await service.get_module_content_details_by_template(
request=payload,
preview=preview,
)
@router.get("/templates/{template_code}/attributes", response_model=TemplateAttributeDefinitionsResponse)
@ -159,10 +174,11 @@ async def search_module_contents(
@router.post("/search", response_model=ContentSearchResponse)
async def search_contents(
payload: ContentSearchRequest,
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service),
) -> ContentSearchResponse:
try:
return await service.search_contents(payload)
return await service.search_contents(payload, preview=preview)
except ModuleNotFoundError as exc:
raise HTTPException(404, detail={"code": "MODULE_NOT_FOUND", "message": str(exc)}) from exc
except TemplateNotFoundError as exc:
@ -181,18 +197,24 @@ async def search_contents(
@router.get("/{content_id}")
async def get_content(
content_id: UUID,
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service),
):
return await service.get_content_json(content_id)
return await service.get_content_json(content_id, preview=preview)
@router.post("/module-contents/{content_id}", response_model=ContentDetailResponse)
async def get_module_content_detail(
content_id: UUID,
payload: ModuleRequest,
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service),
) -> ContentDetailResponse:
return await service.get_module_content_detail(request=payload, content_id=content_id)
return await service.get_module_content_detail(
request=payload,
content_id=content_id,
preview=preview,
)
@router.post("/{content_id}/publish", response_model=PublishContentResponse)

View File

@ -1,6 +1,9 @@
from __future__ import annotations
from fastapi import Depends
from uuid import UUID
from fastapi import Depends, Header, HTTPException, Query, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.cache.content_cache import ContentCache
@ -10,7 +13,10 @@ from app.cache.deps import (
)
from app.cache.invalidation import ContentCacheInvalidator
from app.cache.service import CacheService
from app.core.config import settings
from app.db.models import AppUser, Role, UserRole
from app.db.session import get_db_session
from app.features.auth.security import decode_access_token
from app.features.media_storage import MediaUrlResolver, get_media_url_resolver
from app.features.search.deps import get_search_repository
from app.features.search.repository import SearchRepository
@ -43,3 +49,72 @@ def get_content_service(
search_projection_writer=search_repository,
media_url_resolver=media_url_resolver,
)
async def get_content_preview_mode(
preview: bool = Query(default=False),
authorization: str | None = Header(default=None),
session: AsyncSession = Depends(get_db_session),
) -> bool:
if not preview:
return False
if not settings.content_preview_enabled:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Content preview is disabled.",
)
if not authorization:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Preview requires authentication.",
)
scheme, separator, token = authorization.partition(" ")
if separator != " " or scheme.lower() != "bearer" or not token.strip():
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid session token.",
)
try:
user_id = UUID(str(decode_access_token(token.strip())["sub"]))
except Exception as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid session token.",
) from exc
user = (
await session.execute(
select(AppUser).where(
AppUser.id == user_id,
AppUser.is_active.is_(True),
)
)
).scalar_one_or_none()
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User profile not found.",
)
roles = set(
(
await session.execute(
select(Role.role_name)
.join(UserRole, UserRole.role_id == Role.id)
.where(UserRole.user_id == user.id)
)
).scalars().all()
)
if not ({"admin", "super_admin"} & roles):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Content preview requires admin privileges.",
)
return True

View File

@ -11,6 +11,8 @@ from datetime import datetime
from sqlalchemy import select, bindparam, text, func
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import ModuleStatus, RecordStatus
from app.db.models import (
AttributeDefinition,
AttributeDefinitionMember,
@ -157,10 +159,19 @@ class ContentRepository:
self,
*,
session: AsyncSession,
include_draft: bool = False,
) -> list[Module]:
allowed_statuses = (
[ModuleStatus.ACTIVE, ModuleStatus.DRAFT]
if include_draft
else [ModuleStatus.ACTIVE]
)
stmt = (
select(Module)
.where(Module.is_active.is_(True))
.where(
Module.is_active.is_(True),
Module.status.in_(allowed_statuses),
)
.order_by(Module.name.asc(), Module.id.asc())
)
result = await session.execute(stmt)
@ -236,6 +247,7 @@ class ContentRepository:
session: AsyncSession,
module_id: UUID,
active_content_only: bool = True,
include_draft: bool = False,
) -> list[ModuleContentRow]:
stmt = (
select(ModuleContent, ContentItem)
@ -244,7 +256,15 @@ class ContentRepository:
)
if active_content_only:
stmt = stmt.where(ContentItem.is_active.is_(True))
allowed_statuses = (
[RecordStatus.PUBLISHED, RecordStatus.DRAFT]
if include_draft
else [RecordStatus.PUBLISHED]
)
stmt = stmt.where(
ContentItem.is_active.is_(True),
ContentItem.status.in_(allowed_statuses),
)
stmt = stmt.order_by(
ModuleContent.sort_order.asc(),
@ -274,6 +294,7 @@ class ContentRepository:
module_id: UUID,
content_id: UUID,
active_content_only: bool = True,
include_draft: bool = False,
) -> ModuleContentRow | None:
stmt = (
select(ModuleContent, ContentItem)
@ -285,7 +306,15 @@ class ContentRepository:
)
if active_content_only:
stmt = stmt.where(ContentItem.is_active.is_(True))
allowed_statuses = (
[RecordStatus.PUBLISHED, RecordStatus.DRAFT]
if include_draft
else [RecordStatus.PUBLISHED]
)
stmt = stmt.where(
ContentItem.is_active.is_(True),
ContentItem.status.in_(allowed_statuses),
)
result = await session.execute(stmt)
row = result.one_or_none()
@ -307,6 +336,7 @@ class ContentRepository:
self,
*,
references: set[ContentReferenceLookup],
include_draft: bool = False,
) -> dict[ContentReferenceLookup, ResolvedContentReference]:
"""
Resolve content_ref targets in one query.
@ -353,7 +383,17 @@ class ContentRepository:
Module.code.in_(module_codes),
AttributeDefinitionSet.code.in_(template_codes),
ContentItem.is_active.is_(True),
ContentItem.status.in_(
[RecordStatus.PUBLISHED, RecordStatus.DRAFT]
if include_draft
else [RecordStatus.PUBLISHED]
),
Module.is_active.is_(True),
Module.status.in_(
[ModuleStatus.ACTIVE, ModuleStatus.DRAFT]
if include_draft
else [ModuleStatus.ACTIVE]
),
AttributeDefinitionSet.is_active.is_(True),
)
.order_by(
@ -428,10 +468,19 @@ class ContentRepository:
session: AsyncSession,
content_id: UUID,
active_only: bool = True,
include_draft: bool = False,
) -> ContentItem | None:
stmt = select(ContentItem).where(ContentItem.id == content_id)
if active_only:
stmt = stmt.where(ContentItem.is_active.is_(True))
allowed_statuses = (
[RecordStatus.PUBLISHED, RecordStatus.DRAFT]
if include_draft
else [RecordStatus.PUBLISHED]
)
stmt = stmt.where(
ContentItem.is_active.is_(True),
ContentItem.status.in_(allowed_statuses),
)
result = await session.execute(stmt)
return result.scalar_one_or_none()
@ -460,6 +509,7 @@ class ContentRepository:
module_id: UUID,
definition_set_id: UUID,
active_content_only: bool = True,
include_draft: bool = False,
) -> list[ModuleContentRow]:
"""
Return all content that simultaneously:
@ -494,8 +544,14 @@ class ContentRepository:
)
if active_content_only:
allowed_statuses = (
[RecordStatus.PUBLISHED, RecordStatus.DRAFT]
if include_draft
else [RecordStatus.PUBLISHED]
)
stmt = stmt.where(
ContentItem.is_active.is_(True)
ContentItem.is_active.is_(True),
ContentItem.status.in_(allowed_statuses),
)
stmt = stmt.order_by(
@ -1241,6 +1297,7 @@ class ContentRepository:
definition_set: DefinitionSetRecord,
presentation: PresentationRecord,
definitions: list[AttributeDefinitionRecord],
include_draft: bool = False,
) -> tuple[int, list[SearchPageRow]]:
if presentation.presentation_mode != "collection":
raise TemplateNotCollectionError(
@ -1253,11 +1310,16 @@ class ContentRepository:
for definition in definitions
}
allowed_status_sql = (
"ci.status in ('published', 'draft')"
if include_draft
else "ci.status = 'published'"
)
where_parts = [
"mc.module_id = :module_id",
"ci.attribute_definition_set_id = :definition_set_id",
"ci.is_active = true",
"ci.status = 'published'",
allowed_status_sql,
]
params: dict[str, Any] = {
"module_id": module.id,

View File

@ -14,7 +14,7 @@ from app.features.media_storage import MediaUrlResolver
from app.cache.content_cache import ContentCache
from app.cache.invalidation import ContentCacheInvalidator
from app.db.models import ContentItem
from app.db.enums import RecordStatus
from app.db.enums import ModuleStatus, RecordStatus
from app.features.content.builder import (
AttributeCycleError,
AttributeHierarchyError,
@ -119,10 +119,11 @@ class ContentService:
self.search_projection_writer = search_projection_writer
self.media_url_resolver = media_url_resolver
async def get_modules(self) -> ModuleListResponse:
async def get_modules(self, *, preview: bool = False) -> ModuleListResponse:
async def loader() -> ModuleListResponse:
modules = await self.repository.get_all_active_modules(
session=self.session
session=self.session,
include_draft=preview,
)
return ModuleListResponse(
modules=[
@ -131,6 +132,9 @@ class ContentService:
]
)
if preview:
return await loader()
cached = await self.cache.active_modules(loader=loader)
if isinstance(cached, ModuleListResponse):
@ -142,6 +146,7 @@ class ContentService:
self,
*,
request: ModuleRequest,
preview: bool = False,
) -> ModuleContentListResponse:
module = await self.repository.resolve_module(
session=self.session,
@ -153,11 +158,20 @@ class ContentService:
if module is None:
raise HTTPException(status_code=404, detail="Module not found")
allowed_module_statuses = (
{ModuleStatus.ACTIVE, ModuleStatus.DRAFT}
if preview
else {ModuleStatus.ACTIVE}
)
if module.status not in allowed_module_statuses:
raise HTTPException(status_code=404, detail="Module not found")
async def loader() -> ModuleContentListResponse:
rows = await self.repository.get_module_contents(
session=self.session,
module_id=module.id,
active_content_only=True,
include_draft=preview,
)
return ModuleContentListResponse(
@ -168,6 +182,9 @@ class ContentService:
],
)
if preview:
return await loader()
cached = await self.cache.module_contents(
module_id=module.id,
loader=loader,
@ -182,6 +199,7 @@ class ContentService:
self,
*,
request: ModuleTemplateContentRequest,
preview: bool = False,
) -> ModuleTemplateContentResponse:
module = await self.repository.resolve_module(
session=self.session,
@ -193,6 +211,14 @@ class ContentService:
if module is None:
raise HTTPException(status_code=404, detail="Module not found")
allowed_module_statuses = (
{ModuleStatus.ACTIVE, ModuleStatus.DRAFT}
if preview
else {ModuleStatus.ACTIVE}
)
if module.status not in allowed_module_statuses:
raise HTTPException(status_code=404, detail="Module not found")
template = await self.repository.get_definition_set_by_code(
session=self.session,
template_code=request.template_code,
@ -208,6 +234,7 @@ class ContentService:
module_id=module.id,
definition_set_id=template.id,
active_content_only=True,
include_draft=preview,
)
return ModuleTemplateContentResponse(
@ -219,6 +246,9 @@ class ContentService:
],
)
if preview:
return await loader()
cached = await self.cache.module_template_contents(
module_id=module.id,
template_code=template.code,
@ -234,6 +264,7 @@ class ContentService:
self,
*,
request: ModuleTemplateContentRequest,
preview: bool = False,
) -> ModuleTemplateContentDetailResponse:
module = await self.repository.resolve_module(
session=self.session,
@ -245,6 +276,14 @@ class ContentService:
if module is None:
raise HTTPException(status_code=404, detail="Module not found")
allowed_module_statuses = (
{ModuleStatus.ACTIVE, ModuleStatus.DRAFT}
if preview
else {ModuleStatus.ACTIVE}
)
if module.status not in allowed_module_statuses:
raise HTTPException(status_code=404, detail="Module not found")
template = await self.repository.get_definition_set_by_code(
session=self.session,
template_code=request.template_code,
@ -260,6 +299,7 @@ class ContentService:
module_id=module.id,
definition_set_id=template.id,
active_content_only=True,
include_draft=preview,
)
builder = ContentJsonBuilder(session=self.session)
@ -318,7 +358,8 @@ class ContentService:
try:
hydrated_payloads = await self._hydrate_content_reference_payloads(
[item.data for item in items]
[item.data for item in items],
preview=preview,
)
except ContentReferenceResolutionError as exc:
raise HTTPException(
@ -335,23 +376,37 @@ class ContentService:
items=items,
)
cached = await self.cache.module_template_details(
module_id=module.id,
template_code=template.code,
loader=loader,
)
if isinstance(cached, ModuleTemplateContentDetailResponse):
stable_response = cached
if preview:
stable_response = await loader()
else:
stable_response = ModuleTemplateContentDetailResponse.model_validate(cached)
cached = await self.cache.module_template_details(
module_id=module.id,
template_code=template.code,
loader=loader,
)
if isinstance(cached, ModuleTemplateContentDetailResponse):
stable_response = cached
else:
stable_response = ModuleTemplateContentDetailResponse.model_validate(cached)
return await self._hydrate_template_detail_media(stable_response)
async def get_content_json(
self,
content_id: UUID,
*,
preview: bool = False,
) -> dict[str, Any]:
content = await self.repository.get_content_by_id(
session=self.session,
content_id=content_id,
active_only=True,
include_draft=preview,
)
if content is None:
raise HTTPException(status_code=404, detail="Content not found")
async def loader() -> dict[str, Any]:
builder = ContentJsonBuilder(session=self.session)
@ -364,7 +419,8 @@ class ContentService:
detail="Content builder returned invalid attributes",
)
built["attributes"] = await self._hydrate_content_references(
attributes
attributes,
preview=preview,
)
return built
@ -391,6 +447,9 @@ class ContentService:
detail=f"Content reference structure is invalid: {exc}",
) from exc
if preview:
return await loader()
return await self.cache.content_detail(
content_id=content_id,
loader=loader,
@ -474,6 +533,7 @@ class ContentService:
*,
request: ModuleRequest,
content_id: UUID,
preview: bool = False,
) -> ContentDetailResponse:
module = await self.repository.resolve_module(
session=self.session,
@ -485,11 +545,20 @@ class ContentService:
if module is None:
raise HTTPException(status_code=404, detail="Module not found")
allowed_module_statuses = (
{ModuleStatus.ACTIVE, ModuleStatus.DRAFT}
if preview
else {ModuleStatus.ACTIVE}
)
if module.status not in allowed_module_statuses:
raise HTTPException(status_code=404, detail="Module not found")
association = await self.repository.get_module_content_by_content_id(
session=self.session,
module_id=module.id,
content_id=content_id,
active_content_only=True,
include_draft=preview,
)
if association is None:
@ -498,7 +567,7 @@ class ContentService:
detail="Content item was not found in the requested module",
)
built = await self.get_content_json(content_id)
built = await self.get_content_json(content_id, preview=preview)
dynamic_data = built.get("attributes") or {}
if not isinstance(dynamic_data, dict):
@ -1056,6 +1125,8 @@ class ContentService:
async def search_contents(
self,
request: ContentSearchRequest,
*,
preview: bool = False,
) -> ContentSearchResponse:
module = await self.repository.resolve_module(
session=self.session,
@ -1070,8 +1141,9 @@ class ContentService:
if hasattr(module.status, "value")
else str(module.status)
)
if module_status != "active":
raise ModuleNotFoundError("Requested module is not active")
allowed_module_statuses = {"active", "draft"} if preview else {"active"}
if module_status not in allowed_module_statuses:
raise ModuleNotFoundError("Requested module is not available")
definition_set = (
await self.repository.resolve_definition_set(
request.template_code
@ -1116,6 +1188,7 @@ class ContentService:
definition_set=definition_set,
presentation=presentation,
definitions=definitions,
include_draft=preview,
)
attributes_by_content = (
@ -1131,7 +1204,8 @@ class ContentService:
]
try:
hydrated_payloads = await self._hydrate_content_reference_payloads(
ordered_payloads
ordered_payloads,
preview=preview,
)
except ContentReferenceResolutionError as exc:
raise HTTPException(
@ -1165,13 +1239,20 @@ class ContentService:
async def _hydrate_content_references(
self,
payload: dict[str, Any],
*,
preview: bool = False,
) -> dict[str, Any]:
hydrated = await self._hydrate_content_reference_payloads([payload])
hydrated = await self._hydrate_content_reference_payloads(
[payload],
preview=preview,
)
return hydrated[0]
async def _hydrate_content_reference_payloads(
self,
payloads: list[dict[str, Any]],
*,
preview: bool = False,
) -> list[dict[str, Any]]:
"""Resolve all nested content_ref objects with one repository query."""
references: set[ContentReferenceLookup] = set()
@ -1185,7 +1266,8 @@ class ContentService:
]
resolved = await self.repository.resolve_content_reference_targets(
references=references
references=references,
include_draft=preview,
)
return [
self._hydrate_reference_value(payload, resolved)