"""Read accounting run files from the local filesystem.""" from accounting.models.statement import Statement def read_exchange_rate_file(filename): """Read the lines of the exchange rates file into a list of dicts.""" header = True rows = [] with open(filename, 'r', encoding='utf-8') as lines: for line in lines: if header: header = False continue if not line: continue rate_row = line.strip().split('\t') rows.append({ 'period_id': int(rate_row[0]), 'currency_from_id': int(rate_row[1]), 'currency_to_id': int(rate_row[2]), 'exchange_rate': float(rate_row[3])}) return rows def read_statement_file(filename): """Read the lines of the statement TSV into an array of dicts. Args: filename (str): valid local filepath of a tsv file. Yields: dict: a dict representation of a line from the file. """ header = True with open(filename, 'r', encoding='utf-8') as lines: for line in lines: if header: header = False continue yield build_dict( Statement.fields.keys(), line.strip().split('\t')) def read_transaction_file(filename): """Read the lines of the digital sales TSV into an array of dicts. Args: filename (str): valid local filepath of a tsv file. Yields: dict: a dict representation of a line from the file. """ mapped_fields = [ 'statement_id', 'date', 'upc', 'cd', 'track_id', 'isrc', 'track_name', 'qty', 'unit_price', 'total', 'trans_type', 'retail_price', 'original_price', 'discount' ] with open(filename, 'r', encoding='utf-8') as lines: for line in lines: txn = build_dict(mapped_fields, line.strip().split('\t')) del txn['track_name'] del txn['isrc'] yield txn def build_dict(headers, values): """Combine a list of keys and a list of values into a dict. String stripping is performed to sanitize the input. Args: headers (List): Ordered keys for a dict. values (List): Ordered values for a dict. Returns: dict: A dict representation of combined headers and values. """ for idx, value in enumerate(values): values[idx] = value.strip('\"') return dict(zip(headers, values))