178 lines
5.9 KiB
Python
178 lines
5.9 KiB
Python
"""Contact search provider — works with unified contacts 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 ContactSearchProvider(BaseSearchProvider):
|
|
"""Search provider for Contact entities (all types)."""
|
|
|
|
entity_type = "contact"
|
|
|
|
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 contacts.search_tsv, filtered by visible_ids.
|
|
|
|
If visible_ids is None, no visibility filter is applied (system admin).
|
|
"""
|
|
if visible_ids is not None:
|
|
sql = text(
|
|
"""
|
|
SELECT c.*, ts_rank(c.search_tsv, to_tsquery('pg_catalog.german', :q)) AS rank
|
|
FROM contacts c
|
|
WHERE c.tenant_id = :tid
|
|
AND c.deleted_at IS NULL
|
|
AND c.search_tsv @@ to_tsquery('pg_catalog.german', :q)
|
|
AND c.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 c.*, ts_rank(c.search_tsv, to_tsquery('pg_catalog.german', :q)) AS rank
|
|
FROM contacts c
|
|
WHERE c.tenant_id = :tid
|
|
AND c.deleted_at IS NULL
|
|
AND c.search_tsv @@ 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 on contacts.embedding, filtered by visible_ids.
|
|
|
|
If visible_ids is None, no visibility filter is applied (system admin).
|
|
"""
|
|
if visible_ids is not None:
|
|
sql = text(
|
|
"""
|
|
SELECT c.*, 1 - (c.embedding <=> cast(:emb AS vector)) AS score
|
|
FROM contacts c
|
|
WHERE c.tenant_id = :tid
|
|
AND c.deleted_at IS NULL
|
|
AND c.embedding IS NOT NULL
|
|
AND c.id = ANY(:visible_ids)
|
|
ORDER BY c.embedding <=> cast(:emb AS vector)
|
|
LIMIT :lim
|
|
"""
|
|
)
|
|
result = await db.execute(
|
|
sql,
|
|
{
|
|
"emb": str(embedding),
|
|
"tid": tenant_id,
|
|
"lim": limit,
|
|
"visible_ids": list(visible_ids),
|
|
},
|
|
)
|
|
else:
|
|
sql = text(
|
|
"""
|
|
SELECT c.*, 1 - (c.embedding <=> cast(:emb AS vector)) AS score
|
|
FROM contacts c
|
|
WHERE c.tenant_id = :tid
|
|
AND c.deleted_at IS NULL
|
|
AND c.embedding IS NOT NULL
|
|
ORDER BY c.embedding <=> cast(:emb AS vector)
|
|
LIMIT :lim
|
|
"""
|
|
)
|
|
result = await db.execute(
|
|
sql,
|
|
{"emb": str(embedding), "tid": tenant_id, "lim": limit},
|
|
)
|
|
rows = result.mappings().all()
|
|
return [dict(r) for r in rows]
|
|
|
|
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, name, firstname, surname, email_1, email_2,
|
|
phone_1, phone_2, mailing_city, tags, contact_warning
|
|
FROM contacts
|
|
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("name", ""),
|
|
row.get("firstname", ""),
|
|
row.get("surname", ""),
|
|
row.get("email_1", ""),
|
|
row.get("email_2", ""),
|
|
row.get("phone_1", ""),
|
|
row.get("phone_2", ""),
|
|
row.get("mailing_city", ""),
|
|
row.get("tags", ""),
|
|
]
|
|
return " ".join(str(p) for p in parts if p)
|
|
|
|
def to_search_result(self, entity: object) -> dict[str, Any]:
|
|
"""Convert contact to search result dict."""
|
|
if isinstance(entity, dict):
|
|
displayname = entity.get("displayname", "")
|
|
email = entity.get("email_1", "")
|
|
entity_id = str(entity.get("id", ""))
|
|
contact_type = entity.get("type", "")
|
|
else:
|
|
displayname = getattr(entity, "displayname", "")
|
|
email = getattr(entity, "email_1", "")
|
|
entity_id = str(getattr(entity, "id", ""))
|
|
contact_type = getattr(entity, "type", "")
|
|
return {
|
|
"entity_type": self.entity_type,
|
|
"entity_id": entity_id,
|
|
"title": displayname,
|
|
"snippet": email or "",
|
|
"score": 0.0,
|
|
"data": {"type": contact_type},
|
|
}
|