budget/pfbudget/transform/categorizer.py
Luís Murta ec22b5e5bd
[DB][Refactor] Compact the category selector
The `CategorySelector` was possibly added to be incremented with other
attributes. However, since none other that the selector enum is used at
the moment, it is only adding unnecessary cluter.
The category selector value is moved to the parent
`TransactionCategory`.
2024-01-22 21:47:47 +00:00

36 lines
1.0 KiB
Python

from copy import deepcopy
from typing import Iterable, Sequence
from pfbudget.db.model import (
CategoryRule,
CategorySelector,
Transaction,
TransactionCategory,
)
from .exceptions import TransactionCategorizedError
from .transform import Transformer
class Categorizer(Transformer):
def __init__(self, rules: Iterable[CategoryRule]):
self.rules = rules
def transform(self, transactions: Sequence[Transaction]) -> Sequence[Transaction]:
result = deepcopy(transactions)
self.transform_inplace(result)
return result
def transform_inplace(self, transactions: Sequence[Transaction]) -> None:
for rule in self.rules:
for transaction in transactions:
if transaction.category:
raise TransactionCategorizedError(transaction)
if not rule.matches(transaction):
continue
transaction.category = TransactionCategory(
rule.name, CategorySelector.rules
)