from fastapi import APIRouter, HTTPException, Depends, Body, Path, Request, Response from typing import List, Dict, Any, Optional from fastapi import status import logging # Import auth module from modules.security.auth import limiter, getCurrentUser # Import interfaces import modules.interfaces.serviceManagementClass as serviceManagementClass from modules.interfaces.serviceManagementModel import Mandate, getModelAttributeDefinitions # Import the model classes from modules.interfaces.serviceAppModel import AttributeDefinition # Configure logger logger = logging.getLogger(__name__) # Model attributes for Mandate mandateAttributes = getModelAttributeDefinitions(Mandate) # Create a router for the mandate endpoints router = APIRouter( prefix="/api/mandates", tags=["Manage Mandates"], responses={404: {"description": "Not found"}} ) @router.get("/", response_model=List[Dict[str, Any]], tags=["Mandates"]) @limiter.limit("30/minute") async def get_mandates(currentUser: Dict[str, Any] = Depends(getCurrentUser)): """Get all mandates""" try: appInterface = serviceManagementClass.getInterface(currentUser) return appInterface.getMandates() except Exception as e: logger.error(f"Error getting mandates: {str(e)}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Failed to get mandates: {str(e)}" ) @router.get("/{mandateId}", response_model=Dict[str, Any], tags=["Mandates"]) @limiter.limit("30/minute") async def get_mandate( mandateId: str, currentUser: Dict[str, Any] = Depends(getCurrentUser) ): """Get a specific mandate by ID""" try: appInterface = serviceManagementClass.getInterface(currentUser) mandate = appInterface.getMandateById(mandateId) if not mandate: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Mandate {mandateId} not found" ) return mandate except HTTPException: raise except Exception as e: logger.error(f"Error getting mandate {mandateId}: {str(e)}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Failed to get mandate: {str(e)}" ) @router.post("/", response_model=Mandate, tags=["Mandates"]) @limiter.limit("10/minute") async def create_mandate( mandateData: Mandate, currentUser: Dict[str, Any] = Depends(getCurrentUser) ): """Create a new mandate""" try: appInterface = serviceManagementClass.getInterface(currentUser) try: createdMandate = appInterface.createMandate(mandateData) except ValueError as e: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(e) ) if not createdMandate: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to create mandate" ) return createdMandate except HTTPException: raise except Exception as e: logger.error(f"Error creating mandate: {str(e)}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Failed to create mandate: {str(e)}" ) @router.put("/{mandateId}", response_model=Mandate, tags=["Mandates"]) @limiter.limit("10/minute") async def update_mandate( mandateId: str, mandateData: Mandate, currentUser: Dict[str, Any] = Depends(getCurrentUser) ): """Update an existing mandate""" try: appInterface = serviceManagementClass.getInterface(currentUser) # Check if mandate exists existingMandate = appInterface.getMandateById(mandateId) if not existingMandate: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Mandate {mandateId} not found" ) # Update mandate data try: updatedMandate = appInterface.updateMandate(mandateId, mandateData) except ValueError as e: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(e) ) if not updatedMandate: raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to update mandate" ) return updatedMandate except HTTPException: raise except Exception as e: logger.error(f"Error updating mandate {mandateId}: {str(e)}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Failed to update mandate: {str(e)}" ) @router.delete("/{mandateId}", response_model=Dict[str, Any], tags=["Mandates"]) @limiter.limit("10/minute") async def delete_mandate( mandateId: str, currentUser: Dict[str, Any] = Depends(getCurrentUser) ): """Delete a mandate""" try: appInterface = serviceManagementClass.getInterface(currentUser) # Check if mandate exists existingMandate = appInterface.getMandateById(mandateId) if not existingMandate: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Mandate {mandateId} not found" ) # Delete mandate try: appInterface.deleteMandate(mandateId) except ValueError as e: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(e) ) return {"message": f"Mandate {mandateId} deleted successfully"} except HTTPException: raise except Exception as e: logger.error(f"Error deleting mandate {mandateId}: {str(e)}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Failed to delete mandate: {str(e)}" ) @router.get("/attributes", response_model=List[AttributeDefinition]) @limiter.limit("30/minute") async def get_mandate_attributes( currentUser: Dict[str, Any] = Depends(getCurrentUser) ): """ Retrieves the attribute definitions for mandates. This can be used for dynamic form generation. Returns: - A list of attribute definitions that can be used to generate forms """ # Get attributes from the Mandate model class return Mandate.getModelAttributeDefinitions()