def getBudget(self):

        self.connection = nYnabConnection(self.Config.ynabUser,
                                          self.Config.ynabPassword)
        self.client = nYnabClient(self.connection, self.Config.ynabBudgetName)

        self.fillBudget()
Example #2
0
 def setUp(self):
     super(TestUpdateChangedEntities, self).setUp()
     self.account = Account()
     self.client = nYnabClient(budgetname='Mock Budget')
     self.client.budget.be_accounts = [self.account]
     self.account2 = self.account.copy()
     self.client.session.commit()
Example #3
0
def route_webhook():
    data = json.loads(request.data.decode('utf8'))

    if data['type'] == 'transaction.created':
        ynab_connection = nYnabConnection(settings.ynab_username, settings.ynab_password)
        try:
            ynab_client = nYnabClient(ynab_connection, budget_name=settings.ynab_budget)
        except BudgetNotFound:
            print('No budget by this name found in nYNAB')
            exit(-1)

        accounts = {x.account_name: x for x in ynab_client.budget.be_accounts}
        payees = {p.name: p for p in ynab_client.budget.be_payees}

        def getaccount(accountname):
            try:
                log.debug('searching for account %s' % accountname)
                return accounts[accountname]
            except KeyError:
                log.error('Couldn''t find this account: %s' % accountname)
                exit(-1)

        def getpayee(payeename):
            try:
                log.debug('searching for payee %s' % payeename)
                return payees[payeename]
            except KeyError:
                log.debug('Couldn''t find this payee: %s' % payeename)
                payee=Payee(name=payeename)
                ynab_client.budget.be_payees.append(payee)
                return payee

        entities_account_id = getaccount('Mondo').id
        entities_payee_id = getpayee(data['data']['merchant']['name']).id

        transactions = []
        transaction = Transaction(
            entities_account_id=entities_account_id,
            amount=Decimal(data['data']['amount']) / 100,
            date=parse(data['data']['created']),
            entities_payee_id=entities_payee_id,
            imported_date=datetime.now().date(),
            imported_payee=data['data']['merchant']['name'],
            memo="%s %s" % (data['data']['merchant']['emoji'], data['data']['merchant']['metadata']['suggested_tags']),
            source="Imported"
        )

        if not ynab_client.budget.be_transactions.containsduplicate(transaction):
            log.debug('Appending transaction %s '%transaction.getdict())
            transactions.append(transaction)
        else:
            log.debug('Duplicate transaction found %s '%transaction.getdict())

        ynab_client.add_transactions(transactions)

        return jsonify(data)
    else:
        log.warning('Unsupported webhook type: %s' % data['type'])

    return ''
Example #4
0
    def __init__(self, ynab_user, ynab_password, ynab_budget_name):
        # Set constants
        self.__save_file = 'balances.p'
        self.__money_format = '${:,.2f}'

        connection = nYnabConnection(ynab_user, ynab_password)
        connection.init_session()
        self.__client = nYnabClient(nynabconnection=connection,
                                    budgetname=ynab_budget_name)
        self.__client.sync()

        self.__balances = self.__load_new_balances()
        self.__old_balances = self.__load_old_balances()
        self.__categories, self.__subcategories = self.__get_categories_and_subcategories(
        )
Example #5
0
from pynYNAB.Client import nYnabClient
from pynYNAB.connection import nYnabConnection
from pynYNAB.schema.budget import Payee, Transaction
import datetime

connection = nYnabConnection('*****@*****.**', 'w1r3l355')
client = nYnabClient(connection, 'My Budget')

subs = {}
balances = {}

#Gets subcategories from YNAB that have "Show in Dashboard" in the notes section
for ctg in client.budget.be_subcategories:
    if ctg.note is not None:
        if 'Show in Dashboard' in ctg.note:
            subs[ctg.name] = ctg

#Gets current month budget calculations
for b in client.budget.be_monthly_subcategory_budget_calculations:
    if b.entities_monthly_subcategory_budget_id[4:11] == (
            datetime.datetime.now().strftime('%Y-%m')):
        balances[b.entities_monthly_subcategory_budget_id[12:]] = b

#Displays the balance for each subcategory in the subs dict
for s in subs:
    print s + ':', balances[subs[s].id].balance
