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_version: str = "0.1.0"
app_env: Literal["local", "dev", "test", "stage", "prod"] = "local" app_env: Literal["local", "dev", "test", "stage", "prod"] = "local"
debug: bool = False debug: bool = False
content_preview_enabled: bool = False
api_prefix: str = "/api/v1" api_prefix: str = "/api/v1"
cors_origins: str = "http://localhost:3000,http://localhost:8000" 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 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 ( from .errors import (
AmbiguousTemplateCodeError, AmbiguousTemplateCodeError,
ContentProjectionError, ContentProjectionError,
@ -45,32 +45,47 @@ router = APIRouter(prefix="/contents", tags=["Content"])
@router.get("/modules", response_model=ModuleListResponse) @router.get("/modules", response_model=ModuleListResponse)
async def get_modules(service: ContentService = Depends(get_content_service)) -> ModuleListResponse: async def get_modules(
return await service.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) @router.post("/module-contents", response_model=ModuleContentListResponse)
async def get_module_contents( async def get_module_contents(
payload: ModuleRequest, payload: ModuleRequest,
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service), service: ContentService = Depends(get_content_service),
) -> ModuleContentListResponse: ) -> 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) @router.post("/module-template-contents", response_model=ModuleTemplateContentResponse)
async def get_module_template_contents( async def get_module_template_contents(
payload: ModuleTemplateContentRequest, payload: ModuleTemplateContentRequest,
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service), service: ContentService = Depends(get_content_service),
) -> ModuleTemplateContentResponse: ) -> 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) @router.post("/module-template-content-details", response_model=ModuleTemplateContentDetailResponse)
async def get_module_template_content_details( async def get_module_template_content_details(
payload: ModuleTemplateContentRequest, payload: ModuleTemplateContentRequest,
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service), service: ContentService = Depends(get_content_service),
) -> ModuleTemplateContentDetailResponse: ) -> 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) @router.get("/templates/{template_code}/attributes", response_model=TemplateAttributeDefinitionsResponse)
@ -159,10 +174,11 @@ async def search_module_contents(
@router.post("/search", response_model=ContentSearchResponse) @router.post("/search", response_model=ContentSearchResponse)
async def search_contents( async def search_contents(
payload: ContentSearchRequest, payload: ContentSearchRequest,
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service), service: ContentService = Depends(get_content_service),
) -> ContentSearchResponse: ) -> ContentSearchResponse:
try: try:
return await service.search_contents(payload) return await service.search_contents(payload, preview=preview)
except ModuleNotFoundError as exc: except ModuleNotFoundError as exc:
raise HTTPException(404, detail={"code": "MODULE_NOT_FOUND", "message": str(exc)}) from exc raise HTTPException(404, detail={"code": "MODULE_NOT_FOUND", "message": str(exc)}) from exc
except TemplateNotFoundError as exc: except TemplateNotFoundError as exc:
@ -181,18 +197,24 @@ async def search_contents(
@router.get("/{content_id}") @router.get("/{content_id}")
async def get_content( async def get_content(
content_id: UUID, content_id: UUID,
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service), 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) @router.post("/module-contents/{content_id}", response_model=ContentDetailResponse)
async def get_module_content_detail( async def get_module_content_detail(
content_id: UUID, content_id: UUID,
payload: ModuleRequest, payload: ModuleRequest,
preview: bool = Depends(get_content_preview_mode),
service: ContentService = Depends(get_content_service), service: ContentService = Depends(get_content_service),
) -> ContentDetailResponse: ) -> 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) @router.post("/{content_id}/publish", response_model=PublishContentResponse)

View File

