|
| 1 | +import json |
| 2 | +import requests |
| 3 | +from requests import Response |
| 4 | +from data_creator import DataCreator |
| 5 | + |
| 6 | +CURRENT_CRMSCRIPT_VERSION = 2 |
| 7 | + |
| 8 | +class FetchService: |
| 9 | + """ |
| 10 | + Coordinates the fetch operation at the service level. |
| 11 | + Handles tenant validation, fetch execution, and response formatting. |
| 12 | + """ |
| 13 | + |
| 14 | + @staticmethod |
| 15 | + def build_script_url(tenant: dict) -> str: |
| 16 | + """Builds the URL we call SuperOffice with to fetch data.""" |
| 17 | + script_url: str = ( |
| 18 | + f"{tenant.get('url')}/scripts/customer.fcgi?action=safeParse" |
| 19 | + f"&includeId={tenant.get('include_id')}" |
| 20 | + f"&key={tenant.get('key')}" |
| 21 | + ) |
| 22 | + |
| 23 | + # Append fetch options to URL |
| 24 | + for key, value in tenant["fetch_options"].items(): |
| 25 | + script_url += f"&{key}={str(value)}" |
| 26 | + |
| 27 | + return script_url |
| 28 | + |
| 29 | + def get_superoffice_data(self, tenant: dict) -> tuple[dict | None, str]: |
| 30 | + """ |
| 31 | + Fetches JSON data from SuperOffice. |
| 32 | + Returns tuple of (data, error_message). |
| 33 | + """ |
| 34 | + script_url = self.build_script_url(tenant) |
| 35 | + print(f"Getting JSON data from SuperOffice using endpoint: {script_url}") |
| 36 | + |
| 37 | + try: |
| 38 | + # Do GET request to Superoffice |
| 39 | + response: Response = requests.get(script_url) |
| 40 | + response.raise_for_status() # Raises exception for any bad HTTP status |
| 41 | + |
| 42 | + except requests.ConnectionError as e: |
| 43 | + error = f"Failed to connect to SuperOffice: {str(e)}" |
| 44 | + print(error) |
| 45 | + return None, error |
| 46 | + except requests.Timeout as e: |
| 47 | + error = f"Request to SuperOffice timed out: {str(e)}" |
| 48 | + print(error) |
| 49 | + return None, error |
| 50 | + except requests.HTTPError as e: |
| 51 | + error = f"HTTP error occurred: {str(e)}" |
| 52 | + print(error) |
| 53 | + return None, error |
| 54 | + except requests.RequestException as e: |
| 55 | + error = f"Failed to fetch data from SuperOffice: {str(e)}" |
| 56 | + print(error) |
| 57 | + return None, error |
| 58 | + |
| 59 | + # Parse JSON and return data as dictionary from method |
| 60 | + try: |
| 61 | + data: dict = json.loads(response.text) |
| 62 | + print("JSON fetched!") |
| 63 | + return data, "" |
| 64 | + except json.JSONDecodeError as e: |
| 65 | + error: str = (f"Invalid JSON response from server<br><br>Contacting URL: {script_url}<br<br>" |
| 66 | + f"{str(e)}<br><br>" |
| 67 | + f"GET returned body:<br>{response.text}") |
| 68 | + print(error) |
| 69 | + return None, error |
| 70 | + |
| 71 | + @staticmethod |
| 72 | + def validate_tenant(tenant: dict) -> str: |
| 73 | + """ |
| 74 | + Validates tenant configuration. |
| 75 | + Returns error message if invalid, empty string if valid. |
| 76 | + """ |
| 77 | + errors = [] |
| 78 | + |
| 79 | + if tenant.get("include_id") == "": |
| 80 | + errors.append("Script include ID cannot be empty") |
| 81 | + |
| 82 | + if tenant.get("key") == "": |
| 83 | + errors.append("Script key cannot be empty") |
| 84 | + |
| 85 | + if tenant.get("url") == "": |
| 86 | + errors.append("SuperOffice Service URL cannot be empty") |
| 87 | + |
| 88 | + if tenant.get("local_directory") == "": |
| 89 | + errors.append("Local directory path cannot be empty") |
| 90 | + |
| 91 | + if all(not option for option in tenant.get("fetch_options").values()): |
| 92 | + errors.append("You must check at least one fetch option") |
| 93 | + |
| 94 | + if errors: |
| 95 | + return "Can not fetch CRMScripts because tenant settings are invalid:<br>" + \ |
| 96 | + "<br>".join(f"- {error}" for error in errors) |
| 97 | + |
| 98 | + return "" |
| 99 | + |
| 100 | + def fetch(self, tenant) -> dict: |
| 101 | + """ |
| 102 | + Main entry point for fetching data from SuperOffice for a specific tenant. |
| 103 | + """ |
| 104 | + |
| 105 | + # The result that is returned to frontend |
| 106 | + result: dict = { |
| 107 | + "success": False, |
| 108 | + "validation_error": False, |
| 109 | + "error": "", |
| 110 | + "info": "" |
| 111 | + } |
| 112 | + |
| 113 | + try: |
| 114 | + # Make sure tenant is valid before trying to fetch |
| 115 | + validation_error: str = self.validate_tenant(tenant) |
| 116 | + if validation_error: |
| 117 | + result["validation_error"] = True |
| 118 | + result["error"] = validation_error |
| 119 | + return result |
| 120 | + |
| 121 | + # Fetch data from SuperOffice |
| 122 | + data: dict | None |
| 123 | + error: str |
| 124 | + data, error = self.get_superoffice_data(tenant) |
| 125 | + |
| 126 | + if error: |
| 127 | + result["error"] = error |
| 128 | + return result |
| 129 | + |
| 130 | + if not data: |
| 131 | + raise Exception("No data returned from GET request") |
| 132 | + |
| 133 | + # Get script version |
| 134 | + # Version 1 had no script_version key in JSON, so we default to that if none is present |
| 135 | + script_version: int = data.get("script_version", 1) |
| 136 | + |
| 137 | + if CURRENT_CRMSCRIPT_VERSION > script_version: |
| 138 | + result["info"] = (f"Note! The fetcher CRMScript in use is not of the latest version. " |
| 139 | + f"Updating the script is recommended. Current script version is: {CURRENT_CRMSCRIPT_VERSION}") |
| 140 | + |
| 141 | + # Create files and folder based on the JSON returned |
| 142 | + try: |
| 143 | + data_creator = DataCreator(data, script_version, tenant) |
| 144 | + success: bool = data_creator.create() |
| 145 | + |
| 146 | + if not success: |
| 147 | + raise Exception("Failed to create local data files. Might be due to invalid script version?") |
| 148 | + |
| 149 | + except Exception as e: |
| 150 | + result["error"] = f"Error creating local files: {str(e)}" |
| 151 | + return result |
| 152 | + |
| 153 | + # Fetch and data creation was successful |
| 154 | + result["success"] = True |
| 155 | + return result |
| 156 | + |
| 157 | + # Something went wrong somewhere, return error to frontend |
| 158 | + except Exception as e: |
| 159 | + result["error"] = f"Unexpected error: {str(e)}" |
| 160 | + return result |
0 commit comments