return: SETOF activite.p_gmt_valorises
lang: plpgsql
src: |
  DECLARE
  	_nb_jours_presence int;
  	_zone_sejour int;
  	_montant_valorise int;
  	_montant_fj int;
  	_input_record RECORD;
  	_output_record activite.p_gmt_valorises%ROWTYPE;
  BEGIN
  	FOR _input_record IN
  		SELECT 
  			p_sejours_groupes_smr.no_sejour
  			, p_sejours_groupes_smr.nb_jours_presence
  			, p_sejours_groupes_smr.gme_code
  			, p_sejours_groupes_smr.gmt_code
  			, p_sejours_groupes_smr.date_debut_gmt
  			, p_sejours_groupes_smr.date_fin_gmt
  			, v_tarifs_prive_gmt_non_forfaitisables.texte
  			, v_tarifs_prive_gmt_non_forfaitisables.dzf
  			, v_tarifs_prive_gmt_non_forfaitisables.fzf
  			, v_tarifs_prive_gmt_non_forfaitisables.tzb
  			, v_tarifs_prive_gmt_non_forfaitisables.tzf1
  			, v_tarifs_prive_gmt_non_forfaitisables.szb
  			, v_tarifs_prive_gmt_non_forfaitisables.szh
  		FROM activite.p_sejours_groupes_smr
  			JOIN base.v_tarifs_prive_gmt_non_forfaitisables ON p_sejours_groupes_smr.gmt_code = v_tarifs_prive_gmt_non_forfaitisables.code
  				AND p_sejours_groupes_smr.date_fin_gmt BETWEEN v_tarifs_prive_gmt_non_forfaitisables.date_debut AND v_tarifs_prive_gmt_non_forfaitisables.date_fin
    			AND p_sejours_groupes_smr.gme_code = v_tarifs_prive_gmt_non_forfaitisables.gme_code
  		WHERE p_sejours_groupes_smr.types_gmt_code = 'hc_non_forfaitisable'
  	LOOP
  		_nb_jours_presence := LEAST(_input_record.nb_jours_presence, 90);
  		SELECT COALESCE(activite.get_montant_fj_valorise_par_sejour(_input_record.no_sejour), 0) INTO _montant_fj;
  
  		IF _nb_jours_presence > _input_record.fzf 
  			THEN 
  				_zone_sejour := 3;
  		ELSIF _nb_jours_presence >= _input_record.dzf 
  			THEN 
  				_zone_sejour := 2;
  			ELSE 
  				_zone_sejour := 1;
  		END IF;
    
  		CASE _zone_sejour
  		    WHEN 1 THEN _montant_valorise := _input_record.tzb - (_input_record.dzf - _nb_jours_presence) * _input_record.szb;
  		    WHEN 2 THEN _montant_valorise := _input_record.tzf1;
  		    WHEN 3 THEN _montant_valorise := _input_record.tzf1 + (_nb_jours_presence - _input_record.fzf) * _input_record.szh;
  		END CASE;
    
  		_output_record.no_sejour := _input_record.no_sejour;
  		_output_record.gme_code := _input_record.gme_code;
  		_output_record.gmt_code := _input_record.gmt_code;
  		_output_record.gmt_libelle := _input_record.texte;
  		_output_record.date_debut_gmt := _input_record.date_debut_gmt;
  		_output_record.date_fin_gmt := _input_record.date_fin_gmt;
  		_output_record.montant_valorise := _montant_valorise - _montant_fj;
  		_output_record.montant_valorise_par_jour := (_montant_valorise - _montant_fj) / _nb_jours_presence;
    
  		RETURN NEXT _output_record;
  	END LOOP;
  	RETURN;
  	
  END;