Ejemplo n.º 1
0
def init_monzo(merchants=True):
    client = MonzoAPI()
    # Get the ID of the first account linked to the access token
    account_id = client.accounts()[1].id
    print("[Monzo] Retrieving transactions...")
    transactions = client.transactions(account_id)  # Get client.transaction(
    print("[Monzo] Retrieving merchants...")
    for item in transactions:
        if merchants:
            item.merchant = client.transaction(item.id,
                                               expand_merchant=True).merchant
        identifier = item.merchant.name if hasattr(item.merchant,
                                                   'name') else item.merchant
        print("[Monzo] Retrieved merchant {}.".format(identifier))
    print("Done.")
    return transactions
# Instantiate Monzo API client normally, using tokens from ~/.pymonzo-token generated previously
monzo = MonzoAPI()


# Create method to handle non-serializable data types in transaction object
def json_default(value):
    if isinstance(value, datetime.date):
        return value.isoformat()
    else:
        return value.__dict__


# Loop through all transactions and post them all to YNAB via fintech-to-ynab app deployed on Heroku
for monzoTransactionSimple in monzo.transactions():
    # Fetch full transaction details including merchant, as otherwise merchant name etc. is missing
    monzoTransactionFull = monzo.transaction(monzoTransactionSimple.id, True)

    if monzoTransactionFull.merchant is None:
        merchantName = ""
    else:
        merchantName = monzoTransactionFull.merchant.name

    ynabTransaction = {
        "type": "transaction.created",
        "data": monzoTransactionFull
    }

    ynabTransactionCreationString = json.dumps(ynabTransaction,
                                               indent=4,
                                               default=json_default)