"""General purpose helper methods.""" import csv from io import StringIO from itertools import islice from abacus_common_data.country import Country from lib.constants import ERROR_UNKNOWN_COUNTRY from lib.utils import ows def chunk_collection_by_size(collection, size): """Split provided collection into required chunks. Arguments: collection (list | tuple): initial collection size (int): required chunk size """ collection_type = type(collection) collection = iter(collection) return iter(lambda: collection_type(islice(collection, size)), collection_type()) def json_to_csv(json_data, only_headers=()): """Convert specified json object into csv format. Arguments: json_data (List[dict]): keys are headers for the csv only_headers (tuple): use only specified headers in output """ if not json_data: return '' fields = only_headers or list(json_data[0].keys()) csvfile = StringIO() writer = csv.DictWriter(csvfile, fieldnames=fields, extrasaction='ignore') writer.writeheader() writer.writerows(json_data) return csvfile.getvalue() def get_country_by_code(country_code): """Get country by country_code.""" try: country = Country(str(country_code.upper())) return country except KeyError: raise Exception( ERROR_UNKNOWN_COUNTRY.format(code=country_code) ) def get_accounting_period_state(accounting_period_id: int, action_name: str) -> dict: """Get abacus_state records for an accounting period filtered by action_name. Args: accounting_period_id (int): ID of the parent accounting period action_name (str): name of the abacus_state action_name to filter by Returns: the abacus_state record as a dict """ accounting_period_states = ows.get_accounting_period_state(accounting_period_id) if not accounting_period_states: raise ValueError('Accounting Period states not found') action = [ state for state in accounting_period_states if state['action_name'] == action_name ] if not action: raise ValueError(f'Accounting Period {action_name} state not found') return action[0] def get_sales_file_ids(accounting_period_id: int) -> list: """Get sales files in the parent accounting period. Return their IDs in a list. Args: accounting_period_id (int): ID of the parent accounting period Returns: a list of sales_files """ sales_files = ows.get_accounting_period_sales_files(accounting_period_id) return [sales_file.get('sales_file_id') for sales_file in sales_files]