"""Script utilities.""" import csv import logging import os import requests ROOT_URL = { 'dev': 'http://localhost:5050', 'qa': 'https://qa-ows-moneyhub.theorchard.io', 'prod': 'https://prod-ows-moneyhub.theorchard.io' } class ScriptException(Exception): """Custom exception when running a script.""" pass def get_env( name: str, required: bool | None = False, default: str | None = None ) -> str | None: """Get an environment variable. Args: name (str): Name of the environment variable. required (bool): Whether the variable is required. default (str): Default value. Returns: str: Value of the variable. """ value = os.environ.get(name, default) if required and not value: logging.error(f'Missing required env variable {name}') exit(1) logging.info(f'{name}={value}') return value def get_identity_for_profile(environment: str) -> str: """Make a GET request to ows-users to get user identity. Args: environment (str): Environment the script is running in. Returns: str: Identity id. """ orchard_profile_type = get_env('ORCHARD_PROFILE_TYPE', True) orchard_profile_id = get_env('ORCHARD_PROFILE_ID', True) OWS_USERS_URL = { 'dev': 'https://qa-ows-users.theorchard.io', 'qa': 'https://qa-ows-users.theorchard.io', 'prod': 'https://prod-ows-users.theorchard.io' } endpoint = '/profile/profile_id/{}/profile_type/{}/identity'.format( orchard_profile_id, orchard_profile_type) url = OWS_USERS_URL[environment] + endpoint result = requests.get( url, headers={ 'Orchard-Profile-Type': orchard_profile_type, 'Orchard-Profile-Id': orchard_profile_id } ) if result.status_code < 200 or result.status_code > 299: logging.error(f'Received unexpected status code: {result.status_code}') logging.error(result.text) exit(1) result = result.json() return result['id'] def load_csv_file(file_path: str) -> list: """Load a CSV file, returning a list with its contents. Args: file_path (str): Path to the CSV file. Returns: list: List of the data from the CSV file. """ data = [] logging.info(f'Loading CSV from: {file_path}') with open(file_path) as csvfile: reader = csv.DictReader(csvfile) for row in reader: sanitized_row = {} for key, value in row.items(): sanitized_row[key.lower()] = value data.append(sanitized_row) logging.info(f'Found {len(data)} entries') return data def make_request(environment: str, endpoint: str, body: dict = {}) -> None: """Make a POST request. Args: environment (str): Environment the script is running in. endpoint (str): Endpoint to make a request to. body (dict): Body to send with the request """ orchard_profile_type = get_env('ORCHARD_PROFILE_TYPE', True) orchard_profile_id = get_env('ORCHARD_PROFILE_ID', True) url = ROOT_URL[environment] + endpoint logging.info(f'Sending request to: {url} ' + str(body)) orchard_user_id = get_identity_for_profile(environment) result = requests.post( url, json=body, headers={ 'Orchard-Profile-Type': orchard_profile_type, 'Orchard-Profile-Id': orchard_profile_id, 'Orchard-Roles': 'administrator', 'Orchard-Identity-Id': orchard_user_id } ) if result.status_code < 200 or result.status_code > 299: logging.error(f'Received unexpected status code: {result.status_code}') logging.error(result.text) exit(1) logging.info(f'Received status code: {result.status_code}') logging.info(result.text) def parse_boolean(text: str | None) -> bool: """Parse a text value into boolean. Args: text (str): Text to parse Returns: The text as a boolean """ if text is None: return False affirmative = ['yes', 'true', '1'] negative = ['no', 'false', '0'] if text.lower() in affirmative: return True if text.lower() in negative: return False raise ValueError(f'Unable to parse "{text}" as boolean') def s3_full_path(s3_bucket: str, object_name: str) -> str: """Generate full s3 path to save into the database. Args: s3_bucket (str): bucket to put the file object_name (str): File name generated for the invoice Returns: str: full s3 path to the specified object """ object_name = object_name.lstrip('/') return f's3://{s3_bucket}/{object_name}'