Pythonista Shortcuts

Hi,

I’m excited about the new possibilities and created a small python script to automate daily entered transactions. The script runs locally on my iOS device (see Pythonista app).

Just wanted to share this with you if anyone has a similar use case.

Base script:

# coding: utf-8
import console, requests, json, datetime

def get_id_for_name(collection, name):
    for item in collection:
        if item['name']==name:
            return item['id']
    raise ValueError('name not found in collection!', name, collection)

def get_initdata():
    try:
        with open("ynab_data_file.json") as data_file:
            data = json.load(data_file)
            print('Data loaded:', data)
            return data

    except FileNotFoundError:
        print('Data file not found. Getting new data.')
        pa_token = console.input_alert('YNAB Personal Access Token needed')
        header = {'Authorization': 'Bearer ' + pa_token}

        budgets = requests.get('https://api.youneedabudget.com/v1/budgets', headers=header)
        budgets.raise_for_status()
        budgets = budgets.json()['data']['budgets']
        budget_id = get_id_for_name(budgets, 'W Budget')

        accounts = requests.get('https://api.youneedabudget.com/v1/budgets/' + budget_id + '/accounts', headers=header)
        accounts.raise_for_status()
        accounts = accounts.json()['data']['accounts']
        account_id = get_id_for_name(accounts, 'Company')

        category_groups = requests.get('https://api.youneedabudget.com/v1/budgets/' + budget_id + '/categories', headers=header)
        category_groups.raise_for_status()
        category_groups = category_groups.json()['data']['category_groups']
        for category_group in category_groups:
            if category_group['name']=='Everyday Expenses':
                for category in category_group['categories']:
                    if category['name']=='Aramark':
                        category_id = category['id']
                        break
                break
        if not category_id:
            raise ValueError('Category not found!')

        payees = requests.get('https://api.youneedabudget.com/v1/budgets/' + budget_id + '/payees', headers=header)
        payees.raise_for_status()
        payees = payees.json()['data']['payees']
        payee_name = 'Aramark'
        payee_id = get_id_for_name(payees, payee_name)


        data = {
            'header': {
                'Authorization': 'Bearer ' + pa_token
            },
            'data_cache': {
                'budget_id': budget_id,
                'account_id': account_id,
                'category_id': category_id,
                'payee_id': payee_id,
                'payee_name': payee_name,
                'refresh_date': datetime.datetime.now().date().isoformat()
            }
        }
        with open("ynab_data_file.json", "w") as write_file:
            write_file.write(json.dumps(data, indent=4))

        return get_initdata()

def enter_aramark_tx(amount, memo):
    initdata = get_initdata()
    txdata = {
        'transaction': {
            'account_id': initdata['data_cache']['account_id'],
            'date': datetime.datetime.now().date().isoformat(),
            'amount': amount,
            'payee_id': initdata['data_cache']['payee_id'],
            'payee_name': initdata['data_cache']['payee_name'],
            'category_id': initdata['data_cache']['category_id'],
            'memo': memo + ' (API-Eintrag)',
            'cleared': 'cleared',
            'approved': True,
            'flag_color': None,
            'import_id': None
        }
    }

    txresponse = requests.post('https://api.youneedabudget.com/v1/budgets/' + initdata['data_cache']['budget_id'] + '/transactions', headers=initdata['header'], json=txdata).json()
    print(json.dumps(txresponse, indent=4))

    account_balance = requests.get('https://api.youneedabudget.com/v1/budgets/' + initdata['data_cache']['budget_id'] + '/accounts/' + initdata['data_cache']['account_id'], headers=initdata['header']).json()['data']['account']['balance']
    print('Success. New Account balance: ', account_balance/1000)


if __name__ == '__main__':
    enter_aramark_tx(-50, 'Test')

Example shortcut (gets placed on the homescreen):

from YNAB_API_Aramark import enter_aramark_tx
enter_aramark_tx(-850, 'Wasserkauf')
3replies Oldest first
  • Oldest first
  • Newest first
  • Active threads
  • Popular
  • whustedt This is cool!  Thanks for sharing.

    Reply Like
  • For better readability you can surround the balance statement with font declarations like this: 

        console.set_color(0, 0.5, 0) # green font
        console.set_font('Menlo', 20) # bigger font
        print('Success.\nNew Account balance: ', account_balance/1000)
        console.set_color() # reset font color
        console.set_font() # reset font size

    To show the practicality of my use case I uploaded a sample video to YouTube.

    Reply Like 1
    • whustedt Nice!  That's a handy script, there.  Thanks for sharing!

      Reply Like
Like1 Follow
  • 1 Likes
  • 1 yr agoLast active
  • 3Replies
  • 914Views
  • 2 Following