Esempio n. 1
0
    def getBudget(self):

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

        self.fillBudget()
Esempio n. 2
0
    def create_client(self, args=None, sync=True, **kwargs):
        from pynYNAB.schema.Client import nYnabClient_
        if args is None:

            class Arg(object):
                pass

            args = Arg()
        for k, v in kwargs.items():
            setattr(args, k, v)
        if hasattr(args, 'budgetname'):
            setattr(args, 'budget_name', args.budgetname)

        if hasattr(args,
                   'nynabconnection') and args.nynabconnection is not None:
            setattr(args, 'connection', args.nynabconnection)

        if not hasattr(args, 'budget_name') or args.budget_name is None:
            raise NoBudgetNameException

        try:
            if not hasattr(args, 'connection'):
                if not hasattr(args, 'email') or args.email is None:
                    if not hasattr(args, 'password') or args.password is None:
                        raise NoCredentialsException
                connection = nYnabConnection(args.email, args.password)
                connection.init_session()
            else:
                connection = args.connection

            client_id = connection.id

            def postprocessed_client(cl):
                cl.connection = connection
                cl.catalogClient = CatalogClient(cl)
                cl.budgetClient = BudgetClient(cl)
                return cl

            previous_client = self.session.query(nYnabClient_).get(client_id)
            if previous_client is not None:
                previous_client.session = self.session
                return postprocessed_client(previous_client)

            client = nYnabClient_(id=client_id, budget_name=args.budget_name)
            client.engine = self.engine
            client.session = self.session
            client.add_missing()
            client = postprocessed_client(client)

            self.session.add(client)
            client.session.commit()
            if sync:
                client.sync()
            return client
        except BudgetNotFound:
            LOG.error('No budget by the name %s found in nYNAB' %
                      args.budget_name)
            raise
Esempio n. 3
0
def return_data():
    email = 'YOUR_EMAIL'
    password = '******'
    budget_name = 'YOUR_BUDGET_NAME'
    connection = nYnabConnection(email, password)
    connection.init_session()
    client = nYnabClientFactory().create_client(email, password, budget_name,
                                                connection)
    client.sync()

    #Get current date,year,month
    now = datetime.datetime.now()
    year = now.year
    month = now.month

    #Create dictionary of current months days
    num_days = c.monthrange(year, month)[1]
    current_month_days = [
        datetime.date(year, month, day) for day in range(1, num_days + 1)
    ]
    month_dict = dict((el, 0) for el in current_month_days)

    #Set dictionary values as transaction totals
    for i in current_month_days:
        for t in client.budget.transactions:
            if i == t.date:
                month_dict[t.date] += t.amount

    #Set all values to 2 decimal points
    for key, value in month_dict.items():
        month_dict[key] = float("{0:.2f}".format(value))

    #Create list of dictionaries
    final_data = []

    for key, value in month_dict.items():
        if value < 0:
            final_data.append({
                'title': value,
                'start': key.strftime('%Y-%m-%d'),
                'color': '#f08080'
            })
        elif value > 0:
            final_data.append({
                'title': value,
                'start': key.strftime('%Y-%m-%d'),
                'color': '#b4eeb4'
            })

        else:
            final_data.append({
                'title': value,
                'start': key.strftime('%Y-%m-%d'),
                'color': 'white'
            })

    return jsonify(final_data)
Esempio n. 4
0
def clientfromargs(args, reset=False):
    connection = nYnabConnection(args.email, args.password)
    try:
        client = nYnabClient(connection, budget_name=args.budgetname)
        if reset:
            # deletes the budget
            client.delete_budget(args.budgetname)
            client.create_budget(args.budgetname)
            client.select_budget(args.budgetname)
        return client
    except BudgetNotFound:
        print('No budget by this name found in nYNAB')
        exit(-1)
Esempio n. 5
0
def clientfromargs(args, reset=False):
    connection = nYnabConnection(args.email, args.password)
    try:
        client = nYnabClient(connection, budget_name=args.budgetname)
        if reset:
            # deletes the budget
            client.delete_budget(args.budgetname)
            client.create_budget(args.budgetname)
            client.select_budget(args.budgetname)
        return client
    except BudgetNotFound:
        print('No budget by the name %s found in nYNAB' % args.budgetname)
        exit(-1)
Esempio n. 6
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(
        )
Esempio n. 7
0
    def create_client(self, email=None, password=None, budget_name=None, connection=None, sync=True):
        from pynYNAB.schema.Client import nYnabClient_

        if budget_name is None:
            raise NoBudgetNameException

        try:
            if connection is None:
                if email is None and password is None:
                    raise NoCredentialsException()
                connection = nYnabConnection(email, password)
                connection.init_session()

            client_id = connection.id

            def postprocessed_client(cl):
                cl.connection = connection
                cl.catalogClient = CatalogClient(cl)
                cl.budgetClient = BudgetClient(cl)
                return cl

            previous_client = self.session.query(nYnabClient_).get(client_id)
            if previous_client is not None:
                previous_client.session = self.session
                return postprocessed_client(previous_client)

            client = nYnabClient_(id=client_id, budget_name=budget_name)
            client.engine = self.engine
            client.session = self.session
            client.add_missing()
            client = postprocessed_client(client)

            self.session.add(client)
            client.session.commit()
            if sync:
                client.sync()
            return client
        except BudgetNotFound:
            LOG.error('No budget by the name %s found in nYNAB' % budget_name)
            raise
Esempio n. 8
0
    def from_obj(args, reset=False, sync=True, **kwargs):
        try:
            if not hasattr(args, 'logginglevel'):
                setattr(args, 'logginglevel', 'error')

            kwargs['logger'] = get_logger(args)
            kwargs['budgetname'] = args.budgetname
            kwargs['nynabconnection'] = nYnabConnection(args.email, args.password)
            if hasattr(args, 'engine'):
                kwargs['engine'] = args.engine

            client = nYnabClient(**kwargs)
            if sync:
                client.sync()
            if reset:
                # deletes the budget
                client.delete_budget(args.budgetname)
                client.create_budget(args.budgetname)
                client.select_budget(args.budgetname)
            return client
        except BudgetNotFound:
            print('No budget by the name %s found in nYNAB' % args.budgetname)
            exit(-1)
Esempio n. 9
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
Esempio n. 10
0
def connection():
    obj = nYnabConnection(email='email', password='******')
    obj.session.post = new_post
    return obj
Esempio n. 11
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" ) )
Esempio n. 12
0
from dotenv import load_dotenv,find_dotenv

from pynYNAB.ClientFactory import nYnabClientFactory
from pynYNAB.connection import nYnabConnection
from pynYNAB.schema.budget import Transaction
from pynYNAB.scripts.__main__ import parser

load_dotenv(find_dotenv())

print('test_sync')
args = parser.parse_known_args()[0]

connection = nYnabConnection(args.email,args.password)
args.connection = connection

client = nYnabClientFactory().create_client(args)
client.sync()

for i in range(0,1000):
    client.budget.be_transactions.append(Transaction())
client.push(1000)
print('OK')