acupedia-api/app/bootstrap/seed_content/presentation.py

290 lines
11 KiB
Python

from __future__ import annotations
import json
from typing import Any, Mapping
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from .schema import CONTENT_SCHEMA, resolve_content_schema
from .models import DefinitionSet, PresentationContractSeedResult
from .validators import validate_presentation_contracts
class TemplatePresentationSeeder:
"""Idempotent, version-preserving presentation-contract seeder.
Natural key:
(attribute_definition_set_id, client_type, version_no)
This class never commits. Transaction ownership remains with the existing
SeedOrchestrator. When an incoming version is active, any other active
version for the same definition-set/client is deactivated first so the
database partial unique index is never violated.
"""
def __init__(self, session: AsyncSession, *, schema: str = CONTENT_SCHEMA) -> None:
self._session = session
self._schema = resolve_content_schema(schema)
async def seed(
self,
*,
definition_set: DefinitionSet,
document: Mapping[str, Any],
) -> tuple[PresentationContractSeedResult, ...]:
contracts = validate_presentation_contracts(document)
results: list[PresentationContractSeedResult] = []
for contract in contracts:
results.append(
await self._upsert_contract(
definition_set=definition_set,
contract=contract,
)
)
return tuple(results)
async def _upsert_contract(
self,
*,
definition_set: DefinitionSet,
contract: Mapping[str, Any],
) -> PresentationContractSeedResult:
client_type = str(contract["client_type"])
version_no = int(contract["version_no"])
is_active = bool(contract["is_active"])
renderers = contract["renderers"]
existing_result = await self._session.execute(
text(
f"""
select id
from {self._schema}.template_presentation_contracts
where attribute_definition_set_id = :definition_set_id
and client_type = :client_type
and version_no = :version_no
for update
"""
),
{
"definition_set_id": definition_set.id,
"client_type": client_type,
"version_no": version_no,
},
)
existing_id = existing_result.scalar_one_or_none()
if is_active:
await self._session.execute(
text(
f"""
update {self._schema}.template_presentation_contracts
set is_active = false,
updated_at = now()
where attribute_definition_set_id = :definition_set_id
and client_type = :client_type
and is_active = true
and version_no <> :version_no
"""
),
{
"definition_set_id": definition_set.id,
"client_type": client_type,
"version_no": version_no,
},
)
result = await self._session.execute(
text(
f"""
insert into {self._schema}.template_presentation_contracts (
attribute_definition_set_id,
client_type,
presentation_mode,
collection_renderer,
collection_item_renderer,
detail_renderer,
version_no,
is_active,
metadata
) values (
:definition_set_id,
:client_type,
:presentation_mode,
:collection_renderer,
:collection_item_renderer,
:detail_renderer,
:version_no,
:is_active,
cast(:metadata as jsonb)
)
on conflict (
attribute_definition_set_id,
client_type,
version_no
)
do update set
presentation_mode = excluded.presentation_mode,
collection_renderer = excluded.collection_renderer,
collection_item_renderer = excluded.collection_item_renderer,
detail_renderer = excluded.detail_renderer,
is_active = excluded.is_active,
metadata = excluded.metadata,
updated_at = now()
returning
id,
attribute_definition_set_id,
client_type,
presentation_mode,
version_no,
is_active
"""
),
{
"definition_set_id": definition_set.id,
"client_type": client_type,
"presentation_mode": contract["mode"],
"collection_renderer": renderers.get("collection"),
"collection_item_renderer": renderers.get("collection_item"),
"detail_renderer": renderers["detail"],
"version_no": version_no,
"is_active": is_active,
"metadata": json.dumps(contract.get("metadata") or {}),
},
)
row = result.mappings().one()
await self._reconcile_attribute_presentations(
presentation_contract_id=row["id"],
definition_set=definition_set,
attributes=contract.get("attributes") or [],
)
return PresentationContractSeedResult(
id=row["id"],
definition_set_id=row["attribute_definition_set_id"],
definition_set_code=definition_set.code,
client_type=row["client_type"],
presentation_mode=row["presentation_mode"],
version_no=row["version_no"],
is_active=row["is_active"],
created=existing_id is None,
updated=existing_id is not None,
)
async def _reconcile_attribute_presentations(
self,
*,
presentation_contract_id,
definition_set: DefinitionSet,
attributes: list[Mapping[str, Any]],
) -> None:
"""Upsert declared attribute overrides and remove stale overrides.
The template JSON is the source of truth for a given contract version.
An omitted/empty attributes array therefore means there are no explicit
overrides for that contract; effective behavior falls back to HIDE.
"""
definition_result = await self._session.execute(
text(
f"""
select id, attribute_key
from {self._schema}.attribute_definitions
where attribute_definition_set_id = :definition_set_id
"""
),
{"definition_set_id": definition_set.id},
)
definitions_by_key = {
str(row["attribute_key"]): row["id"]
for row in definition_result.mappings().all()
}
desired_definition_ids = []
for attribute in attributes:
attribute_key = str(attribute["attribute_key"])
attribute_metadata = dict(attribute.get("metadata") or {})
attribute_metadata["visibility"] = attribute.get("visibility", "show")
# display_order is a presentation concern, not a definition concern.
# Persist it in the existing JSONB metadata so no schema migration is
# required. Omission removes any previously seeded override.
display_order = attribute.get("display_order")
if display_order is None:
attribute_metadata.pop("display_order", None)
else:
attribute_metadata["display_order"] = int(display_order)
attribute_definition_id = definitions_by_key.get(attribute_key)
if attribute_definition_id is None:
raise ValueError(
f"Presentation attribute {attribute_key!r} does not belong to "
f"definition set {definition_set.code!r}"
)
await self._session.execute(
text(
f"""
insert into {self._schema}.template_attribute_presentations (
template_presentation_contract_id,
attribute_definition_id,
empty_behavior,
empty_text,
metadata
) values (
:presentation_contract_id,
:attribute_definition_id,
:empty_behavior,
:empty_text,
cast(:metadata as jsonb)
)
on conflict (
template_presentation_contract_id,
attribute_definition_id
)
do update set
empty_behavior = excluded.empty_behavior,
empty_text = excluded.empty_text,
metadata = excluded.metadata,
updated_at = now()
"""
),
{
"presentation_contract_id": presentation_contract_id,
"attribute_definition_id": attribute_definition_id,
"empty_behavior": attribute["empty_behavior"],
"empty_text": attribute.get("empty_text"),
"metadata": json.dumps(attribute_metadata),
},
)
desired_definition_ids.append(attribute_definition_id)
if desired_definition_ids:
await self._session.execute(
text(
f"""
delete from {self._schema}.template_attribute_presentations
where template_presentation_contract_id = :presentation_contract_id
and attribute_definition_id <> all(:desired_definition_ids)
"""
),
{
"presentation_contract_id": presentation_contract_id,
"desired_definition_ids": desired_definition_ids,
},
)
else:
await self._session.execute(
text(
f"""
delete from {self._schema}.template_attribute_presentations
where template_presentation_contract_id = :presentation_contract_id
"""
),
{"presentation_contract_id": presentation_contract_id},
)