jantman / biweeklybudget

Responsive Flask/SQLAlchemy personal finance app, specifically for biweekly budgeting.
http://biweeklybudget.readthedocs.io/en/latest/
GNU Affero General Public License v3.0
101 stars 19 forks source link

Plaid - Add ability to delete an item #269

Open jantman opened 1 year ago

jantman commented 1 year ago

There's currently no way via the UI to delete a Plaid Item. Need to add this.

Until I do, here's the process.

First, query the database and find the access_token for the Item you want to remove (SELECT access_token FROM plaid_items WHERE item_id='YourItemId';. Then update any Accounts that use that item to set their Plaid Account association to "none". Finally, delete the plaid Item and Accounts from the database: DELETE FROM plaid_accounts WHERE item_id='YourItemId'; DELETE FROM plaid_items WHERE item_id='YourItemId';

Next:

$ docker exec -it biweeklybudget /bin/sh
# /app/bin/python

And enter the script:

from biweeklybudget.utils import plaid_client
from plaid.models import ItemRemoveRequest
client = plaid_client()
token = 'access-YOUR-TOKEN-HERE'
request = ItemRemoveRequest(access_token=token)
response = client.item_remove(request)
print(response)

This should generate output like {'request_id': 'SomeRequestId'}

Finally, in the Plaid Update UI, click the "Update Item Information From Plaid" button.

jantman commented 1 year ago

Here's a simpler script to do all of this much faster, using just the Plaid item_id, with NO other steps needed (no manual SQL queries, nothing in the UI):

First:

$ docker exec -it biweeklybudget /app/bin/python

Then:

item_id = 'YourPlaidItemIdHere'
# do NOT modify anything below this line

from biweeklybudget.utils import plaid_client
from plaid.models import ItemRemoveRequest
from biweeklybudget.db import init_db, db_session
from biweeklybudget.models.account import Account
from biweeklybudget.models.plaid_items import PlaidItem
from biweeklybudget.models.plaid_accounts import PlaidAccount

init_db()
item = db_session.query(PlaidItem).get(item_id)
print(f'Got Plaid Item: {item}')
client = plaid_client()
request = ItemRemoveRequest(access_token=item.access_token)
response = client.item_remove(request)
print(response)
plaid_acct = db_session.query(PlaidAccount).filter(PlaidAccount.plaid_item == item)
plaid_accts = db_session.query(PlaidAccount).filter(PlaidAccount.plaid_item == item).all()
assert len(plaid_accts) == 1
plaid_acct = plaid_accts[0]
accts = db_session.query(Account).filter(Account.plaid_account == plaid_acct).all()
assert len(accts) == 1
acct = accts[0]
acct.plaid_account_id = None
acct.plaid_account = None
db_session.add(acct)
db_session.delete(plaid_acct)
db_session.delete(item)
db_session.commit()