"""Interface for the ows-account microservice.""" from oto import response from owsrequest import request as requests from ows_product_physical.constant import account from ows_product_physical.constant import error from ows_product_physical.constant import field from ows_product_physical.constant import service_name from ows_product_physical.utils.response_handler_util import safe_decode_json def get_vendor_id_from_grass_headers(account_type, account_id): """Get vendor_id from grass headers. Args: account_type (str): Grass account type. account_id (str): Grass account id. Returns: Response: The vendor_id from grass headers || by fetching subaccount. """ if account_type == account.VENDOR: return response.Response( status=200, message={field.VENDOR_ID: int(account_id)}) if account_type == account.SUBACCOUNT: subaccount_response = get_subaccount_by_id(account_id) if subaccount_response.status != 200: return subaccount_response return response.Response( status=subaccount_response.status, message={ field.VENDOR_ID: int( subaccount_response.message.get('vendor_id'))}) return response.create_error_response( status=400, code=error.BAD_REQUEST_ERROR, message='Invalid account type.') def get_subaccount_by_id(subaccount_id): """Fetch subaccount details by subaccount_id. Args: subaccount_id (int): Id of the subaccount to fetch. Returns: Response: Response containing the subaccount details. """ subaccount_response = requests.get( service_name.OWS_ACCOUNT, '/subaccount/{}'.format(subaccount_id)) content = safe_decode_json(subaccount_response, service_name.OWS_ACCOUNT) if subaccount_response.status_code != 200: return response.create_error_response( status=subaccount_response.status_code, code=content.get('code'), message=content.get('message')) return response.Response( status=subaccount_response.status_code, message=content) def get_vendor(account_type, account_id): """Get vendor from ows-account. Args: account_type (str): The account type. account_id (str): The account id. Returns: Response: Response containing the vendor object as returned by ows-account. """ vendor_id_response = get_vendor_id_from_grass_headers(account_type, account_id) if not vendor_id_response: return vendor_id_response vendor_id = vendor_id_response.message.get('vendor_id') vendor_response = requests.get( service_name.OWS_ACCOUNT, f'/vendor/{vendor_id}') content = safe_decode_json(vendor_response, service_name.OWS_ACCOUNT) if vendor_response.status_code != 200: return response.create_error_response( status=vendor_response.status_code, code=content.get('code'), message=content.get('message')) return response.Response( status=vendor_response.status_code, message=content)