| 1 | from typing import Dict |
| 2 | |
| 3 | from fastapi import HTTPException |
| 4 | from loguru import logger |
| 5 | from sqlalchemy.ext.asyncio import AsyncSession |
| 6 | |
| 7 | from app.integrations.routes import get_customer_integrations_by_customer_code |
| 8 | from app.integrations.schema import CustomerIntegrations |
| 9 | from app.integrations.schema import CustomerIntegrationsResponse |
| 10 | |
| 11 | |
| 12 | async def get_customer_integration_response( |
| 13 | customer_code: str, |
| 14 | session: AsyncSession, |
| 15 | ) -> CustomerIntegrationsResponse: |
| 16 | """ |
| 17 | Retrieves the integration response for a customer. |
| 18 | |
| 19 | Args: |
| 20 | customer_code (str): The code of the customer. |
| 21 | session (AsyncSession): The async session object for database operations. |
| 22 | |
| 23 | Returns: |
| 24 | CustomerIntegrationsResponse: The integration response for the customer. |
| 25 | |
| 26 | Raises: |
| 27 | HTTPException: If the customer integration settings are not found. |
| 28 | """ |
| 29 | customer_integration_response = await get_customer_integrations_by_customer_code( |
| 30 | customer_code, |
| 31 | session, |
| 32 | ) |
| 33 | if customer_integration_response.available_integrations == []: |
| 34 | raise HTTPException( |
| 35 | status_code=404, |
| 36 | detail="Customer integration settings not found.", |
| 37 | ) |
| 38 | return customer_integration_response |
| 39 | |
| 40 | |
| 41 | def extract_auth_keys(customer_integration: CustomerIntegrations, service_name: str) -> Dict[str, str]: |
| 42 | """ |
| 43 | Extracts the authentication keys for the given service name from the customer integration. |
| 44 | |
| 45 | Args: |
| 46 | customer_integration (CustomerIntegrations): The customer integration object. |
| 47 | service_name (str): The name of the service to extract the authentication keys for. |
| 48 | |
| 49 | Returns: |
| 50 | Dict[str, str]: A dictionary containing the authentication keys for the service. |
| 51 | |
| 52 | Raises: |
| 53 | HTTPException: If no authentication keys are found for the service. |
| 54 | """ |
| 55 | auth_keys = {} |
| 56 | try: |
| 57 | for subscription in customer_integration.integration_subscriptions: |
| 58 | if subscription.integration_service.service_name == service_name: |
| 59 | for auth_key in subscription.integration_auth_keys: |
| 60 | auth_keys[auth_key.auth_key_name] = auth_key.auth_value |
| 61 | if not auth_keys: |
| 62 | raise HTTPException( |
| 63 | status_code=404, |
| 64 | detail=f"No auth keys found for {service_name} integration. Please create auth keys for {service_name} integration.", |
| 65 | ) |
| 66 | except Exception as e: |
| 67 | logger.error(f"Error extracting auth keys for {service_name} integration: {e}") |
| 68 | raise HTTPException( |
| 69 | status_code=404, |
| 70 | detail=f"No auth keys found for {service_name} integration. Please create auth keys for {service_name} integration.", |
| 71 | ) |
| 72 | return auth_keys |