Skip to content

Commit

Permalink
Merge pull request #34 from stenjo/ynabmodel
Browse files Browse the repository at this point in the history
Ynabmodel
  • Loading branch information
stenjo authored Feb 9, 2022
2 parents dcc577e + 195e198 commit 68b2e57
Show file tree
Hide file tree
Showing 85 changed files with 148 additions and 15,801 deletions.
21 changes: 9 additions & 12 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
personal_api_settings.py
.vscode/*
*.csv
ynab/models/__pycache__/*
ynab/ynab/__pycache__/*
ynab/__pycache__/*
*/*/*/__pycache__/*
*/__pycache__/*
__pycache__/*
api_settings.py
*settings.py*
sync_accounts.1.py
bash_script.sh
api_settings_temp.py
api_settings.live.py
.gitignore
*/*.pyc
*.pyc
sync_accounts.log
.coverage
log/*
*.log
transacti*
statement*
workspace*
secret*
coverage.xml
workspace.code-workspace
log/*.json
.coverage
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,13 @@ Want to try YNAB? Help me out by using this referral link: https://ynab.com/refe
* Requires Python 3
* Requires package ``requests_oauthlib``:
```
$ pip3 install requests-oauthlib
c:> pip3 install requests-oauthlib
$ pip install requests-oauthlib
c:> pip install requests-oauthlib
```
* Requires package ``ynab_api``:
```
$ pip install git+https://github.com/dmlerner/ynab-api.git@nullfix
c:> pip install git+https://github.com/dmlerner/ynab-api.git@nullfix
```
* For running publication via MQTT (publish_accounts_status.py) package ``paho-mqtt`` is required
```
Expand Down
16 changes: 16 additions & 0 deletions helpers/Helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,22 @@ def getYnabTransactionDate(transaction):
d = datetime.datetime.strptime( getTransactionDate(transaction), "%d.%m.%Y")
return d.strftime('%Y-%m-%d')

def getYnabTransactionDateAsDate(transaction):
"""
Extract transaction date from an SBanken transaction and return this in a YNAB format
Args:
transaction (object): Transaction from a transaction list
Returns:
string: Transaction date in the format YYYY-MM-DD
"""
if 'beneficiaryName' in transaction:
return datetime.datetime.strptime(getPaymentsDate(transaction), "%d.%m.%Y").date()
# return d.strftime('%Y-%m-%d')
else:
return datetime.datetime.strptime( getTransactionDate(transaction), "%d.%m.%Y").date()
# return d.strftime('%Y-%m-%d')

def getPayee(transaction):
"""
Expand Down
15 changes: 8 additions & 7 deletions sync_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import platform

from pprint import pprint
from helpers.Helpers import getTransactionDate, getPayee, getMemo, getOut, getIn, getIntAmountMilli, getYnabTransactionDate, getYnabSyncId, findMatchingTransfer
from helpers.Helpers import getTransactionDate, getPayee, getMemo, getOut, getIn, getIntAmountMilli, getYnabTransactionDate, getYnabTransactionDateAsDate, getYnabSyncId, findMatchingTransfer
from sbanken.Sbanken import Sbanken
from ynab.Ynab import Ynab

Expand Down Expand Up @@ -70,22 +70,23 @@

logging.info("Transaction: %s, amount: %s, typecode: %s, text: %s", getYnabTransactionDate(transaction_item), transaction_item['amount'], transaction_item['transactionTypeCode'], getMemo(transaction_item))

yTrn = ynab.Transaction(
getYnabTransactionDate(transaction_item),
yTrn = ynab.SaveTransaction(
getYnabTransactionDateAsDate(transaction_item),
getIntAmountMilli(transaction_item),
account_map['account'],
getMemo(transaction_item),
getYnabSyncId(transaction_item)
getYnabSyncId(transaction_item),
account_map['Name']
)


yTrn.payee_name = payee_name

if 'transactionFlagColor' in vars(api_settings) and api_settings.transactionFlagColor != None:
yTrn.flag_color = api_settings.transactionFlagColor
yTrn.flag_color = api_settings.transactionFlagColor.lower()

if 'reservedFlagColor' in vars(api_settings) and api_settings.reservedFlagColor != None and (transaction_item.get('isReservation') == True or (transaction_item.get('otherAccountNumberSpecified') == False and transaction_item.get('source') != 'Archive')):
yTrn.flag_color = api_settings.reservedFlagColor
yTrn.flag_color = api_settings.reservedFlagColor.lower()


# Change import_id if same amount on same day several times
Expand Down Expand Up @@ -134,7 +135,7 @@
yTrn.payee_id = None
else:
yTrn.payee_id = update_transaction.payee_id
ynab_updates.append(yTrn)
ynab_updates.append(ynab.UpdateTransaction(yTrn))

elif len(account_map['account']) > 2: # New transactions not yet in YNAB
yTrs.append(yTrn)
Expand Down
23 changes: 23 additions & 0 deletions testynabapi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import datetime
from pprint import pprint
from ynab.Ynab import Ynab
import api_settings

# YNAB auth
ynab = Ynab(api_settings.api_key, api_settings.budget_id)

ynab_accounts = ynab.GetAccounts()

pprint(ynab_accounts)

today = datetime.date.today()
endDate = today
startDate = today - datetime.timedelta(80) # Last 8 days - unless changed in api_settings

existing_transactions = ynab.GetTransactionsByAccount('9280f4d8-92c4-46a4-aba1-0cb41a92f85b', startDate)

pprint(existing_transactions)
yTrs = [] # Transactions to YNAB
sTrns = ynab.SaveTransaction(today, -20000, '9280f4d8-92c4-46a4-aba1-0cb41a92f85b', 'Tesing memo', '46a47-aba1', 'Brukskonto', [])
yTrs.append(sTrns)
ynab.CreateTransactions(yTrs)
108 changes: 85 additions & 23 deletions ynab/Ynab.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,126 @@
import ynab
from ynab.rest import ApiException
import ynab_api
from ynab_api.api import accounts_api, transactions_api
from ynab_api.models import TransactionDetail, SaveTransaction, UpdateTransaction
# from ynab_api import exceptions, models

class Ynab:

configuration = ynab.Configuration()

def __init__(self, api_key, budgetId):
self.budgetId = budgetId
self.api_key = api_key

# Configure API key authorization: bearer
self.configuration.api_key['Authorization'] = api_key
self.configuration.api_key_prefix['Authorization'] = 'Bearer'
self.configuration = ynab_api.Configuration(host="https://api.youneedabudget.com/v1")
self.configuration.api_key['bearer'] = self.api_key
self.configuration.api_key_prefix['bearer'] = 'Bearer'

# create an instance of the API class
self.api_instance = ynab.TransactionsApi(ynab.ApiClient(self.configuration))
self.api_accounts = ynab.AccountsApi(ynab.ApiClient(self.configuration))

self.budgetId = budgetId
# # create an instance of the API class
self.api_client = ynab_api.ApiClient(self.configuration)
self.accounts_instance = accounts_api.AccountsApi(self.api_client)
self.transactions_instance = transactions_api.TransactionsApi(self.api_client)



def GetAccounts(self):
# Find ynab accounts
# create an instance of the API class
# with ynab_api.ApiClient(self.configuration) as api_client:
# self.configuration = ynab_api.Configuration(host="https://api.youneedabudget.com/v1")
# self.configuration.api_key['bearer'] = self.api_key
# self.configuration.api_key_prefix['bearer'] = 'Bearer'


# create an instance of the API class
# self.api_client = ynab_api.ApiClient(self.configuration)
# self.accounts_instance = accounts_api.AccountsApi(self.api_client)
try:
# Get existing accounts for the budget
api_response = self.api_accounts.get_accounts(self.budgetId)
except ApiException as e:
api_response = self.accounts_instance.get_accounts(self.budgetId)
except ynab_api.ApiException as e:
print("Exception when calling AccountsApi->get_accounts: %s\n" % e)

return api_response.data.accounts


def GetTransactionsByAccount(self, accountId, fromDate):
# Configure API key authorization: bearer
# self.configuration = ynab_api.Configuration(host="https://api.youneedabudget.com/v1")
# self.configuration.api_key['bearer'] = self.api_key
# self.configuration.api_key_prefix['bearer'] = 'Bearer'


# create an instance of the API class
# self.api_client = ynab_api.ApiClient(self.configuration)
# self.transactions_instance = transactions_api.TransactionsApi(self.api_client)
try:
# Get existing transactions that are Reserved in case they need to be updated
api_response = self.api_instance.get_transactions_by_account(self.budgetId, accountId, since_date=fromDate)
api_response = self.transactions_instance.get_transactions_by_account(self.budgetId, accountId, since_date=fromDate)

except ApiException as e:
except ynab_api.ApiException as e:
print("Exception when calling AccountsApi->get_accounts: %s\n" % e)

return api_response.data.transactions

def CreateTransactions(self, transactionList):
# create an instance of the API class
# api_instance = self.transactions_instance.TransactionsApi(self.api_client)
try:
# Create new transaction
api_response = self.api_instance.create_transaction(self.budgetId, {"transactions":transactionList})
except ApiException as e:
api_response = self.transactions_instance.create_transaction(self.budgetId, {"transactions":transactionList})
except ynab_api.ApiException as e:
print("Exception when calling TransactionsApi->create_transaction: %s\n" % e)

def UpdateTransactions(self, transactionList):
# create an instance of the API class
# api_instance = transactions_api.TransactionsApi(self.api_client)
try:
# Update existing transactions
api_response = self.api_instance.update_transactions(self.budgetId, {"transactions": transactionList})
except ApiException as e:
api_response = self.transactions_instance.update_transactions(self.budgetId, {"transactions": transactionList})
except ynab_api.ApiException as e:
print("Exception when calling TransactionsApi->update_transaction: %s\n" % e)

def Transaction(self, tdate, tamount, accountId, tmemo, timportId):
return ynab.TransactionDetail(
def Transaction(self, tdate, tamount, accountId, tmemo, timportId, accountName, subtrans=[], transactionId = ''):
# api_instance = accounts_api.TransactionsApi(self.api_client)
return TransactionDetail(
date=tdate,
amount=tamount,
cleared='uncleared',
approved=False,
account_id=accountId,
account_name=accountName,
memo=tmemo,
import_id=timportId,
subtransactions=subtrans,
deleted=False,
id = transactionId
)

def SaveTransaction(self, tdate, tamount, accountId, tmemo, timportId, accountName, subtrans=[], transactionId = ''):
# api_instance = accounts_api.TransactionsApi(self.api_client)
return SaveTransaction(
date=tdate,
amount=tamount,
cleared='uncleared',
approved=False,
account_id=accountId,
account_name=accountName,
memo=tmemo,
import_id=timportId
import_id=timportId,
subtransactions=subtrans,
deleted=False,
id = transactionId
)

def UpdateTransaction(self, transaction):
return UpdateTransaction(
date = transaction.date,
amount = transaction.amount,
cleared = transaction.cleared,
approved = transaction.approved,
account_id = transaction.account_id,
account_name = transaction.account_name,
memo = transaction.memo,
import_id = transaction.import_id,
subtransactions = transaction.subtransactions,
deleted = transaction.deleted,
id = transaction.id
)
96 changes: 0 additions & 96 deletions ynab/__init__.py

This file was deleted.

Loading

0 comments on commit 68b2e57

Please sign in to comment.