1633 lines
56 KiB
Python
1633 lines
56 KiB
Python
from __future__ import annotations
|
|
|
|
import re
|
|
from datetime import datetime, timezone
|
|
from typing import Any
|
|
from uuid import UUID
|
|
|
|
from fastapi import HTTPException
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
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 ModuleStatus, RecordStatus
|
|
from app.features.content.builder import (
|
|
AttributeCycleError,
|
|
AttributeHierarchyError,
|
|
AttributeValueError,
|
|
ContentJsonBuilder,
|
|
ContentNotFoundError as BuilderContentNotFoundError,
|
|
DuplicateScalarAttributeError,
|
|
)
|
|
|
|
from .ports import SearchProjectionWriter
|
|
|
|
from .capabilities import (
|
|
is_sortable_definition,
|
|
operators_for_definition,
|
|
renderer_hint_for_definition,
|
|
)
|
|
|
|
from .domain import ContentReferenceLookup, ResolvedContentReference
|
|
|
|
from .repository import (
|
|
AttributeDefinitionMemberRow,
|
|
AttributeDefinitionRow,
|
|
ContentRepository,
|
|
ModuleContentRow,
|
|
TemplateInfo,
|
|
validate_content_for_publish,
|
|
)
|
|
from .schema import (
|
|
AttributeDefinitionResponse,
|
|
ContentDetailResponse,
|
|
ContentMediaResponse,
|
|
ContentItemResponse,
|
|
ContentListItemResponse,
|
|
ModuleContentItemResponse,
|
|
ModuleContentListResponse,
|
|
ModuleListResponse,
|
|
ModuleRequest,
|
|
ModuleResponse,
|
|
ModuleSummaryResponse,
|
|
ModuleTemplateContentDetailItem,
|
|
ModuleTemplateContentDetailResponse,
|
|
ModuleTemplateContentRequest,
|
|
ModuleTemplateContentResponse,
|
|
PublishContentResponse,
|
|
TemplateAttributeDefinitionsResponse,
|
|
TemplateSummaryResponse,
|
|
ContentSearchRequest,
|
|
ContentSearchResponse,
|
|
LogicalOperator,
|
|
SearchContentItem,
|
|
SearchFieldContract,
|
|
SearchProfileContract,
|
|
SearchOperator,
|
|
SortCriterion,
|
|
SortDirection,
|
|
SortFieldContract,
|
|
TemplateAttributePresentationContract,
|
|
TemplateContractResponse,
|
|
TemplatePresentationContract,
|
|
TemplateRendererContract,
|
|
EmptyBehavior,
|
|
AttributeVisibility,
|
|
ModuleContentSearchRequest,
|
|
ModuleContentSearchResponse,
|
|
ModuleSearchContentItem,
|
|
ModuleSearchContractResponse,
|
|
ModuleSearchFieldContract,
|
|
)
|
|
|
|
from .errors import (
|
|
PublishValidationError,
|
|
ContentAttributeHierarchyError,
|
|
ContentDefinitionSetError,
|
|
RequiredAttributeMissingError,
|
|
InvalidPresentationContractError,
|
|
ContentReferenceResolutionError,
|
|
ModuleNotFoundError,
|
|
TemplateNotInModuleError,
|
|
)
|
|
|
|
_MODULE_PREFIX_RE = re.compile(r"^(M\d+)_CT\d+$", re.IGNORECASE)
|
|
|
|
class InvalidContentStateError(Exception):
|
|
pass
|
|
|
|
|
|
class ContentService:
|
|
def __init__(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
repository: ContentRepository,
|
|
cache: ContentCache,
|
|
invalidator: ContentCacheInvalidator,
|
|
search_projection_writer: SearchProjectionWriter,
|
|
media_url_resolver: MediaUrlResolver | None = None,
|
|
) -> None:
|
|
self.session = session
|
|
self.repository = repository
|
|
self.cache = cache
|
|
self.invalidator = invalidator
|
|
self.search_projection_writer = search_projection_writer
|
|
self.media_url_resolver = media_url_resolver
|
|
|
|
async def get_modules(self, *, preview: bool = False) -> ModuleListResponse:
|
|
async def loader() -> ModuleListResponse:
|
|
modules = await self.repository.get_all_active_modules(
|
|
session=self.session,
|
|
include_draft=preview,
|
|
)
|
|
return ModuleListResponse(
|
|
modules=[
|
|
ModuleResponse.model_validate(module)
|
|
for module in modules
|
|
]
|
|
)
|
|
|
|
if preview:
|
|
return await loader()
|
|
|
|
cached = await self.cache.active_modules(loader=loader)
|
|
|
|
if isinstance(cached, ModuleListResponse):
|
|
return cached
|
|
|
|
return ModuleListResponse.model_validate(cached)
|
|
|
|
async def get_module_contents(
|
|
self,
|
|
*,
|
|
request: ModuleRequest,
|
|
preview: bool = False,
|
|
) -> ModuleContentListResponse:
|
|
module = await self.repository.resolve_module(
|
|
session=self.session,
|
|
module_id=request.module_id,
|
|
module_code=request.module_code,
|
|
active_only=True,
|
|
)
|
|
|
|
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(
|
|
module=ModuleSummaryResponse.model_validate(module),
|
|
items=[
|
|
self._module_content_item_response(row)
|
|
for row in rows
|
|
],
|
|
)
|
|
|
|
if preview:
|
|
return await loader()
|
|
|
|
cached = await self.cache.module_contents(
|
|
module_id=module.id,
|
|
loader=loader,
|
|
)
|
|
|
|
if isinstance(cached, ModuleContentListResponse):
|
|
return cached
|
|
|
|
return ModuleContentListResponse.model_validate(cached)
|
|
|
|
async def get_module_contents_by_template(
|
|
self,
|
|
*,
|
|
request: ModuleTemplateContentRequest,
|
|
preview: bool = False,
|
|
) -> ModuleTemplateContentResponse:
|
|
module = await self.repository.resolve_module(
|
|
session=self.session,
|
|
module_id=request.module_id,
|
|
module_code=request.module_code,
|
|
active_only=True,
|
|
)
|
|
|
|
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,
|
|
active_only=True,
|
|
)
|
|
|
|
if template is None:
|
|
raise HTTPException(status_code=404, detail="Template not found")
|
|
|
|
async def loader() -> ModuleTemplateContentResponse:
|
|
rows = await self.repository.get_module_contents_by_template(
|
|
session=self.session,
|
|
module_id=module.id,
|
|
definition_set_id=template.id,
|
|
active_content_only=True,
|
|
include_draft=preview,
|
|
)
|
|
|
|
return ModuleTemplateContentResponse(
|
|
module=ModuleSummaryResponse.model_validate(module),
|
|
template=self._template_summary_response(template),
|
|
items=[
|
|
self._content_list_item_response(row.content)
|
|
for row in rows
|
|
],
|
|
)
|
|
|
|
if preview:
|
|
return await loader()
|
|
|
|
cached = await self.cache.module_template_contents(
|
|
module_id=module.id,
|
|
template_code=template.code,
|
|
loader=loader,
|
|
)
|
|
|
|
if isinstance(cached, ModuleTemplateContentResponse):
|
|
return cached
|
|
|
|
return ModuleTemplateContentResponse.model_validate(cached)
|
|
|
|
async def get_module_content_details_by_template(
|
|
self,
|
|
*,
|
|
request: ModuleTemplateContentRequest,
|
|
preview: bool = False,
|
|
) -> ModuleTemplateContentDetailResponse:
|
|
module = await self.repository.resolve_module(
|
|
session=self.session,
|
|
module_id=request.module_id,
|
|
module_code=request.module_code,
|
|
active_only=True,
|
|
)
|
|
|
|
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,
|
|
active_only=True,
|
|
)
|
|
|
|
if template is None:
|
|
raise HTTPException(status_code=404, detail="Template not found")
|
|
|
|
async def loader() -> ModuleTemplateContentDetailResponse:
|
|
rows = await self.repository.get_module_contents_by_template(
|
|
session=self.session,
|
|
module_id=module.id,
|
|
definition_set_id=template.id,
|
|
active_content_only=True,
|
|
include_draft=preview,
|
|
)
|
|
|
|
builder = ContentJsonBuilder(session=self.session)
|
|
media_by_content = await self.repository.get_content_media_for_content_ids(
|
|
session=self.session,
|
|
content_ids=[row.content.id for row in rows],
|
|
)
|
|
items: list[ModuleTemplateContentDetailItem] = []
|
|
|
|
for row in rows:
|
|
try:
|
|
built = await builder.build_content_json(row.content.id)
|
|
except BuilderContentNotFoundError as exc:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail=str(exc),
|
|
) from exc
|
|
except (
|
|
AttributeHierarchyError,
|
|
AttributeCycleError,
|
|
AttributeValueError,
|
|
DuplicateScalarAttributeError,
|
|
) as exc:
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail=(
|
|
"Content attribute structure is invalid "
|
|
f"for content {row.content.id}"
|
|
),
|
|
) from exc
|
|
|
|
dynamic_data = built.get("attributes") or {}
|
|
if not isinstance(dynamic_data, dict):
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail=(
|
|
"Content builder returned invalid "
|
|
f"attributes for content {row.content.id}"
|
|
),
|
|
)
|
|
|
|
items.append(
|
|
ModuleTemplateContentDetailItem(
|
|
module_content_sort_order=row.sort_order,
|
|
is_highlighted=row.is_highlighted,
|
|
content=ContentItemResponse.model_validate(
|
|
row.content
|
|
),
|
|
data=dynamic_data,
|
|
media=[
|
|
self._media_response(media_row)
|
|
for media_row in media_by_content.get(row.content.id, [])
|
|
],
|
|
)
|
|
)
|
|
|
|
try:
|
|
hydrated_payloads = await self._hydrate_content_reference_payloads(
|
|
[item.data for item in items],
|
|
preview=preview,
|
|
)
|
|
except ContentReferenceResolutionError as exc:
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail=f"Content reference structure is invalid: {exc}",
|
|
) from exc
|
|
|
|
for item, hydrated_data in zip(items, hydrated_payloads, strict=True):
|
|
item.data = hydrated_data
|
|
|
|
# Inherit media from referenced content items when direct media is absent
|
|
items_needing_media: list[
|
|
tuple[ModuleTemplateContentDetailItem, list[tuple[UUID, str | None]]]
|
|
] = []
|
|
all_ref_ids: set[UUID] = set()
|
|
for item in items:
|
|
if not item.media:
|
|
refs: list[tuple[UUID, str | None]] = []
|
|
self._extract_referenced_content_items(item.data, refs)
|
|
if refs:
|
|
items_needing_media.append((item, refs))
|
|
all_ref_ids.update(cid for cid, _ in refs)
|
|
|
|
if items_needing_media and all_ref_ids:
|
|
ref_media_by_content = (
|
|
await self.repository.get_content_media_for_content_ids(
|
|
session=self.session,
|
|
content_ids=list(all_ref_ids),
|
|
)
|
|
)
|
|
for item, refs in items_needing_media:
|
|
inherited: list[ContentMediaResponse] = []
|
|
for cid, label in refs:
|
|
for row in ref_media_by_content.get(cid, []):
|
|
row_copy = dict(row)
|
|
if label:
|
|
row_copy["caption"] = label
|
|
row_copy["alt_text"] = label
|
|
row_copy["media_role"] = "gallery"
|
|
row_copy["sort_order"] = len(inherited)
|
|
inherited.append(self._media_response(row_copy))
|
|
item.media = inherited
|
|
|
|
return ModuleTemplateContentDetailResponse(
|
|
module=ModuleSummaryResponse.model_validate(module),
|
|
template=self._template_summary_response(template),
|
|
items=items,
|
|
)
|
|
|
|
if preview:
|
|
stable_response = await loader()
|
|
else:
|
|
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)
|
|
|
|
try:
|
|
built = await builder.build_content_json(content_id)
|
|
attributes = built.get("attributes") or {}
|
|
if not isinstance(attributes, dict):
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail="Content builder returned invalid attributes",
|
|
)
|
|
built["attributes"] = await self._hydrate_content_references(
|
|
attributes,
|
|
preview=preview,
|
|
)
|
|
return built
|
|
|
|
except BuilderContentNotFoundError as exc:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail=str(exc),
|
|
) from exc
|
|
|
|
except (
|
|
AttributeHierarchyError,
|
|
AttributeCycleError,
|
|
AttributeValueError,
|
|
DuplicateScalarAttributeError,
|
|
) as exc:
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail="Content attribute structure is invalid",
|
|
) from exc
|
|
|
|
except ContentReferenceResolutionError as exc:
|
|
raise HTTPException(
|
|
status_code=500,
|
|
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,
|
|
)
|
|
|
|
|
|
@staticmethod
|
|
def _media_response(row: dict[str, Any]) -> ContentMediaResponse:
|
|
"""
|
|
Build the stable/cache-safe media projection.
|
|
|
|
Permanent http(s) file_path values may be returned directly. Object
|
|
storage keys deliberately remain unsigned here so cached content never
|
|
contains an expiring presigned URL.
|
|
"""
|
|
file_path = str(row.get("file_path") or "").strip()
|
|
direct_url = (
|
|
file_path
|
|
if file_path.startswith(("https://", "http://"))
|
|
else None
|
|
)
|
|
|
|
return ContentMediaResponse(
|
|
id=row["id"],
|
|
media_asset_id=row["media_asset_id"],
|
|
media_role=str(row.get("media_role") or "gallery"),
|
|
usage_type=str(row.get("usage_type") or "general"),
|
|
sort_order=int(row.get("sort_order") or 0),
|
|
caption=row.get("caption"),
|
|
alt_text=row.get("alt_text"),
|
|
mime_type=row.get("mime_type"),
|
|
width=row.get("width"),
|
|
height=row.get("height"),
|
|
storage_key=row.get("storage_key"),
|
|
url=direct_url,
|
|
requires_auth=False,
|
|
)
|
|
|
|
async def _hydrate_media_urls(
|
|
self,
|
|
media: list[ContentMediaResponse],
|
|
) -> list[ContentMediaResponse]:
|
|
"""Attach fresh presigned URLs after cache retrieval."""
|
|
hydrated = [item.model_copy(deep=True) for item in media]
|
|
if not hydrated or self.media_url_resolver is None:
|
|
return hydrated
|
|
|
|
keys = [
|
|
item.storage_key.strip()
|
|
for item in hydrated
|
|
if not item.url and item.storage_key and item.storage_key.strip()
|
|
]
|
|
if not keys:
|
|
return hydrated
|
|
|
|
signed = await self.media_url_resolver.resolve_many(keys)
|
|
for item in hydrated:
|
|
key = item.storage_key.strip() if item.storage_key else None
|
|
if not item.url and key:
|
|
item.url = signed.get(key)
|
|
# A presigned object-store URL authenticates through its query
|
|
# signature; the mobile client must not attach the API bearer
|
|
# token to the MinIO/S3 request.
|
|
item.requires_auth = False
|
|
|
|
return hydrated
|
|
|
|
async def _hydrate_template_detail_media(
|
|
self,
|
|
response: ModuleTemplateContentDetailResponse,
|
|
) -> ModuleTemplateContentDetailResponse:
|
|
# Deep-copy because the cache implementation may return a live model
|
|
# instance. Never mutate cache-resident objects with expiring URLs.
|
|
hydrated = response.model_copy(deep=True)
|
|
for item in hydrated.items:
|
|
item.media = await self._hydrate_media_urls(item.media)
|
|
return hydrated
|
|
|
|
async def get_module_content_detail(
|
|
self,
|
|
*,
|
|
request: ModuleRequest,
|
|
content_id: UUID,
|
|
preview: bool = False,
|
|
) -> ContentDetailResponse:
|
|
module = await self.repository.resolve_module(
|
|
session=self.session,
|
|
module_id=request.module_id,
|
|
module_code=request.module_code,
|
|
active_only=True,
|
|
)
|
|
|
|
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:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="Content item was not found in the requested module",
|
|
)
|
|
|
|
built = await self.get_content_json(content_id, preview=preview)
|
|
dynamic_data = built.get("attributes") or {}
|
|
|
|
if not isinstance(dynamic_data, dict):
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail="Invalid reconstructed content data",
|
|
)
|
|
|
|
media_rows = await self.repository.get_content_media(
|
|
session=self.session,
|
|
content_id=content_id,
|
|
)
|
|
|
|
if not media_rows:
|
|
referenced_items: list[tuple[UUID, str | None]] = []
|
|
self._extract_referenced_content_items(dynamic_data, referenced_items)
|
|
if referenced_items:
|
|
ref_ids = [cid for cid, _ in referenced_items]
|
|
media_by_content = (
|
|
await self.repository.get_content_media_for_content_ids(
|
|
session=self.session,
|
|
content_ids=ref_ids,
|
|
)
|
|
)
|
|
inherited_rows: list[dict[str, Any]] = []
|
|
for cid, label in referenced_items:
|
|
rows = media_by_content.get(cid, [])
|
|
for r in rows:
|
|
row_copy = dict(r)
|
|
if label:
|
|
row_copy["caption"] = label
|
|
row_copy["alt_text"] = label
|
|
row_copy["media_role"] = "gallery"
|
|
row_copy["sort_order"] = len(inherited_rows)
|
|
inherited_rows.append(row_copy)
|
|
media_rows = inherited_rows
|
|
|
|
response = ContentDetailResponse(
|
|
module=ModuleSummaryResponse.model_validate(module),
|
|
content=ContentItemResponse.model_validate(
|
|
association.content
|
|
),
|
|
data=dynamic_data,
|
|
media=[self._media_response(row) for row in media_rows],
|
|
)
|
|
response.media = await self._hydrate_media_urls(response.media)
|
|
return response
|
|
|
|
async def get_template_attribute_definitions(
|
|
self,
|
|
*,
|
|
template_code: str,
|
|
) -> TemplateAttributeDefinitionsResponse:
|
|
normalized_code = template_code.strip()
|
|
|
|
if not normalized_code:
|
|
raise HTTPException(
|
|
status_code=422,
|
|
detail="template_code is required",
|
|
)
|
|
|
|
async def loader() -> TemplateAttributeDefinitionsResponse:
|
|
template = await self.repository.get_definition_set_by_code(
|
|
session=self.session,
|
|
template_code=normalized_code,
|
|
active_only=True,
|
|
)
|
|
|
|
if template is None:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="Template not found",
|
|
)
|
|
|
|
definitions = await self.repository.get_attribute_definitions_by_set(
|
|
session=self.session,
|
|
definition_set_id=template.id,
|
|
active_only=True,
|
|
)
|
|
|
|
members = await self.repository.get_attribute_definition_members(
|
|
session=self.session,
|
|
definition_set_id=template.id,
|
|
)
|
|
|
|
return self._build_definition_response(
|
|
template=template,
|
|
definitions=definitions,
|
|
members=members,
|
|
)
|
|
|
|
cached = await self.cache.template_definitions(
|
|
template_code=normalized_code,
|
|
loader=loader,
|
|
)
|
|
|
|
if isinstance(cached, TemplateAttributeDefinitionsResponse):
|
|
return cached
|
|
|
|
return TemplateAttributeDefinitionsResponse.model_validate(cached)
|
|
|
|
async def publish_content(
|
|
self,
|
|
*,
|
|
content_id: UUID,
|
|
actor_id: UUID,
|
|
) -> PublishContentResponse:
|
|
stmt = (
|
|
select(ContentItem)
|
|
.where(ContentItem.id == content_id)
|
|
.with_for_update()
|
|
)
|
|
|
|
result = await self.session.execute(stmt)
|
|
content = result.scalar_one_or_none()
|
|
|
|
if content is None:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail=f"Content item not found: {content_id}",
|
|
)
|
|
|
|
if content.status != RecordStatus.DRAFT:
|
|
current_status = (
|
|
content.status.value
|
|
if hasattr(content.status, "value")
|
|
else str(content.status)
|
|
)
|
|
|
|
raise HTTPException(
|
|
status_code=409,
|
|
detail=(
|
|
"Content cannot be published from "
|
|
f"status {current_status!r}"
|
|
),
|
|
)
|
|
|
|
try:
|
|
await validate_content_for_publish(
|
|
session=self.session,
|
|
content_id=content_id,
|
|
)
|
|
except (
|
|
ContentDefinitionSetError,
|
|
RequiredAttributeMissingError,
|
|
ContentAttributeHierarchyError,
|
|
PublishValidationError,
|
|
) as exc:
|
|
raise HTTPException(
|
|
status_code=422,
|
|
detail=str(exc),
|
|
) from exc
|
|
|
|
content.status = RecordStatus.PUBLISHED
|
|
content.published_at = datetime.now(timezone.utc)
|
|
content.updated_by = actor_id
|
|
|
|
await self.session.flush()
|
|
|
|
# Search is a derived projection, never an authoring source of truth.
|
|
# Rebuild inside the same transaction so a successfully published row
|
|
# and its search projection become visible atomically at commit time.
|
|
await self.search_projection_writer.rebuild_content_projection(content_id)
|
|
|
|
return PublishContentResponse.model_validate(content)
|
|
|
|
async def invalidate_after_content_commit(
|
|
self,
|
|
*,
|
|
content_id: UUID,
|
|
) -> None:
|
|
context = await self.repository.get_content_cache_context(
|
|
session=self.session,
|
|
content_id=content_id,
|
|
)
|
|
|
|
if context is None:
|
|
await self.invalidator.invalidate_content(
|
|
content_id=content_id
|
|
)
|
|
return
|
|
|
|
await self.invalidator.invalidate_content_change(
|
|
content_id=content_id,
|
|
module_ids=set(context.module_ids),
|
|
template_code=context.template_code,
|
|
)
|
|
|
|
async def get_template_contract(
|
|
self,
|
|
*,
|
|
template_code: str,
|
|
client_type: str = "mobile",
|
|
) -> TemplateContractResponse:
|
|
normalized_client = client_type.strip().lower()
|
|
definition_set = (
|
|
await self.repository.resolve_definition_set(
|
|
template_code
|
|
)
|
|
)
|
|
presentation = (
|
|
await self.repository.get_active_presentation(
|
|
definition_set=definition_set,
|
|
client_type=normalized_client,
|
|
)
|
|
)
|
|
|
|
if (
|
|
presentation.presentation_mode == "collection"
|
|
and (
|
|
not presentation.collection_renderer
|
|
or not presentation.collection_item_renderer
|
|
)
|
|
):
|
|
raise InvalidPresentationContractError(
|
|
f"Collection presentation for {definition_set.code!r} "
|
|
"is missing collection renderer codes"
|
|
)
|
|
|
|
if (
|
|
presentation.presentation_mode == "single"
|
|
and (
|
|
presentation.collection_renderer is not None
|
|
or presentation.collection_item_renderer is not None
|
|
)
|
|
):
|
|
raise InvalidPresentationContractError(
|
|
f"Single presentation for {definition_set.code!r} "
|
|
"must not define collection renderer codes"
|
|
)
|
|
|
|
definitions = (
|
|
await self.repository.load_active_definitions(
|
|
definition_set.id
|
|
)
|
|
)
|
|
|
|
attribute_presentations = (
|
|
await self.repository.load_attribute_presentations(
|
|
presentation_contract_id=presentation.id,
|
|
)
|
|
)
|
|
|
|
if presentation.attribute_definition_set_id != definition_set.id:
|
|
raise InvalidPresentationContractError(
|
|
"Presentation contract definition-set mismatch: "
|
|
f"contract={presentation.id}, "
|
|
f"contract_definition_set={presentation.attribute_definition_set_id}, "
|
|
f"resolved_definition_set={definition_set.id}"
|
|
)
|
|
|
|
if presentation.client_type.strip().lower() != normalized_client:
|
|
raise InvalidPresentationContractError(
|
|
"Presentation contract client mismatch: "
|
|
f"contract={presentation.id}, "
|
|
f"persisted_client={presentation.client_type!r}, "
|
|
f"requested_client={normalized_client!r}"
|
|
)
|
|
|
|
definition_ids = {definition.id for definition in definitions}
|
|
definition_keys = {definition.attribute_key for definition in definitions}
|
|
|
|
seen_attribute_ids: set[UUID] = set()
|
|
seen_attribute_keys: set[str] = set()
|
|
effective_attribute_presentations: list[
|
|
TemplateAttributePresentationContract
|
|
] = []
|
|
|
|
overrides_by_definition_id = {
|
|
item.attribute_definition_id: item
|
|
for item in attribute_presentations
|
|
}
|
|
|
|
if len(overrides_by_definition_id) != len(attribute_presentations):
|
|
raise InvalidPresentationContractError(
|
|
"Duplicate attribute presentation overrides found for "
|
|
f"presentation contract {presentation.id}"
|
|
)
|
|
|
|
for override in attribute_presentations:
|
|
if override.presentation_contract_id != presentation.id:
|
|
raise InvalidPresentationContractError(
|
|
"Attribute presentation contract mismatch for "
|
|
f"attribute {override.attribute_key!r}"
|
|
)
|
|
if override.attribute_definition_set_id != definition_set.id:
|
|
raise InvalidPresentationContractError(
|
|
"Attribute presentation references an attribute from a "
|
|
"different definition set: "
|
|
f"attribute={override.attribute_key!r}"
|
|
)
|
|
if override.attribute_definition_id not in definition_ids:
|
|
raise InvalidPresentationContractError(
|
|
"Attribute presentation references an inactive or unknown "
|
|
"attribute definition: "
|
|
f"attribute={override.attribute_key!r}"
|
|
)
|
|
if override.attribute_key not in definition_keys:
|
|
raise InvalidPresentationContractError(
|
|
"Attribute presentation key does not belong to the resolved "
|
|
f"template: attribute={override.attribute_key!r}"
|
|
)
|
|
if override.attribute_definition_id in seen_attribute_ids:
|
|
raise InvalidPresentationContractError(
|
|
"Duplicate attribute presentation definition id: "
|
|
f"{override.attribute_definition_id}"
|
|
)
|
|
if override.attribute_key in seen_attribute_keys:
|
|
raise InvalidPresentationContractError(
|
|
"Duplicate attribute presentation key: "
|
|
f"{override.attribute_key!r}"
|
|
)
|
|
|
|
seen_attribute_ids.add(override.attribute_definition_id)
|
|
seen_attribute_keys.add(override.attribute_key)
|
|
|
|
# Return an effective rule for every active attribute. Persisted
|
|
# overrides win; otherwise the deterministic default is `hide`.
|
|
for definition in definitions:
|
|
override = overrides_by_definition_id.get(definition.id)
|
|
if override is None:
|
|
effective_attribute_presentations.append(
|
|
TemplateAttributePresentationContract(
|
|
attribute_key=definition.attribute_key,
|
|
visibility=AttributeVisibility.SHOW,
|
|
empty_behavior=EmptyBehavior.HIDE,
|
|
empty_text=None,
|
|
)
|
|
)
|
|
continue
|
|
|
|
try:
|
|
empty_behavior = EmptyBehavior(override.empty_behavior)
|
|
except ValueError as exc:
|
|
raise InvalidPresentationContractError(
|
|
"Unsupported empty_behavior "
|
|
f"{override.empty_behavior!r} for "
|
|
f"{override.attribute_key!r}"
|
|
) from exc
|
|
|
|
if (
|
|
empty_behavior == EmptyBehavior.HIDE
|
|
and override.empty_text is not None
|
|
and override.empty_text.strip()
|
|
):
|
|
raise InvalidPresentationContractError(
|
|
"empty_text is only valid with empty_behavior='show': "
|
|
f"attribute={override.attribute_key!r}"
|
|
)
|
|
|
|
visibility_raw = str(
|
|
(override.metadata_json or {}).get("visibility", "show")
|
|
).strip().lower()
|
|
try:
|
|
visibility = AttributeVisibility(visibility_raw)
|
|
except ValueError as exc:
|
|
raise InvalidPresentationContractError(
|
|
"Unsupported visibility "
|
|
f"{visibility_raw!r} for {override.attribute_key!r}"
|
|
) from exc
|
|
|
|
display_order_raw = (override.metadata_json or {}).get("display_order")
|
|
display_order: int | None
|
|
if (
|
|
isinstance(display_order_raw, int)
|
|
and not isinstance(display_order_raw, bool)
|
|
and display_order_raw >= 0
|
|
):
|
|
display_order = display_order_raw
|
|
else:
|
|
display_order = None
|
|
|
|
effective_attribute_presentations.append(
|
|
TemplateAttributePresentationContract(
|
|
attribute_key=override.attribute_key,
|
|
visibility=visibility,
|
|
empty_behavior=empty_behavior,
|
|
empty_text=override.empty_text,
|
|
display_order=display_order,
|
|
)
|
|
)
|
|
|
|
if presentation.presentation_mode == "single":
|
|
search_profile = SearchProfileContract(
|
|
free_text_enabled=False,
|
|
default_logic=LogicalOperator.AND,
|
|
fields=[],
|
|
sort_fields=[],
|
|
default_sort=[],
|
|
)
|
|
else:
|
|
filter_fields = []
|
|
for definition in definitions:
|
|
if (
|
|
not definition.is_filterable
|
|
or definition.definition_kind != "scalar"
|
|
):
|
|
continue
|
|
operators = operators_for_definition(definition)
|
|
if not operators:
|
|
continue
|
|
filter_fields.append(
|
|
SearchFieldContract(
|
|
attribute_key=definition.attribute_key,
|
|
label=definition.attribute_label,
|
|
operators=operators,
|
|
renderer_hint=renderer_hint_for_definition(
|
|
definition
|
|
),
|
|
allowed_values=definition.allowed_values,
|
|
)
|
|
)
|
|
|
|
sort_fields = [
|
|
SortFieldContract(
|
|
field="module_sort_order",
|
|
label="Display Order",
|
|
),
|
|
SortFieldContract(
|
|
field="title",
|
|
label="Title",
|
|
),
|
|
]
|
|
for definition in definitions:
|
|
if (
|
|
is_sortable_definition(definition)
|
|
and (
|
|
definition.is_searchable
|
|
or definition.is_filterable
|
|
)
|
|
):
|
|
sort_fields.append(
|
|
SortFieldContract(
|
|
field=definition.attribute_key,
|
|
label=definition.attribute_label,
|
|
)
|
|
)
|
|
|
|
search_profile = SearchProfileContract(
|
|
# Title/summary are system search fields, so collection
|
|
# templates always support free-text search. Attribute values
|
|
# additionally participate when is_searchable=true.
|
|
free_text_enabled=True,
|
|
default_logic=LogicalOperator.AND,
|
|
fields=filter_fields,
|
|
sort_fields=sort_fields,
|
|
default_sort=[
|
|
SortCriterion(
|
|
field="module_sort_order",
|
|
direction=SortDirection.ASC,
|
|
)
|
|
],
|
|
)
|
|
|
|
module_code = self._derive_module_code(
|
|
definition_set.code
|
|
)
|
|
|
|
return TemplateContractResponse(
|
|
template_code=definition_set.code,
|
|
module_code=module_code,
|
|
presentation=TemplatePresentationContract(
|
|
mode=presentation.presentation_mode,
|
|
renderers=TemplateRendererContract(
|
|
collection=presentation.collection_renderer,
|
|
collection_item=presentation.collection_item_renderer,
|
|
detail=presentation.detail_renderer,
|
|
),
|
|
attributes=effective_attribute_presentations,
|
|
),
|
|
search=search_profile,
|
|
)
|
|
|
|
|
|
async def get_module_search_contract(
|
|
self,
|
|
*,
|
|
module_code: str,
|
|
client_type: str = "mobile",
|
|
) -> ModuleSearchContractResponse:
|
|
module = await self.repository.resolve_module(
|
|
session=self.session,
|
|
module_code=module_code,
|
|
active_only=True,
|
|
)
|
|
if module is None:
|
|
raise ModuleNotFoundError("Requested active module was not found")
|
|
|
|
definitions = await self.repository.get_module_search_definitions(
|
|
module_id=module.id,
|
|
client_type=client_type,
|
|
)
|
|
fields = []
|
|
for definition in definitions:
|
|
operators = operators_for_definition(definition) if definition.is_filterable else []
|
|
searchable = (
|
|
definition.is_searchable
|
|
and definition.data_type in {"text", "rich_text"}
|
|
)
|
|
if not searchable and not operators:
|
|
continue
|
|
if SearchOperator.CONTAINS in operators:
|
|
default_operator = SearchOperator.CONTAINS
|
|
elif SearchOperator.EQ in operators:
|
|
default_operator = SearchOperator.EQ
|
|
elif operators:
|
|
default_operator = operators[0]
|
|
else:
|
|
default_operator = None
|
|
|
|
fields.append(
|
|
ModuleSearchFieldContract(
|
|
attribute_key=definition.attribute_key,
|
|
label=definition.attribute_label,
|
|
template_code=definition.template_code,
|
|
template_name=definition.template_name,
|
|
data_type=definition.data_type,
|
|
is_searchable=searchable,
|
|
is_filterable=bool(operators),
|
|
operators=operators,
|
|
default_operator=default_operator,
|
|
renderer_hint=renderer_hint_for_definition(definition),
|
|
allowed_values=definition.allowed_values,
|
|
)
|
|
)
|
|
|
|
return ModuleSearchContractResponse(
|
|
module_code=module.code,
|
|
fields=fields,
|
|
sort_fields=[
|
|
SortFieldContract(field="module_sort_order", label="Display Order"),
|
|
SortFieldContract(field="title", label="Title"),
|
|
],
|
|
default_sort=[
|
|
SortCriterion(field="module_sort_order", direction=SortDirection.ASC)
|
|
],
|
|
)
|
|
|
|
async def search_module_contents(
|
|
self,
|
|
request: ModuleContentSearchRequest,
|
|
) -> ModuleContentSearchResponse:
|
|
module = await self.repository.resolve_module(
|
|
session=self.session,
|
|
module_id=request.module_id,
|
|
module_code=request.module_code,
|
|
active_only=True,
|
|
)
|
|
if module is None:
|
|
raise ModuleNotFoundError("Requested active module was not found")
|
|
|
|
definitions = await self.repository.get_module_search_definitions(
|
|
module_id=module.id,
|
|
client_type="mobile",
|
|
)
|
|
total, rows = await self.repository.search_module(
|
|
request=request,
|
|
module=module,
|
|
definitions=definitions,
|
|
)
|
|
return ModuleContentSearchResponse(
|
|
page=request.page,
|
|
page_size=request.page_size,
|
|
total=total,
|
|
items=[
|
|
ModuleSearchContentItem(
|
|
id=row.id,
|
|
template_code=row.template_code,
|
|
template_name=row.template_name,
|
|
content_kind=row.content_kind,
|
|
title=row.title,
|
|
slug=row.slug,
|
|
summary=row.summary,
|
|
)
|
|
for row in rows
|
|
],
|
|
)
|
|
|
|
async def search_contents(
|
|
self,
|
|
request: ContentSearchRequest,
|
|
*,
|
|
preview: bool = False,
|
|
) -> ContentSearchResponse:
|
|
module = await self.repository.resolve_module(
|
|
session=self.session,
|
|
module_id=request.module_id,
|
|
module_code=request.module_code,
|
|
active_only=True,
|
|
)
|
|
if module is None:
|
|
raise ModuleNotFoundError("Requested active module was not found")
|
|
module_status = (
|
|
module.status.value
|
|
if hasattr(module.status, "value")
|
|
else str(module.status)
|
|
)
|
|
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
|
|
)
|
|
)
|
|
|
|
derived_module_code = self._derive_module_code(
|
|
definition_set.code
|
|
)
|
|
if (
|
|
derived_module_code is not None
|
|
and derived_module_code.lower() != module.code.lower()
|
|
):
|
|
# Prevent a caller from using a template from M0002 against M0001
|
|
# even if content associations have been accidentally corrupted.
|
|
raise TemplateNotInModuleError(
|
|
f"Template {definition_set.code!r} belongs to "
|
|
f"{derived_module_code!r}, not {module.code!r}"
|
|
)
|
|
|
|
await self.repository.assert_template_has_module_content(
|
|
module_id=module.id,
|
|
definition_set_id=definition_set.id,
|
|
template_code=definition_set.code,
|
|
)
|
|
|
|
presentation = (
|
|
await self.repository.get_active_presentation(
|
|
definition_set=definition_set,
|
|
client_type="mobile",
|
|
)
|
|
)
|
|
definitions = (
|
|
await self.repository.load_active_definitions(
|
|
definition_set.id
|
|
)
|
|
)
|
|
|
|
total, rows = await self.repository.search(
|
|
request=request,
|
|
module=module,
|
|
definition_set=definition_set,
|
|
presentation=presentation,
|
|
definitions=definitions,
|
|
include_draft=preview,
|
|
)
|
|
|
|
attributes_by_content = (
|
|
await self.repository.build_attributes_for_content_ids(
|
|
definition_set_id=definition_set.id,
|
|
content_ids=[row.id for row in rows],
|
|
)
|
|
)
|
|
|
|
ordered_payloads = [
|
|
attributes_by_content.get(row.id, {})
|
|
for row in rows
|
|
]
|
|
try:
|
|
hydrated_payloads = await self._hydrate_content_reference_payloads(
|
|
ordered_payloads,
|
|
preview=preview,
|
|
)
|
|
except ContentReferenceResolutionError as exc:
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail=f"Content reference structure is invalid: {exc}",
|
|
) from exc
|
|
hydrated_by_content = {
|
|
row.id: payload
|
|
for row, payload in zip(rows, hydrated_payloads, strict=True)
|
|
}
|
|
|
|
return ContentSearchResponse(
|
|
page=request.page,
|
|
page_size=request.page_size,
|
|
total=total,
|
|
items=[
|
|
SearchContentItem(
|
|
id=row.id,
|
|
content_kind=row.content_kind,
|
|
title=row.title,
|
|
slug=row.slug,
|
|
summary=row.summary,
|
|
attributes=hydrated_by_content.get(
|
|
row.id, {}
|
|
),
|
|
)
|
|
for row in rows
|
|
],
|
|
)
|
|
|
|
async def _hydrate_content_references(
|
|
self,
|
|
payload: dict[str, Any],
|
|
*,
|
|
preview: bool = False,
|
|
) -> dict[str, Any]:
|
|
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()
|
|
for payload in payloads:
|
|
self._collect_content_reference_lookups(payload, references)
|
|
|
|
if not references:
|
|
return [
|
|
self._hydrate_reference_value(payload, {})
|
|
for payload in payloads
|
|
]
|
|
|
|
resolved = await self.repository.resolve_content_reference_targets(
|
|
references=references,
|
|
include_draft=preview,
|
|
)
|
|
return [
|
|
self._hydrate_reference_value(payload, resolved)
|
|
for payload in payloads
|
|
]
|
|
|
|
@classmethod
|
|
def _extract_referenced_content_items(
|
|
cls,
|
|
value: Any,
|
|
output: list[tuple[UUID, str | None]],
|
|
seen_ids: set[UUID] | None = None,
|
|
) -> None:
|
|
"""Recursively collect (content_id, label) tuples from all content_ref objects in order."""
|
|
if seen_ids is None:
|
|
seen_ids = set()
|
|
|
|
if isinstance(value, list):
|
|
for item in value:
|
|
cls._extract_referenced_content_items(item, output, seen_ids)
|
|
return
|
|
|
|
if not isinstance(value, dict):
|
|
return
|
|
|
|
if value.get("type") == "content_ref":
|
|
target = value.get("target")
|
|
raw_id = target.get("content_id") if isinstance(target, dict) else None
|
|
if raw_id:
|
|
try:
|
|
cid = UUID(str(raw_id))
|
|
if cid not in seen_ids:
|
|
seen_ids.add(cid)
|
|
label = value.get("label") or (
|
|
target.get("source_key") if isinstance(target, dict) else None
|
|
)
|
|
output.append((cid, str(label) if label else None))
|
|
except (ValueError, TypeError):
|
|
pass
|
|
|
|
for child in value.values():
|
|
cls._extract_referenced_content_items(child, output, seen_ids)
|
|
|
|
@classmethod
|
|
def _collect_content_reference_lookups(
|
|
cls,
|
|
value: Any,
|
|
output: set[ContentReferenceLookup],
|
|
) -> None:
|
|
if isinstance(value, list):
|
|
for item in value:
|
|
cls._collect_content_reference_lookups(item, output)
|
|
return
|
|
|
|
if not isinstance(value, dict):
|
|
return
|
|
|
|
if value.get("type") == "content_ref":
|
|
output.add(cls._parse_content_reference_lookup(value))
|
|
|
|
for child in value.values():
|
|
cls._collect_content_reference_lookups(child, output)
|
|
|
|
@classmethod
|
|
def _parse_content_reference_lookup(
|
|
cls,
|
|
reference: dict[str, Any],
|
|
) -> ContentReferenceLookup:
|
|
target = reference.get("target")
|
|
if not isinstance(target, dict):
|
|
raise ContentReferenceResolutionError(
|
|
"content_ref.target must be an object"
|
|
)
|
|
|
|
module_code = cls._required_reference_string(target, "module_code")
|
|
template_code = cls._required_reference_string(target, "template_code")
|
|
source_key = cls._required_reference_string(target, "source_key")
|
|
|
|
return ContentReferenceLookup(
|
|
module_code=module_code,
|
|
template_code=template_code,
|
|
source_key=source_key,
|
|
)
|
|
|
|
@staticmethod
|
|
def _required_reference_string(
|
|
target: dict[str, Any],
|
|
key: str,
|
|
) -> str:
|
|
value = target.get(key)
|
|
if not isinstance(value, str) or not value.strip():
|
|
raise ContentReferenceResolutionError(
|
|
f"content_ref.target.{key} must be a non-empty string"
|
|
)
|
|
return value.strip()
|
|
|
|
@classmethod
|
|
def _hydrate_reference_value(
|
|
cls,
|
|
value: Any,
|
|
resolved: dict[ContentReferenceLookup, ResolvedContentReference],
|
|
) -> Any:
|
|
if isinstance(value, list):
|
|
return [
|
|
cls._hydrate_reference_value(item, resolved)
|
|
for item in value
|
|
]
|
|
|
|
if not isinstance(value, dict):
|
|
return value
|
|
|
|
hydrated = {
|
|
key: cls._hydrate_reference_value(child, resolved)
|
|
for key, child in value.items()
|
|
}
|
|
|
|
if value.get("type") != "content_ref":
|
|
return hydrated
|
|
|
|
lookup = cls._parse_content_reference_lookup(value)
|
|
target_record = resolved.get(lookup)
|
|
if target_record is None:
|
|
raise ContentReferenceResolutionError(
|
|
"Resolved content reference was not returned for "
|
|
f"{lookup.module_code}/{lookup.template_code}/{lookup.source_key}"
|
|
)
|
|
|
|
target = hydrated.get("target")
|
|
if not isinstance(target, dict):
|
|
raise ContentReferenceResolutionError(
|
|
"content_ref.target must be an object"
|
|
)
|
|
|
|
existing_content_id = target.get("content_id")
|
|
if existing_content_id is not None:
|
|
if str(existing_content_id) != str(target_record.content_id):
|
|
raise ContentReferenceResolutionError(
|
|
"Persisted content_ref target.content_id conflicts with "
|
|
"the target resolved from source_key"
|
|
)
|
|
|
|
target["content_id"] = str(target_record.content_id)
|
|
return hydrated
|
|
|
|
@staticmethod
|
|
def _derive_module_code(
|
|
template_code: str,
|
|
) -> str | None:
|
|
match = _MODULE_PREFIX_RE.fullmatch(
|
|
template_code.strip()
|
|
)
|
|
if match is None:
|
|
return None
|
|
# Preserve the canonical casing stored in the template code.
|
|
#
|
|
# Module/template identifiers are data identities, not display values.
|
|
# Earlier code forced the derived module prefix to uppercase, which
|
|
# caused lowercase canonical templates such as ``m0042_ct0001`` to
|
|
# produce ``M0042`` in the contract response and to fail module/template
|
|
# ownership checks against a persisted ``m0042`` module code.
|
|
return match.group(1)
|
|
|
|
@staticmethod
|
|
def _content_list_item_response(
|
|
content: ContentItem,
|
|
) -> ContentListItemResponse:
|
|
return ContentListItemResponse(
|
|
id=content.id,
|
|
content_kind=(
|
|
content.content_kind.value
|
|
if hasattr(content.content_kind, "value")
|
|
else content.content_kind
|
|
),
|
|
title=content.title,
|
|
slug=content.slug,
|
|
summary=content.summary,
|
|
thumbnail_media_id=None,
|
|
has_detail=True,
|
|
)
|
|
|
|
def _module_content_item_response(
|
|
self,
|
|
row: ModuleContentRow,
|
|
) -> ModuleContentItemResponse:
|
|
return ModuleContentItemResponse(
|
|
module_id=row.module_id,
|
|
content_id=row.content_id,
|
|
sort_order=row.sort_order,
|
|
is_highlighted=row.is_highlighted,
|
|
created_at=row.created_at,
|
|
created_by=row.created_by,
|
|
content=self._content_list_item_response(row.content),
|
|
)
|
|
|
|
@staticmethod
|
|
def _template_summary_response(
|
|
template: TemplateInfo,
|
|
) -> TemplateSummaryResponse:
|
|
return TemplateSummaryResponse(
|
|
id=template.id,
|
|
code=template.code,
|
|
name=template.name,
|
|
attribute_prefix_code=template.attribute_prefix_code,
|
|
attribute_prefix_name=template.attribute_prefix_name,
|
|
)
|
|
|
|
def _build_definition_response(
|
|
self,
|
|
*,
|
|
template: TemplateInfo,
|
|
definitions: list[AttributeDefinitionRow],
|
|
members: list[AttributeDefinitionMemberRow],
|
|
) -> TemplateAttributeDefinitionsResponse:
|
|
by_id = {item.id: item for item in definitions}
|
|
|
|
member_children: dict[
|
|
UUID,
|
|
list[AttributeDefinitionMemberRow],
|
|
] = {}
|
|
|
|
child_ids: set[UUID] = set()
|
|
|
|
for member in members:
|
|
member_children.setdefault(
|
|
member.parent_definition_id,
|
|
[],
|
|
).append(member)
|
|
child_ids.add(member.child_definition_id)
|
|
|
|
for member_rows in member_children.values():
|
|
member_rows.sort(
|
|
key=lambda item: (
|
|
item.sort_order,
|
|
str(item.child_definition_id),
|
|
)
|
|
)
|
|
|
|
def build_node(
|
|
definition: AttributeDefinitionRow,
|
|
path: frozenset[UUID],
|
|
) -> AttributeDefinitionResponse:
|
|
if definition.id in path:
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail="Cycle detected in attribute definition tree",
|
|
)
|
|
|
|
current_path = path | frozenset({definition.id})
|
|
children: list[AttributeDefinitionResponse] = []
|
|
|
|
for member in member_children.get(
|
|
definition.id,
|
|
[],
|
|
):
|
|
child = by_id.get(member.child_definition_id)
|
|
|
|
if child is None:
|
|
continue
|
|
|
|
children.append(
|
|
build_node(
|
|
child,
|
|
current_path,
|
|
)
|
|
)
|
|
|
|
return AttributeDefinitionResponse(
|
|
id=definition.id,
|
|
code=definition.attribute_key.rsplit(".", 1)[-1],
|
|
attribute_key=definition.attribute_key,
|
|
label=definition.attribute_label,
|
|
definition_kind=definition.definition_kind,
|
|
data_type=definition.data_type,
|
|
is_root=definition.is_root,
|
|
is_required=definition.is_required,
|
|
is_searchable=definition.is_searchable,
|
|
is_filterable=definition.is_filterable,
|
|
is_multivalue=definition.is_multivalue,
|
|
sort_order=definition.sort_order,
|
|
allowed_values=definition.allowed_values,
|
|
metadata=definition.metadata_json,
|
|
children=children,
|
|
)
|
|
|
|
roots = [
|
|
definition
|
|
for definition in definitions
|
|
if definition.is_root
|
|
and definition.id not in child_ids
|
|
]
|
|
|
|
roots.sort(
|
|
key=lambda item: (
|
|
item.sort_order,
|
|
item.attribute_key,
|
|
str(item.id),
|
|
)
|
|
)
|
|
|
|
return TemplateAttributeDefinitionsResponse(
|
|
template=self._template_summary_response(template),
|
|
attributes=[
|
|
build_node(root, frozenset())
|
|
for root in roots
|
|
],
|
|
) |