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

280 lines
12 KiB
Python

from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from .schema import CONTENT_SCHEMA, resolve_content_schema
from app.features.search.repository import SearchRepository
class SearchFacetSeedError(ValueError):
pass
def _required_string(value: Any, field: str) -> str:
if not isinstance(value, str) or not value.strip():
raise SearchFacetSeedError(f"{field} must be a non-empty string")
return value.strip()
class SearchFacetSeeder:
"""Idempotently seed canonical search facets and attribute mappings."""
def __init__(self, session: AsyncSession, *, schema: str = CONTENT_SCHEMA) -> None:
self.session = session
self.schema = resolve_content_schema(schema)
self.repository = SearchRepository(session, schema=self.schema)
async def seed_file(self, path: Path, *, module_code: str) -> tuple[int, int]:
if not path.exists():
return 0, 0
document = json.loads(path.read_text(encoding="utf-8"))
return await self.seed_document(document, module_code=module_code)
async def seed_document(
self,
document: dict[str, Any],
*,
module_code: str,
) -> tuple[int, int]:
facets = document.get("facets")
if not isinstance(facets, list):
raise SearchFacetSeedError("search_facets.json.facets must be an array")
module_code = module_code.strip().lower()
module_result = await self.session.execute(
text(
f"select id from {self.schema}.modules where code = :code"
),
{"code": module_code},
)
module_id = module_result.scalar_one_or_none()
if module_id is None:
raise SearchFacetSeedError(f"Module not found: {module_code}")
facet_count = 0
mapping_count = 0
# `search_facets.json` is the desired mapping state for this module.
# We collect the module-scoped mapping IDs declared by the file and
# deactivate stale mappings owned by this module after all upserts.
# Global/unscoped mappings and mappings owned by other modules are
# deliberately outside this reconciliation boundary.
declared_module_mapping_ids: set[Any] = set()
for facet_raw in facets:
if not isinstance(facet_raw, dict):
raise SearchFacetSeedError("Each facet must be an object")
code = _required_string(facet_raw.get("code"), "facet.code").lower()
label = _required_string(facet_raw.get("label"), f"facet[{code}].label")
category = _required_string(
facet_raw.get("category", "General"),
f"facet[{code}].category",
)
control_type = str(facet_raw.get("control_type", "typeahead_multi")).strip()
value_source = str(facet_raw.get("value_source", "projected")).strip()
facet_result = await self.session.execute(
text(
f"""
insert into {self.schema}.search_facet_definitions (
code, label, category, description, control_type,
allow_multiple_values, value_source, sort_order,
is_active, metadata, updated_at
) values (
:code, :label, :category, :description, :control_type,
:allow_multiple_values, :value_source, :sort_order,
:is_active, cast(:metadata as jsonb), now()
)
on conflict (code) do update set
label = excluded.label,
category = excluded.category,
description = excluded.description,
control_type = excluded.control_type,
allow_multiple_values = excluded.allow_multiple_values,
value_source = excluded.value_source,
sort_order = excluded.sort_order,
is_active = excluded.is_active,
metadata = excluded.metadata,
updated_at = now()
returning id
"""
),
{
"code": code,
"label": label,
"category": category,
"description": facet_raw.get("description"),
"control_type": control_type,
"allow_multiple_values": bool(facet_raw.get("allow_multiple_values", True)),
"value_source": value_source,
"sort_order": int(facet_raw.get("sort_order", 0)),
"is_active": bool(facet_raw.get("is_active", True)),
"metadata": json.dumps(facet_raw.get("metadata") or {}),
},
)
facet_id = facet_result.scalar_one()
facet_count += 1
for index, mapping_raw in enumerate(facet_raw.get("mappings") or []):
if not isinstance(mapping_raw, dict):
raise SearchFacetSeedError(f"facet[{code}].mappings[{index}] must be an object")
attribute_key = _required_string(
mapping_raw.get("attribute_key"),
f"facet[{code}].mappings[{index}].attribute_key",
)
template_code = _required_string(
mapping_raw.get("template_code"),
f"facet[{code}].mappings[{index}].template_code",
).lower()
definition_result = await self.session.execute(
text(
f"""
select ad.id
from {self.schema}.attribute_definitions ad
join {self.schema}.attribute_definition_sets ads
on ads.id = ad.attribute_definition_set_id
where ads.code = :template_code
and ad.attribute_key = :attribute_key
and ad.is_active = true
"""
),
{
"template_code": template_code,
"attribute_key": attribute_key,
},
)
attribute_definition_id = definition_result.scalar_one_or_none()
if attribute_definition_id is None:
raise SearchFacetSeedError(
f"Active attribute definition not found: {template_code}/{attribute_key}"
)
mapping_module_id = (
module_id if mapping_raw.get("module_scoped", True) else None
)
mapping_content_kind = mapping_raw.get("content_kind")
existing_result = await self.session.execute(
text(
f"""
select id
from {self.schema}.search_facet_mappings
where facet_id = :facet_id
and attribute_definition_id = :attribute_definition_id
and module_id is not distinct from :module_id
and content_kind is not distinct from :content_kind
"""
),
{
"facet_id": facet_id,
"attribute_definition_id": attribute_definition_id,
"module_id": mapping_module_id,
"content_kind": mapping_content_kind,
},
)
existing_id = existing_result.scalar_one_or_none()
mapping_params = {
"facet_id": facet_id,
"attribute_definition_id": attribute_definition_id,
"module_id": mapping_module_id,
"content_kind": mapping_content_kind,
"mapping_strategy": mapping_raw.get("mapping_strategy", "auto"),
"weight": float(mapping_raw.get("weight", 1.0)),
"sort_order": int(mapping_raw.get("sort_order", index)),
"is_active": bool(mapping_raw.get("is_active", True)),
"metadata": json.dumps(mapping_raw.get("metadata") or {}),
}
if existing_id is None:
inserted_mapping = await self.session.execute(
text(
f"""
insert into {self.schema}.search_facet_mappings (
facet_id, attribute_definition_id, module_id,
content_kind, mapping_strategy, weight,
sort_order, is_active, metadata, updated_at
) values (
:facet_id, :attribute_definition_id, :module_id,
:content_kind, :mapping_strategy, :weight,
:sort_order, :is_active, cast(:metadata as jsonb), now()
)
returning id
"""
),
mapping_params,
)
mapping_id = inserted_mapping.scalar_one()
else:
await self.session.execute(
text(
f"""
update {self.schema}.search_facet_mappings
set mapping_strategy = :mapping_strategy,
weight = :weight,
sort_order = :sort_order,
is_active = :is_active,
metadata = cast(:metadata as jsonb),
updated_at = now()
where id = :id
"""
),
{**mapping_params, "id": existing_id},
)
mapping_id = existing_id
if mapping_module_id == module_id:
declared_module_mapping_ids.add(mapping_id)
mapping_count += 1
await self._deactivate_stale_module_mappings(
module_id=module_id,
declared_mapping_ids=declared_module_mapping_ids,
)
# Mapping changes are immediately reflected in the projection.
await self.repository.rebuild_all([module_code])
return facet_count, mapping_count
async def _deactivate_stale_module_mappings(
self,
*,
module_id: Any,
declared_mapping_ids: set[Any],
) -> None:
"""
Reconcile only mappings owned by the module currently being seeded.
Facet definitions are canonical/global entities, so omission from one
module's file must never deactivate the facet itself. Likewise,
mappings with module_id NULL are global/unscoped and are intentionally
not reconciled by a module-specific configuration file.
"""
params: dict[str, Any] = {"module_id": module_id}
if declared_mapping_ids:
params["declared_mapping_ids"] = list(declared_mapping_ids)
stale_predicate = "and not (id = any(:declared_mapping_ids))"
else:
stale_predicate = ""
await self.session.execute(
text(
f"""
update {self.schema}.search_facet_mappings
set is_active = false,
updated_at = now()
where module_id = :module_id
and is_active = true
{stale_predicate}
"""
),
params,
)