schmeckels/schmeckels/autosort.py
2020-11-05 00:11:23 +01:00

69 lines
2.1 KiB
Python

#! /usr/bin/env python3
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from schmeckels.models import Tag, Transaction
from schmeckels.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(cf.yellow("Found {} unsorted transcations".format(len(unsorted))))
new = []
matched = 0
for transaction in unsorted:
taglist = apply_rules(transaction, rules)
if taglist:
matched += 1
if verbose:
print(cf.green(f"Match: {transaction} -> {taglist}"))
if not dry_run:
for tag_label in taglist:
tag = session.query(Tag).filter(Tag.name == tag_label).first()
if not tag and not dry_run:
tag = create_tag(tag_label, profile, session)
transaction.tags.append(tag)
new.append(transaction)
if not dry_run:
session.bulk_save_objects(new)
session.commit()
print(cf.yellow(f"Automatically matched {matched} transactions"))
else:
print(cf.red(f"Automatically matched {matched} transactions. Not saved due to --dry-run!"))
def apply_rules(t, rules):
tags = []
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
tags.extend(r["tags"].split(","))
return tags