mirror of
https://github.com/idrainformatica/PecFlow.git
synced 2026-06-16 12:45:42 +02:00
338 lines
11 KiB
Python
338 lines
11 KiB
Python
"""
|
|
Router Impostazioni Tenant.
|
|
|
|
Endpoint esistenti:
|
|
GET /settings -> legge le impostazioni del tenant corrente (admin)
|
|
PUT /settings -> aggiorna le impostazioni del tenant corrente (admin)
|
|
|
|
Endpoint indicizzazione full-text (Fase 8):
|
|
GET /settings/indexing/stats -> statistiche copertura indicizzazione
|
|
GET /settings/indexing/status -> stato job reindex in corso
|
|
POST /settings/indexing/reindex -> avvia reindex (full o differential)
|
|
DELETE /settings/indexing/reindex -> cancella job in corso
|
|
|
|
Solo admin e super_admin possono accedere.
|
|
Il super_admin puo' operare su qualsiasi tenant tramite query param ?tenant_id=<uuid>.
|
|
"""
|
|
|
|
import uuid
|
|
from typing import Annotated, Optional
|
|
|
|
from fastapi import APIRouter, HTTPException, Query, status
|
|
|
|
from app.config import get_settings as get_app_settings
|
|
from app.dependencies import AdminUser, DB
|
|
from app.schemas.tenant_settings import (
|
|
IndexingJobStatus,
|
|
IndexingStats,
|
|
StartReindexRequest,
|
|
StartRescanRequest,
|
|
TenantSettingsResponse,
|
|
TenantSettingsUpdate,
|
|
)
|
|
from app.services.indexing_service import IndexingService
|
|
from app.services.tenant_settings_service import TenantSettingsService
|
|
|
|
router = APIRouter(prefix="/settings", tags=["Impostazioni"])
|
|
|
|
# ─── Helper tenant_id resolution ─────────────────────────────────────────────
|
|
|
|
def _resolve_tenant_id(
|
|
current_user: AdminUser,
|
|
tenant_id_param: Optional[uuid.UUID] = None,
|
|
) -> uuid.UUID:
|
|
"""
|
|
Risolve il tenant_id da usare per l'operazione.
|
|
- super_admin: puo' passare un tenant_id arbitrario
|
|
- admin: usa sempre il proprio tenant_id (tenant_id_param ignorato)
|
|
"""
|
|
if current_user.role == "super_admin" and tenant_id_param is not None:
|
|
return tenant_id_param
|
|
return current_user.tenant_id
|
|
|
|
|
|
# ─── Impostazioni generali ────────────────────────────────────────────────────
|
|
|
|
@router.get(
|
|
"",
|
|
response_model=TenantSettingsResponse,
|
|
summary="Legge le impostazioni del tenant",
|
|
description=(
|
|
"Restituisce la configurazione operativa del tenant: "
|
|
"modalita' archiviazione (mock/produzione), endpoint e stato credenziali conservatore."
|
|
),
|
|
)
|
|
async def get_settings(
|
|
current_user: AdminUser,
|
|
db: DB,
|
|
) -> TenantSettingsResponse:
|
|
service = TenantSettingsService(db)
|
|
settings = await service.get_or_create(current_user.tenant_id)
|
|
return TenantSettingsService.to_response(settings)
|
|
|
|
|
|
@router.put(
|
|
"",
|
|
response_model=TenantSettingsResponse,
|
|
summary="Aggiorna le impostazioni del tenant",
|
|
description=(
|
|
"Aggiorna la configurazione operativa del tenant. "
|
|
"Tutti i campi sono opzionali (semantica PATCH). "
|
|
"Il passaggio a modalita' 'production' richiede un endpoint conservatore configurato."
|
|
),
|
|
)
|
|
async def update_settings(
|
|
body: TenantSettingsUpdate,
|
|
current_user: AdminUser,
|
|
db: DB,
|
|
) -> TenantSettingsResponse:
|
|
service = TenantSettingsService(db)
|
|
settings = await service.update(current_user.tenant_id, body)
|
|
await db.commit()
|
|
await db.refresh(settings)
|
|
return TenantSettingsService.to_response(settings)
|
|
|
|
|
|
# ─── Indicizzazione full-text ─────────────────────────────────────────────────
|
|
|
|
@router.get(
|
|
"/indexing/stats",
|
|
response_model=IndexingStats,
|
|
summary="Statistiche indicizzazione full-text",
|
|
description=(
|
|
"Restituisce il numero di messaggi totali, indicizzati e non indicizzati "
|
|
"per il tenant, con percentuale di copertura. "
|
|
"Include anche le statistiche sugli allegati PDF/DOCX con testo estratto. "
|
|
"Il super_admin puo' specificare ?tenant_id=<uuid> per un tenant arbitrario."
|
|
),
|
|
)
|
|
async def get_indexing_stats(
|
|
current_user: AdminUser,
|
|
db: DB,
|
|
tenant_id: Optional[uuid.UUID] = Query(
|
|
default=None,
|
|
description="(solo super_admin) UUID del tenant su cui operare",
|
|
),
|
|
) -> IndexingStats:
|
|
target_tenant_id = _resolve_tenant_id(current_user, tenant_id)
|
|
service = IndexingService(db)
|
|
stats = await service.get_stats(target_tenant_id)
|
|
return IndexingStats(**stats)
|
|
|
|
|
|
@router.get(
|
|
"/indexing/status",
|
|
response_model=IndexingJobStatus,
|
|
summary="Stato job indicizzazione in corso",
|
|
description=(
|
|
"Restituisce lo stato del job di reindex per il tenant: "
|
|
"idle, running (con progresso), completed, failed o cancelled. "
|
|
"Se il job e' running da piu' di 2 ore, il flag is_stale e' True."
|
|
),
|
|
)
|
|
async def get_indexing_status(
|
|
current_user: AdminUser,
|
|
db: DB,
|
|
tenant_id: Optional[uuid.UUID] = Query(
|
|
default=None,
|
|
description="(solo super_admin) UUID del tenant su cui operare",
|
|
),
|
|
) -> IndexingJobStatus:
|
|
target_tenant_id = _resolve_tenant_id(current_user, tenant_id)
|
|
app_settings = get_app_settings()
|
|
status_data = await IndexingService.get_job_status(
|
|
target_tenant_id, app_settings.redis_url
|
|
)
|
|
return IndexingJobStatus(**status_data)
|
|
|
|
|
|
@router.post(
|
|
"/indexing/reindex",
|
|
response_model=IndexingJobStatus,
|
|
status_code=status.HTTP_202_ACCEPTED,
|
|
summary="Avvia job di reindex",
|
|
description=(
|
|
"Avvia un job di reindex full-text in background. "
|
|
"mode='differential' indicizza solo i messaggi con search_vector NULL (piu' veloce). "
|
|
"mode='full' riscrive il vettore di tutti i messaggi del tenant. "
|
|
"Restituisce 409 se un job e' gia' in corso."
|
|
),
|
|
)
|
|
async def start_reindex(
|
|
body: StartReindexRequest,
|
|
current_user: AdminUser,
|
|
db: DB,
|
|
tenant_id: Optional[uuid.UUID] = Query(
|
|
default=None,
|
|
description="(solo super_admin) UUID del tenant su cui operare",
|
|
),
|
|
) -> IndexingJobStatus:
|
|
target_tenant_id = _resolve_tenant_id(current_user, tenant_id)
|
|
app_settings = get_app_settings()
|
|
|
|
try:
|
|
await IndexingService.start_reindex(
|
|
tenant_id=target_tenant_id,
|
|
mode=body.mode,
|
|
started_by_email=current_user.email,
|
|
redis_url=app_settings.redis_url,
|
|
db_url=app_settings.database_url,
|
|
)
|
|
except ValueError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
detail=str(exc),
|
|
)
|
|
|
|
# Ritorna lo stato appena creato
|
|
status_data = await IndexingService.get_job_status(
|
|
target_tenant_id, app_settings.redis_url
|
|
)
|
|
return IndexingJobStatus(**status_data)
|
|
|
|
|
|
@router.delete(
|
|
"/indexing/reindex",
|
|
response_model=IndexingJobStatus,
|
|
summary="Cancella job di reindex in corso",
|
|
description=(
|
|
"Invia il segnale di cancellazione al job di reindex in corso. "
|
|
"Il job si fermera' alla fine del batch corrente (max qualche secondo). "
|
|
"Se non c'e' nessun job in corso, ritorna 404."
|
|
),
|
|
)
|
|
async def cancel_reindex(
|
|
current_user: AdminUser,
|
|
db: DB,
|
|
tenant_id: Optional[uuid.UUID] = Query(
|
|
default=None,
|
|
description="(solo super_admin) UUID del tenant su cui operare",
|
|
),
|
|
) -> IndexingJobStatus:
|
|
target_tenant_id = _resolve_tenant_id(current_user, tenant_id)
|
|
app_settings = get_app_settings()
|
|
|
|
cancelled = await IndexingService.cancel_reindex(
|
|
target_tenant_id, app_settings.redis_url
|
|
)
|
|
|
|
if not cancelled:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Nessun job di reindex in corso per questo tenant",
|
|
)
|
|
|
|
status_data = await IndexingService.get_job_status(
|
|
target_tenant_id, app_settings.redis_url
|
|
)
|
|
return IndexingJobStatus(**status_data)
|
|
|
|
|
|
# ─── Scansione allegati ───────────────────────────────────────────────────────
|
|
|
|
@router.get(
|
|
"/indexing/rescan-status",
|
|
response_model=IndexingJobStatus,
|
|
summary="Stato job scansione allegati in corso",
|
|
description=(
|
|
"Restituisce lo stato del job di scansione allegati per il tenant: "
|
|
"idle, running (con progresso), completed, failed o cancelled."
|
|
),
|
|
)
|
|
async def get_rescan_status(
|
|
current_user: AdminUser,
|
|
db: DB,
|
|
tenant_id: Optional[uuid.UUID] = Query(
|
|
default=None,
|
|
description="(solo super_admin) UUID del tenant su cui operare",
|
|
),
|
|
) -> IndexingJobStatus:
|
|
target_tenant_id = _resolve_tenant_id(current_user, tenant_id)
|
|
app_settings = get_app_settings()
|
|
status_data = await IndexingService.get_rescan_status(
|
|
target_tenant_id, app_settings.redis_url
|
|
)
|
|
return IndexingJobStatus(**status_data)
|
|
|
|
|
|
@router.post(
|
|
"/indexing/rescan",
|
|
response_model=IndexingJobStatus,
|
|
status_code=status.HTTP_202_ACCEPTED,
|
|
summary="Avvia job di scansione allegati",
|
|
description=(
|
|
"Avvia un job di scansione allegati in background. "
|
|
"force=false (default): estrae il testo solo dagli allegati non ancora elaborati. "
|
|
"force=true: ri-estrae il testo da tutti gli allegati del tenant. "
|
|
"Al termine di ogni batch aggiorna anche il search_vector dei messaggi interessati. "
|
|
"Restituisce 409 se un job di scansione o reindex e' gia' in corso."
|
|
),
|
|
)
|
|
async def start_rescan(
|
|
body: StartRescanRequest,
|
|
current_user: AdminUser,
|
|
db: DB,
|
|
tenant_id: Optional[uuid.UUID] = Query(
|
|
default=None,
|
|
description="(solo super_admin) UUID del tenant su cui operare",
|
|
),
|
|
) -> IndexingJobStatus:
|
|
target_tenant_id = _resolve_tenant_id(current_user, tenant_id)
|
|
app_settings = get_app_settings()
|
|
|
|
try:
|
|
await IndexingService.start_rescan(
|
|
tenant_id=target_tenant_id,
|
|
started_by_email=current_user.email,
|
|
redis_url=app_settings.redis_url,
|
|
db_url=app_settings.database_url,
|
|
force=body.force,
|
|
)
|
|
except ValueError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
detail=str(exc),
|
|
)
|
|
|
|
status_data = await IndexingService.get_rescan_status(
|
|
target_tenant_id, app_settings.redis_url
|
|
)
|
|
return IndexingJobStatus(**status_data)
|
|
|
|
|
|
@router.delete(
|
|
"/indexing/rescan",
|
|
response_model=IndexingJobStatus,
|
|
summary="Cancella job di scansione allegati in corso",
|
|
description=(
|
|
"Invia il segnale di cancellazione al job di scansione allegati in corso. "
|
|
"Il job si fermera' alla fine del batch corrente. "
|
|
"Se non c'e' nessun job in corso, ritorna 404."
|
|
),
|
|
)
|
|
async def cancel_rescan(
|
|
current_user: AdminUser,
|
|
db: DB,
|
|
tenant_id: Optional[uuid.UUID] = Query(
|
|
default=None,
|
|
description="(solo super_admin) UUID del tenant su cui operare",
|
|
),
|
|
) -> IndexingJobStatus:
|
|
target_tenant_id = _resolve_tenant_id(current_user, tenant_id)
|
|
app_settings = get_app_settings()
|
|
|
|
cancelled = await IndexingService.cancel_rescan(
|
|
target_tenant_id, app_settings.redis_url
|
|
)
|
|
|
|
if not cancelled:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Nessun job di scansione allegati in corso per questo tenant",
|
|
)
|
|
|
|
status_data = await IndexingService.get_rescan_status(
|
|
target_tenant_id, app_settings.redis_url
|
|
)
|
|
return IndexingJobStatus(**status_data)
|