Add user delete process

This commit is contained in:
Urtzi Alfaro
2025-10-31 11:54:19 +01:00
parent 63f5c6d512
commit 269d3b5032
74 changed files with 16783 additions and 213 deletions

View File

@@ -12,10 +12,11 @@ import json
from app.core.database import get_db
from shared.auth.decorators import get_current_user_dep
from shared.auth.access_control import require_user_role, admin_role_required
from shared.auth.access_control import require_user_role, admin_role_required, service_only_access
from shared.routing import RouteBuilder
from app.services.pos_transaction_service import POSTransactionService
from app.services.pos_config_service import POSConfigurationService
from app.services.tenant_deletion_service import POSTenantDeletionService
router = APIRouter()
logger = structlog.get_logger()
@@ -385,3 +386,112 @@ def _get_supported_events(pos_system: str) -> Dict[str, Any]:
"format": "JSON",
"authentication": "signature_verification"
}
# ============================================================================
# Tenant Data Deletion Operations (Internal Service Only)
# ============================================================================
@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=Depends(get_db)
):
"""
Delete all POS data for a tenant (Internal service only)
This endpoint is called by the orchestrator during tenant deletion.
It permanently deletes all POS-related data including:
- POS configurations
- POS transactions and items
- Webhook logs
- Sync logs
- Audit logs
**WARNING**: This operation is irreversible!
Returns:
Deletion summary with counts of deleted records
"""
try:
logger.info("pos.tenant_deletion.api_called", tenant_id=tenant_id)
deletion_service = POSTenantDeletionService(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("pos.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=Depends(get_db)
):
"""
Preview what data would be deleted for a tenant (dry-run)
This endpoint shows counts of all data that would be deleted
without actually deleting anything. Useful for:
- Confirming deletion scope before execution
- Auditing and compliance
- Troubleshooting
Returns:
Dictionary with entity names and their counts
"""
try:
logger.info("pos.tenant_deletion.preview_called", tenant_id=tenant_id)
deletion_service = POSTenantDeletionService(db)
preview = await deletion_service.get_tenant_data_preview(tenant_id)
total_records = sum(preview.values())
return {
"tenant_id": tenant_id,
"service": "pos",
"preview": preview,
"total_records": total_records,
"warning": "These records will be permanently deleted and cannot be recovered"
}
except Exception as e:
logger.error("pos.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

@@ -0,0 +1,260 @@
# services/pos/app/services/tenant_deletion_service.py
"""
Tenant Data Deletion Service for POS Service
Handles deletion of all POS-related data for a tenant
"""
from typing import Dict
from sqlalchemy import select, func, delete
from sqlalchemy.ext.asyncio import AsyncSession
import structlog
from shared.services.tenant_deletion import (
BaseTenantDataDeletionService,
TenantDataDeletionResult
)
from app.models import (
POSConfiguration,
POSTransaction,
POSTransactionItem,
POSWebhookLog,
POSSyncLog,
AuditLog
)
logger = structlog.get_logger(__name__)
class POSTenantDeletionService(BaseTenantDataDeletionService):
"""Service for deleting all POS-related data for a tenant"""
def __init__(self, db: AsyncSession):
self.db = db
self.service_name = "pos"
async def get_tenant_data_preview(self, tenant_id: str) -> Dict[str, int]:
"""
Get counts of what would be deleted for a tenant (dry-run)
Args:
tenant_id: The tenant ID to preview deletion for
Returns:
Dictionary with entity names and their counts
"""
logger.info("pos.tenant_deletion.preview", tenant_id=tenant_id)
preview = {}
try:
# Count POS configurations
config_count = await self.db.scalar(
select(func.count(POSConfiguration.id)).where(
POSConfiguration.tenant_id == tenant_id
)
)
preview["pos_configurations"] = config_count or 0
# Count POS transactions
transaction_count = await self.db.scalar(
select(func.count(POSTransaction.id)).where(
POSTransaction.tenant_id == tenant_id
)
)
preview["pos_transactions"] = transaction_count or 0
# Count POS transaction items
item_count = await self.db.scalar(
select(func.count(POSTransactionItem.id)).where(
POSTransactionItem.tenant_id == tenant_id
)
)
preview["pos_transaction_items"] = item_count or 0
# Count webhook logs
webhook_count = await self.db.scalar(
select(func.count(POSWebhookLog.id)).where(
POSWebhookLog.tenant_id == tenant_id
)
)
preview["pos_webhook_logs"] = webhook_count or 0
# Count sync logs
sync_count = await self.db.scalar(
select(func.count(POSSyncLog.id)).where(
POSSyncLog.tenant_id == tenant_id
)
)
preview["pos_sync_logs"] = sync_count or 0
# Count audit logs
audit_count = await self.db.scalar(
select(func.count(AuditLog.id)).where(
AuditLog.tenant_id == tenant_id
)
)
preview["audit_logs"] = audit_count or 0
logger.info(
"pos.tenant_deletion.preview_complete",
tenant_id=tenant_id,
preview=preview
)
except Exception as e:
logger.error(
"pos.tenant_deletion.preview_error",
tenant_id=tenant_id,
error=str(e),
exc_info=True
)
raise
return preview
async def delete_tenant_data(self, tenant_id: str) -> TenantDataDeletionResult:
"""
Permanently delete all POS data for a tenant
Deletion order (respecting foreign key constraints):
1. POSTransactionItem (references POSTransaction)
2. POSTransaction (references POSConfiguration)
3. POSWebhookLog (independent)
4. POSSyncLog (references POSConfiguration)
5. POSConfiguration (base configuration)
6. AuditLog (independent)
Args:
tenant_id: The tenant ID to delete data for
Returns:
TenantDataDeletionResult with deletion counts and any errors
"""
logger.info("pos.tenant_deletion.started", tenant_id=tenant_id)
result = TenantDataDeletionResult(tenant_id=tenant_id, service_name=self.service_name)
try:
# Step 1: Delete POS transaction items (child of transactions)
logger.info("pos.tenant_deletion.deleting_transaction_items", tenant_id=tenant_id)
items_result = await self.db.execute(
delete(POSTransactionItem).where(
POSTransactionItem.tenant_id == tenant_id
)
)
result.deleted_counts["pos_transaction_items"] = items_result.rowcount
logger.info(
"pos.tenant_deletion.transaction_items_deleted",
tenant_id=tenant_id,
count=items_result.rowcount
)
# Step 2: Delete POS transactions
logger.info("pos.tenant_deletion.deleting_transactions", tenant_id=tenant_id)
transactions_result = await self.db.execute(
delete(POSTransaction).where(
POSTransaction.tenant_id == tenant_id
)
)
result.deleted_counts["pos_transactions"] = transactions_result.rowcount
logger.info(
"pos.tenant_deletion.transactions_deleted",
tenant_id=tenant_id,
count=transactions_result.rowcount
)
# Step 3: Delete webhook logs
logger.info("pos.tenant_deletion.deleting_webhook_logs", tenant_id=tenant_id)
webhook_result = await self.db.execute(
delete(POSWebhookLog).where(
POSWebhookLog.tenant_id == tenant_id
)
)
result.deleted_counts["pos_webhook_logs"] = webhook_result.rowcount
logger.info(
"pos.tenant_deletion.webhook_logs_deleted",
tenant_id=tenant_id,
count=webhook_result.rowcount
)
# Step 4: Delete sync logs
logger.info("pos.tenant_deletion.deleting_sync_logs", tenant_id=tenant_id)
sync_result = await self.db.execute(
delete(POSSyncLog).where(
POSSyncLog.tenant_id == tenant_id
)
)
result.deleted_counts["pos_sync_logs"] = sync_result.rowcount
logger.info(
"pos.tenant_deletion.sync_logs_deleted",
tenant_id=tenant_id,
count=sync_result.rowcount
)
# Step 5: Delete POS configurations (last, as it's referenced by transactions and sync logs)
logger.info("pos.tenant_deletion.deleting_configurations", tenant_id=tenant_id)
config_result = await self.db.execute(
delete(POSConfiguration).where(
POSConfiguration.tenant_id == tenant_id
)
)
result.deleted_counts["pos_configurations"] = config_result.rowcount
logger.info(
"pos.tenant_deletion.configurations_deleted",
tenant_id=tenant_id,
count=config_result.rowcount
)
# Step 6: Delete audit logs
logger.info("pos.tenant_deletion.deleting_audit_logs", tenant_id=tenant_id)
audit_result = await self.db.execute(
delete(AuditLog).where(
AuditLog.tenant_id == tenant_id
)
)
result.deleted_counts["audit_logs"] = audit_result.rowcount
logger.info(
"pos.tenant_deletion.audit_logs_deleted",
tenant_id=tenant_id,
count=audit_result.rowcount
)
# Commit the transaction
await self.db.commit()
# Calculate total deleted
total_deleted = sum(result.deleted_counts.values())
logger.info(
"pos.tenant_deletion.completed",
tenant_id=tenant_id,
total_deleted=total_deleted,
breakdown=result.deleted_counts
)
result.success = True
except Exception as e:
await self.db.rollback()
error_msg = f"Failed to delete POS data for tenant {tenant_id}: {str(e)}"
logger.error(
"pos.tenant_deletion.failed",
tenant_id=tenant_id,
error=str(e),
exc_info=True
)
result.errors.append(error_msg)
result.success = False
return result
def get_pos_tenant_deletion_service(db: AsyncSession) -> POSTenantDeletionService:
"""
Factory function to create POSTenantDeletionService instance
Args:
db: AsyncSession database session
Returns:
POSTenantDeletionService instance
"""
return POSTenantDeletionService(db)