--
-- This file is part of TALER
-- Copyright (C) 2024 Taler Systems SA
--
-- TALER is free software; you can redistribute it and/or modify it under the
-- terms of the GNU General Public License as published by the Free Software
-- Foundation; either version 3, or (at your option) any later version.
--
-- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
-- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-- A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along with
-- TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
--

CREATE OR REPLACE FUNCTION do_insert_issued_receipts (
  IN in_charity_id BIGINT -- charity id which made the issue receitps request
  ,IN in_blinded_sig BYTEA[] -- blinded signatures
  ,IN in_receipt_hash BYTEA -- hash over all budi key pairs (primary key)
  ,IN in_amount taler_amount -- total amount of the requested receipts
  ,OUT out_smaller_than_max_per_year BOOLEAN
)
LANGUAGE plpgsql
AS $$
DECLARE
  old_receipts_to_date taler_amount;
  new_receipts_to_date taler_amount;
  max_per_year taler_amount;
BEGIN
  -- Get charity values
  SELECT 
     (chari.receipts_to_date).val 
    ,(chari.receipts_to_date).frac 
    ,(chari.max_per_year).val 
    ,(chari.max_per_year).frac 
   INTO
      old_receipts_to_date.val
     ,old_receipts_to_date.frac
     ,max_per_year.val
     ,max_per_year.frac
   FROM charities chari
   WHERE charity_id=in_charity_id;
  -- calculate sum of the recent amount of receipts and the issued amount
  SELECT *
    FROM amount_add(old_receipts_to_date, in_amount)
    INTO new_receipts_to_date;
  -- check if the new receipts to date is below or equal the limit for the charity
  IF ( (max_per_year.val > new_receipts_to_date.val) OR
       ( (max_per_year.val = new_receipts_to_date.val) AND
         (max_per_year.frac > new_receipts_to_date.frac) ) )
  THEN  
    out_smaller_than_max_per_year=TRUE;
    UPDATE charities 
      SET receipts_to_date=new_receipts_to_date
      WHERE charity_id=in_charity_id;
    INSERT INTO receipts_issued (blinded_sig, charity_id, receipt_hash, amount)
      VALUES (in_blinded_sig, in_charity_id, in_receipt_hash, in_amount);
  ELSE
    out_smaller_than_max_per_year=FALSE;
  END IF;
END $$;
COMMIT;

COMMENT ON FUNCTION do_insert_issued_receipts
  IS 'This is a transaction for updating the current amount of receipts of a year of a charity and saves the receipts request what makes it idempotent';
