This is to handle refunds, which are invoices with negative amounts, that can be both issued or received (i.e., an “expense”). The API provided by PostgreSQL is mostly the same, and internally it deals with negatives, so the Go package only had to change selects of collection.
69 lines
1.7 KiB
PL/PgSQL
69 lines
1.7 KiB
PL/PgSQL
-- Deploy numerus:add_collection to pg
|
||
-- requires: roles
|
||
-- requires: schema_numerus
|
||
-- requires: payment
|
||
-- requires: invoice_payment
|
||
-- requires: company
|
||
-- requires: currency
|
||
-- requires: parse_price
|
||
-- requires: tag_name
|
||
-- requires: update_invoice_collection_status
|
||
|
||
begin;
|
||
|
||
set search_path to numerus, public;
|
||
|
||
create or replace function add_collection(company integer, invoice_id integer, collection_date date, payment_account_id integer, description text, amount text, tags tag_name[]) returns uuid as
|
||
$$
|
||
declare
|
||
cid integer;
|
||
cslug uuid;
|
||
amount_cents integer;
|
||
begin
|
||
insert into payment
|
||
( company_id
|
||
, payment_account_id
|
||
, description
|
||
, payment_date
|
||
, amount
|
||
, currency_code
|
||
, payment_status
|
||
, tags
|
||
)
|
||
select company_id
|
||
, payment_account_id
|
||
, description
|
||
, collection_date
|
||
, parse_price(amount, currency.decimal_digits)
|
||
, currency_code
|
||
, 'complete'
|
||
, tags
|
||
from company
|
||
join currency using (currency_code)
|
||
where company.company_id = add_collection.company
|
||
returning payment_id, slug, payment.amount
|
||
into cid, cslug, amount_cents
|
||
;
|
||
|
||
if invoice_id is not null then
|
||
-- must be inserted before updating statuses, so that it can see this
|
||
-- collection’s amount too.
|
||
insert into invoice_payment (invoice_id, payment_id)
|
||
values (invoice_id, cid)
|
||
;
|
||
|
||
perform update_invoice_collection_status(cid, invoice_id, amount_cents);
|
||
end if;
|
||
|
||
return cslug;
|
||
end
|
||
$$
|
||
language plpgsql
|
||
;
|
||
|
||
revoke execute on function add_collection(integer, integer, date, integer, text, text, tag_name[]) from public;
|
||
grant execute on function add_collection(integer, integer, date, integer, text, text, tag_name[]) to invoicer;
|
||
grant execute on function add_collection(integer, integer, date, integer, text, text, tag_name[]) to admin;
|
||
|
||
commit;
|