importers.amazon: Initial version.

This commit is contained in:
Brett Smith 2017-12-27 13:44:35 -05:00
parent 11eccb60dd
commit 25c6454e2d

View file

@ -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