Add user delete process 2

This commit is contained in:
Urtzi Alfaro
2025-10-31 18:57:58 +01:00
parent 269d3b5032
commit f44d235c6d
15 changed files with 166 additions and 145 deletions

View File

@@ -889,84 +889,3 @@ async def preview_tenant_data_deletion(
status_code=500,
detail=f"Failed to preview tenant data deletion: {str(e)}"
)
# ============================================================================
# Tenant Data Deletion Operations (Internal Service Only)
# ============================================================================
from shared.auth.access_control import service_only_access
from app.services.tenant_deletion_service import NotificationTenantDeletionService
@router.delete(
route_builder.build_base_route("tenant/{tenant_id}", include_tenant_prefix=False),
response_model=dict
)
@service_only_access
async def delete_tenant_data(
tenant_id: str = Path(..., description="Tenant ID to delete data for"),
current_user: dict = Depends(get_current_user_dep),
db: AsyncSession = Depends(get_db)
):
"""
Delete all notification data for a tenant (Internal service only)
"""
try:
logger.info("notification.tenant_deletion.api_called", tenant_id=tenant_id)
deletion_service = NotificationTenantDeletionService(db)
result = await deletion_service.safe_delete_tenant_data(tenant_id)
if not result.success:
raise HTTPException(
status_code=500,
detail=f"Tenant data deletion failed: {', '.join(result.errors)}"
)
return {
"message": "Tenant data deletion completed successfully",
"summary": result.to_dict()
}
except HTTPException:
raise
except Exception as e:
logger.error("notification.tenant_deletion.api_error", tenant_id=tenant_id, error=str(e), exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to delete tenant data: {str(e)}")
@router.get(
route_builder.build_base_route("tenant/{tenant_id}/deletion-preview", include_tenant_prefix=False),
response_model=dict
)
@service_only_access
async def preview_tenant_data_deletion(
tenant_id: str = Path(..., description="Tenant ID to preview deletion for"),
current_user: dict = Depends(get_current_user_dep),
db: AsyncSession = Depends(get_db)
):
"""
Preview what data would be deleted for a tenant (dry-run)
"""
try:
logger.info("notification.tenant_deletion.preview_called", tenant_id=tenant_id)
deletion_service = NotificationTenantDeletionService(db)
result = await deletion_service.preview_deletion(tenant_id)
if not result.success:
raise HTTPException(
status_code=500,
detail=f"Tenant deletion preview failed: {', '.join(result.errors)}"
)
return {
"tenant_id": tenant_id,
"service": "notification-service",
"data_counts": result.deleted_counts,
"total_items": sum(result.deleted_counts.values())
}
except HTTPException:
raise
except Exception as e:
logger.error("notification.tenant_deletion.preview_error", tenant_id=tenant_id, error=str(e), exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to preview tenant data deletion: {str(e)}")

View File

@@ -49,7 +49,7 @@ class NotificationTenantDeletionService(BaseTenantDataDeletionService):
# Count notifications
notification_count = await self.db.scalar(
select(func.count(Notification.id)).where(
Notification.tenant_id == UUID(tenant_id)
Notification.tenant_id == tenant_id
)
)
preview["notifications"] = notification_count or 0
@@ -57,7 +57,7 @@ class NotificationTenantDeletionService(BaseTenantDataDeletionService):
# Count tenant-specific notification templates
template_count = await self.db.scalar(
select(func.count(NotificationTemplate.id)).where(
NotificationTemplate.tenant_id == UUID(tenant_id),
NotificationTemplate.tenant_id == tenant_id,
NotificationTemplate.is_system == False # Don't delete system templates
)
)
@@ -66,15 +66,17 @@ class NotificationTenantDeletionService(BaseTenantDataDeletionService):
# Count notification preferences
preference_count = await self.db.scalar(
select(func.count(NotificationPreference.id)).where(
NotificationPreference.tenant_id == UUID(tenant_id)
NotificationPreference.tenant_id == tenant_id
)
)
preview["notification_preferences"] = preference_count or 0
# Count notification logs
# Count notification logs (join with Notification to get tenant_id)
log_count = await self.db.scalar(
select(func.count(NotificationLog.id)).where(
NotificationLog.tenant_id == UUID(tenant_id)
select(func.count(NotificationLog.id)).select_from(NotificationLog).join(
Notification, NotificationLog.notification_id == Notification.id
).where(
Notification.tenant_id == tenant_id
)
)
preview["notification_logs"] = log_count or 0
@@ -82,7 +84,7 @@ class NotificationTenantDeletionService(BaseTenantDataDeletionService):
# Count audit logs
audit_count = await self.db.scalar(
select(func.count(AuditLog.id)).where(
AuditLog.tenant_id == UUID(tenant_id)
AuditLog.tenant_id == tenant_id
)
)
preview["audit_logs"] = audit_count or 0
@@ -127,11 +129,12 @@ class NotificationTenantDeletionService(BaseTenantDataDeletionService):
result = TenantDataDeletionResult(tenant_id=tenant_id, service_name=self.service_name)
try:
# Step 1: Delete notification logs
# Step 1: Delete notification logs (via subquery to get notification_ids for this tenant)
logger.info("notification.tenant_deletion.deleting_logs", tenant_id=tenant_id)
notification_ids_subquery = select(Notification.id).where(Notification.tenant_id == tenant_id)
logs_result = await self.db.execute(
delete(NotificationLog).where(
NotificationLog.tenant_id == UUID(tenant_id)
NotificationLog.notification_id.in_(notification_ids_subquery)
)
)
result.deleted_counts["notification_logs"] = logs_result.rowcount
@@ -145,7 +148,7 @@ class NotificationTenantDeletionService(BaseTenantDataDeletionService):
logger.info("notification.tenant_deletion.deleting_preferences", tenant_id=tenant_id)
preferences_result = await self.db.execute(
delete(NotificationPreference).where(
NotificationPreference.tenant_id == UUID(tenant_id)
NotificationPreference.tenant_id == tenant_id
)
)
result.deleted_counts["notification_preferences"] = preferences_result.rowcount
@@ -159,7 +162,7 @@ class NotificationTenantDeletionService(BaseTenantDataDeletionService):
logger.info("notification.tenant_deletion.deleting_notifications", tenant_id=tenant_id)
notifications_result = await self.db.execute(
delete(Notification).where(
Notification.tenant_id == UUID(tenant_id)
Notification.tenant_id == tenant_id
)
)
result.deleted_counts["notifications"] = notifications_result.rowcount
@@ -173,7 +176,7 @@ class NotificationTenantDeletionService(BaseTenantDataDeletionService):
logger.info("notification.tenant_deletion.deleting_templates", tenant_id=tenant_id)
templates_result = await self.db.execute(
delete(NotificationTemplate).where(
NotificationTemplate.tenant_id == UUID(tenant_id),
NotificationTemplate.tenant_id == tenant_id,
NotificationTemplate.is_system == False
)
)
@@ -189,7 +192,7 @@ class NotificationTenantDeletionService(BaseTenantDataDeletionService):
logger.info("notification.tenant_deletion.deleting_audit_logs", tenant_id=tenant_id)
audit_result = await self.db.execute(
delete(AuditLog).where(
AuditLog.tenant_id == UUID(tenant_id)
AuditLog.tenant_id == tenant_id
)
)
result.deleted_counts["audit_logs"] = audit_result.rowcount