def get_or_create(cls, **kwargs): kwargs.pop( "import_timestamp" ) # Import Date should not be used to identify uniqueness exists = session.query(Transaction.id).filter_by(**kwargs).scalar() is not None if exists: return session.query(Transaction).filter_by(**kwargs).first() return Transaction(**kwargs)
def filter_transactions(self, filter_attr, value, *, number_of_rows=1): return ( session.query(Transaction) .filter(getattr(Transaction, filter_attr) == value) .limit(number_of_rows) .all() )
def import_transactions_from_file( self, file_path: Path, *, account_name: str = None ): self.file_state[f"{file_path.stem}{file_path.suffix}"] = { "hash": parser.hash_file(file_path), "account_name": account_name, } old_number = self.num_transactions max_account_date = ( session.query(func.max(Transaction.date)) .filter(Transaction.account == account_name) .first() ) if max_account_date[0] is not None: max_account_date = pendulum.instance(max_account_date[0]) else: max_account_date = None # Make Optional new_transactions = parser.parse_file( file_path, account_name, max_account_date=max_account_date ) for transaction_dict in new_transactions: transaction = Transaction.get_or_create(**transaction_dict) transaction.save() return self.num_transactions - old_number
def balance( self, *, date: pendulum.DateTime = pendulum.now(), group: str = "account" ) -> Dict[pendulum.DateTime, float]: balance_rows = ( session.query(getattr(Transaction, group), func.sum(Transaction.amount)) .filter(Transaction.date <= date) .group_by(group) .all() ) return dict(balance_rows)
def income_statement( self, start_date: pendulum.DateTime, end_date: pendulum.DateTime ) -> Dict[str, float]: balance_rows = ( session.query(Transaction.payee, func.sum(Transaction.amount)) .filter(Transaction.date <= end_date) .filter(Transaction.date >= start_date) .filter(Transaction.amount >= 0) .group_by(Transaction.payee) .all() ) return dict(balance_rows)
def end_date(self) -> Optional[pendulum.DateTime]: result = session.query(func.max(Transaction.date)).first() if len(result) == 1: return pendulum.instance(result[0]) return None
def last_import(self) -> Optional[pendulum.DateTime]: result = session.query(func.max(Transaction.added_timestamp)).first() if len(result) == 1: return pendulum.instance(result[0]) return None
def accounts(self) -> Set: return session.query(Transaction.account).distinct().all()
def currencies(self) -> Set: return session.query(Transaction.currency).distinct().all()
def payees(self) -> Set: return session.query(Transaction.payee).distinct().all()
def num_transactions(self): return session.query(Transaction).count()