2150 lines
72 KiB
Python
2150 lines
72 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
|
|
from dataclasses import dataclass
|
|
from typing import Any
|
|
from uuid import UUID
|
|
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,
|
|
AttributeDefinitionSet,
|
|
ContentAttribute,
|
|
ContentItem,
|
|
Module,
|
|
ModuleContent,
|
|
)
|
|
|
|
from .db_schema import CONTENT_SCHEMA, resolve_content_schema
|
|
|
|
from .errors import (
|
|
ContentNotFoundError,
|
|
ContentDefinitionSetError,
|
|
RequiredAttributeMissingError,
|
|
ContentAttributeHierarchyError,
|
|
AmbiguousTemplateCodeError,
|
|
ContentProjectionError,
|
|
ContentReferenceResolutionError,
|
|
InvalidSearchFieldError,
|
|
InvalidSortFieldError,
|
|
ModuleIdentityConflictError,
|
|
ModuleNotFoundError,
|
|
PresentationContractNotFoundError,
|
|
TemplateNotCollectionError,
|
|
TemplateNotFoundError,
|
|
TemplateNotInModuleError,
|
|
)
|
|
|
|
from .capabilities import coerce_filter_value, is_sortable_definition
|
|
from .domain import (
|
|
AttributeDefinitionRecord,
|
|
AttributePresentationRecord,
|
|
DefinitionSetRecord,
|
|
ModuleSearchDefinitionRecord,
|
|
PresentationRecord,
|
|
ContentReferenceLookup,
|
|
ResolvedContentReference,
|
|
)
|
|
from .schema import (
|
|
ContentSearchRequest,
|
|
ModuleContentSearchRequest,
|
|
LogicalOperator,
|
|
SearchCriterion,
|
|
SearchOperator,
|
|
SortCriterion,
|
|
SortDirection,
|
|
)
|
|
|
|
|
|
_SHORT_TEMPLATE_RE = re.compile(r"^CT\d+$", re.IGNORECASE)
|
|
|
|
_SYSTEM_SORT_FIELDS = {
|
|
"module_sort_order",
|
|
"title",
|
|
}
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class ModuleRecord:
|
|
id: UUID
|
|
code: str
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class SearchPageRow:
|
|
id: UUID
|
|
content_kind: str | None
|
|
title: str
|
|
slug: str
|
|
summary: str | None
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class ModuleSearchPageRow:
|
|
id: UUID
|
|
template_code: str
|
|
template_name: str
|
|
content_kind: str | None
|
|
title: str
|
|
slug: str
|
|
summary: str | None
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class ModuleContentRow:
|
|
module_id: UUID
|
|
content_id: UUID
|
|
sort_order: int
|
|
is_highlighted: bool
|
|
created_at: datetime
|
|
created_by: UUID | None
|
|
content: ContentItem
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class TemplateInfo:
|
|
id: UUID
|
|
code: str
|
|
name: str
|
|
attribute_prefix_code: str
|
|
attribute_prefix_name: str
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class AttributeDefinitionRow:
|
|
id: UUID
|
|
attribute_definition_set_id: UUID
|
|
attribute_key: str
|
|
attribute_label: str
|
|
definition_kind: str
|
|
data_type: str | None
|
|
is_root: bool
|
|
is_required: bool
|
|
is_searchable: bool
|
|
is_filterable: bool
|
|
is_multivalue: bool
|
|
allowed_values: list[Any] | None
|
|
sort_order: int
|
|
metadata_json: dict[str, Any]
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class AttributeDefinitionMemberRow:
|
|
parent_definition_id: UUID
|
|
child_definition_id: UUID
|
|
sort_order: int
|
|
is_required: bool
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class ContentCacheContext:
|
|
template_code: str
|
|
module_ids: tuple[UUID, ...]
|
|
|
|
|
|
class ContentRepository:
|
|
"""SQLAlchemy 2.x async repository; no FastAPI Depends usage here."""
|
|
def __init__(
|
|
self,
|
|
session: AsyncSession,
|
|
*,
|
|
schema: str = CONTENT_SCHEMA,
|
|
) -> None:
|
|
self._session = session
|
|
self._schema = resolve_content_schema(schema)
|
|
|
|
async def get_all_active_modules(
|
|
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),
|
|
Module.status.in_(allowed_statuses),
|
|
)
|
|
.order_by(Module.name.asc(), Module.id.asc())
|
|
)
|
|
result = await session.execute(stmt)
|
|
return list(result.scalars().all())
|
|
|
|
async def get_module_by_id(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
module_id: UUID,
|
|
active_only: bool = True,
|
|
) -> Module | None:
|
|
stmt = select(Module).where(Module.id == module_id)
|
|
if active_only:
|
|
stmt = stmt.where(Module.is_active.is_(True))
|
|
result = await session.execute(stmt)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_module_by_code(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
module_code: str,
|
|
active_only: bool = True,
|
|
) -> Module | None:
|
|
stmt = select(Module).where(Module.code == module_code.strip())
|
|
if active_only:
|
|
stmt = stmt.where(Module.is_active.is_(True))
|
|
result = await session.execute(stmt)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_module_by_slug(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
slug: str,
|
|
active_only: bool = True,
|
|
) -> Module | None:
|
|
stmt = select(Module).where(Module.slug == slug.strip())
|
|
if active_only:
|
|
stmt = stmt.where(Module.is_active.is_(True))
|
|
result = await session.execute(stmt)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def resolve_module(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
module_id: UUID | None = None,
|
|
module_code: str | None = None,
|
|
active_only: bool = True,
|
|
) -> Module | None:
|
|
if (module_id is None) == (module_code is None):
|
|
raise ValueError("Exactly one of module_id or module_code is required.")
|
|
|
|
if module_id is not None:
|
|
return await self.get_module_by_id(
|
|
session=session,
|
|
module_id=module_id,
|
|
active_only=active_only,
|
|
)
|
|
|
|
assert module_code is not None
|
|
return await self.get_module_by_code(
|
|
session=session,
|
|
module_code=module_code,
|
|
active_only=active_only,
|
|
)
|
|
|
|
async def get_module_contents(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
module_id: UUID,
|
|
active_content_only: bool = True,
|
|
include_draft: bool = False,
|
|
) -> list[ModuleContentRow]:
|
|
stmt = (
|
|
select(ModuleContent, ContentItem)
|
|
.join(ContentItem, ContentItem.id == ModuleContent.content_id)
|
|
.where(ModuleContent.module_id == module_id)
|
|
)
|
|
|
|
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.status.in_(allowed_statuses),
|
|
)
|
|
|
|
stmt = stmt.order_by(
|
|
ModuleContent.sort_order.asc(),
|
|
ContentItem.sort_title.asc(),
|
|
ContentItem.id.asc(),
|
|
)
|
|
|
|
result = await session.execute(stmt)
|
|
|
|
return [
|
|
ModuleContentRow(
|
|
module_id=mc.module_id,
|
|
content_id=mc.content_id,
|
|
sort_order=mc.sort_order,
|
|
is_highlighted=mc.is_highlighted,
|
|
created_at=mc.created_at,
|
|
created_by=mc.created_by,
|
|
content=content,
|
|
)
|
|
for mc, content in result.all()
|
|
]
|
|
|
|
async def get_module_content_by_content_id(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
module_id: UUID,
|
|
content_id: UUID,
|
|
active_content_only: bool = True,
|
|
include_draft: bool = False,
|
|
) -> ModuleContentRow | None:
|
|
stmt = (
|
|
select(ModuleContent, ContentItem)
|
|
.join(ContentItem, ContentItem.id == ModuleContent.content_id)
|
|
.where(
|
|
ModuleContent.module_id == module_id,
|
|
ModuleContent.content_id == content_id,
|
|
)
|
|
)
|
|
|
|
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.status.in_(allowed_statuses),
|
|
)
|
|
|
|
result = await session.execute(stmt)
|
|
row = result.one_or_none()
|
|
if row is None:
|
|
return None
|
|
|
|
mc, content = row
|
|
return ModuleContentRow(
|
|
module_id=mc.module_id,
|
|
content_id=mc.content_id,
|
|
sort_order=mc.sort_order,
|
|
is_highlighted=mc.is_highlighted,
|
|
created_at=mc.created_at,
|
|
created_by=mc.created_by,
|
|
content=content,
|
|
)
|
|
|
|
async def resolve_content_reference_targets(
|
|
self,
|
|
*,
|
|
references: set[ContentReferenceLookup],
|
|
include_draft: bool = False,
|
|
) -> dict[ContentReferenceLookup, ResolvedContentReference]:
|
|
"""
|
|
Resolve content_ref targets in one query.
|
|
|
|
A reference is valid only when all three persisted identities agree:
|
|
- target module code
|
|
- target template/definition-set code
|
|
- target content source_key
|
|
|
|
Only active modules, templates, content items and module-content
|
|
associations are considered. Publication/subscription authorization is
|
|
intentionally not performed here; destination APIs remain authoritative
|
|
for access enforcement.
|
|
"""
|
|
if not references:
|
|
return {}
|
|
|
|
source_keys = sorted({ref.source_key for ref in references})
|
|
module_codes = sorted({ref.module_code for ref in references})
|
|
template_codes = sorted({ref.template_code for ref in references})
|
|
|
|
stmt = (
|
|
select(
|
|
ContentItem.id.label("content_id"),
|
|
ContentItem.source_key.label("source_key"),
|
|
Module.code.label("module_code"),
|
|
AttributeDefinitionSet.code.label("template_code"),
|
|
)
|
|
.join(
|
|
AttributeDefinitionSet,
|
|
AttributeDefinitionSet.id
|
|
== ContentItem.attribute_definition_set_id,
|
|
)
|
|
.join(
|
|
ModuleContent,
|
|
ModuleContent.content_id == ContentItem.id,
|
|
)
|
|
.join(
|
|
Module,
|
|
Module.id == ModuleContent.module_id,
|
|
)
|
|
.where(
|
|
ContentItem.source_key.in_(source_keys),
|
|
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(
|
|
Module.code.asc(),
|
|
AttributeDefinitionSet.code.asc(),
|
|
ContentItem.source_key.asc(),
|
|
ContentItem.id.asc(),
|
|
)
|
|
)
|
|
|
|
result = await self._session.execute(stmt)
|
|
requested = set(references)
|
|
requested_by_identity: dict[tuple[str, str, str], list[ContentReferenceLookup]] = {}
|
|
for ref in requested:
|
|
identity = (
|
|
ref.module_code,
|
|
ref.template_code,
|
|
ref.source_key,
|
|
)
|
|
requested_by_identity.setdefault(identity, []).append(ref)
|
|
|
|
resolved: dict[ContentReferenceLookup, ResolvedContentReference] = {}
|
|
|
|
for row in result.mappings():
|
|
row_identity = (
|
|
str(row["module_code"]),
|
|
str(row["template_code"]),
|
|
str(row["source_key"]),
|
|
)
|
|
matching_requests = requested_by_identity.get(row_identity, [])
|
|
if not matching_requests:
|
|
continue
|
|
|
|
for lookup in matching_requests:
|
|
existing = resolved.get(lookup)
|
|
if existing is not None and existing.content_id != row["content_id"]:
|
|
raise ContentReferenceResolutionError(
|
|
"Content reference resolves to multiple content items: "
|
|
f"module_code={lookup.module_code!r}, "
|
|
f"template_code={lookup.template_code!r}, "
|
|
f"source_key={lookup.source_key!r}"
|
|
)
|
|
|
|
resolved[lookup] = ResolvedContentReference(
|
|
lookup=lookup,
|
|
content_id=row["content_id"],
|
|
)
|
|
|
|
missing = sorted(
|
|
requested.difference(resolved.keys()),
|
|
key=lambda ref: (
|
|
ref.module_code,
|
|
ref.template_code,
|
|
ref.source_key,
|
|
),
|
|
)
|
|
if missing:
|
|
details = "; ".join(
|
|
f"{ref.module_code}/{ref.template_code}/{ref.source_key}"
|
|
for ref in missing
|
|
)
|
|
raise ContentReferenceResolutionError(
|
|
"Unable to resolve active content reference target(s): "
|
|
+ details
|
|
)
|
|
|
|
return resolved
|
|
|
|
async def get_content_by_id(
|
|
self,
|
|
*,
|
|
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:
|
|
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()
|
|
|
|
async def content_belongs_to_module(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
module_id: UUID,
|
|
content_id: UUID,
|
|
) -> bool:
|
|
stmt = (
|
|
select(ModuleContent.module_id)
|
|
.where(
|
|
ModuleContent.module_id == module_id,
|
|
ModuleContent.content_id == content_id,
|
|
)
|
|
.limit(1)
|
|
)
|
|
result = await session.execute(stmt)
|
|
return result.scalar_one_or_none() is not None
|
|
|
|
async def get_module_contents_by_template(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
module_id: UUID,
|
|
definition_set_id: UUID,
|
|
active_content_only: bool = True,
|
|
include_draft: bool = False,
|
|
) -> list[ModuleContentRow]:
|
|
"""
|
|
Return all content that simultaneously:
|
|
|
|
1. belongs to the requested module through module_contents
|
|
2. belongs to the requested definition/template set through
|
|
content_items.attribute_definition_set_id
|
|
|
|
This deliberately uses relational keys instead of source_key parsing.
|
|
"""
|
|
|
|
stmt = (
|
|
select(
|
|
ModuleContent,
|
|
ContentItem,
|
|
)
|
|
|
|
.join(
|
|
ContentItem,
|
|
ContentItem.id
|
|
== ModuleContent.content_id,
|
|
)
|
|
|
|
.where(
|
|
ModuleContent.module_id
|
|
== module_id,
|
|
|
|
ContentItem
|
|
.attribute_definition_set_id
|
|
== definition_set_id,
|
|
)
|
|
)
|
|
|
|
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.status.in_(allowed_statuses),
|
|
)
|
|
|
|
stmt = stmt.order_by(
|
|
ModuleContent.sort_order.asc(),
|
|
ContentItem.sort_title.asc(),
|
|
ContentItem.id.asc(),
|
|
)
|
|
|
|
result = await session.execute(
|
|
stmt
|
|
)
|
|
|
|
rows: list[
|
|
ModuleContentRow
|
|
] = []
|
|
|
|
for (
|
|
module_content,
|
|
content,
|
|
) in result.all():
|
|
|
|
rows.append(
|
|
ModuleContentRow(
|
|
module_id=(
|
|
module_content.module_id
|
|
),
|
|
|
|
content_id=(
|
|
module_content.content_id
|
|
),
|
|
|
|
sort_order=(
|
|
module_content.sort_order
|
|
),
|
|
|
|
is_highlighted=(
|
|
module_content
|
|
.is_highlighted
|
|
),
|
|
|
|
created_at=(
|
|
module_content.created_at
|
|
),
|
|
|
|
created_by=(
|
|
module_content.created_by
|
|
),
|
|
|
|
content=content,
|
|
)
|
|
)
|
|
|
|
return rows
|
|
|
|
async def get_definition_set_by_code(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
template_code: str,
|
|
active_only: bool = True,
|
|
) -> TemplateInfo | None:
|
|
stmt = select(
|
|
AttributeDefinitionSet.id,
|
|
AttributeDefinitionSet.code,
|
|
AttributeDefinitionSet.name,
|
|
AttributeDefinitionSet.attribute_prefix_code,
|
|
AttributeDefinitionSet.attribute_prefix_name,
|
|
).where(
|
|
AttributeDefinitionSet.code == template_code.strip()
|
|
)
|
|
|
|
if active_only:
|
|
stmt = stmt.where(
|
|
AttributeDefinitionSet.is_active.is_(True)
|
|
)
|
|
|
|
row = (
|
|
await session.execute(stmt)
|
|
).mappings().one_or_none()
|
|
|
|
if row is None:
|
|
return None
|
|
|
|
return TemplateInfo(
|
|
id=row["id"],
|
|
code=row["code"],
|
|
name=row["name"],
|
|
attribute_prefix_code=row["attribute_prefix_code"],
|
|
attribute_prefix_name=row["attribute_prefix_name"],
|
|
)
|
|
|
|
async def get_attribute_definitions_by_set(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
definition_set_id: UUID,
|
|
active_only: bool = True,
|
|
) -> list[AttributeDefinitionRow]:
|
|
stmt = select(
|
|
AttributeDefinition.id,
|
|
AttributeDefinition.attribute_definition_set_id,
|
|
AttributeDefinition.attribute_key,
|
|
AttributeDefinition.attribute_label,
|
|
AttributeDefinition.definition_kind,
|
|
AttributeDefinition.data_type,
|
|
AttributeDefinition.is_root,
|
|
AttributeDefinition.is_required,
|
|
AttributeDefinition.is_searchable,
|
|
AttributeDefinition.is_filterable,
|
|
AttributeDefinition.is_multivalue,
|
|
AttributeDefinition.allowed_values,
|
|
AttributeDefinition.sort_order,
|
|
AttributeDefinition.metadata_json,
|
|
).where(
|
|
AttributeDefinition.attribute_definition_set_id
|
|
== definition_set_id
|
|
)
|
|
|
|
if active_only:
|
|
stmt = stmt.where(
|
|
AttributeDefinition.is_active.is_(True)
|
|
)
|
|
|
|
stmt = stmt.order_by(
|
|
AttributeDefinition.sort_order.asc(),
|
|
AttributeDefinition.attribute_key.asc(),
|
|
AttributeDefinition.id.asc(),
|
|
)
|
|
|
|
result = await session.execute(stmt)
|
|
|
|
return [
|
|
AttributeDefinitionRow(
|
|
id=row["id"],
|
|
attribute_definition_set_id=row[
|
|
"attribute_definition_set_id"
|
|
],
|
|
attribute_key=row["attribute_key"],
|
|
attribute_label=row["attribute_label"],
|
|
definition_kind=row["definition_kind"],
|
|
data_type=row["data_type"],
|
|
is_root=row["is_root"],
|
|
is_required=row["is_required"],
|
|
is_searchable=row["is_searchable"],
|
|
is_filterable=row["is_filterable"],
|
|
is_multivalue=row["is_multivalue"],
|
|
allowed_values=row["allowed_values"],
|
|
sort_order=row["sort_order"],
|
|
metadata_json=row["metadata_json"] or {},
|
|
)
|
|
for row in result.mappings().all()
|
|
]
|
|
|
|
async def get_attribute_definition_members(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
definition_set_id: UUID,
|
|
) -> list[AttributeDefinitionMemberRow]:
|
|
stmt = (
|
|
select(
|
|
AttributeDefinitionMember.parent_attribute_definition_id,
|
|
AttributeDefinitionMember.child_attribute_definition_id,
|
|
AttributeDefinitionMember.sort_order,
|
|
AttributeDefinitionMember.is_required,
|
|
)
|
|
.join(
|
|
AttributeDefinition,
|
|
AttributeDefinition.id
|
|
== AttributeDefinitionMember.parent_attribute_definition_id,
|
|
)
|
|
.where(
|
|
AttributeDefinition.attribute_definition_set_id
|
|
== definition_set_id
|
|
)
|
|
.order_by(
|
|
AttributeDefinitionMember.parent_attribute_definition_id.asc(),
|
|
AttributeDefinitionMember.sort_order.asc(),
|
|
AttributeDefinitionMember.child_attribute_definition_id.asc(),
|
|
)
|
|
)
|
|
|
|
result = await session.execute(stmt)
|
|
|
|
return [
|
|
AttributeDefinitionMemberRow(
|
|
parent_definition_id=row[
|
|
"parent_attribute_definition_id"
|
|
],
|
|
child_definition_id=row[
|
|
"child_attribute_definition_id"
|
|
],
|
|
sort_order=row["sort_order"],
|
|
is_required=row["is_required"],
|
|
)
|
|
for row in result.mappings().all()
|
|
]
|
|
|
|
async def get_content_cache_context(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
content_id: UUID,
|
|
) -> ContentCacheContext | None:
|
|
template_stmt = (
|
|
select(AttributeDefinitionSet.code)
|
|
.join(
|
|
ContentItem,
|
|
ContentItem.attribute_definition_set_id
|
|
== AttributeDefinitionSet.id,
|
|
)
|
|
.where(ContentItem.id == content_id)
|
|
)
|
|
|
|
template_code = (
|
|
await session.execute(template_stmt)
|
|
).scalar_one_or_none()
|
|
|
|
if template_code is None:
|
|
return None
|
|
|
|
module_stmt = select(ModuleContent.module_id).where(
|
|
ModuleContent.content_id == content_id
|
|
)
|
|
|
|
module_ids = tuple(
|
|
(
|
|
await session.execute(module_stmt)
|
|
).scalars().all()
|
|
)
|
|
|
|
return ContentCacheContext(
|
|
template_code=template_code,
|
|
module_ids=module_ids,
|
|
)
|
|
|
|
### search
|
|
async def resolve_definition_set(
|
|
self,
|
|
template_code: str,
|
|
) -> DefinitionSetRecord:
|
|
requested = template_code.strip()
|
|
if not requested:
|
|
raise TemplateNotFoundError(template_code)
|
|
|
|
result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select
|
|
id,
|
|
code,
|
|
attribute_prefix_code,
|
|
content_kind::text as content_kind
|
|
from {self._schema}.attribute_definition_sets
|
|
where is_active = true
|
|
and (
|
|
code = :requested
|
|
or attribute_prefix_code = :requested
|
|
)
|
|
order by
|
|
case when code = :requested then 0 else 1 end,
|
|
id
|
|
"""
|
|
),
|
|
{"requested": requested},
|
|
)
|
|
exact = result.mappings().all()
|
|
|
|
if exact:
|
|
# code and prefix are both unique in the current schema. If the
|
|
# logical values point to different rows, fail rather than guess.
|
|
unique_ids = {row["id"] for row in exact}
|
|
if len(unique_ids) > 1:
|
|
raise AmbiguousTemplateCodeError(
|
|
requested,
|
|
[str(row["code"]) for row in exact],
|
|
)
|
|
row = exact[0]
|
|
return DefinitionSetRecord(
|
|
id=row["id"],
|
|
code=row["code"],
|
|
attribute_prefix_code=row["attribute_prefix_code"],
|
|
content_kind=row["content_kind"],
|
|
)
|
|
|
|
if not _SHORT_TEMPLATE_RE.fullmatch(requested):
|
|
raise TemplateNotFoundError(requested)
|
|
|
|
# CT0003 -> M0001_CT0003. Escape "_" because LIKE treats it as a
|
|
# wildcard. The short alias is accepted only when it resolves uniquely.
|
|
suffix = "%\\_" + requested
|
|
alias_result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select
|
|
id,
|
|
code,
|
|
attribute_prefix_code,
|
|
content_kind::text as content_kind
|
|
from {self._schema}.attribute_definition_sets
|
|
where is_active = true
|
|
and (
|
|
code like :suffix escape '\\'
|
|
or attribute_prefix_code like :suffix escape '\\'
|
|
)
|
|
order by code, id
|
|
"""
|
|
),
|
|
{"suffix": suffix},
|
|
)
|
|
rows = alias_result.mappings().all()
|
|
|
|
unique: dict[UUID, Any] = {row["id"]: row for row in rows}
|
|
if not unique:
|
|
raise TemplateNotFoundError(requested)
|
|
if len(unique) > 1:
|
|
raise AmbiguousTemplateCodeError(
|
|
requested,
|
|
sorted({str(row["code"]) for row in unique.values()}),
|
|
)
|
|
|
|
row = next(iter(unique.values()))
|
|
return DefinitionSetRecord(
|
|
id=row["id"],
|
|
code=row["code"],
|
|
attribute_prefix_code=row["attribute_prefix_code"],
|
|
content_kind=row["content_kind"],
|
|
)
|
|
|
|
async def get_active_presentation(
|
|
self,
|
|
*,
|
|
definition_set: DefinitionSetRecord,
|
|
client_type: str,
|
|
) -> PresentationRecord:
|
|
result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select
|
|
id,
|
|
attribute_definition_set_id,
|
|
client_type,
|
|
version_no,
|
|
presentation_mode,
|
|
collection_renderer,
|
|
collection_item_renderer,
|
|
detail_renderer
|
|
from {self._schema}.template_presentation_contracts
|
|
where attribute_definition_set_id = :definition_set_id
|
|
and client_type = :client_type
|
|
and is_active = true
|
|
order by version_no desc
|
|
"""
|
|
),
|
|
{
|
|
"definition_set_id": definition_set.id,
|
|
"client_type": client_type,
|
|
},
|
|
)
|
|
row = result.mappings().one_or_none()
|
|
if row is None:
|
|
raise PresentationContractNotFoundError(
|
|
definition_set.code,
|
|
client_type,
|
|
)
|
|
return PresentationRecord(
|
|
id=row["id"],
|
|
attribute_definition_set_id=row["attribute_definition_set_id"],
|
|
client_type=row["client_type"],
|
|
version_no=row["version_no"],
|
|
presentation_mode=row["presentation_mode"],
|
|
collection_renderer=row["collection_renderer"],
|
|
collection_item_renderer=row["collection_item_renderer"],
|
|
detail_renderer=row["detail_renderer"],
|
|
)
|
|
|
|
async def load_attribute_presentations(
|
|
self,
|
|
*,
|
|
presentation_contract_id: UUID,
|
|
) -> list[AttributePresentationRecord]:
|
|
result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select
|
|
tap.template_presentation_contract_id,
|
|
tap.attribute_definition_id,
|
|
ad.attribute_definition_set_id,
|
|
ad.attribute_key,
|
|
tap.empty_behavior,
|
|
tap.empty_text,
|
|
tap.metadata as metadata_json
|
|
from {self._schema}.template_attribute_presentations tap
|
|
join {self._schema}.attribute_definitions ad
|
|
on ad.id = tap.attribute_definition_id
|
|
where tap.template_presentation_contract_id = :presentation_contract_id
|
|
order by ad.sort_order asc, ad.attribute_key asc
|
|
"""
|
|
),
|
|
{
|
|
"presentation_contract_id": presentation_contract_id,
|
|
},
|
|
)
|
|
return [
|
|
AttributePresentationRecord(
|
|
presentation_contract_id=row["template_presentation_contract_id"],
|
|
attribute_definition_id=row["attribute_definition_id"],
|
|
attribute_definition_set_id=row["attribute_definition_set_id"],
|
|
attribute_key=row["attribute_key"],
|
|
empty_behavior=row["empty_behavior"],
|
|
empty_text=row["empty_text"],
|
|
metadata_json=dict(row["metadata_json"] or {}),
|
|
)
|
|
for row in result.mappings().all()
|
|
]
|
|
|
|
async def load_active_definitions(
|
|
self,
|
|
definition_set_id: UUID,
|
|
) -> list[AttributeDefinitionRecord]:
|
|
result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select
|
|
id,
|
|
attribute_key,
|
|
attribute_label,
|
|
data_type,
|
|
definition_kind,
|
|
is_root,
|
|
is_searchable,
|
|
is_filterable,
|
|
is_multivalue,
|
|
allowed_values,
|
|
sort_order
|
|
from {self._schema}.attribute_definitions
|
|
where attribute_definition_set_id = :definition_set_id
|
|
and is_active = true
|
|
order by sort_order, attribute_key, id
|
|
"""
|
|
),
|
|
{"definition_set_id": definition_set_id},
|
|
)
|
|
|
|
return [
|
|
AttributeDefinitionRecord(
|
|
id=row["id"],
|
|
attribute_key=row["attribute_key"],
|
|
attribute_label=row["attribute_label"],
|
|
data_type=row["data_type"],
|
|
definition_kind=row["definition_kind"],
|
|
is_root=row["is_root"],
|
|
is_searchable=row["is_searchable"],
|
|
is_filterable=row["is_filterable"],
|
|
is_multivalue=row["is_multivalue"],
|
|
allowed_values=row["allowed_values"],
|
|
sort_order=row["sort_order"],
|
|
)
|
|
for row in result.mappings()
|
|
]
|
|
|
|
|
|
async def get_module_search_definitions(
|
|
self,
|
|
*,
|
|
module_id: UUID,
|
|
client_type: str = "mobile",
|
|
) -> list[ModuleSearchDefinitionRecord]:
|
|
result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select
|
|
ad.id,
|
|
ads.code as template_code,
|
|
ads.name as template_name,
|
|
ad.attribute_key,
|
|
ad.attribute_label,
|
|
ad.data_type,
|
|
ad.definition_kind,
|
|
ad.is_root,
|
|
ad.is_searchable,
|
|
ad.is_filterable,
|
|
ad.is_multivalue,
|
|
ad.allowed_values,
|
|
ad.sort_order,
|
|
coalesce(tap.metadata ->> 'visibility', 'show') as visibility
|
|
from {self._schema}.attribute_definition_sets ads
|
|
join {self._schema}.attribute_definitions ad
|
|
on ad.attribute_definition_set_id = ads.id
|
|
and ad.is_active = true
|
|
left join {self._schema}.template_presentation_contracts tpc
|
|
on tpc.attribute_definition_set_id = ads.id
|
|
and tpc.client_type = :client_type
|
|
and tpc.is_active = true
|
|
left join {self._schema}.template_attribute_presentations tap
|
|
on tap.template_presentation_contract_id = tpc.id
|
|
and tap.attribute_definition_id = ad.id
|
|
where exists (
|
|
select 1
|
|
from {self._schema}.module_contents mc
|
|
join {self._schema}.content_items ci
|
|
on ci.id = mc.content_id
|
|
where mc.module_id = :module_id
|
|
and ci.attribute_definition_set_id = ads.id
|
|
and ci.is_active = true
|
|
and ci.status = 'published'
|
|
)
|
|
and ad.definition_kind = 'scalar'
|
|
and (ad.is_searchable = true or ad.is_filterable = true)
|
|
and coalesce(tap.metadata ->> 'visibility', 'show') <> 'hide'
|
|
order by ads.name, ad.sort_order, ad.attribute_label, ad.attribute_key
|
|
"""
|
|
),
|
|
{"module_id": module_id, "client_type": client_type.strip().lower()},
|
|
)
|
|
return [
|
|
ModuleSearchDefinitionRecord(
|
|
id=row["id"],
|
|
template_code=row["template_code"],
|
|
template_name=row["template_name"],
|
|
attribute_key=row["attribute_key"],
|
|
attribute_label=row["attribute_label"],
|
|
data_type=row["data_type"],
|
|
definition_kind=row["definition_kind"],
|
|
is_root=row["is_root"],
|
|
is_searchable=row["is_searchable"],
|
|
is_filterable=row["is_filterable"],
|
|
is_multivalue=row["is_multivalue"],
|
|
allowed_values=row["allowed_values"],
|
|
sort_order=row["sort_order"],
|
|
visibility=row["visibility"],
|
|
)
|
|
for row in result.mappings()
|
|
]
|
|
|
|
async def search_module(
|
|
self,
|
|
*,
|
|
request: ModuleContentSearchRequest,
|
|
module: Module | ModuleRecord,
|
|
definitions: list[ModuleSearchDefinitionRecord],
|
|
) -> tuple[int, list[ModuleSearchPageRow]]:
|
|
definition_by_key = {d.attribute_key: d for d in definitions}
|
|
where_parts = [
|
|
"mc.module_id = :module_id",
|
|
"ci.is_active = true",
|
|
"ci.status = 'published'",
|
|
]
|
|
params: dict[str, Any] = {"module_id": module.id}
|
|
|
|
normalized_query = (request.query or "").strip()
|
|
if normalized_query:
|
|
params["free_text_query"] = normalized_query
|
|
selected = []
|
|
for key in request.search_attributes:
|
|
definition = definition_by_key.get(key)
|
|
if (
|
|
definition is None
|
|
or not definition.is_searchable
|
|
or definition.data_type not in {"text", "rich_text"}
|
|
):
|
|
raise InvalidSearchFieldError(
|
|
f"Attribute {key!r} is not an active visible searchable text field for this module"
|
|
)
|
|
selected.append(definition)
|
|
|
|
if selected:
|
|
predicates = []
|
|
for index, definition in enumerate(selected):
|
|
param = f"module_search_attribute_id_{index}"
|
|
params[param] = definition.id
|
|
predicates.append(f"module_ft.attribute_definition_id = :{param}")
|
|
where_parts.append(
|
|
f"""
|
|
exists (
|
|
select 1
|
|
from {self._schema}.content_attributes module_ft
|
|
where module_ft.content_id = ci.id
|
|
and ({' or '.join(predicates)})
|
|
and module_ft.value_text is not null
|
|
and to_tsvector('simple', module_ft.value_text)
|
|
@@ websearch_to_tsquery('simple', :free_text_query)
|
|
)
|
|
"""
|
|
)
|
|
else:
|
|
attribute_exists = f"""
|
|
or exists (
|
|
select 1
|
|
from {self._schema}.content_attributes module_ft
|
|
join {self._schema}.attribute_definitions module_ad
|
|
on module_ad.id = module_ft.attribute_definition_id
|
|
and module_ad.is_active = true
|
|
left join {self._schema}.template_presentation_contracts module_tpc
|
|
on module_tpc.attribute_definition_set_id = module_ad.attribute_definition_set_id
|
|
and module_tpc.client_type = 'mobile'
|
|
and module_tpc.is_active = true
|
|
left join {self._schema}.template_attribute_presentations module_tap
|
|
on module_tap.template_presentation_contract_id = module_tpc.id
|
|
and module_tap.attribute_definition_id = module_ad.id
|
|
where module_ft.content_id = ci.id
|
|
and module_ad.is_searchable = true
|
|
and module_ad.definition_kind = 'scalar'
|
|
and module_ad.data_type in ('text', 'rich_text')
|
|
and coalesce(module_tap.metadata ->> 'visibility', 'show') <> 'hide'
|
|
and module_ft.value_text is not null
|
|
and to_tsvector('simple', module_ft.value_text)
|
|
@@ websearch_to_tsquery('simple', :free_text_query)
|
|
)
|
|
"""
|
|
where_parts.append(
|
|
f"""
|
|
(
|
|
to_tsvector(
|
|
'simple',
|
|
concat_ws(' ', coalesce(ci.title, ''), coalesce(ci.summary, ''))
|
|
) @@ websearch_to_tsquery('simple', :free_text_query)
|
|
{attribute_exists}
|
|
)
|
|
"""
|
|
)
|
|
|
|
filter_clauses = []
|
|
for index, criterion in enumerate(request.filters):
|
|
definition = definition_by_key.get(criterion.attribute_key)
|
|
if definition is None or not definition.is_filterable:
|
|
raise InvalidSearchFieldError(
|
|
f"Attribute {criterion.attribute_key!r} is not an active visible filterable field for this module"
|
|
)
|
|
converted = coerce_filter_value(definition, criterion.operator, criterion.value)
|
|
filter_clauses.append(
|
|
self._build_filter_clause(
|
|
index=index,
|
|
definition=definition,
|
|
operator=criterion.operator,
|
|
value=converted,
|
|
params=params,
|
|
)
|
|
)
|
|
if filter_clauses:
|
|
joiner = " AND " if request.logic == LogicalOperator.AND else " OR "
|
|
where_parts.append("(" + joiner.join(filter_clauses) + ")")
|
|
|
|
order_parts = []
|
|
requested_sort = request.sort or [
|
|
SortCriterion(field="module_sort_order", direction=SortDirection.ASC)
|
|
]
|
|
for criterion in requested_sort:
|
|
direction = "asc" if criterion.direction == SortDirection.ASC else "desc"
|
|
if criterion.field == "module_sort_order":
|
|
order_parts.append(f"mc.sort_order {direction} nulls last")
|
|
elif criterion.field == "title":
|
|
order_parts.append(f"ci.sort_title {direction} nulls last")
|
|
else:
|
|
raise InvalidSortFieldError(
|
|
f"Sort field {criterion.field!r} is not allowed for module-wide search"
|
|
)
|
|
order_parts.append("ci.id asc")
|
|
where_sql = "\n AND ".join(where_parts)
|
|
|
|
count_result = await self._session.execute(
|
|
text(f"""
|
|
select count(*)
|
|
from {self._schema}.module_contents mc
|
|
join {self._schema}.content_items ci on ci.id = mc.content_id
|
|
where {where_sql}
|
|
"""),
|
|
params,
|
|
)
|
|
total = int(count_result.scalar_one())
|
|
|
|
page_result = await self._session.execute(
|
|
text(f"""
|
|
select
|
|
ci.id,
|
|
ads.code as template_code,
|
|
ads.name as template_name,
|
|
ci.content_kind::text as content_kind,
|
|
ci.title,
|
|
ci.slug,
|
|
ci.summary
|
|
from {self._schema}.module_contents mc
|
|
join {self._schema}.content_items ci on ci.id = mc.content_id
|
|
join {self._schema}.attribute_definition_sets ads
|
|
on ads.id = ci.attribute_definition_set_id
|
|
where {where_sql}
|
|
order by {', '.join(order_parts)}
|
|
limit :limit offset :offset
|
|
"""),
|
|
{
|
|
**params,
|
|
"limit": request.page_size,
|
|
"offset": (request.page - 1) * request.page_size,
|
|
},
|
|
)
|
|
return total, [
|
|
ModuleSearchPageRow(
|
|
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 page_result.mappings()
|
|
]
|
|
|
|
async def assert_template_has_module_content(
|
|
self,
|
|
*,
|
|
module_id: UUID,
|
|
definition_set_id: UUID,
|
|
template_code: str,
|
|
) -> None:
|
|
result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select 1
|
|
from {self._schema}.module_contents mc
|
|
join {self._schema}.content_items ci
|
|
on ci.id = mc.content_id
|
|
where mc.module_id = :module_id
|
|
and ci.attribute_definition_set_id = :definition_set_id
|
|
limit 1
|
|
"""
|
|
),
|
|
{
|
|
"module_id": module_id,
|
|
"definition_set_id": definition_set_id,
|
|
},
|
|
)
|
|
if result.scalar_one_or_none() is None:
|
|
raise TemplateNotInModuleError(
|
|
f"Template {template_code!r} has no content in the requested module"
|
|
)
|
|
|
|
async def search(
|
|
self,
|
|
*,
|
|
request: ContentSearchRequest,
|
|
module: Module | ModuleRecord,
|
|
definition_set: DefinitionSetRecord,
|
|
presentation: PresentationRecord,
|
|
definitions: list[AttributeDefinitionRecord],
|
|
include_draft: bool = False,
|
|
) -> tuple[int, list[SearchPageRow]]:
|
|
if presentation.presentation_mode != "collection":
|
|
raise TemplateNotCollectionError(
|
|
f"Template {definition_set.code!r} is configured as "
|
|
f"{presentation.presentation_mode!r}, not 'collection'"
|
|
)
|
|
|
|
definition_by_key = {
|
|
definition.attribute_key: definition
|
|
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",
|
|
allowed_status_sql,
|
|
]
|
|
params: dict[str, Any] = {
|
|
"module_id": module.id,
|
|
"definition_set_id": definition_set.id,
|
|
}
|
|
|
|
normalized_query = (request.query or "").strip()
|
|
if normalized_query:
|
|
params["free_text_query"] = normalized_query
|
|
|
|
selected_search_definitions: list[AttributeDefinitionRecord] = []
|
|
seen_search_keys: set[str] = set()
|
|
|
|
for raw_key in request.search_attributes:
|
|
key = raw_key.strip()
|
|
if not key or key in seen_search_keys:
|
|
continue
|
|
seen_search_keys.add(key)
|
|
|
|
definition = definition_by_key.get(key)
|
|
if (
|
|
definition is None
|
|
or not definition.is_searchable
|
|
or definition.definition_kind != "scalar"
|
|
or definition.data_type not in {"text", "rich_text"}
|
|
):
|
|
raise InvalidSearchFieldError(
|
|
f"Attribute {key!r} is not an active searchable scalar "
|
|
"text field for this template"
|
|
)
|
|
|
|
selected_search_definitions.append(definition)
|
|
|
|
if selected_search_definitions:
|
|
attribute_predicates: list[str] = []
|
|
|
|
for index, definition in enumerate(
|
|
selected_search_definitions
|
|
):
|
|
parameter_name = f"search_attribute_id_{index}"
|
|
params[parameter_name] = definition.id
|
|
attribute_predicates.append(
|
|
"ft_ca.attribute_definition_id = "
|
|
f":{parameter_name}"
|
|
)
|
|
|
|
where_parts.append(
|
|
f"""
|
|
exists (
|
|
select 1
|
|
from {self._schema}.content_attributes ft_ca
|
|
where ft_ca.content_id = ci.id
|
|
and ({' or '.join(attribute_predicates)})
|
|
and ft_ca.value_text is not null
|
|
and to_tsvector(
|
|
'simple',
|
|
ft_ca.value_text
|
|
)
|
|
@@ websearch_to_tsquery(
|
|
'simple',
|
|
:free_text_query
|
|
)
|
|
)
|
|
"""
|
|
)
|
|
else:
|
|
where_parts.append(
|
|
f"""
|
|
(
|
|
to_tsvector(
|
|
'simple',
|
|
concat_ws(
|
|
' ',
|
|
coalesce(ci.title, ''),
|
|
coalesce(ci.summary, '')
|
|
)
|
|
)
|
|
@@ websearch_to_tsquery(
|
|
'simple',
|
|
:free_text_query
|
|
)
|
|
|
|
or exists (
|
|
select 1
|
|
from {self._schema}.content_attributes ft_ca
|
|
join {self._schema}.attribute_definitions ft_ad
|
|
on ft_ad.id = ft_ca.attribute_definition_id
|
|
where ft_ca.content_id = ci.id
|
|
and ft_ad.attribute_definition_set_id = :definition_set_id
|
|
and ft_ad.is_active = true
|
|
and ft_ad.is_searchable = true
|
|
and ft_ad.definition_kind = 'scalar'
|
|
and ft_ad.data_type in ('text', 'rich_text')
|
|
and ft_ca.value_text is not null
|
|
and to_tsvector(
|
|
'simple',
|
|
ft_ca.value_text
|
|
)
|
|
@@ websearch_to_tsquery(
|
|
'simple',
|
|
:free_text_query
|
|
)
|
|
)
|
|
)
|
|
"""
|
|
)
|
|
|
|
filter_clauses: list[str] = []
|
|
for index, criterion in enumerate(request.filters):
|
|
definition = definition_by_key.get(criterion.attribute_key)
|
|
if (
|
|
definition is None
|
|
or not definition.is_filterable
|
|
or definition.definition_kind != "scalar"
|
|
):
|
|
raise InvalidSearchFieldError(
|
|
f"Attribute {criterion.attribute_key!r} is not an active "
|
|
"filterable scalar field for this template"
|
|
)
|
|
|
|
converted = coerce_filter_value(
|
|
definition,
|
|
criterion.operator,
|
|
criterion.value,
|
|
)
|
|
clause = self._build_filter_clause(
|
|
index=index,
|
|
definition=definition,
|
|
operator=criterion.operator,
|
|
value=converted,
|
|
params=params,
|
|
)
|
|
filter_clauses.append(clause)
|
|
|
|
if filter_clauses:
|
|
joiner = (
|
|
" AND "
|
|
if request.logic == LogicalOperator.AND
|
|
else " OR "
|
|
)
|
|
where_parts.append(
|
|
"(" + joiner.join(filter_clauses) + ")"
|
|
)
|
|
|
|
order_parts: list[str] = []
|
|
requested_sort = request.sort or [
|
|
SortCriterion(
|
|
field="module_sort_order",
|
|
direction=SortDirection.ASC,
|
|
)
|
|
]
|
|
|
|
for index, criterion in enumerate(requested_sort):
|
|
direction = (
|
|
"asc"
|
|
if criterion.direction == SortDirection.ASC
|
|
else "desc"
|
|
)
|
|
|
|
if criterion.field == "module_sort_order":
|
|
order_parts.append(
|
|
f"mc.sort_order {direction} nulls last"
|
|
)
|
|
continue
|
|
|
|
if criterion.field == "title":
|
|
order_parts.append(
|
|
f"ci.sort_title {direction} nulls last"
|
|
)
|
|
continue
|
|
|
|
definition = definition_by_key.get(criterion.field)
|
|
if (
|
|
definition is None
|
|
or not is_sortable_definition(definition)
|
|
or not (
|
|
definition.is_searchable
|
|
or definition.is_filterable
|
|
)
|
|
):
|
|
raise InvalidSortFieldError(
|
|
f"Sort field {criterion.field!r} is not allowed "
|
|
"for this template"
|
|
)
|
|
|
|
sort_param = f"sort_definition_id_{index}"
|
|
params[sort_param] = definition.id
|
|
value_column = self._sort_value_column(definition)
|
|
order_parts.append(
|
|
f"""
|
|
(
|
|
select min(sort_ca.{value_column})
|
|
from {self._schema}.content_attributes sort_ca
|
|
where sort_ca.content_id = ci.id
|
|
and sort_ca.attribute_definition_id = :{sort_param}
|
|
) {direction} nulls last
|
|
"""
|
|
)
|
|
|
|
# A stable UUID tie-breaker guarantees deterministic pages even when
|
|
# all user-visible sort values are identical.
|
|
order_parts.append("ci.id asc")
|
|
|
|
where_sql = "\n AND ".join(where_parts)
|
|
|
|
count_result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select count(*)
|
|
from {self._schema}.module_contents mc
|
|
join {self._schema}.content_items ci
|
|
on ci.id = mc.content_id
|
|
where {where_sql}
|
|
"""
|
|
),
|
|
params,
|
|
)
|
|
total = int(count_result.scalar_one())
|
|
|
|
offset = (request.page - 1) * request.page_size
|
|
page_params = {
|
|
**params,
|
|
"limit": request.page_size,
|
|
"offset": offset,
|
|
}
|
|
|
|
page_result = await self._session.execute(
|
|
text(
|
|
f"""
|
|
select
|
|
ci.id,
|
|
ci.content_kind::text as content_kind,
|
|
ci.title,
|
|
ci.slug,
|
|
ci.summary
|
|
from {self._schema}.module_contents mc
|
|
join {self._schema}.content_items ci
|
|
on ci.id = mc.content_id
|
|
where {where_sql}
|
|
order by {", ".join(order_parts)}
|
|
limit :limit
|
|
offset :offset
|
|
"""
|
|
),
|
|
page_params,
|
|
)
|
|
|
|
rows = [
|
|
SearchPageRow(
|
|
id=row["id"],
|
|
content_kind=row["content_kind"],
|
|
title=row["title"],
|
|
slug=row["slug"],
|
|
summary=row["summary"],
|
|
)
|
|
for row in page_result.mappings()
|
|
]
|
|
return total, rows
|
|
|
|
def _build_filter_clause(
|
|
self,
|
|
*,
|
|
index: int,
|
|
definition: AttributeDefinitionRecord,
|
|
operator: SearchOperator,
|
|
value: Any,
|
|
params: dict[str, Any],
|
|
) -> str:
|
|
definition_param = f"filter_definition_id_{index}"
|
|
value_param = f"filter_value_{index}"
|
|
params[definition_param] = definition.id
|
|
|
|
value_column = self._filter_value_column(definition)
|
|
positive_operator_sql: str
|
|
|
|
if operator == SearchOperator.IN:
|
|
params[value_param] = value
|
|
positive_operator_sql = (
|
|
f"filter_ca.{value_column} = any(:{value_param})"
|
|
)
|
|
|
|
elif operator == SearchOperator.CONTAINS:
|
|
if definition.data_type in {"text", "rich_text"}:
|
|
params[value_param] = f"%{self._escape_like(str(value))}%"
|
|
positive_operator_sql = (
|
|
f"filter_ca.{value_column} ilike :{value_param} escape '\\'"
|
|
)
|
|
elif definition.data_type == "json":
|
|
params[value_param] = json.dumps(value)
|
|
positive_operator_sql = (
|
|
f"filter_ca.{value_column} @> cast(:{value_param} as jsonb)"
|
|
)
|
|
else:
|
|
raise InvalidSearchFieldError(
|
|
f"contains is not supported for {definition.attribute_key!r}"
|
|
)
|
|
|
|
elif operator == SearchOperator.STARTS_WITH:
|
|
params[value_param] = f"{self._escape_like(str(value))}%"
|
|
positive_operator_sql = (
|
|
f"filter_ca.{value_column} ilike :{value_param} escape '\\'"
|
|
)
|
|
|
|
else:
|
|
params[value_param] = (
|
|
json.dumps(value)
|
|
if definition.data_type == "json"
|
|
else value
|
|
)
|
|
|
|
if definition.data_type == "json":
|
|
rhs = f"cast(:{value_param} as jsonb)"
|
|
else:
|
|
rhs = f":{value_param}"
|
|
|
|
sql_operator = {
|
|
SearchOperator.EQ: "=",
|
|
SearchOperator.NEQ: "=",
|
|
SearchOperator.GT: ">",
|
|
SearchOperator.GTE: ">=",
|
|
SearchOperator.LT: "<",
|
|
SearchOperator.LTE: "<=",
|
|
}[operator]
|
|
positive_operator_sql = (
|
|
f"filter_ca.{value_column} {sql_operator} {rhs}"
|
|
)
|
|
|
|
exists_sql = f"""
|
|
exists (
|
|
select 1
|
|
from {self._schema}.content_attributes filter_ca
|
|
where filter_ca.content_id = ci.id
|
|
and filter_ca.attribute_definition_id = :{definition_param}
|
|
and {positive_operator_sql}
|
|
)
|
|
"""
|
|
|
|
# NEQ means "the content has no value equal to X". This gives correct
|
|
# semantics for multivalue EAV attributes. "exists(value != X)" would
|
|
# incorrectly match [X, Y].
|
|
if operator == SearchOperator.NEQ:
|
|
return f"not ({exists_sql})"
|
|
|
|
return exists_sql
|
|
|
|
@staticmethod
|
|
def _escape_like(value: str) -> str:
|
|
return (
|
|
value.replace("\\", "\\\\")
|
|
.replace("%", "\\%")
|
|
.replace("_", "\\_")
|
|
)
|
|
|
|
@staticmethod
|
|
def _filter_value_column(
|
|
definition: AttributeDefinitionRecord,
|
|
) -> str:
|
|
mapping = {
|
|
"text": "value_text",
|
|
"rich_text": "value_text",
|
|
"number": "value_number",
|
|
"boolean": "value_boolean",
|
|
"date": "value_date",
|
|
"json": "value_json",
|
|
"media": "media_asset_id",
|
|
}
|
|
try:
|
|
return mapping[str(definition.data_type)]
|
|
except KeyError as exc:
|
|
raise InvalidSearchFieldError(
|
|
f"Unsupported filter data type {definition.data_type!r}"
|
|
) from exc
|
|
|
|
@staticmethod
|
|
def _sort_value_column(
|
|
definition: AttributeDefinitionRecord,
|
|
) -> str:
|
|
mapping = {
|
|
"text": "value_text",
|
|
"rich_text": "value_text",
|
|
"number": "value_number",
|
|
"date": "value_date",
|
|
}
|
|
try:
|
|
return mapping[str(definition.data_type)]
|
|
except KeyError as exc:
|
|
raise InvalidSortFieldError(
|
|
f"Unsupported sort data type {definition.data_type!r}"
|
|
) from exc
|
|
|
|
async def build_attributes_for_content_ids(
|
|
self,
|
|
*,
|
|
definition_set_id: UUID,
|
|
content_ids: list[UUID],
|
|
) -> dict[UUID, dict[str, Any]]:
|
|
if not content_ids:
|
|
return {}
|
|
|
|
definitions = await self.load_active_definitions(
|
|
definition_set_id
|
|
)
|
|
definition_by_id = {
|
|
definition.id: definition
|
|
for definition in definitions
|
|
}
|
|
|
|
statement = text(
|
|
f"""
|
|
select
|
|
id,
|
|
content_id,
|
|
attribute_definition_id,
|
|
parent_attribute_value_id,
|
|
value_text,
|
|
value_number,
|
|
value_boolean,
|
|
value_date,
|
|
value_json,
|
|
media_asset_id,
|
|
sort_order
|
|
from {self._schema}.content_attributes
|
|
where content_id in :content_ids
|
|
order by
|
|
content_id,
|
|
parent_attribute_value_id nulls first,
|
|
sort_order,
|
|
id
|
|
"""
|
|
).bindparams(
|
|
bindparam("content_ids", expanding=True)
|
|
)
|
|
|
|
result = await self._session.execute(
|
|
statement,
|
|
{"content_ids": content_ids},
|
|
)
|
|
rows = [dict(row) for row in result.mappings()]
|
|
|
|
rows_by_content: dict[UUID, list[dict[str, Any]]] = {
|
|
content_id: []
|
|
for content_id in content_ids
|
|
}
|
|
for row in rows:
|
|
rows_by_content.setdefault(
|
|
row["content_id"], []
|
|
).append(row)
|
|
|
|
return {
|
|
content_id: self._project_content_attributes(
|
|
rows=rows_by_content.get(content_id, []),
|
|
definition_by_id=definition_by_id,
|
|
)
|
|
for content_id in content_ids
|
|
}
|
|
|
|
def _project_content_attributes(
|
|
self,
|
|
*,
|
|
rows: list[dict[str, Any]],
|
|
definition_by_id: dict[UUID, AttributeDefinitionRecord],
|
|
) -> dict[str, Any]:
|
|
by_parent: dict[UUID | None, list[dict[str, Any]]] = {}
|
|
for row in rows:
|
|
definition = definition_by_id.get(
|
|
row["attribute_definition_id"]
|
|
)
|
|
if definition is None:
|
|
# Historical/inactive values are deliberately omitted from the
|
|
# collection projection. Detail endpoints may use a historical
|
|
# builder if they need inactive definitions.
|
|
continue
|
|
by_parent.setdefault(
|
|
row["parent_attribute_value_id"], []
|
|
).append(row)
|
|
|
|
def build_level(
|
|
parent_id: UUID | None,
|
|
) -> dict[str, Any]:
|
|
grouped: dict[
|
|
UUID, list[dict[str, Any]]
|
|
] = {}
|
|
for row in by_parent.get(parent_id, []):
|
|
grouped.setdefault(
|
|
row["attribute_definition_id"], []
|
|
).append(row)
|
|
|
|
output: dict[str, Any] = {}
|
|
ordered_groups = sorted(
|
|
grouped.items(),
|
|
key=lambda pair: (
|
|
definition_by_id[pair[0]].sort_order,
|
|
definition_by_id[pair[0]].attribute_key,
|
|
),
|
|
)
|
|
|
|
for definition_id, values in ordered_groups:
|
|
definition = definition_by_id[definition_id]
|
|
projected = [
|
|
project_row(row, definition)
|
|
for row in sorted(
|
|
values,
|
|
key=lambda item: (
|
|
item["sort_order"],
|
|
str(item["id"]),
|
|
),
|
|
)
|
|
]
|
|
|
|
if definition.is_multivalue:
|
|
output[definition.local_code] = projected
|
|
else:
|
|
if len(projected) > 1:
|
|
raise ContentProjectionError(
|
|
"Multiple values exist for non-multivalue "
|
|
f"attribute {definition.attribute_key!r}"
|
|
)
|
|
output[definition.local_code] = projected[0]
|
|
|
|
return output
|
|
|
|
def project_row(
|
|
row: dict[str, Any],
|
|
definition: AttributeDefinitionRecord,
|
|
) -> Any:
|
|
if definition.definition_kind == "object":
|
|
return build_level(row["id"])
|
|
|
|
data_type = definition.data_type
|
|
if data_type in {"text", "rich_text"}:
|
|
return row["value_text"]
|
|
if data_type == "number":
|
|
value = row["value_number"]
|
|
return float(value) if value is not None else None
|
|
if data_type == "boolean":
|
|
return row["value_boolean"]
|
|
if data_type == "date":
|
|
value = row["value_date"]
|
|
return value.isoformat() if value is not None else None
|
|
if data_type == "json":
|
|
return row["value_json"]
|
|
if data_type == "media":
|
|
value = row["media_asset_id"]
|
|
return str(value) if value is not None else None
|
|
|
|
raise ContentProjectionError(
|
|
f"Unsupported data type {data_type!r} for "
|
|
f"{definition.attribute_key!r}"
|
|
)
|
|
|
|
return build_level(None)
|
|
|
|
### search end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def get_content_media_for_content_ids(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
content_ids: list[UUID],
|
|
) -> dict[UUID, list[dict[str, Any]]]:
|
|
"""
|
|
Load normalized relational media for a set of content items in one query.
|
|
|
|
Ordering is deterministic: primary first, then association sort_order,
|
|
then association UUID. Only active image assets are returned.
|
|
"""
|
|
if not content_ids:
|
|
return {}
|
|
|
|
stmt = text(f"""
|
|
SELECT
|
|
cm.id AS id,
|
|
cm.content_id AS content_id,
|
|
ma.id AS media_asset_id,
|
|
COALESCE(cm.media_role, 'gallery') AS media_role,
|
|
COALESCE(cm.usage_type, 'general') AS usage_type,
|
|
COALESCE(cm.sort_order, 0) AS sort_order,
|
|
cm.caption AS caption,
|
|
ma.alt_text AS alt_text,
|
|
ma.mime_type AS mime_type,
|
|
COALESCE(ma.width_px, ma.width) AS width,
|
|
COALESCE(ma.height_px, ma.height) AS height,
|
|
ma.storage_key AS storage_key,
|
|
ma.file_path AS file_path
|
|
FROM {self._schema}.content_media cm
|
|
JOIN {self._schema}.media_assets ma
|
|
ON ma.id = cm.media_asset_id
|
|
WHERE cm.content_id = ANY(CAST(:content_ids AS uuid[]))
|
|
AND COALESCE(ma.status, 'active') = 'active'
|
|
AND (ma.media_kind IS NULL OR ma.media_kind::text = 'image')
|
|
ORDER BY
|
|
cm.content_id,
|
|
CASE WHEN cm.media_role = 'primary' THEN 0 ELSE 1 END,
|
|
COALESCE(cm.sort_order, 0),
|
|
cm.id
|
|
""")
|
|
|
|
result = await session.execute(
|
|
stmt,
|
|
{"content_ids": content_ids},
|
|
)
|
|
|
|
grouped: dict[UUID, list[dict[str, Any]]] = {}
|
|
for row in result.mappings().all():
|
|
grouped.setdefault(row["content_id"], []).append(dict(row))
|
|
|
|
return grouped
|
|
|
|
async def get_content_media(
|
|
self,
|
|
*,
|
|
session: AsyncSession,
|
|
content_id: UUID,
|
|
) -> list[dict[str, Any]]:
|
|
grouped = await self.get_content_media_for_content_ids(
|
|
session=session,
|
|
content_ids=[content_id],
|
|
)
|
|
return grouped.get(content_id, [])
|
|
|
|
|
|
async def validate_content_for_publish(
|
|
*,
|
|
session: AsyncSession,
|
|
content_id: UUID,
|
|
) -> None:
|
|
"""Validate persisted typed-EAV content before publishing."""
|
|
|
|
content = await session.get(ContentItem, content_id)
|
|
if content is None:
|
|
raise ContentNotFoundError(f"Content item not found: {content_id}")
|
|
|
|
definition_set_id = content.attribute_definition_set_id
|
|
if definition_set_id is None:
|
|
raise ContentDefinitionSetError(
|
|
f"Content {content_id} has no attribute_definition_set_id"
|
|
)
|
|
|
|
stmt = (
|
|
select(
|
|
ContentAttribute.id,
|
|
ContentAttribute.content_id,
|
|
ContentAttribute.attribute_definition_id,
|
|
ContentAttribute.parent_attribute_value_id,
|
|
ContentAttribute.value_text,
|
|
ContentAttribute.value_number,
|
|
ContentAttribute.value_boolean,
|
|
ContentAttribute.value_date,
|
|
ContentAttribute.value_json,
|
|
ContentAttribute.media_asset_id,
|
|
AttributeDefinition.attribute_definition_set_id,
|
|
AttributeDefinition.attribute_key,
|
|
AttributeDefinition.definition_kind,
|
|
AttributeDefinition.is_root,
|
|
)
|
|
.join(
|
|
AttributeDefinition,
|
|
AttributeDefinition.id == ContentAttribute.attribute_definition_id,
|
|
)
|
|
.where(ContentAttribute.content_id == content_id)
|
|
)
|
|
|
|
result = await session.execute(stmt)
|
|
values = [dict(row) for row in result.mappings().all()]
|
|
|
|
for row in values:
|
|
if row["attribute_definition_set_id"] != definition_set_id:
|
|
raise ContentDefinitionSetError(
|
|
"Stored attribute belongs to another definition set. "
|
|
f"attribute={row['attribute_key']!r}"
|
|
)
|
|
|
|
required_stmt = (
|
|
select(AttributeDefinition.id, AttributeDefinition.attribute_key)
|
|
.where(
|
|
AttributeDefinition.attribute_definition_set_id == definition_set_id,
|
|
AttributeDefinition.is_active.is_(True),
|
|
AttributeDefinition.is_root.is_(True),
|
|
AttributeDefinition.is_required.is_(True),
|
|
)
|
|
.order_by(
|
|
AttributeDefinition.sort_order.asc(),
|
|
AttributeDefinition.attribute_key.asc(),
|
|
)
|
|
)
|
|
|
|
required_roots = (await session.execute(required_stmt)).mappings().all()
|
|
|
|
for definition in required_roots:
|
|
exists_stmt = (
|
|
select(ContentAttribute.id)
|
|
.where(
|
|
ContentAttribute.content_id == content_id,
|
|
ContentAttribute.attribute_definition_id == definition["id"],
|
|
ContentAttribute.parent_attribute_value_id.is_(None),
|
|
)
|
|
.limit(1)
|
|
)
|
|
if (await session.execute(exists_stmt)).scalar_one_or_none() is None:
|
|
raise RequiredAttributeMissingError(
|
|
f"Required root attribute missing: {definition['attribute_key']}"
|
|
)
|
|
|
|
by_id = {row["id"]: row for row in values}
|
|
|
|
for row in values:
|
|
parent_id = row["parent_attribute_value_id"]
|
|
|
|
if parent_id is None:
|
|
if not row["is_root"]:
|
|
raise ContentAttributeHierarchyError(
|
|
f"Non-root definition stored at root: {row['attribute_key']}"
|
|
)
|
|
else:
|
|
parent = by_id.get(parent_id)
|
|
if parent is None:
|
|
raise ContentAttributeHierarchyError(
|
|
f"Missing parent value {parent_id} for {row['id']}"
|
|
)
|
|
if parent["content_id"] != row["content_id"]:
|
|
raise ContentAttributeHierarchyError(
|
|
"Parent and child values belong to different content items"
|
|
)
|
|
if parent["definition_kind"] != "object":
|
|
raise ContentAttributeHierarchyError(
|
|
f"Scalar attribute used as parent: {parent['attribute_key']}"
|
|
)
|
|
|
|
allowed_stmt = (
|
|
select(AttributeDefinitionMember.id)
|
|
.where(
|
|
AttributeDefinitionMember.parent_attribute_definition_id
|
|
== parent["attribute_definition_id"],
|
|
AttributeDefinitionMember.child_attribute_definition_id
|
|
== row["attribute_definition_id"],
|
|
)
|
|
.limit(1)
|
|
)
|
|
if (await session.execute(allowed_stmt)).scalar_one_or_none() is None:
|
|
raise ContentAttributeHierarchyError(
|
|
f"Child {row['attribute_key']} is not allowed below "
|
|
f"{parent['attribute_key']}"
|
|
)
|
|
|
|
populated = sum(
|
|
value is not None
|
|
for value in (
|
|
row["value_text"],
|
|
row["value_number"],
|
|
row["value_boolean"],
|
|
row["value_date"],
|
|
row["value_json"],
|
|
row["media_asset_id"],
|
|
)
|
|
)
|
|
|
|
if row["definition_kind"] == "object" and populated != 0:
|
|
raise ContentAttributeHierarchyError(
|
|
f"Object attribute contains scalar payload: {row['attribute_key']}"
|
|
)
|
|
if row["definition_kind"] == "scalar" and populated != 1:
|
|
raise ContentAttributeHierarchyError(
|
|
f"Scalar attribute must have exactly one typed value: "
|
|
f"{row['attribute_key']}"
|
|
)
|
|
|
|
for object_row in [r for r in values if r["definition_kind"] == "object"]:
|
|
member_stmt = (
|
|
select(
|
|
AttributeDefinitionMember.child_attribute_definition_id,
|
|
AttributeDefinitionMember.is_required.label("member_required"),
|
|
AttributeDefinition.attribute_key,
|
|
AttributeDefinition.is_required.label("definition_required"),
|
|
AttributeDefinition.is_active,
|
|
)
|
|
.join(
|
|
AttributeDefinition,
|
|
AttributeDefinition.id
|
|
== AttributeDefinitionMember.child_attribute_definition_id,
|
|
)
|
|
.where(
|
|
AttributeDefinitionMember.parent_attribute_definition_id
|
|
== object_row["attribute_definition_id"],
|
|
AttributeDefinition.attribute_definition_set_id == definition_set_id,
|
|
)
|
|
)
|
|
|
|
members = (await session.execute(member_stmt)).mappings().all()
|
|
|
|
for member in members:
|
|
if not member["is_active"]:
|
|
continue
|
|
if not (member["member_required"] or member["definition_required"]):
|
|
continue
|
|
|
|
child_stmt = (
|
|
select(ContentAttribute.id)
|
|
.where(
|
|
ContentAttribute.content_id == content_id,
|
|
ContentAttribute.parent_attribute_value_id == object_row["id"],
|
|
ContentAttribute.attribute_definition_id
|
|
== member["child_attribute_definition_id"],
|
|
)
|
|
.limit(1)
|
|
)
|
|
if (await session.execute(child_stmt)).scalar_one_or_none() is None:
|
|
raise RequiredAttributeMissingError(
|
|
"Required child attribute missing. "
|
|
f"parent={object_row['attribute_key']!r}, "
|
|
f"child={member['attribute_key']!r}"
|
|
)
|