21 lines
658 B
Python
21 lines
658 B
Python
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.tables import CategoryRule, Transaction
|
|
|
|
|
|
def apply_rules(session: Session, transactions: list[Transaction]) -> int:
|
|
rules = session.execute(
|
|
select(CategoryRule).order_by(CategoryRule.priority)).scalars().all()
|
|
hits = 0
|
|
for tx in transactions:
|
|
if tx.category_id is not None:
|
|
continue
|
|
haystack = f"{tx.purpose} {tx.counterparty}".lower()
|
|
for rule in rules:
|
|
if rule.pattern.lower() in haystack:
|
|
tx.category_id = rule.category_id
|
|
hits += 1
|
|
break
|
|
return hits
|