create
or replace procedure public.import_transactions_from_csv (
  p_bank_name varchar,
  p_bank_account_number varchar
) language plpgsql as $$

declare
	_acct int;

begin

raise notice 'PROC: import_transactions_from_csv';
raise notice 'INPUT: % p_bank_name = %; % p_bank_account_number = %;', E'\n', p_bank_name, E'\n', p_bank_account_number;

_acct := public.get_account_id(p_bank_name, p_bank_account_number);

if _acct is null then
	raise exception 'could not get the account id for bank_name (%) and bank account number (%)', p_bank_name, p_bank_account_number;
end if;

truncate table public.budgetimport;

copy
	public.budgetimport(dt, amount, description)
from
	'/usr/share/budget.csv'
delimiter ',' csv header;

delete from public.budgetdetails where acct_id = _acct;
insert into public.budgetdetails (trx_description, trx_date, trx_amount, acct_id)
select
	description
	, cast(dt as date) as dt_converted
	, amount
	, _acct
from public.budgetimport
where coalesce(amount, 0) <> 0;

end
$$;

grant
execute on PROCEDURE public.import_transactions_from_csv (varchar, varchar) to acedanger;

grant
execute on PROCEDURE public.import_transactions_from_csv (varchar, varchar) to budgetuser;