"""ContactPerson search provider — queries contactpersons table.""" from __future__ import annotations import logging import uuid from typing import Any from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession from app.plugins.builtins.unified_search.base_provider import BaseSearchProvider logger = logging.getLogger(__name__) class ContactPersonSearchProvider(BaseSearchProvider): """Search provider for ContactPerson (Ansprechpartner) entities.""" entity_type = "contactperson" async def _search_fts_filtered( self, db: AsyncSession, tsquery: str, tenant_id: uuid.UUID, limit: int, visible_ids: set[uuid.UUID] | None, ) -> list[dict[str, Any]]: """Full-text search on contactpersons fields.""" if visible_ids is not None: sql = text( """ SELECT cp.*, ts_rank( to_tsvector('pg_catalog.german', coalesce(cp.displayname, '') || ' ' || coalesce(cp.firstname, '') || ' ' || coalesce(cp.lastname, '') || ' ' || coalesce(cp.email, '') || ' ' || coalesce(cp.function, '') || ' ' || coalesce(cp.tags, '') ), to_tsquery('pg_catalog.german', :q) ) AS rank FROM contactpersons cp WHERE cp.tenant_id = :tid AND cp.deleted_at IS NULL AND to_tsvector('pg_catalog.german', coalesce(cp.displayname, '') || ' ' || coalesce(cp.firstname, '') || ' ' || coalesce(cp.lastname, '') || ' ' || coalesce(cp.email, '') || ' ' || coalesce(cp.function, '') || ' ' || coalesce(cp.tags, '') ) @@ to_tsquery('pg_catalog.german', :q) AND cp.id = ANY(:visible_ids) ORDER BY rank DESC LIMIT :lim """ ) result = await db.execute( sql, { "q": tsquery, "tid": tenant_id, "lim": limit, "visible_ids": list(visible_ids), }, ) else: sql = text( """ SELECT cp.*, ts_rank( to_tsvector('pg_catalog.german', coalesce(cp.displayname, '') || ' ' || coalesce(cp.firstname, '') || ' ' || coalesce(cp.lastname, '') || ' ' || coalesce(cp.email, '') || ' ' || coalesce(cp.function, '') || ' ' || coalesce(cp.tags, '') ), to_tsquery('pg_catalog.german', :q) ) AS rank FROM contactpersons cp WHERE cp.tenant_id = :tid AND cp.deleted_at IS NULL AND to_tsvector('pg_catalog.german', coalesce(cp.displayname, '') || ' ' || coalesce(cp.firstname, '') || ' ' || coalesce(cp.lastname, '') || ' ' || coalesce(cp.email, '') || ' ' || coalesce(cp.function, '') || ' ' || coalesce(cp.tags, '') ) @@ to_tsquery('pg_catalog.german', :q) ORDER BY rank DESC LIMIT :lim """ ) result = await db.execute( sql, {"q": tsquery, "tid": tenant_id, "lim": limit}, ) rows = result.mappings().all() return [dict(r) for r in rows] async def _search_vector_filtered( self, db: AsyncSession, embedding: list[float], tenant_id: uuid.UUID, limit: int, visible_ids: set[uuid.UUID] | None, ) -> list[dict[str, Any]]: """Semantic search — contactpersons table has no embedding column yet.""" return [] async def get_embedding_text( self, db: AsyncSession, entity_id: uuid.UUID, tenant_id: uuid.UUID ) -> str: """Get text for embedding generation.""" sql = text( """ SELECT displayname, firstname, lastname, email, function, tags FROM contactpersons WHERE id = :eid AND tenant_id = :tid """ ) result = await db.execute(sql, {"eid": entity_id, "tid": tenant_id}) row = result.mappings().first() if not row: return "" parts = [ row.get("displayname", ""), row.get("firstname", ""), row.get("lastname", ""), row.get("email", ""), row.get("function", ""), row.get("tags", ""), ] return " ".join(str(p) for p in parts if p) def to_search_result(self, entity: object) -> dict[str, Any]: """Convert contactperson to search result dict.""" if isinstance(entity, dict): displayname = entity.get("displayname", "") email = entity.get("email", "") or "" entity_id = str(entity.get("id", "")) contact_id = str(entity.get("contact_id", "")) if entity.get("contact_id") else "" else: displayname = getattr(entity, "displayname", "") email = getattr(entity, "email", "") or "" entity_id = str(getattr(entity, "id", "")) contact_id = str(getattr(entity, "contact_id", "")) if getattr(entity, "contact_id", None) else "" return { "entity_type": self.entity_type, "entity_id": entity_id, "title": displayname, "snippet": email[:200], "score": 0.0, "data": {"contact_id": contact_id}, }