Newer
Older
pan_au_chocolat / db.py
Francesco Mecca on 19 Jan 2020 1 KB fst
from expenses import SharedExpense, Debit, Credit

import shelve

class Database:
    def __init__(self, filename):
        self.store = shelve.open(filename)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.store.close()

    def report(self):
        values = list(self.store.values())
        issuers = set(map(lambda x: x['issuer'], values))
        report = dict()
        for issuer in issuers:
            sharedexpenses = sum(
                map(lambda x: x['expense'],
                    filter(lambda x: type(x['pyobj']) is SharedExpense,
                           filter(lambda x: x['issuer'] == issuer,
                                  values)
                    )))
            credits = sum(
                map(lambda x: x['expense'],
                    filter(lambda x: type(x['pyobj']) is Credit,
                           filter(lambda x: x['issuer'] == issuer,
                                  self.store.values())
                    )))
            debits = sum(
                map(lambda x: x['expense'],
                    filter(lambda x: type(x['pyobj']) is Debit,
                           filter(lambda x: x['issuer'] == issuer,
                                  values)
                    )))
            report[issuer] = (sharedexpenses, credits, debits)
        return report
    
    def write_expense(self, issuer, expense):
        id = str(len(self.store))
        self.store[id] = {'issuer': issuer, 'type': str(type(expense)),
                          'expense': expense.amount, 'reason': expense.reason,
                          'pyobj': expense}
        self.store.sync()