Example #6
0
def main():

    ynabUser = settings.ynab_user
    ynabPassword = settings.ynab_password
    ynabBudgetName = settings.ynab_budgetname

    print('Getting YNAB info')

    connection = nYnabConnection(ynabUser, ynabPassword)
    connection.init_session()
    client = nYnabClient(nynabconnection=connection, budgetname=ynabBudgetName)

    cats = {}
    subs = {}
    balances = defaultdict(Bal)

    if os.path.isfile('balances.p'):
        old_balances = pickle.load( open( "balances.p", "rb" ) )
        if type(old_balances) is not defaultdict:
            old_balances = defaultdict(Bal, old_balances)
    else:
        old_balances = defaultdict(Bal)

    #Creates hiarichy structure of category/subcategory and only those that have the keyword in YNAB subcategory notes section
    for cat in client.budget.be_master_categories:
            cats[cat.name]=cat
            subs[cat.name+'_subs'] = {}
            for subcat in client.budget.be_subcategories:
                    if subcat.entities_master_category_id == cat.id:
                            subs[cat.name+'_subs'][subcat.name] = subcat

    #Gets current month budget calculations
    for b in client.budget.be_monthly_subcategory_budget_calculations:
            if b.entities_monthly_subcategory_budget_id[4:11]==(datetime.datetime.now().strftime('%Y-%m')):
                    balances[b.entities_monthly_subcategory_budget_id[12:]]=b
                    #print(b.entities_monthly_subcategory_budget_id[12:]+': ' + str(b.balance))

    #Displays the balance for each subcategory in the subs dict
    bal_str = '<p>'
    for cat in cats:
        if 'Internal' not in cat:
            if len(subs[cat+'_subs'])>0:
                    bal_str += '<b>'+cat+'</b> <br>'
                    for scat in subs[cat+"_subs"]:
                            #print(cat + ' - ' + scat)
                            bal_str += '&nbsp;&nbsp;&nbsp;&nbsp;'+ scat + ': ' + str(balances[subs[cat+"_subs"][scat].id].balance)
                            bal_diff = balances[subs[cat+"_subs"][scat].id].balance - old_balances[subs[cat+"_subs"][scat].id].balance
                            bal_diff = round(bal_diff,2)
                            if bal_diff:
                                if bal_diff > 0:
                                    #Balance goes up
                                    bal_str += "&nbsp;&nbsp;<span style='color:green'>$" + str(bal_diff) + "&nbsp;&uarr;</span>"
                                else:
                                    #Balance went down
                                    bal_str += "&nbsp;&nbsp;<span style='color:red'>$" + str(abs(bal_diff)) + "&nbsp;&darr;</span>"
                            bal_str += '<br>'

    print('Sending Email')

    sendemail(settings.from_address, settings.to_list, '',
              'YNAB Balances for ' + datetime.datetime.now().strftime('%x'), bal_str, settings.gmail_user, settings.gmail_password, 'smtp.gmail.com:587')

    print('Saving balances')

    pickle.dump( balances, open( "balances.p", "wb" ) )
Example #7
0
from dotenv import load_dotenv, find_dotenv

from pynYNAB.Client import nYnabClient
from pynYNAB.scripts.__main__ import parser
load_dotenv(find_dotenv())

args = parser.parse_known_args()[0]

client = nYnabClient(email=args.email,
                     password=args.password,
                     budgetname='TestBudget')
client.sync()
Example #8
0
def init():
    global client
    client = nYnabClient(email=settings.ynab_username,
                         password=settings.ynab_password,
                         budgetname=settings.ynab_budget,
                         logger=settings.log)
Example #9
0
 def create_client_no_budget():
     client = nYnabClient()
Example #10
0
def route_webhook():
    data = json.loads(request.data.decode('utf8'))

    if data['type'] == 'transaction.created':
        ynab_connection = nYnabConnection(settings.ynab_username,
                                          settings.ynab_password)
        try:
            ynab_client = nYnabClient(ynab_connection,
                                      budget_name=settings.ynab_budget)
        except BudgetNotFound:
            print('No budget by this name found in nYNAB')
            exit(-1)

        accounts = {x.account_name: x for x in ynab_client.budget.be_accounts}
        payees = {p.name: p for p in ynab_client.budget.be_payees}

        def getaccount(accountname):
            try:
                log.debug('searching for account %s' % accountname)
                return accounts[accountname]
            except KeyError:
                log.error('Couldn' 't find this account: %s' % accountname)
                exit(-1)

        def getpayee(payeename):
            try:
                log.debug('searching for payee %s' % payeename)
                return payees[payeename]
            except KeyError:
                log.debug('Couldn' 't find this payee: %s' % payeename)
                payee = Payee(name=payeename)
                ynab_client.budget.be_payees.append(payee)
                return payee

        entities_account_id = getaccount('Mondo').id
        entities_payee_id = getpayee(data['data']['merchant']['name']).id

        # Try and get the suggested tags
        try:
            suggested_tags = data['data']['merchant']['metadata'][
                'suggested_tags']
        except KeyError:
            suggested_tags = ''

        # Try and get the emoji
        try:
            emoji = data['data']['merchant']['emoji']
        except KeyError:
            emoji = ''

        transactions = []
        transaction = Transaction(
            entities_account_id=entities_account_id,
            amount=Decimal(data['data']['amount']) / 100,
            date=parse(data['data']['created']),
            entities_payee_id=entities_payee_id,
            imported_date=datetime.now().date(),
            imported_payee=data['data']['merchant']['name'],
            memo="%s %s" % (emoji, suggested_tags),
            source="Imported")

        if not ynab_client.budget.be_transactions.containsduplicate(
                transaction):
            log.debug('Appending transaction %s ' % transaction.getdict())
            transactions.append(transaction)
        else:
            log.debug('Duplicate transaction found %s ' %
                      transaction.getdict())

        ynab_client.add_transactions(transactions)

        return jsonify(data)
    else:
        log.warning('Unsupported webhook type: %s' % data['type'])

    return ''