Skip to content

Commit

Permalink
improved robustness of transaction_date handling all possible cases f…
Browse files Browse the repository at this point in the history
…rom api
  • Loading branch information
dnbasta committed Feb 11, 2024
1 parent dc4b8fd commit bad3a09
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
22 changes: 22 additions & 0 deletions tests/test_transaction.py
Original file line number Diff line number Diff line change
@@ -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'
22 changes: 18 additions & 4 deletions ynabapiimport/models/transaction.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from dataclasses import dataclass
from datetime import date
from datetime import datetime


@dataclass
Expand All @@ -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,
Expand Down

0 comments on commit bad3a09

Please sign in to comment.