diff --git a/tests/test_transaction.py b/tests/test_transaction.py new file mode 100644 index 0000000..308819e --- /dev/null +++ b/tests/test_transaction.py @@ -0,0 +1,22 @@ +from datetime import datetime +from unittest.mock import patch + +import pytest + +from ynabapiimport.models.transaction import Transaction + + +@patch('ynabapiimport.models.transaction.datetime', wraps=datetime) +@pytest.mark.parametrize('test_input', [{'valueDate': '2024-01-01'}, + {'bookingDate': '2024-01-01'}, + {'valueDateTime': '2024-01-01T00:00:'}, + {'bookingDateTime': '2024-01-01T00:00:00'}, + {}]) +def test_from_dict_datetimes(mock_datetime, test_input): + mock_datetime.now.return_value = datetime(2024, 1,1) + transaction_dict = {'internalTransactionId': 'id', + 'creditorName': 'payee', + 'transactionAmount': {'amount': '100'}} + transaction_dict = {**transaction_dict, **test_input} + t = Transaction.from_dict(transaction_dict) + assert t.transaction_date == '2024-01-01' diff --git a/ynabapiimport/models/transaction.py b/ynabapiimport/models/transaction.py index 7c9f4c2..ad68b79 100644 --- a/ynabapiimport/models/transaction.py +++ b/ynabapiimport/models/transaction.py @@ -1,5 +1,5 @@ from dataclasses import dataclass -from datetime import date +from datetime import datetime @dataclass @@ -12,21 +12,35 @@ class Transaction: @classmethod def from_dict(cls, t_dict: dict): - payee = None + if 'creditorName' in t_dict: payee = t_dict['creditorName'].strip() elif 'debtorName' in t_dict: payee = t_dict['debtorName'].strip() + else: + payee = None - memo = None if 'remittanceInformationUnstructured' in t_dict: memo = str(' '.join(t_dict['remittanceInformationUnstructured'].replace('\n', ' ')[:127].strip().split())) + else: + memo = None + + if 'valueDate' in t_dict.keys(): + transaction_date = t_dict['valueDate'] + elif 'valueDateTime' in t_dict.keys(): + transaction_date = t_dict['valueDateTime'][:10] + elif 'bookingDate' in t_dict.keys(): + transaction_date = t_dict['bookingDate'] + elif 'bookingDateTime' in t_dict.keys(): + transaction_date = t_dict['bookingDateTime'][:10] + else: + transaction_date = datetime.strftime(datetime.now(), '%Y-%m-%d') return cls(import_id=t_dict['internalTransactionId'], memo=memo, payee_name=payee, amount=int(float(t_dict['transactionAmount']['amount']) * 1000), - transaction_date=t_dict['valueDate']) + transaction_date=transaction_date) def as_dict(self): raw_dict = {'memo': self.memo,