Newer
Older
pan_au_chocolat / expenses.py
Francesco Mecca on 19 Jan 2020 1 KB fst
from parsimonious import Grammar

grammar = Grammar("""
start = plus_expense / minus_expense / untagged_expense
plus_expense = PLUS amount text
minus_expense = MINUS amount text
untagged_expense = amount text
PLUS = "+"
MINUS = "-"
text = ~"[A-Z 0-9]*"iu
amount = ~"[0-9]+(.[0-9]+)?"
""")

class Expense:
    def __init__(self, amount, reason):
        if type(amount) is not str:
            raise TypeError("initialize using a string")

        self.amount = float(amount)
        self.reason = reason

class SharedExpense(Expense):
    # soldi messi nella cassa comune
    def __str__(self):
        return f'SharedExpense({self.amount}, {self.reason})'

class Credit(Expense):
    # soldi prestati per spese dell'altro
    def __str__(self):
        return f'Credit({self.amount}, {self.reason})'

class Debit(Expense):
    # soldi chiesti per spese proprie
    def __str__(self):
        return f'Debit({self.amount}, {self.reason})'

def parse(msg):
    parsed = grammar.parse(msg)
    head = parsed.children[0]

    if head.expr_name == 'untagged_expense':
        return SharedExpense(head.children[0].text, head.children[1].text)        
    elif head.expr_name == 'plus_expense':
        return Credit(head.children[1].text, head.children[2].text)
    elif head.expr_name == 'minus_expense':
        return Debit(head.children[1].text, head.children[2].text)
    else:
        assert False
        # import IPython
        # IPython.embed()