import os import requests import json from config import settings import logging # Configure Logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("superoffice-client") class SuperOfficeClient: """A client for interacting with the SuperOffice REST API.""" def __init__(self): # Configuration self.client_id = settings.SO_CLIENT_ID self.client_secret = settings.SO_CLIENT_SECRET self.refresh_token = settings.SO_REFRESH_TOKEN self.env = settings.SO_ENVIRONMENT self.cust_id = settings.SO_CONTEXT_IDENTIFIER if not all([self.client_id, self.client_secret, self.refresh_token]): # Graceful failure: Log error but allow init (for help/docs/discovery scripts) logger.error("❌ SuperOffice credentials missing in .env file (or environment variables).") self.base_url = None self.access_token = None return self.base_url = f"https://app-{self.env}.superoffice.com/{self.cust_id}/api/v1" self.access_token = self._refresh_access_token() if not self.access_token: logger.error("❌ Failed to authenticate with SuperOffice.") else: self.headers = { "Authorization": f"Bearer {self.access_token}", "Content-Type": "application/json", "Accept": "application/json" } logger.info("✅ SuperOffice Client initialized and authenticated.") def _refresh_access_token(self): """Refreshes and returns a new access token.""" url = f"https://{self.env}.superoffice.com/login/common/oauth/tokens" logger.debug(f"DEBUG: Refresh URL: '{url}' (Env: '{self.env}')") data = { "grant_type": "refresh_token", "client_id": self.client_id, "client_secret": self.client_secret, "refresh_token": self.refresh_token, "redirect_uri": settings.SO_REDIRECT_URI } try: resp = requests.post(url, data=data) resp.raise_for_status() return resp.json().get("access_token") except requests.exceptions.HTTPError as e: logger.error(f"❌ Token Refresh Error: {e.response.text}") return None except Exception as e: logger.error(f"❌ Connection Error during token refresh: {e}") return None def _get(self, endpoint): """Generic GET request.""" if not self.access_token: return None try: resp = requests.get(f"{self.base_url}/{endpoint}", headers=self.headers) resp.raise_for_status() return resp.json() except requests.exceptions.HTTPError as e: logger.error(f"❌ API GET Error for {endpoint}: {e.response.text}") return None def _put(self, endpoint, payload): """Generic PUT request.""" if not self.access_token: return None try: resp = requests.put(f"{self.base_url}/{endpoint}", headers=self.headers, json=payload) resp.raise_for_status() return resp.json() except requests.exceptions.HTTPError as e: logger.error(f"❌ API PUT Error for {endpoint}: {e.response.text}") return None def _post(self, endpoint, payload): """Generic POST request.""" if not self.access_token: return None try: resp = requests.post(f"{self.base_url}/{endpoint}", headers=self.headers, json=payload) resp.raise_for_status() return resp.json() except requests.exceptions.HTTPError as e: logger.error(f"❌ API POST Error for {endpoint} (Status: {e.response.status_code}): {e.response.text}") return None except Exception as e: logger.error(f"❌ Connection Error during POST for {endpoint}: {e}") return None # --- Convenience Wrappers --- def get_person(self, person_id): return self._get(f"Person/{person_id}") def get_contact(self, contact_id): return self._get(f"Contact/{contact_id}") def search(self, query_string: str): """ Performs a search using OData syntax and handles pagination. Example: "Person?$select=personId&$filter=lastname eq 'Godelmann'" """ if not self.access_token: return None all_results = [] next_page_url = f"{self.base_url}/{query_string}" while next_page_url: try: resp = requests.get(next_page_url, headers=self.headers) resp.raise_for_status() data = resp.json() all_results.extend(data.get('value', [])) next_page_url = data.get('next_page_url', None) except requests.exceptions.HTTPError as e: logger.error(f"❌ API Search Error for {query_string}: {e.response.text}") return None return all_results def create_project(self, name: str, contact_id: int, person_id: int = None): """Creates a new project linked to a contact, and optionally adds a person.""" payload = { "Name": name, "Contact": {"ContactId": contact_id} } if person_id: # Adding a person to a project requires a ProjectMember object payload["ProjectMembers"] = [ { "Person": {"PersonId": person_id}, "Role": "Member" # Default role, can be configured if needed } ] print(f"Creating new project: {name}...") return self._post("Project", payload) def create_appointment(self, subject: str, description: str, contact_id: int, person_id: int = None): """Creates a new appointment (to simulate a sent activity).""" import datetime now = datetime.datetime.utcnow().isoformat() + "Z" payload = { "Description": f"{subject}\n\n{description}", "Contact": {"ContactId": contact_id}, "StartDate": now, "EndDate": now, "Task": {"Id": 1} # Usually 'Follow-up' or similar, depending on SO config } if person_id: payload["Person"] = {"PersonId": person_id} print(f"Creating new appointment: {subject}...") return self._post("Appointment", payload) def update_entity_udfs(self, entity_id: int, entity_type: str, udf_data: dict): """ Updates UDFs for a given entity (Contact or Person). entity_type: 'Contact' or 'Person' udf_data: {ProgId: Value} """ endpoint = f"{entity_type}/{entity_id}" # 1. GET existing existing_entity = self._get(endpoint) if not existing_entity: logger.error(f"❌ Failed to retrieve existing {entity_type} {entity_id} for UDF update.") return False if "UserDefinedFields" not in existing_entity: existing_entity["UserDefinedFields"] = {} # 2. Merge payload existing_entity["UserDefinedFields"].update(udf_data) logger.info(f"Updating {entity_type} {entity_id} UDFs: {udf_data}...") # 3. PUT update result = self._put(endpoint, existing_entity) return bool(result) def update_person_position(self, person_id: int, position_id: int): """ Updates the standard 'Position' field of a Person. """ endpoint = f"Person/{person_id}" # 1. GET existing existing_person = self._get(endpoint) if not existing_person: logger.error(f"❌ Failed to retrieve Person {person_id} for Position update.") return False # 2. Check current value to avoid redundant updates current_pos = existing_person.get("Position", {}) if current_pos and str(current_pos.get("Id")) == str(position_id): logger.info(f"Person {person_id} Position already set to {position_id}. Skipping.") return True # 3. Update existing_person["Position"] = {"Id": int(position_id)} logger.info(f"Updating Person {person_id} Position to ID {position_id}...") # 4. PUT result = self._put(endpoint, existing_person) return bool(result)