Add user delete process
This commit is contained in:
81
services/production/app/api/production_orders_operations.py
Normal file
81
services/production/app/api/production_orders_operations.py
Normal file
@@ -0,0 +1,81 @@
|
||||
|
||||
# ============================================================================
|
||||
# Tenant Data Deletion Operations (Internal Service Only)
|
||||
# ============================================================================
|
||||
|
||||
from shared.auth.access_control import service_only_access
|
||||
from app.services.tenant_deletion_service import ProductionTenantDeletionService
|
||||
|
||||
|
||||
@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 production data for a tenant (Internal service only)
|
||||
"""
|
||||
try:
|
||||
logger.info("production.tenant_deletion.api_called", tenant_id=tenant_id)
|
||||
|
||||
deletion_service = ProductionTenantDeletionService(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("production.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("production.tenant_deletion.preview_called", tenant_id=tenant_id)
|
||||
|
||||
deletion_service = ProductionTenantDeletionService(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": "production-service",
|
||||
"data_counts": result.deleted_counts,
|
||||
"total_items": sum(result.deleted_counts.values())
|
||||
}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error("production.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)}")
|
||||
161
services/production/app/services/tenant_deletion_service.py
Normal file
161
services/production/app/services/tenant_deletion_service.py
Normal file
@@ -0,0 +1,161 @@
|
||||
"""
|
||||
Production Service - Tenant Data Deletion
|
||||
Handles deletion of all production-related data for a tenant
|
||||
"""
|
||||
from typing import Dict
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, delete, func
|
||||
import structlog
|
||||
|
||||
from shared.services.tenant_deletion import BaseTenantDataDeletionService, TenantDataDeletionResult
|
||||
|
||||
logger = structlog.get_logger()
|
||||
|
||||
|
||||
class ProductionTenantDeletionService(BaseTenantDataDeletionService):
|
||||
"""Service for deleting all production-related data for a tenant"""
|
||||
|
||||
def __init__(self, db_session: AsyncSession):
|
||||
super().__init__("production-service")
|
||||
self.db = db_session
|
||||
|
||||
async def get_tenant_data_preview(self, tenant_id: str) -> Dict[str, int]:
|
||||
"""Get counts of what would be deleted"""
|
||||
|
||||
try:
|
||||
preview = {}
|
||||
|
||||
# Import models here to avoid circular imports
|
||||
from app.models.production import (
|
||||
ProductionBatch,
|
||||
ProductionSchedule,
|
||||
Equipment,
|
||||
QualityCheck
|
||||
)
|
||||
|
||||
# Count production batches
|
||||
batch_count = await self.db.scalar(
|
||||
select(func.count(ProductionBatch.id)).where(ProductionBatch.tenant_id == tenant_id)
|
||||
)
|
||||
preview["production_batches"] = batch_count or 0
|
||||
|
||||
# Count production schedules
|
||||
try:
|
||||
schedule_count = await self.db.scalar(
|
||||
select(func.count(ProductionSchedule.id)).where(ProductionSchedule.tenant_id == tenant_id)
|
||||
)
|
||||
preview["production_schedules"] = schedule_count or 0
|
||||
except Exception:
|
||||
# Model might not exist in all versions
|
||||
preview["production_schedules"] = 0
|
||||
|
||||
# Count equipment
|
||||
try:
|
||||
equipment_count = await self.db.scalar(
|
||||
select(func.count(Equipment.id)).where(Equipment.tenant_id == tenant_id)
|
||||
)
|
||||
preview["equipment"] = equipment_count or 0
|
||||
except Exception:
|
||||
# Model might not exist in all versions
|
||||
preview["equipment"] = 0
|
||||
|
||||
# Count quality checks
|
||||
try:
|
||||
qc_count = await self.db.scalar(
|
||||
select(func.count(QualityCheck.id)).where(QualityCheck.tenant_id == tenant_id)
|
||||
)
|
||||
preview["quality_checks"] = qc_count or 0
|
||||
except Exception:
|
||||
# Model might not exist in all versions
|
||||
preview["quality_checks"] = 0
|
||||
|
||||
return preview
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Error getting deletion preview",
|
||||
tenant_id=tenant_id,
|
||||
error=str(e))
|
||||
return {}
|
||||
|
||||
async def delete_tenant_data(self, tenant_id: str) -> TenantDataDeletionResult:
|
||||
"""Delete all data for a tenant"""
|
||||
|
||||
result = TenantDataDeletionResult(tenant_id, self.service_name)
|
||||
|
||||
try:
|
||||
# Import models here to avoid circular imports
|
||||
from app.models.production import (
|
||||
ProductionBatch,
|
||||
ProductionSchedule,
|
||||
Equipment,
|
||||
QualityCheck
|
||||
)
|
||||
|
||||
# Delete quality checks first (might have FK to batches)
|
||||
try:
|
||||
qc_delete = await self.db.execute(
|
||||
delete(QualityCheck).where(QualityCheck.tenant_id == tenant_id)
|
||||
)
|
||||
result.add_deleted_items("quality_checks", qc_delete.rowcount)
|
||||
except Exception as e:
|
||||
logger.warning("Error deleting quality checks (table might not exist)",
|
||||
tenant_id=tenant_id,
|
||||
error=str(e))
|
||||
result.add_error(f"Quality check deletion: {str(e)}")
|
||||
|
||||
# Delete production batches
|
||||
try:
|
||||
batch_delete = await self.db.execute(
|
||||
delete(ProductionBatch).where(ProductionBatch.tenant_id == tenant_id)
|
||||
)
|
||||
result.add_deleted_items("production_batches", batch_delete.rowcount)
|
||||
|
||||
logger.info("Deleted production batches for tenant",
|
||||
tenant_id=tenant_id,
|
||||
count=batch_delete.rowcount)
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Error deleting production batches",
|
||||
tenant_id=tenant_id,
|
||||
error=str(e))
|
||||
result.add_error(f"Production batch deletion: {str(e)}")
|
||||
|
||||
# Delete production schedules
|
||||
try:
|
||||
schedule_delete = await self.db.execute(
|
||||
delete(ProductionSchedule).where(ProductionSchedule.tenant_id == tenant_id)
|
||||
)
|
||||
result.add_deleted_items("production_schedules", schedule_delete.rowcount)
|
||||
except Exception as e:
|
||||
logger.warning("Error deleting production schedules (table might not exist)",
|
||||
tenant_id=tenant_id,
|
||||
error=str(e))
|
||||
result.add_error(f"Production schedule deletion: {str(e)}")
|
||||
|
||||
# Delete equipment
|
||||
try:
|
||||
equipment_delete = await self.db.execute(
|
||||
delete(Equipment).where(Equipment.tenant_id == tenant_id)
|
||||
)
|
||||
result.add_deleted_items("equipment", equipment_delete.rowcount)
|
||||
except Exception as e:
|
||||
logger.warning("Error deleting equipment (table might not exist)",
|
||||
tenant_id=tenant_id,
|
||||
error=str(e))
|
||||
result.add_error(f"Equipment deletion: {str(e)}")
|
||||
|
||||
# Commit all deletions
|
||||
await self.db.commit()
|
||||
|
||||
logger.info("Tenant data deletion completed",
|
||||
tenant_id=tenant_id,
|
||||
deleted_counts=result.deleted_counts)
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Fatal error during tenant data deletion",
|
||||
tenant_id=tenant_id,
|
||||
error=str(e))
|
||||
await self.db.rollback()
|
||||
result.add_error(f"Fatal error: {str(e)}")
|
||||
|
||||
return result
|
||||
Reference in New Issue
Block a user