@ -1,6 +1,9 @@
from __future__ import annotations 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 sqlalchemy.ext.asyncio import AsyncSession
from app.cache.content_cache import ContentCache 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.invalidation import ContentCacheInvalidator
from app.cache.service import CacheService 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.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.media_storage import MediaUrlResolver, get_media_url_resolver
from app.features.search.deps import get_search_repository from app.features.search.deps import get_search_repository
from app.features.search.repository import SearchRepository from app.features.search.repository import SearchRepository
@ -43,3 +49,72 @@ def get_content_service(
search_projection_writer=search_repository, search_projection_writer=search_repository,
media_url_resolver=media_url_resolver, 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 import select, bindparam, text, func
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import ModuleStatus, RecordStatus
from app.db.models import ( from app.db.models import (
AttributeDefinition, AttributeDefinition,
AttributeDefinitionMember, AttributeDefinitionMember,
@ -157,10 +159,19 @@ class ContentRepository:
self, self,
*, *,
session: AsyncSession, session: AsyncSession,
include_draft: bool = False,
) -> list[Module]: ) -> list[Module]:
allowed_statuses = (
[ModuleStatus.ACTIVE, ModuleStatus.DRAFT]
if include_draft
else [ModuleStatus.ACTIVE]
)
stmt = ( stmt = (
select(Module) 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()) .order_by(Module.name.asc(), Module.id.asc())
) )
result = await session.execute(stmt) result = await session.execute(stmt)
@ -236,6 +247,7 @@ class ContentRepository:
session: AsyncSession, session: AsyncSession,
module_id: UUID, module_id: UUID,
active_content_only: bool = True, active_content_only: bool = True,
include_draft: bool = False,
) -> list[ModuleContentRow]: ) -> list[ModuleContentRow]:
stmt = ( stmt = (
select(ModuleContent, ContentItem) select(ModuleContent, ContentItem)
@ -244,7 +256,15 @@ class ContentRepository:
) )
if active_content_only: 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( stmt = stmt.order_by(
ModuleContent.sort_order.asc(), ModuleContent.sort_order.asc(),
@ -274,6 +294,7 @@ class ContentRepository:
module_id: UUID, module_id: UUID,
content_id: UUID, content_id: UUID,
active_content_only: bool = True, active_content_only: bool = True,
include_draft: bool = False,
) -> ModuleContentRow | None: ) -> ModuleContentRow | None:
stmt = ( stmt = (
select(ModuleContent, ContentItem) select(ModuleContent, ContentItem)
@ -285,7 +306,15 @@ class ContentRepository:
) )
if active_content_only: 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) result = await session.execute(stmt)
row = result.one_or_none() row = result.one_or_none()
@ -307,6 +336,7 @@ class ContentRepository:
self, self,
*, *,
references: set[ContentReferenceLookup], references: set[ContentReferenceLookup],
include_draft: bool = False,
) -> dict[ContentReferenceLookup, ResolvedContentReference]: ) -> dict[ContentReferenceLookup, ResolvedContentReference]:
""" """
Resolve content_ref targets in one query. Resolve content_ref targets in one query.
@ -353,7 +383,17 @@ class ContentRepository:
Module.code.in_(module_codes), Module.code.in_(module_codes),
AttributeDefinitionSet.code.in_(template_codes), AttributeDefinitionSet.code.in_(template_codes),
ContentItem.is_active.is_(True), ContentItem.is_active.is_(True),
ContentItem.status.in_(
[RecordStatus.PUBLISHED, RecordStatus.DRAFT]
if include_draft
else [RecordStatus.PUBLISHED]
),
Module.is_active.is_(True), Module.is_active.is_(True),
Module.status.in_(
[ModuleStatus.ACTIVE, ModuleStatus.DRAFT]
if include_draft
else [ModuleStatus.ACTIVE]
),
AttributeDefinitionSet.is_active.is_(True), AttributeDefinitionSet.is_active.is_(True),
) )
.order_by( .order_by(
@ -428,10 +468,19 @@ class ContentRepository:
session: AsyncSession, session: AsyncSession,
content_id: UUID, content_id: UUID,
active_only: bool = True, active_only: bool = True,
include_draft: bool = False,
) -> ContentItem | None: ) -> ContentItem | None:
stmt = select(ContentItem).where(ContentItem.id == content_id) stmt = select(ContentItem).where(ContentItem.id == content_id)
if active_only: 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) result = await session.execute(stmt)
return result.scalar_one_or_none() return result.scalar_one_or_none()
@ -460,6 +509,7 @@ class ContentRepository:
module_id: UUID, module_id: UUID,
definition_set_id: UUID, definition_set_id: UUID,
active_content_only: bool = True, active_content_only: bool = True,
include_draft: bool = False,
) -> list[ModuleContentRow]: ) -> list[ModuleContentRow]:
""" """
Return all content that simultaneously: Return all content that simultaneously:
@ -494,8 +544,14 @@ class ContentRepository:
) )
if active_content_only: if active_content_only:
allowed_statuses = (
[RecordStatus.PUBLISHED, RecordStatus.DRAFT]
if include_draft
else [RecordStatus.PUBLISHED]
)
stmt = stmt.where( stmt = stmt.where(
ContentItem.is_active.is_(True) ContentItem.is_active.is_(True),
ContentItem.status.in_(allowed_statuses),
) )
stmt = stmt.order_by( stmt = stmt.order_by(
@ -1241,6 +1297,7 @@ class ContentRepository:
definition_set: DefinitionSetRecord, definition_set: DefinitionSetRecord,
presentation: PresentationRecord, presentation: PresentationRecord,
definitions: list[AttributeDefinitionRecord], definitions: list[AttributeDefinitionRecord],
include_draft: bool = False,
) -> tuple[int, list[SearchPageRow]]: ) -> tuple[int, list[SearchPageRow]]:
if presentation.presentation_mode != "collection": if presentation.presentation_mode != "collection":
raise TemplateNotCollectionError( raise TemplateNotCollectionError(
@ -1253,11 +1310,16 @@ class ContentRepository:
for definition in definitions for definition in definitions
} }
allowed_status_sql = (
"ci.status in ('published', 'draft')"
if include_draft
else "ci.status = 'published'"
)
where_parts = [ where_parts = [
"mc.module_id = :module_id", "mc.module_id = :module_id",
"ci.attribute_definition_set_id = :definition_set_id", "ci.attribute_definition_set_id = :definition_set_id",
"ci.is_active = true", "ci.is_active = true",
"ci.status = 'published'", allowed_status_sql,
] ]
params: dict[str, Any] = { params: dict[str, Any] = {
"module_id": module.id, "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.content_cache import ContentCache
from app.cache.invalidation import ContentCacheInvalidator from app.cache.invalidation import ContentCacheInvalidator
from app.db.models import ContentItem 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 ( from app.features.content.builder import (
AttributeCycleError, AttributeCycleError,
AttributeHierarchyError, AttributeHierarchyError,
@ -119,10 +119,11 @@ class ContentService:
self.search_projection_writer = search_projection_writer self.search_projection_writer = search_projection_writer
self.media_url_resolver = media_url_resolver 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: async def loader() -> ModuleListResponse:
modules = await self.repository.get_all_active_modules( modules = await self.repository.get_all_active_modules(
session=self.session session=self.session,
include_draft=preview,
) )
return ModuleListResponse( return ModuleListResponse(
modules=[ modules=[
@ -131,6 +132,9 @@ class ContentService:
] ]
) )
if preview:
return await loader()
cached = await self.cache.active_modules(loader=loader) cached = await self.cache.active_modules(loader=loader)
if isinstance(cached, ModuleListResponse): if isinstance(cached, ModuleListResponse):
@ -142,6 +146,7 @@ class ContentService:
self, self,
*, *,
request: ModuleRequest, request: ModuleRequest,
preview: bool = False,
) -> ModuleContentListResponse: ) -> ModuleContentListResponse:
module = await self.repository.resolve_module( module = await self.repository.resolve_module(
session=self.session, session=self.session,
@ -153,11 +158,20 @@ class ContentService:
if module is None: if module is None:
raise HTTPException(status_code=404, detail="Module not found") 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: async def loader() -> ModuleContentListResponse:
rows = await self.repository.get_module_contents( rows = await self.repository.get_module_contents(
session=self.session, session=self.session,
module_id=module.id, module_id=module.id,
active_content_only=True, active_content_only=True,
include_draft=preview,
) )
return ModuleContentListResponse( return ModuleContentListResponse(
@ -168,6 +182,9 @@ class ContentService:
], ],
) )
if preview:
return await loader()
cached = await self.cache.module_contents( cached = await self.cache.module_contents(
module_id=module.id, module_id=module.id,
loader=loader, loader=loader,
@ -182,6 +199,7 @@ class ContentService:
self, self,
*, *,
request: ModuleTemplateContentRequest, request: ModuleTemplateContentRequest,
preview: bool = False,
) -> ModuleTemplateContentResponse: ) -> ModuleTemplateContentResponse:
module = await self.repository.resolve_module( module = await self.repository.resolve_module(
session=self.session, session=self.session,
@ -193,6 +211,14 @@ class ContentService:
if module is None: if module is None:
raise HTTPException(status_code=404, detail="Module not found") 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( template = await self.repository.get_definition_set_by_code(
session=self.session, session=self.session,
template_code=request.template_code, template_code=request.template_code,
@ -208,6 +234,7 @@ class ContentService:
module_id=module.id, module_id=module.id,
definition_set_id=template.id, definition_set_id=template.id,
active_content_only=True, active_content_only=True,
include_draft=preview,
) )
return ModuleTemplateContentResponse( return ModuleTemplateContentResponse(
@ -219,6 +246,9 @@ class ContentService:
], ],
) )
if preview:
return await loader()
cached = await self.cache.module_template_contents( cached = await self.cache.module_template_contents(
module_id=module.id, module_id=module.id,
template_code=template.code, template_code=template.code,
@ -234,6 +264,7 @@ class ContentService:
self, self,
*, *,
request: ModuleTemplateContentRequest, request: ModuleTemplateContentRequest,
preview: bool = False,
) -> ModuleTemplateContentDetailResponse: ) -> ModuleTemplateContentDetailResponse:
module = await self.repository.resolve_module( module = await self.repository.resolve_module(
session=self.session, session=self.session,
@ -245,6 +276,14 @@ class ContentService:
if module is None: if module is None:
raise HTTPException(status_code=404, detail="Module not found") 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( template = await self.repository.get_definition_set_by_code(
session=self.session, session=self.session,
template_code=request.template_code, template_code=request.template_code,
@ -260,6 +299,7 @@ class ContentService:
module_id=module.id, module_id=module.id,
definition_set_id=template.id, definition_set_id=template.id,
active_content_only=True, active_content_only=True,
include_draft=preview,
) )
builder = ContentJsonBuilder(session=self.session) builder = ContentJsonBuilder(session=self.session)
@ -318,7 +358,8 @@ class ContentService:
try: try:
hydrated_payloads = await self._hydrate_content_reference_payloads( 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: except ContentReferenceResolutionError as exc:
raise HTTPException( raise HTTPException(
@ -335,6 +376,9 @@ class ContentService:
items=items, items=items,
) )
if preview:
stable_response = await loader()
else:
cached = await self.cache.module_template_details( cached = await self.cache.module_template_details(
module_id=module.id, module_id=module.id,
template_code=template.code, template_code=template.code,
@ -351,7 +395,18 @@ class ContentService:
async def get_content_json( async def get_content_json(
self, self,
content_id: UUID, content_id: UUID,
*,
preview: bool = False,
) -> dict[str, Any]: ) -> 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]: async def loader() -> dict[str, Any]:
builder = ContentJsonBuilder(session=self.session) builder = ContentJsonBuilder(session=self.session)
@ -364,7 +419,8 @@ class ContentService:
detail="Content builder returned invalid attributes", detail="Content builder returned invalid attributes",
) )
built["attributes"] = await self._hydrate_content_references( built["attributes"] = await self._hydrate_content_references(
attributes attributes,
preview=preview,
) )
return built return built
@ -391,6 +447,9 @@ class ContentService:
detail=f"Content reference structure is invalid: {exc}", detail=f"Content reference structure is invalid: {exc}",
) from exc ) from exc
if preview:
return await loader()
return await self.cache.content_detail( return await self.cache.content_detail(
content_id=content_id, content_id=content_id,
loader=loader, loader=loader,
@ -474,6 +533,7 @@ class ContentService:
*, *,
request: ModuleRequest, request: ModuleRequest,
content_id: UUID, content_id: UUID,
preview: bool = False,
) -> ContentDetailResponse: ) -> ContentDetailResponse:
module = await self.repository.resolve_module( module = await self.repository.resolve_module(
session=self.session, session=self.session,
@ -485,11 +545,20 @@ class ContentService:
if module is None: if module is None:
raise HTTPException(status_code=404, detail="Module not found") 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( association = await self.repository.get_module_content_by_content_id(
session=self.session, session=self.session,
module_id=module.id, module_id=module.id,
content_id=content_id, content_id=content_id,
active_content_only=True, active_content_only=True,
include_draft=preview,
) )
if association is None: if association is None:
@ -498,7 +567,7 @@ class ContentService:
detail="Content item was not found in the requested module", 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 {} dynamic_data = built.get("attributes") or {}
if not isinstance(dynamic_data, dict): if not isinstance(dynamic_data, dict):
@ -1056,6 +1125,8 @@ class ContentService:
async def search_contents( async def search_contents(
self, self,
request: ContentSearchRequest, request: ContentSearchRequest,
*,
preview: bool = False,
) -> ContentSearchResponse: ) -> ContentSearchResponse:
module = await self.repository.resolve_module( module = await self.repository.resolve_module(
session=self.session, session=self.session,
@ -1070,8 +1141,9 @@ class ContentService:
if hasattr(module.status, "value") if hasattr(module.status, "value")
else str(module.status) else str(module.status)
) )
if module_status != "active": allowed_module_statuses = {"active", "draft"} if preview else {"active"}
raise ModuleNotFoundError("Requested module is not active") if module_status not in allowed_module_statuses:
raise ModuleNotFoundError("Requested module is not available")
definition_set = ( definition_set = (
await self.repository.resolve_definition_set( await self.repository.resolve_definition_set(
request.template_code request.template_code
@ -1116,6 +1188,7 @@ class ContentService:
definition_set=definition_set, definition_set=definition_set,
presentation=presentation, presentation=presentation,
definitions=definitions, definitions=definitions,
include_draft=preview,
) )
attributes_by_content = ( attributes_by_content = (
@ -1131,7 +1204,8 @@ class ContentService:
] ]
try: try:
hydrated_payloads = await self._hydrate_content_reference_payloads( hydrated_payloads = await self._hydrate_content_reference_payloads(
ordered_payloads ordered_payloads,
preview=preview,
) )
except ContentReferenceResolutionError as exc: except ContentReferenceResolutionError as exc:
raise HTTPException( raise HTTPException(
@ -1165,13 +1239,20 @@ class ContentService:
async def _hydrate_content_references( async def _hydrate_content_references(
self, self,
payload: dict[str, Any], payload: dict[str, Any],
*,
preview: bool = False,
) -> dict[str, Any]: ) -> dict[str, Any]:
hydrated = await self._hydrate_content_reference_payloads([payload]) hydrated = await self._hydrate_content_reference_payloads(
[payload],
preview=preview,
)
return hydrated[0] return hydrated[0]
async def _hydrate_content_reference_payloads( async def _hydrate_content_reference_payloads(
self, self,
payloads: list[dict[str, Any]], payloads: list[dict[str, Any]],
*,
preview: bool = False,
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
"""Resolve all nested content_ref objects with one repository query.""" """Resolve all nested content_ref objects with one repository query."""
references: set[ContentReferenceLookup] = set() references: set[ContentReferenceLookup] = set()
@ -1185,7 +1266,8 @@ class ContentService:
] ]
resolved = await self.repository.resolve_content_reference_targets( resolved = await self.repository.resolve_content_reference_targets(
references=references references=references,
include_draft=preview,
) )
return [ return [
self._hydrate_reference_value(payload, resolved) self._hydrate_reference_value(payload, resolved)