def tag_apply(request, pk, account_id): """Tag transactions using the Monzo API.""" tag = get_object_or_404(Tag, pk=pk) client = Monzo(os.environ.get('MONZO_ACCESS_TOKEN')) txns = client.get_transactions(account_id)['transactions'] txns = parse_datetimes(txns) txns_updated = 0 for txn in txns: try: if eval(tag.expression): if tag.label not in txn['notes']: updated_txn = client.update_transaction_notes( txn['id'], txn['notes'] + ' ' + tag.label) txns_updated += 1 except (TypeError, KeyError): pass except Exception as e: raise e messages.warning( request, 'There is a problem with your Python expression: ' + str(e)) return redirect('account', account_id) if txns_updated: messages.info( request, '{} transactions tagged. Android users may need to delete App Cache and Data before changes are visible in the app.' .format(txns_updated)) else: messages.warning(request, 'No transactions match the given criteria') return redirect('account', account_id)
def tag_by_time(request, account_id, time_period): """Tag all transactions according to time period.""" client = Monzo(os.environ.get('MONZO_ACCESS_TOKEN')) txns = client.get_transactions(account_id)['transactions'] txns = parse_datetimes(txns) txns_updated = 0 for txn in txns: tag = '#{}'.format(txn['created'].strftime(strftime_code[time_period]).lower()) if tag not in txn['notes']: updated_txn = client.update_transaction_notes( txn['id'], txn['notes'] + ' ' + tag ) txns_updated += 1 messages.info(request, 'All {} transactions were tagged. Android users may need to delete App Cache and App Data before changes are visible in the app.'.format(txns_updated)) return redirect('account', account_id)