"""Supply Chain TSV parser and methods.""" import csv import os from oto import response from product_configuration.constants import supply_chain as supply_chain_ids from product_configuration.supply_chain import supply_chain_configuration_schemas # noqa APP_BASE_PATH = os.getcwd() SUPPLY_CHAIN_BASE_PATH = 'product_configuration/supply_chain' SUPPLY_CHAIN_MAPPING = { supply_chain_ids.GRAS_SUPPLY_CHAIN_ID: os.path.join( APP_BASE_PATH, SUPPLY_CHAIN_BASE_PATH, 'gras.tsv'), supply_chain_ids.PROPER_SUPPLY_CHAIN_ID: os.path.join( APP_BASE_PATH, SUPPLY_CHAIN_BASE_PATH, 'proper.tsv'), supply_chain_ids.AMAZON_SUPPLY_CHAIN_ID: os.path.join( APP_BASE_PATH, SUPPLY_CHAIN_BASE_PATH, 'amazon.tsv'), supply_chain_ids.FORTY_FIVE_PRESS_SUPPLY_CHAIN_ID: os.path.join( APP_BASE_PATH, SUPPLY_CHAIN_BASE_PATH, '45press.tsv') } def parse(path): """Parse a `.tsv` file. Args: path (str): absolute path to the file to parse Returns: parsed_tsv (list): containing rows of the tsv. """ with open(path) as tsv: dict_reader = csv.DictReader(tsv, delimiter='\t') return [{key: tsv_row[key] or None for key in tsv_row.keys()} for tsv_row in dict_reader] def get_supply_chain_path(supply_chain_id): """Return path to appropriate supply chain data. Args: supply_chain_id (int): id of the supply chain. Returns: path (str): absolute path to the appropriate supply chain data. """ return SUPPLY_CHAIN_MAPPING[supply_chain_id] def get_configurations(supply_chain_id): """Get list of configurations for a supply chain. Args: supply_chain_id (int): id of the supply chain Returns: Response - list of supply chains """ supply_chain_path = get_supply_chain_path(supply_chain_id) parsed_tsv = parse(supply_chain_path) return response.Response(status=200, message=parsed_tsv) def get_configuration_by_distribution_format( supply_chain_id, distribution_format_id): """Get a single configuration by distribution format id. Args: supply_chain_id (int): id of the supply chain. distribution_format_id (int): id of the distribution format configuration to retrieve. Returns: response.Response: a single configuration object. """ configurations = get_configurations(supply_chain_id) configuration = list(filter( lambda c: c['distribution_format_id'] == str(distribution_format_id), configurations.message)) if not len(configuration): return response.create_not_found_response() return response.Response(status=200, message=configuration[0]) def get_configuration_schemas(): """Get list of supply chain configuration schemas. Returns: Response - list of supply chain configuration schemas. """ return response.Response( status=200, message=supply_chain_configuration_schemas.SUPPLY_CHAIN_CONFIGURATION_SCHEMAS) # noqa def is_supply_chain_id_valid(supply_chain_id): """Check validity of supplied supply chain id. Args: supply_chain_id (int): supply chain id to verify. Returns: boolean: supply chain validity. """ return supply_chain_id in SUPPLY_CHAIN_MAPPING.keys()