163 lines
5.6 KiB
Python
163 lines
5.6 KiB
Python
|
|
"""User search provider — queries users table via user_tenants for tenant scope."""
|
||
|
|
|
||
|
|
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 UserSearchProvider(BaseSearchProvider):
|
||
|
|
"""Search provider for User entities.
|
||
|
|
|
||
|
|
Users are global entities (no tenant_id on users table).
|
||
|
|
Tenant membership is resolved via user_tenants join.
|
||
|
|
"""
|
||
|
|
|
||
|
|
entity_type = "user"
|
||
|
|
|
||
|
|
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 users fields, filtered by tenant membership."""
|
||
|
|
if visible_ids is not None:
|
||
|
|
sql = text(
|
||
|
|
"""
|
||
|
|
SELECT u.*, ts_rank(
|
||
|
|
to_tsvector('pg_catalog.german',
|
||
|
|
coalesce(u.name, '') || ' ' ||
|
||
|
|
coalesce(u.first_name, '') || ' ' ||
|
||
|
|
coalesce(u.last_name, '') || ' ' ||
|
||
|
|
coalesce(u.email, '')
|
||
|
|
),
|
||
|
|
to_tsquery('pg_catalog.german', :q)
|
||
|
|
) AS rank
|
||
|
|
FROM users u
|
||
|
|
JOIN user_tenants ut ON ut.user_id = u.id
|
||
|
|
WHERE ut.tenant_id = :tid
|
||
|
|
AND u.deleted_at IS NULL
|
||
|
|
AND u.is_active = true
|
||
|
|
AND to_tsvector('pg_catalog.german',
|
||
|
|
coalesce(u.name, '') || ' ' ||
|
||
|
|
coalesce(u.first_name, '') || ' ' ||
|
||
|
|
coalesce(u.last_name, '') || ' ' ||
|
||
|
|
coalesce(u.email, '')
|
||
|
|
) @@ to_tsquery('pg_catalog.german', :q)
|
||
|
|
AND u.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 u.*, ts_rank(
|
||
|
|
to_tsvector('pg_catalog.german',
|
||
|
|
coalesce(u.name, '') || ' ' ||
|
||
|
|
coalesce(u.first_name, '') || ' ' ||
|
||
|
|
coalesce(u.last_name, '') || ' ' ||
|
||
|
|
coalesce(u.email, '')
|
||
|
|
),
|
||
|
|
to_tsquery('pg_catalog.german', :q)
|
||
|
|
) AS rank
|
||
|
|
FROM users u
|
||
|
|
JOIN user_tenants ut ON ut.user_id = u.id
|
||
|
|
WHERE ut.tenant_id = :tid
|
||
|
|
AND u.deleted_at IS NULL
|
||
|
|
AND u.is_active = true
|
||
|
|
AND to_tsvector('pg_catalog.german',
|
||
|
|
coalesce(u.name, '') || ' ' ||
|
||
|
|
coalesce(u.first_name, '') || ' ' ||
|
||
|
|
coalesce(u.last_name, '') || ' ' ||
|
||
|
|
coalesce(u.email, '')
|
||
|
|
) @@ 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 — users 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 name, first_name, last_name, email
|
||
|
|
FROM users
|
||
|
|
WHERE id = :eid
|
||
|
|
"""
|
||
|
|
)
|
||
|
|
result = await db.execute(sql, {"eid": entity_id})
|
||
|
|
row = result.mappings().first()
|
||
|
|
if not row:
|
||
|
|
return ""
|
||
|
|
parts = [
|
||
|
|
row.get("name", ""),
|
||
|
|
row.get("first_name", ""),
|
||
|
|
row.get("last_name", ""),
|
||
|
|
row.get("email", ""),
|
||
|
|
]
|
||
|
|
return " ".join(str(p) for p in parts if p)
|
||
|
|
|
||
|
|
def to_search_result(self, entity: object) -> dict[str, Any]:
|
||
|
|
"""Convert user to search result dict."""
|
||
|
|
if isinstance(entity, dict):
|
||
|
|
name = entity.get("name", "")
|
||
|
|
email = entity.get("email", "") or ""
|
||
|
|
entity_id = str(entity.get("id", ""))
|
||
|
|
first_name = entity.get("first_name", "") or ""
|
||
|
|
last_name = entity.get("last_name", "") or ""
|
||
|
|
else:
|
||
|
|
name = getattr(entity, "name", "")
|
||
|
|
email = getattr(entity, "email", "") or ""
|
||
|
|
entity_id = str(getattr(entity, "id", ""))
|
||
|
|
first_name = getattr(entity, "first_name", "") or ""
|
||
|
|
last_name = getattr(entity, "last_name", "") or ""
|
||
|
|
display_name = f"{first_name} {last_name}".strip() or name
|
||
|
|
return {
|
||
|
|
"entity_type": self.entity_type,
|
||
|
|
"entity_id": entity_id,
|
||
|
|
"title": display_name,
|
||
|
|
"snippet": email[:200],
|
||
|
|
"score": 0.0,
|
||
|
|
"data": {"email": email},
|
||
|
|
}
|