create or replace view bill.v_closed_bills as 
SELECT bill.pk, bill.fk_receiver_identity AS fk_identity, 
bill.total_amount, bill.close_date::date AS close_date
FROM bill.bill
WHERE bill.close_date IS NOT NULL;


grant select on bill.v_closed_bills to "gm-doctors", "gm-staff";
                 
create or replace view bill.acc_export_lines as 
select me.*, 
 'Re.'||pk||' vom '|| value_date || ',Kdnr.'||fk_identity as description
  from ( 
 select 'Income' as account, inv.pk, fk_identity, inv.close_date as value_date, -inv.total_amount as amount 
 from bill.v_closed_bills inv
 union all
 select 'Debitor.'||fk_identity , inv.pk, fk_identity, close_date, total_amount 
 from bill.v_closed_bills inv
) me
order by 2,1
;


grant select on bill.acc_export_lines  to "gm-staff";


