Skip to content

New accounts should be set to default when none exist for that currency #734

@gudnuf

Description

@gudnuf

When a user adds an account for a currency that does not have any other accounts, the new account does not get set as default.

For example, if the user has no USD accounts and adds https://mint.lnvoltz.com for USD, the account gets added successfully, but they still have no default USD account. This is because of the change we made in #699 that makes a default usd account optional, and I didn't handle this case.

We could address this at the database level with a trigger function that sets the default_usd_account_id to the new account ID if no USD accounts exist for that user. The downside of this is that if we add more currencies, then we have to make new triggers (unless we changed our default currency schema to be more general).

To solve this problem, what do you think @jbojcic1 about a trigger that looks something like:

-- Create a trigger function that updates default_usd_account_id
create or replace function wallet.set_default_usd_account_on_insert()
returns trigger
language plpgsql
as $$
begin
  -- If this is a USD account and the user doesn't have a default USD account yet
  if NEW.currency = 'USD' then
    update wallet.users
    set default_usd_account_id = NEW.id
    where id = NEW.user_id
      and default_usd_account_id is null;
  end if;
  
  return NEW;
end;
$$;

-- Create the trigger
create trigger set_default_usd_account_trigger
after insert on wallet.accounts
for each row
execute function wallet.set_default_usd_account_on_insert();

Otherwise, I think we would need to make an add_account database function with a make_default: bool param that we call from the client so that we can be sure that when the account is added the default is set at the same time. If we were to first add the account, then once added set the default_usd_account_id there's a chance the second step would fail.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions