From 25c6454e2d968f4a8e5076d87a859e0782549efa Mon Sep 17 00:00:00 2001 From: Brett Smith Date: Wed, 27 Dec 2017 13:44:35 -0500 Subject: [PATCH] importers.amazon: Initial version. --- import2ledger/importers/amazon.py | 66 +++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 import2ledger/importers/amazon.py diff --git a/import2ledger/importers/amazon.py b/import2ledger/importers/amazon.py new file mode 100644 index 0000000..6927e97 --- /dev/null +++ b/import2ledger/importers/amazon.py @@ -0,0 +1,66 @@ +import datetime +import itertools + +from . import _csv +from .. import strparse + +class NewMonthEarnings(Exception): + pass + + +class MonthlyEarnings: + def __init__(self): + self.dates = [] + self.amounts = [] + + def in_same_month(self, date): + try: + start_date = self.dates[0] + except IndexError: + return True + else: + return start_date.year == date.year and start_date.month == date.month + + def add(self, row): + date = strparse.date(strparse.slice_words(row['Date Shipped'], 0), '%Y-%m-%d') + amount = strparse.currency_decimal(row['Ad Fees($)']) + if self.in_same_month(date): + self.dates.append(date) + self.amounts.append(amount) + else: + raise NewMonthEarnings() + + def report(self): + return { + 'amount': sum(self.amounts), + 'date': max(self.dates), + } + + +class EarningsImporter(_csv.CSVImporterBase): + SENTINEL_ROW = { + 'Ad Fees($)': '0', + 'Date Shipped': '1979-07-09', + } + NEEDED_FIELDS = frozenset(SENTINEL_ROW.keys()) + TEMPLATE_KEY = 'template amazon earnings' + ENTRY_SEED = { + 'currency': 'USD', + 'payee': 'Amazon', + } + + def __init__(self, input_file): + super().__init__(input_file) + self.in_csv = itertools.chain(self.in_csv, [self.SENTINEL_ROW]) + self.earnings = MonthlyEarnings() + + def _read_row(self, row): + try: + self.earnings.add(row) + except NewMonthEarnings: + retval = self.earnings.report() + self.earnings = MonthlyEarnings() + self.earnings.add(row) + else: + retval = None + return retval