return: text
lang: plpgsql
src: |
  DECLARE	
  	
  	
  	
  	result TEXT;
  BEGIN
  	INSERT INTO pmsi.p_rss_etat
  		(
  		rss_id,
  		est_groupe,
  		est_valide,
  		date_groupage,
  		est_facture,
  		date_facture
  		)
  	SELECT
  		p_rss.oid AS rss_id,
  		CASE 
  			WHEN en_cours = '0' AND ghm_id <> 0 THEN '1'
  			WHEN en_cours = '0' AND ghm_id = 0 THEN '9'
  			WHEN en_cours = '1' AND ghm_id = 0 THEN '9'
  			WHEN en_cours_etat IN ('G', 'V') THEN '1' 
  			ELSE '0' END AS est_groupe,
  		CASE 
  			WHEN en_cours = '0' AND ghm_id <> 0 THEN '1'
  			WHEN en_cours = '0' AND ghm_id = 0 THEN '9'
  			WHEN en_cours = '1' AND ghm_id = 0 THEN '9'
  			WHEN en_cours_etat IN ('V') THEN '1' 
  			ELSE '0' END AS est_valide,
  		'20991231' AS date_groupage,
  		CASE 
  			WHEN en_cours = '0' THEN '1'
  			WHEN en_cours_etat IN ('F') THEN '1' 
  			WHEN base_remboursement > 0 THEN '1' 
  			ELSE '0' END AS est_facture,
  		'20991231' AS date_facture
  	FROM pmsi.p_rss
  	LEFT JOIN pmsi.p_rss_etat ON p_rss_etat.rss_id = p_rss.oid
  	WHERE p_rss_etat.rss_id IS NULL;

  	UPDATE pmsi.p_rss_etat
  	SET
  		est_groupe = CASE 
  			WHEN en_cours = '0' AND ghm_id <> 0 THEN '1'
  			WHEN en_cours = '0' AND ghm_id = 0 THEN '9'
  			WHEN en_cours = '1' AND ghm_id = 0 THEN '9'
  			WHEN en_cours_etat IN ('G', 'V') THEN '1' 
  			ELSE '0' END,
  		est_valide = CASE 
  			WHEN en_cours = '0' AND ghm_id <> 0 THEN '1'
  			WHEN en_cours = '0' AND ghm_id = 0 THEN '9'
  			WHEN en_cours = '1' AND ghm_id = 0 THEN '9'
  			WHEN en_cours_etat IN ('V') THEN '1' 
  			ELSE '0' END,
  		est_facture = CASE 
  			WHEN en_cours = '0' THEN '1'
  			WHEN en_cours_etat IN ('F') THEN '1' 
  			WHEN base_remboursement > 0 AND rss_id NOT IN (SELECT rss_id FROM pmsi.p_rsf_detail WHERE nature = 'V') THEN '1' 
  			ELSE '0' END
  	FROM pmsi.p_rss
  	WHERE p_rss.oid = p_rss_etat.rss_id AND
  		(
  		est_groupe IS DISTINCT FROM CASE 
  			WHEN en_cours = '0' AND ghm_id <> 0 THEN '1'
  			WHEN en_cours = '0' AND ghm_id = 0 THEN '9'
  			WHEN en_cours = '1' AND ghm_id = 0 THEN '9'
  			WHEN en_cours_etat IN ('G', 'V') THEN '1' 
  			ELSE '0' END OR
  		est_valide IS DISTINCT FROM  CASE 
  			WHEN en_cours = '0' AND ghm_id <> 0 THEN '1'
  			WHEN en_cours = '0' AND ghm_id = 0 THEN '9'
  			WHEN en_cours = '1' AND ghm_id = 0 THEN '9'
  			WHEN en_cours_etat IN ('V') THEN '1' 
  			ELSE '0' END OR
  		est_facture IS DISTINCT FROM CASE 
  			WHEN en_cours = '0' THEN '1'
  			WHEN en_cours_etat IN ('F') THEN '1' 
  			WHEN base_remboursement > 0 AND rss_id NOT IN (SELECT rss_id FROM pmsi.p_rsf_detail WHERE nature = 'V') THEN '1' 
  			ELSE '0' END
  		);

  	DELETE FROM pmsi.p_rss_etat
		WHERE rss_id IN (
			SELECT p_rss_etat.rss_id
			FROM pmsi.p_rss_etat
			LEFT JOIN pmsi.p_rss ON p_rss.oid = p_rss_etat.rss_id
			WHERE p_rss.oid IS NULL
		);
  		
  	RETURN 'OK';
  END;