#! /usr/bin/env python3 from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from models import Tag, Transaction from helper import get_session, create_tag, get_rules import re import sys import click import colorful as cf @click.command(name="autosort") @click.option("--profile", "-p") @click.option("--dry-run", default=False, is_flag=True) @click.option("--verbose", "-v", default=False, is_flag=True) def command(profile, dry_run, verbose): session = get_session(profile) rules = get_rules(profile) unsorted = session.query(Transaction).filter(Transaction.tags == None).all() print("Found {} unsorted transcations".format(len(unsorted))) new = [] for transaction in unsorted: taglist = apply_rules(transaction, rules) if taglist: for tag_label in taglist: tag = session.query(Tag).filter(Tag.name == tag_label).first() if not tag: tag = create_tag(tag_label, profile, session) transaction.tags.append(tag) new.append(transaction) print(f"Automatically matched {len(new)} transactions") if not dry_run: session.bulk_save_objects(new) session.commit() def apply_rules(t, rules): for r in rules: iban = r.get("iban") name_regex = r.get("name") desc_regex = r.get("description") if iban: if t.iban != iban: continue if name_regex: if not re.search(name_regex, t.name): continue if desc_regex: if not re.search(desc_regex, t.description): continue return r["tags"].split(",")