<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>




	<NODE name="POST" label="TRAITEMENTS COMPLEMENTAIRES COMMUNS">

		<NODE label="Type d'environnement">
			<sqlcmd><![CDATA[
				CTISELECT_PROPERTY_READ 'ENV_WITHPMSI', MAX(CASE WHEN schemaname = 'pmsi' AND tablename = 'p_rss' THEN 1 ELSE 0 END)
				FROM pg_tables 
				WHERE schemaname = 'pmsi' AND tablename = 'p_rss'
			]]></sqlcmd>
		</NODE>

		<NODE label="Transformations">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
            
                -- Transformation de rubriques 
				UPDATE activite.p_factures_lignes_c
                SET rubrique_facturation_id = t_transformation.to_id
                FROM activite.t_transformation
                WHERE p_factures_lignes_c.rubrique_facturation_id = t_transformation.rubrique_id AND
                    p_factures_lignes_c.prestation_id = t_transformation.prestation_id AND
                    t_transformation.type = 'RUB' AND
                    t_transformation.to_id <> 0
				;	
                
                -- Services + UF vers service
				UPDATE activite.t_lieux
                SET service_facturation_id = t_transformation.to_id
                FROM activite.t_transformation
                WHERE t_lieux.service_facturation_id = t_transformation.service_facturation_id AND
					t_lieux.unite_fonctionnelle_id = t_transformation.unite_fonctionnelle_id AND
                    t_transformation.type = 'UFSER' AND
                    t_transformation.to_id <> 0
				;
                
                -- Services
                UPDATE activite.t_lieux
                SET service_facturation_id = t_transformation.to_id
                FROM activite.t_transformation
                WHERE t_lieux.service_facturation_id = t_transformation.service_facturation_id AND
                    t_transformation.type = 'SER' AND
                    t_transformation.to_id <> 0
				;
                                
                -- Unités fonctionnelles
                UPDATE activite.t_lieux
                SET unite_fonctionnelle_id = t_transformation.to_id
                FROM activite.t_transformation
                WHERE t_lieux.unite_fonctionnelle_id = t_transformation.unite_fonctionnelle_id AND
                    t_transformation.type = 'UF' AND
                    t_transformation.to_id <> 0 
				;
                
                -- Activites
                UPDATE activite.t_lieux
                SET activite_id = t_transformation.to_id
                FROM activite.t_transformation
                WHERE t_lieux.activite_id = t_transformation.activite_id AND
                    t_transformation.type = 'ACT' AND
                    t_transformation.to_id <> 0
				;
                
                
				-- Correction de comptes en double
				UPDATE activite.t_compte
				SET code = t_compte.code || '#' || indice::text
				FROM
				(
				SELECT code, max(oid) AS dupplicate_oid, count(*) AS indice
				FROM activite.t_compte
				WHERE oid <> 0
				GROUP BY 1
				HAVING count(*)>1
				) subview 
				WHERE t_compte.oid = dupplicate_oid
				;

                UPDATE activite.t_compte
                SET code = 'N/R'
                WHERE oid = 0
                ;
				
				-- Prestation forcée
				UPDATE activite.p_factures_lignes_c
				SET prestation_id = t_service_rubrique.prestation_forcee_id
				FROM activite.t_lieux,
					activite.t_service_rubrique
				WHERE lieu_id = t_lieux.oid AND
					t_service_rubrique.service_facturation_id = t_lieux.service_facturation_id AND
					t_service_rubrique.rubrique_facturation_id = p_factures_lignes_c.rubrique_facturation_id AND
					t_service_rubrique.prestation_forcee_id <> 0 AND
					p_factures_lignes_c.prestation_id IS DISTINCT FROM t_service_rubrique.prestation_forcee_id
				;
				
				UPDATE activite.p_factures_lignes_non_facturees_c p_factures_lignes_c
				SET prestation_id = t_service_rubrique.prestation_forcee_id
				FROM activite.t_lieux,
					activite.t_service_rubrique
				WHERE lieu_id = t_lieux.oid AND
					t_service_rubrique.service_facturation_id = t_lieux.service_facturation_id AND
					t_service_rubrique.rubrique_facturation_id = p_factures_lignes_c.rubrique_facturation_id AND
					t_service_rubrique.prestation_forcee_id <> 0 AND
					p_factures_lignes_c.prestation_id IS DISTINCT FROM t_service_rubrique.prestation_forcee_id
				;
				
				-- FJ non facturés qui sont à cheval sur plusieurs factures en cours SMR
				-- Il faut ventiler par facture
				DROP TABLE IF EXISTS w_factures_lignes_non_facturees_c_cheval;
				CREATE TEMP TABLE w_factures_lignes_non_facturees_c_cheval AS
				SELECT
					p_factures_lignes_non_facturees_c.CTID AS from_ctid
					, p_factures_lignes_non_facturees_c.no_facture
					, facture_id
					, p_factures_lignes_non_facturees_c.date_debut AS date_debut_ligne
					, p_factures_lignes_non_facturees_c.date_fin AS date_fin_ligne 
					, p_factures_lignes_non_facturees_c.nb_rubrique
					, p_factures_lignes_non_facturees_c.coefficient
					, p_factures_lignes_non_facturees_c.rubrique_facturation_id
					, p_factures_lignes_non_facturees_c.prestation_id
					, p_factures_lignes_non_facturees_c.prix_unitaire
					, p_factures_lignes_non_facturees_c.lieu_id
					, p_factures_lignes_non_facturees_c.montant_encours
					, p_factures_lignes_non_facturees_c.coefficient_mco
					, p_factures_lignes_non_facturees_c.lpp_id
					, p_factures_lignes_non_facturees_c.ucd_id
					, p_factures.date_debut AS date_debut_facture
					, p_factures.date_fin AS date_fin_facture
					, p_factures_to.no_facture AS to_no_facture
					, p_factures_to.oid AS to_facture_id
					, base.cti_division(
						p_factures_lignes_non_facturees_c.nb_rubrique * p_factures_lignes_non_facturees_c.prix_unitaire, 
						(p_factures_lignes_non_facturees_c.date_fin-p_factures_lignes_non_facturees_c.date_debut+1)::numeric
					) AS prix_unitaire_jour
					, base.cti_division(
						p_factures_lignes_non_facturees_c.montant_encours 
						, (p_factures_lignes_non_facturees_c.date_fin-p_factures_lignes_non_facturees_c.date_debut+1)::numeric
					) AS montant_encours_jour
					, GREATEST(p_factures_to.date_debut, p_factures_lignes_non_facturees_c.date_debut) AS to_date_debut_ligne
					, LEAST(p_factures_to.date_fin, p_factures_lignes_non_facturees_c.date_fin) AS to_date_fin_ligne
					, 1::numeric AS to_nb_rubrique
					, 0::numeric AS to_prix_unitaire
					, 0::numeric AS to_montant_encours
				FROM activite.p_factures_lignes_non_facturees_c
				JOIN activite.p_factures on p_factures_lignes_non_facturees_c.no_facture = p_factures.no_facture
				JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				JOIN activite.t_lieux ON lieu_sortie_id = t_lieux.oid
				JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				JOIN activite.p_factures p_factures_to ON p_factures.no_sejour = p_factures_to.no_sejour 
					AND (
						p_factures_to.date_debut BETWEEN p_factures_lignes_non_facturees_c.date_debut AND p_factures_lignes_non_facturees_c.date_fin
						OR p_factures_to.date_fin BETWEEN p_factures_lignes_non_facturees_c.date_debut AND p_factures_lignes_non_facturees_c.date_fin
					) 
					AND p_factures_to.code_facture = '0'
				WHERE 
					p_factures.code_facture = '0' 
					AND t_services_facturation.avec_facturation_intermediaire = '1' 
					AND t_prestations.code IN ('FJ') 
					AND (
						p_factures_lignes_non_facturees_c.date_debut NOT BETWEEN p_factures.date_debut AND p_factures.date_fin 
						OR p_factures_lignes_non_facturees_c.date_fin NOT BETWEEN p_factures.date_debut AND p_factures.date_fin
					)
					;

				ANALYSE w_factures_lignes_non_facturees_c_cheval
				;


				UPDATE w_factures_lignes_non_facturees_c_cheval SET
					to_prix_unitaire = round((to_date_fin_ligne - to_date_debut_ligne + 1) * prix_unitaire_jour,2),
					to_montant_encours = round((to_date_fin_ligne - to_date_debut_ligne + 1) * montant_encours_jour,2)
				;

				DELETE FROM activite.p_factures_lignes_non_facturees_c
				WHERE CTID IN (SELECT from_CTID FROM w_factures_lignes_non_facturees_c_cheval)
				;

				INSERT INTO activite.p_factures_lignes_non_facturees_c(
					no_facture, 
					date_debut, 
					date_fin, 
					nb_rubrique, 
					coefficient, 
					rubrique_facturation_id, 
					prestation_id, 
					prix_unitaire, 
					lieu_id, 
					facture_id, 
					montant_encours, 
					coefficient_mco, 
					lpp_id, 
					ucd_id
					)
				SELECT
					to_no_facture, 
					to_date_debut_ligne, 
					to_date_fin_ligne, 
					to_nb_rubrique, 
					coefficient, 
					rubrique_facturation_id, 
					prestation_id, 
					to_prix_unitaire, 
					lieu_id, 
					to_facture_id, 
					to_montant_encours, 
					coefficient_mco, 
					lpp_id, 
					ucd_id
				FROM w_factures_lignes_non_facturees_c_cheval
				;
                
			]]></sqlcmd>

		</NODE>

		<NODE label="Compléments patients">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
				INSERT INTO activite.t_medecins_traitants_administratifs(oid, code_original, code, nom, prenom, specialite_id, medecin_id) 
				SELECT 0, '', '****', 'Non renseigné', '', 0, 0 WHERE 0 NOT IN (SELECT oid FROM activite.t_medecins_traitants_administratifs);
				
				UPDATE activite.p_coordonnees_patient
				SET 
					telephone_fixe = CASE WHEN telephone_fixe != '' THEN regexp_replace(telephone_fixe,'[^0-9,]','','g') ELSE null END,
					telephone_portable = CASE WHEN telephone_portable != '' THEN regexp_replace(telephone_portable,'[^0-9,]','','g') ELSE null END
				;
				
				UPDATE activite.p_coordonnees_patient
				SET 
					telephone_fixe =
									SUBSTR(telephone_fixe,1,2) || '.' || 
									SUBSTR(telephone_fixe,3,2) || '.' ||
									SUBSTR(telephone_fixe,5,2) || '.' ||
									SUBSTR(telephone_fixe,7,2) || '.' ||
									SUBSTR(telephone_fixe,9,2),
					telephone_portable = 
									SUBSTR(telephone_portable,1,2) || '.' || 
									SUBSTR(telephone_portable,3,2) || '.' ||
									SUBSTR(telephone_portable,5,2) || '.' ||
									SUBSTR(telephone_portable,7,2) || '.' ||
									SUBSTR(telephone_portable,9,2)
				;
					
				UPDATE activite.p_coordonnees_patient
				SET 
					telephone_fixe = CASE 
						WHEN SUBSTR(telephone_fixe,2,1) IN (1,2,3,4,5,9) AND  SUBSTR(telephone_portable,2,1) IN (1,2,3,4,5,9) THEN telephone_fixe || ',' || telephone_portable
						WHEN SUBSTR(telephone_fixe,2,1) IN (1,2,3,4,5,9) THEN telephone_fixe
						WHEN SUBSTR(telephone_portable,2,1) IN (1,2,3,4,5,9) THEN telephone_portable
						ELSE '' END,
					telephone_portable = CASE 
						WHEN SUBSTR(telephone_portable,2,1) NOT IN (1,2,3,4,5,9) AND telephone_portable != '' AND SUBSTR(telephone_fixe,2,1) NOT IN (1,2,3,4,5,9) AND telephone_fixe != '' THEN telephone_fixe || ',' || telephone_portable
						WHEN SUBSTR(telephone_fixe,2,1) NOT IN (1,2,3,4,5,9) THEN telephone_fixe
						WHEN SUBSTR(telephone_portable,2,1) NOT IN (1,2,3,4,5,9) THEN telephone_portable
						ELSE '' END,
					email = CASE WHEN STRPOS(email,'@') > 1 THEN email ELSE '' END
				;
				
				UPDATE activite.p_sejours
				SET medecin_sejour_id = subview.medecin_sejour_id
				FROM
				(
					SELECT p_factures.no_sejour,
						(MAX(ARRAY[to_char(p_factures_lignes_h.montant_facture,'FM000000000000'),medecin_facture_id::text]))[2]::bigint AS medecin_sejour_id
					FROM activite.p_factures_lignes_h
					JOIN activite.p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture
					JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
					WHERE p_sejours.type_sejour = '3' AND
						p_sejours.medecin_sejour_id = 0 AND
						medecin_facture_id <> 0
					GROUP BY 1
				) subview
				WHERE p_sejours.no_sejour = subview.no_sejour
				;
					
			]]></sqlcmd>

		</NODE>

		<NODE label="Traitement dépassements">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[

				-- Pour standardiser la présentation des dépassements
				
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'TRTDEPASSEMENT',
					'Traitement des dépassements',
					'',
					'Inclusion dépassements dans montant facturé : ''I'' = Inclus, ''X'' = Exclus  '
				WHERE 'TRTDEPASSEMENT' NOT IN (SELECT code FROM activite.t_divers);
				
				-- Dépassements inclus
				DROP TABLE IF EXISTS w_depassements_detail;
				CREATE TEMP TABLE w_depassements_detail AS
				SELECT p_factures_lignes_h.CTID AS fromCTID,
					no_facture, 
					prix_unitaire, 
					coefficient, 
					nb_prestation, 
					coefficient_mco, 
					montant_depassement
				FROM activite.p_factures_lignes_h
				JOIN activite.t_divers ON t_divers.code = 'TRTDEPASSEMENT' AND 
					t_divers.valeur = 'I'
				WHERE montant_depassement <> 0 AND
					montant_facture_0 = 0 AND
					(
					taux_1+taux_2 = 100 AND
					round(montant_facture_1,0) = round(montant_facture*taux_1/100,0) AND 
					round(montant_facture_2,0) = round(montant_facture*taux_2/100,0)
					) 
				;

				UPDATE activite.p_factures_lignes_h SET
					montant_facture = montant_facture+w_depassements_detail.montant_depassement,
					montant_facture_0 = montant_facture_0+w_depassements_detail.montant_depassement
				FROM w_depassements_detail
				WHERE p_factures_lignes_h.no_facture = w_depassements_detail.no_facture AND
					p_factures_lignes_h.CTID = fromCTID;

				UPDATE activite.p_factures SET
					montant_facture_h = subview.montant_facture,
					montant_facture_0_h = subview.montant_facture_0
				FROM (
					SELECT no_facture, 
						SUM(montant_facture) AS montant_facture,
						SUM(montant_facture_0) AS montant_facture_0
					FROM activite.p_factures_lignes_h
					WHERE no_facture IN (SELECT no_facture FROM w_depassements_detail)
					GROUP BY 1
					) subview
				WHERE p_factures.no_facture = subview.no_facture AND
					 p_factures.no_facture IN (SELECT no_facture FROM w_depassements_detail);

				UPDATE activite.p_sejours SET
					montant_facture_h = subview.montant_facture_h,
					montant_facture_0_h = subview.montant_facture_0_h
				FROM (
					SELECT no_sejour, 
						SUM(montant_facture_h) AS montant_facture_h,
						SUM(montant_facture_0_h) AS montant_facture_0_h
					FROM activite.p_factures
					WHERE no_facture IN (SELECT no_facture FROM w_depassements_detail)
					GROUP BY 1
					) subview
				WHERE p_sejours.no_sejour = subview.no_sejour;
				
				-- Suppression montant dépassement sur avoirs et factures annulées (pour comptage des sejours avec dépassement)
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'DELDEPASSEMENTAVOIR',
					'Suppression dépassements sur avoirs',
					'0',
					'1=Suppression sur avoirs et factures annulées'
				WHERE 'DELDEPASSEMENTAVOIR' NOT IN (SELECT code FROM activite.t_divers)
				;
				
				DROP TABLE IF EXISTS w_factures_avoir;
				CREATE TEMP TABLE w_factures_avoir AS
				SELECT p_factures.no_facture, p_factures.no_facture_od_avoir
				FROM activite.p_factures
				JOIN activite.p_factures p_factures_avoir ON p_factures.no_facture_od_avoir = p_factures_avoir.no_facture
				JOIN activite.t_divers ON t_divers.code = 'DELDEPASSEMENTAVOIR'
				WHERE t_divers.valeur = '1' AND
					p_factures.type_facture = 'X' AND
					p_factures.montant_facture_h = 0-p_factures_avoir.montant_facture_h AND
					p_factures.montant_facture_h <> 0
				;
				ANALYSE w_factures_avoir
				;

				UPDATE activite.p_factures_lignes_h
				SET montant_depassement = 0
				WHERE no_facture = ANY (SELECT w_factures_avoir.no_facture FROM w_factures_avoir) AND
					montant_depassement <> 0
				;
				UPDATE activite.p_factures_lignes_h
				SET montant_depassement = 0
				WHERE no_facture = ANY (SELECT w_factures_avoir.no_facture_od_avoir FROM w_factures_avoir) AND
					montant_depassement <> 0
				;
					
			]]></sqlcmd>

		</NODE>

		<NODE label="Compléments mouvements séjour">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
                
                -- Date sortie sur séances non saisie, prendre date dernière seance
				UPDATE activite.p_sejours SET
					date_sortie = subview.date_sortie,
					heure_sortie = 230000,
					code_sorti = '1'
				FROM 
				(
					SELECT p_mouvements_sejour.no_sejour, MAX(p_mouvements_sejour.date) AS date_sortie, MAX(avec_facturation_intermediaire) AS avec_facturation_intermediaire
					FROM activite.p_mouvements_sejour
					JOIN activite.p_sejours ON p_mouvements_sejour.no_sejour = p_sejours.no_sejour
					JOIN activite.t_lieux ON lieu_id = t_lieux.oid
					JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
					WHERE p_sejours.type_sejour = '5' AND
						p_sejours.code_prevu <> '1' AND
						p_sejours.code_sorti = '0'
				GROUP BY 1
				HAVING (
					MAX(p_mouvements_sejour.date) < date((SELECT MAX(date) FROM activite.p_mouvements_sejour WHERE est_mouvement_previsionnel = '0') - interval '7 days') OR
					(MAX(avec_facturation_intermediaire) <> '1' AND p_mouvements_sejour.no_sejour IN (SELECT no_sejour FROM activite.p_factures where code_facture = '1'))
					)
				) subview
				WHERE p_sejours.no_sejour = subview.no_sejour
				;
            
                -- GHM et GHS selon PMSI
                SELECT base.cti_execute(
				'DROP TABLE IF EXISTS w_sejours_ghm
                .,
                CREATE TEMP TABLE w_sejours_ghm AS
                SELECT oid, no_sejour, date_naissance, p_sejours.ghm_id, p_sejours.ghs_id, date_entree, date_sortie, type_sejour
                FROM activite.p_sejours
                                JOIN activite.p_patients ON p_sejours.no_patient = p_patients.no_patient
                                WHERE type_sejour IN (''1'',''2'',''5'',''6'')
                .,
                DROP TABLE IF EXISTS w_ghm_corres
                .,
                CREATE TEMP TABLE w_ghm_corres AS
                SELECT t_ghm_p.code AS ghm_code, t_ghm_p.oid AS ghm_p_id, t_ghm_a.oid AS ghm_a_id
                FROM pmsi.t_ghm t_ghm_p
                JOIN base.t_ghm t_ghm_a ON t_ghm_a.code = t_ghm_p.code
                WHERE t_ghm_p.code BETWEEN ''01    '' AND ''29    ''
                .,

                DROP TABLE IF EXISTS w_ghs_corres
                .,
                CREATE TEMP TABLE w_ghs_corres AS
                SELECT t_ghs_p.code AS ghs_code, t_ghs_p.oid AS ghs_p_id, t_ghs_a.oid AS ghs_a_id
                FROM pmsi.t_ghs t_ghs_p
                JOIN base.t_ghs t_ghs_a ON t_ghs_a.code = t_ghs_p.code
                .,
                UPDATE activite.p_sejours
                SET
                 ghm_id = subview.ghm_id
                 ,ghs_id = CASE WHEN subview.ghs_id > 0 THEN subview.ghs_id ELSE p_sejours.ghs_id END
                FROM
                (
                    SELECT p_sejours.no_sejour, ghm_a_id AS ghm_id, ghs_a_id AS ghs_id
                    FROM w_sejours_ghm p_sejours
					JOIN activite.p_sejour_pmsi ON  p_sejour_pmsi.sejour_id = p_sejours.oid
                    JOIN pmsi.p_rss ON p_sejour_pmsi.rss_id  = p_rss.oid AND
                        date_trunc(''month'',p_sejours.date_sortie) = date_trunc(''month'',p_rss.date_sortie) AND
                        p_sejours.date_naissance = p_rss.date_naissance
					JOIN w_ghm_corres ON p_rss.ghm_id = ghm_p_id
                    JOIN w_ghs_corres ON p_rss.ghs_id = ghs_p_id
                    WHERE (p_sejours.ghm_id <> ghm_a_id OR p_sejours.ghs_id <> ghs_a_id) AND
                        p_rss.ghm_id > 0 AND
                        p_rss.etat = '''' AND
						(p_rss.en_cours = ''0'' OR p_rss.en_cours_etat IN (''V'',''F''))
                ) subview
                WHERE p_sejours.no_sejour = subview.no_sejour
                ',1)
                WHERE 'p_rss' IN (SELECT tablename FROM pg_tables WHERE schemaname = 'pmsi' AND tablename = 'p_rss')
				;
                
                -- Date groupage selon PMSI
				SELECT base.cti_execute(
				'UPDATE activite.p_sejours
				SET date_groupage = subview.date_groupage
				FROM
				(
					SELECT
						p_sejours.no_sejour
						,MAX(p_rss_etat.date_groupage) AS date_groupage
					FROM activite.p_sejours
						JOIN activite.p_sejour_pmsi ON  p_sejour_pmsi.sejour_id = p_sejours.oid
                    	JOIN pmsi.p_rss ON p_sejour_pmsi.rss_id  = p_rss.oid AND
						date_trunc(''month'',p_sejours.date_sortie) = date_trunc(''month'',p_rss.date_sortie)
					JOIN pmsi.p_rss_etat ON p_rss_etat.rss_id = p_rss.oid
					JOIN pmsi.t_ghm t_ghm_p ON p_rss.ghm_id = t_ghm_p.oid
					WHERE type_sejour IN (''1'',''2'',''5'',''6'') AND
						p_rss.ghm_id > 0 AND
						p_rss_etat.date_groupage < ''20991231''::date AND
						t_ghm_p.code NOT LIKE ''90%'' AND t_ghm_p.code NOT LIKE ''99%'' AND
						(p_rss.en_cours = ''0'' OR p_rss.en_cours_etat IN (''V'',''F''))
					GROUP BY 1
				) subview
				WHERE p_sejours.no_sejour = subview.no_sejour AND
					p_sejours.date_groupage IS DISTINCT FROM subview.date_groupage
				',1)
				WHERE 'p_rss' IN (SELECT tablename FROM pg_tables WHERE schemaname = 'pmsi' AND tablename = 'p_rss')
				;
				
				UPDATE activite.p_factures SET
					ghs_id = p_sejours.ghs_id,
					gmt_id = p_sejours.gmt_id
				FROM activite.p_sejours
				WHERE p_factures.no_sejour = p_sejours.no_sejour AND
					(
					p_factures.ghs_id IS DISTINCT FROM p_sejours.ghs_id OR
					p_factures.gmt_id IS DISTINCT FROM p_sejours.gmt_id
					)
				;
		
            
                -- Chambres particulières selon facturation
                DROP TABLE IF EXISTS w_cp_facturees;
                CREATE TEMP TABLE w_cp_facturees AS
                SELECT no_sejour, p_factures_lignes_c.date_debut, SUM(montant_facture)
                FROM activite.p_factures_lignes_c 
                JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
                JOIN activite.t_listes ON t_listes.code = 'CTI_SHO_R'
                JOIN activite.t_listes_contenu ON t_listes.oid = t_listes_contenu.liste_id AND
                    rubrique_facturation_id = t_listes_contenu.to_id
                WHERE p_factures_lignes_c.date_debut = p_factures_lignes_c.date_fin
                GROUP BY 1,2
                HAVING SUM(montant_facture) > 0
                ;


                UPDATE activite.p_mouvements_sejour SET
                    est_chambre_particuliere = '1',
                    nb_chambres_particulieres = 1,
                    est_chambre_particuliere_facturee = '1'
                FROM w_cp_facturees
                WHERE w_cp_facturees.no_sejour = p_mouvements_sejour.no_sejour AND
                    w_cp_facturees.date_debut = p_mouvements_sejour.date AND
                    (
					p_mouvements_sejour.heure_fin = 240000 OR
                    nb_sorties_directes = 1 OR
					nb_ambulatoires = 1 OR
					nb_externes = 1
                    )
                ;
            
                -- Séjours ambulatoires avec prestation externe -> transformation
				DROP TABLE IF EXISTS w_sejours_ambu_to_externe;
				CREATE TEMP TABLE w_sejours_ambu_to_externe AS
				SELECT p_sejours.no_sejour
				FROM activite.p_sejours
				JOIN activite.t_lieux ON lieu_sortie_id = t_lieux.oid
				JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
				JOIN activite.p_factures ON p_factures.no_sejour = p_sejours.no_sejour
				JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				WHERE t_prestations.code IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'ATU', 'FPU', 'FFM') AND
					p_sejours.type_sejour = '2' AND
					t_services_facturation.type_sejour NOT IN ('1','2','3','4','5','6','9') AND
					montant_facture <> 0
				GROUP BY 1
				HAVING SUM(ABS(montant_facture)) > 0 AND SUM(montant_facture) <> 0
                ;

				UPDATE activite.p_sejours 
				SET type_sejour = '3'
				WHERE no_sejour IN (SELECT no_sejour FROM w_sejours_ambu_to_externe)
                ;

				UPDATE activite.p_mouvements_sejour
				SET nb_externes = 1, nb_ambulatoires = 0
				WHERE nb_ambulatoires = 1 AND
					no_sejour IN
					(SELECT no_sejour FROM w_sejours_ambu_to_externe)
				;
				
				-- Séjours externes avec prestation ambu -> transformation
				DROP TABLE IF EXISTS w_sejours_externe_to_ambu;
				CREATE TEMP TABLE w_sejours_externe_to_ambu AS
				SELECT p_sejours.no_sejour
				FROM activite.p_sejours
				JOIN activite.t_lieux ON lieu_sortie_id = t_lieux.oid
				JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
				JOIN activite.p_factures ON p_factures.no_sejour = p_sejours.no_sejour
				JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				LEFT JOIN activite.t_sejour ON p_sejours.no_sejour = t_sejour.no_sejour
				WHERE t_prestations.code IN ('GHS') AND
					p_sejours.type_sejour = '3' AND
					(
					t_services_facturation.type_sejour NOT IN ('1','2','3','4','5','6','9') OR
					p_sejours.ghm_id > 0
					) AND
					t_sejour.type_sejour IS DISTINCT FROM '3' AND
					montant_facture <> 0
				GROUP BY 1
				HAVING SUM(ABS(montant_facture)) > 0 AND SUM(montant_facture) <> 0
                ;

				UPDATE activite.p_sejours 
				SET type_sejour = '2'
				WHERE no_sejour IN (SELECT no_sejour FROM w_sejours_externe_to_ambu)
                ;

				UPDATE activite.p_mouvements_sejour
				SET nb_ambulatoires = 1, nb_externes= 0
				WHERE nb_externes = 1 AND
					no_sejour IN
					(SELECT no_sejour FROM w_sejours_externe_to_ambu)
				;
			
				-- Si Service sans facturation et sans mouvement, alors séjour fictif
				UPDATE activite[PX].p_sejours
				SET type_sejour = '9'
				FROM activite[PX].t_lieux 
				JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
				WHERE lieu_sortie_id = t_lieux.oid AND
					t_services_facturation.est_sans_mouvement = '1' AND 
					t_services_facturation.est_sans_facturation = '1' AND
					p_sejours.type_sejour <> '9'
				;
                
                UPDATE activite[PX].p_sejours
                SET lieu_sortie_id = 0
                WHERE lieu_sortie_id IS NULL
                ;
                
				-- Idem si séjour sans acte et service sans acte fictif, alors séjour fictif
                UPDATE activite[PX].p_sejours
                SET type_sejour = '9'
                WHERE 
                    p_sejours.type_sejour != '9' AND
                    lieu_sortie_id = ANY(
                        SELECT t_lieux.oid FROM activite[PX].t_lieux
                            JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
                        WHERE    
                            t_services_facturation.sej_sans_acte_fictif = '1') AND 
                    oid != ALL (
                        SELECT DISTINCT p_sejours.oid FROM 
                            activite[PX].p_sejours
                            LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour
                            LEFT JOIN activite[PX].p_factures_lignes_h ON p_factures.oid = p_factures_lignes_h.facture_id
                            LEFT JOIN activite[PX].p_factures_lignes_non_facturees_h ON p_factures.oid = p_factures_lignes_non_facturees_h.facture_id
                    WHERE (p_factures_lignes_h.facture_id IS NOT NULL OR
                        p_factures_lignes_non_facturees_h.facture_id IS NOT NULL)
                        )
                ;

				
                -- Ajout ligne fictive dans mouvements séjour pour que chaque séjour ait au moins une ligne
				-- dans les mouvements 
                INSERT INTO activite.p_mouvements_sejour 
                (no_sejour, date, heure_debut, heure_fin, lieu_id, medecin_sejour_id)
                WITH w_mv AS (SELECT DISTINCT no_sejour FROM activite.p_mouvements_sejour)
				SELECT 
					  p_sejours.no_sejour
					, p_sejours.date_entree
					, p_sejours.heure_entree
					, p_sejours.heure_sortie
					, p_sejours.lieu_sortie_id
					, p_sejours.medecin_sejour_id
                FROM 
					activite.p_sejours
					LEFT JOIN w_mv ON p_sejours.no_sejour = w_mv.no_sejour
                WHERE 1=1
					AND type_sejour <> '9'
                    AND code_prevu <> 1
					AND p_sejours.etat NOT IN ('A', 'R', 'C') 
                    AND w_mv.no_sejour IS NULL
                ;
                INSERT INTO activite.p_mouvements_sejour 
                    (no_sejour, date, heure_debut, heure_fin, lieu_id, medecin_sejour_id)
                SELECT p_sejours.no_sejour, date_sortie, 0, heure_sortie, lieu_sortie_id, p_sejours.medecin_sejour_id
                FROM activite.p_sejours
                LEFT JOIN activite.p_mouvements_sejour ON p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
                    p_mouvements_sejour.date = p_sejours.date_sortie
                WHERE type_sejour <> '9' AND
                    code_prevu <> 1 AND
                    p_sejours.code_sorti = '1' AND
                    p_mouvements_sejour.no_sejour IS NULL
                ;
				
				-- Ajout des séjours annulés dans les mouvements pour regroupement et tri dans les requêtes
                INSERT INTO activite.p_mouvements_sejour 
                    (no_sejour, date, lieu_id, medecin_sejour_id, is_annulation)
                SELECT 
					p_sejours.no_sejour, 
					date_entree, 
					lieu_sortie_id, 
					p_sejours.medecin_sejour_id, 
					CASE WHEN date_entree = date(date_etat) THEN 1 ELSE 0 END AS is_annulation
                FROM activite.p_sejours
                LEFT JOIN activite.p_mouvements_sejour ON p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
                    p_mouvements_sejour.date = p_sejours.date_sortie
                WHERE p_sejours.etat IN ('A', 'R', 'C') AND
                    p_mouvements_sejour.no_sejour IS NULL
                ;
			
				-- Correction séjours à séance selon GHM
				
				DROP TABLE IF EXISTS w_correction_seances_28z14;
				CREATE TEMP TABLE w_correction_seances_28z14 AS
				SELECT p_factures.no_sejour, p_factures_lignes_h.date_debut, SUM(p_factures_lignes_h.nb_prestation) AS nb_seances
				FROM activite.p_factures_lignes_h
				JOIN activite.p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture
				JOIN activite.p_sejours On p_factures.no_sejour = p_sejours.no_sejour AND type_sejour = '1'
				JOIN base.t_ghm ON p_sejours.ghm_id = t_ghm.oid AND t_ghm.code LIKE '28Z14%'
				JOIN base.t_actes ON acte_id = t_actes.oid AND t_actes.code = 'FELF011'
				GROUP BY 1,2
				HAVING SUM(p_factures_lignes_h.nb_prestation) > 0
				;
				
				UPDATE activite.p_mouvements_sejour
				SET nb_seances = w_correction_seances_28z14.nb_seances
				FROM w_correction_seances_28z14
				WHERE p_mouvements_sejour.no_sejour = w_correction_seances_28z14.no_sejour AND
					p_mouvements_sejour.date = w_correction_seances_28z14.date_debut AND
					p_mouvements_sejour.nb_seances <> w_correction_seances_28z14.nb_seances;

				DROP TABLE IF EXISTS w_correction_seances;
				CREATE TEMP TABLE w_correction_seances AS
				SELECT p_sejours.no_sejour, 
					p_sejours.date_entree, 
					p_sejours.date_sortie, 
					COALESCE(t_services_facturation.type_sejour,'0') AS type_sejour_force,
					t_ghm.code AS ghm_code,
					SUM(nb_entrees_directes) AS nb_entrees_directes, 
					SUM(nb_sorties_directes)AS nb_sorties_directes, 
					SUM(nb_ambulatoires) AS nb_ambulatoires, 
					SUM(nb_externes) AS nb_externes,
					SUM(nb_seances) AS nb_seances
				FROM activite.p_sejours
				JOIN activite.t_lieux ON lieu_sortie_id = t_lieux.oid
				JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
				LEFT JOIN activite.p_mouvements_sejour ON p_sejours.no_sejour = p_mouvements_sejour.no_sejour
				JOIN base.t_ghm ON ghm_id = t_ghm.oid
				WHERE p_sejours.type_sejour <> '9' AND
					t_ghm.code LIKE '28%' AND
					t_services_facturation.type_sejour IS DISTINCT FROM '0sauf5'
				GROUP BY 1,2,3,4,5
				HAVING 
				(
					SUM(nb_entrees_directes) <> 0 OR
					SUM(nb_ambulatoires) <> 0 OR
					SUM(nb_externes) <> 0 OR
					SUM(nb_seances) = 0
				)
				;

				UPDATE activite.p_mouvements_sejour SET
					nb_seances = 1, 
					nb_ambulatoires = CASE WHEN w_correction_seances.type_sejour_force <> '0sauf5' AND w_correction_seances.type_sejour_force <> '2' THEN 0 ELSE p_mouvements_sejour.nb_ambulatoires END
				FROM w_correction_seances
				WHERE w_correction_seances.no_sejour = p_mouvements_sejour.no_sejour AND
					p_mouvements_sejour.nb_ambulatoires <> 0 AND
					w_correction_seances.nb_seances = 0 AND 
					w_correction_seances.nb_ambulatoires <> 0;

				UPDATE activite.p_sejours SET
					type_sejour = '5'
				FROM w_correction_seances
				WHERE w_correction_seances.type_sejour_force <> '0sauf5' AND
                    w_correction_seances.type_sejour_force <> '2' AND
					w_correction_seances.no_sejour = p_sejours.no_sejour AND
					p_sejours.type_sejour = '2' AND
					w_correction_seances.nb_seances = 0 AND 
					w_correction_seances.nb_ambulatoires <> 0;

				UPDATE activite.p_mouvements_sejour SET
					nb_seances = 1
				FROM w_correction_seances
				WHERE w_correction_seances.no_sejour = p_mouvements_sejour.no_sejour AND
					p_mouvements_sejour.nb_entrees_directes <> 0 AND
					p_mouvements_sejour.nb_seances = 0 AND
					w_correction_seances.nb_seances = 0 AND 
					w_correction_seances.nb_ambulatoires = 0 AND 
					w_correction_seances.nb_entrees_directes <> 0;
					
					
				-- Types séjours Hospitalisés vers séances
				UPDATE activite.p_sejours
				SET type_sejour = '5'
				FROM activite.t_lieux 
				JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
				WHERE lieu_sortie_id = t_lieux.oid AND
					t_services_facturation.type_sejour <> '0sauf5' AND
                    t_services_facturation.type_sejour <> '1' AND
                    t_services_facturation.type_sejour <> '2' AND
					p_sejours.type_sejour <> '5' AND
					p_sejours.type_sejour <> '9' AND
					ghs_id > 0 AND
					ghm_id in (SELECT oid FROm base.t_ghm where code LIKE '28%')
				;

				UPDATE activite.p_mouvements_sejour
				SET nb_entrees_directes = 0,
					nb_sorties_directes = 0,
					est_jour_hospitalisation = '0',
					nb_ambulatoires = 0,
					nb_externes = 0,
					nb_urgences = 0,
					nb_entrees_mutation_service = 0,
					nb_sorties_mutation_service = 0,
					nb_entrees_mutation_etage = 0,
					nb_sorties_mutation_etage = 0,
					nb_entrees_mutation_activite = 0,
					nb_sorties_mutation_activite = 0,
					nb_entrees_mutation_unite_medicale = 0,
					nb_sorties_mutation_unite_medicale = 0,
					nb_jours_js_inclus = 0,
					nb_jours_js_non_inclus = 0,
					est_chambre_particuliere = '0',
					nb_chambres_particulieres = 0,
					nb_bebes = 0
				WHERE no_sejour IN (SELECT no_sejour FROM activite.p_sejours WHERE type_sejour = '5') AND
					(
					nb_entrees_directes IS DISTINCT FROM 0 OR
					nb_sorties_directes IS DISTINCT FROM 0 OR
					est_jour_hospitalisation IS DISTINCT FROM '0' OR
					nb_ambulatoires IS DISTINCT FROM 0 OR
					nb_externes IS DISTINCT FROM 0 OR
					nb_urgences IS DISTINCT FROM 0 OR
					nb_entrees_mutation_service IS DISTINCT FROM 0 OR
					nb_sorties_mutation_service IS DISTINCT FROM 0 OR
					nb_entrees_mutation_etage IS DISTINCT FROM 0 OR
					nb_sorties_mutation_etage IS DISTINCT FROM 0 OR
					nb_entrees_mutation_activite IS DISTINCT FROM 0 OR
					nb_sorties_mutation_activite IS DISTINCT FROM 0 OR
					nb_entrees_mutation_unite_medicale IS DISTINCT FROM 0 OR
					nb_sorties_mutation_unite_medicale IS DISTINCT FROM 0 OR
					nb_jours_js_inclus IS DISTINCT FROM 0 OR
					nb_jours_js_non_inclus IS DISTINCT FROM 0 OR
					est_chambre_particuliere IS DISTINCT FROM '0' OR
					nb_chambres_particulieres IS DISTINCT FROM 0 OR
					nb_bebes IS DISTINCT FROM 0
					)
				;
				
				-- Séjours hospît vers externe si duree séjour <= 1
				DROP TABLE IF EXISTS w_sejours_hospit_to_externe;
				CREATE TEMP TABLE w_sejours_hospit_to_externe AS
				SELECT p_sejours.no_sejour
                FROM activite.p_sejours
                JOIN activite.t_lieux ON lieu_sortie_id = t_lieux.oid
				JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
				WHERE p_sejours.type_sejour = '1' AND
					date_sortie - date_entree <= 1 AND
					code_sorti = '1' AND
					t_services_facturation.type_sejour = '31' 
				;

				UPDATE activite.p_sejours 
				SET type_sejour = '3'
				WHERE no_sejour IN (SELECT no_sejour FROM w_sejours_hospit_to_externe)
                ;


				UPDATE activite.p_mouvements_sejour
				SET nb_externes = 1, nb_entrees_directes = 0
				WHERE nb_entrees_directes = 1 AND
					no_sejour IN
					(SELECT no_sejour FROM w_sejours_hospit_to_externe)
				;


				
				UPDATE activite.p_mouvements_sejour
				SET nb_entrees_directes = 0,
					nb_sorties_directes = 0,
					est_jour_hospitalisation = '0',
					nb_ambulatoires = 0,
					nb_seances = 0,
					nb_urgences = 0,
					nb_entrees_mutation_service = 0,
					nb_sorties_mutation_service = 0,
					nb_entrees_mutation_etage = 0,
					nb_sorties_mutation_etage = 0,
					nb_entrees_mutation_activite = 0,
					nb_sorties_mutation_activite = 0,
					nb_entrees_mutation_unite_medicale = 0,
					nb_sorties_mutation_unite_medicale = 0,
					nb_jours_js_inclus = 0,
					nb_jours_js_non_inclus = 0,
					est_chambre_particuliere = '0',
					nb_chambres_particulieres = 0,
					nb_bebes = 0
				WHERE no_sejour IN
					(SELECT no_sejour FROM w_sejours_hospit_to_externe)
				;
                
                -- Forcage ambulatoires non traité dans import prestataire
                DROP TABLE IF EXISTS w_correction_seances;
                CREATE TEMP TABLE w_correction_seances AS
                SELECT p_sejours.no_sejour
                FROM activite.p_sejours 
                JOIN activite.t_lieux on lieu_sortie_id = t_lieux.oid
                JOIN activite.t_services_facturation on service_facturation_id = t_services_facturation.oid
                LEFT JOIN base.t_ghm on ghm_id = t_ghm.oid
                WHERE p_sejours.type_sejour = '5' AND 
                    t_services_facturation.type_sejour = '2'
                ;
                
                UPDATE activite.p_sejours
                SET type_sejour = '2'
                FROM w_correction_seances
                WHERE p_sejours.no_sejour = w_correction_seances.no_sejour
                ;

                UPDATE activite.p_mouvements_sejour
                SET nb_ambulatoires = 1
                FROM w_correction_seances
                WHERE p_mouvements_sejour.no_sejour = w_correction_seances.no_sejour AND
                    nb_seances = 1
                ;
			
				-- Premiers et derniers mouvements par jour pour journées HDJ
				UPDATE activite.p_mouvements_sejour SET
					est_premier_mouvement_jour = '1' 
				FROM
					(
					SELECT no_sejour, date, MIN(heure_fin) AS heure_fin
					FROM activite.p_mouvements_sejour
					GROUP BY 1,2
					HAVING MIN(heure_fin) < 240000
					) subview
				WHERE p_mouvements_sejour.no_sejour = subview.no_sejour AND
					p_mouvements_sejour.heure_fin = subview.heure_fin AND
					p_mouvements_sejour.date = subview.date AND
					est_premier_mouvement_jour IS DISTINCT FROM '1' ;		

				UPDATE activite.p_mouvements_sejour SET
					est_dernier_mouvement_jour = '1' 
				FROM
					(
					SELECT no_sejour, date, MAX(heure_debut) AS heure_debut
					FROM activite.p_mouvements_sejour
					GROUP BY 1,2
					HAVING MAX(heure_debut) <> 0
					) subview
				WHERE p_mouvements_sejour.no_sejour = subview.no_sejour AND
					p_mouvements_sejour.heure_debut = subview.heure_debut AND
					p_mouvements_sejour.date = subview.date AND
					est_dernier_mouvement_jour IS DISTINCT FROM '1';
					
				UPDATE activite.p_mouvements_sejour SET
					est_premier_mouvement_jour = CASE WHEN heure_premier = heure_debut THEN '1' ELSE '0' END,
					est_dernier_mouvement_jour = CASE WHEN heure_dernier = heure_debut THEN '1' ELSE '0' END
				FROM
				(
				SELECT no_sejour, date,
					MIN(CASE WHEN est_jour_hospitalisation = '1' THEN heure_debut ELSE 999999 END) AS heure_premier,
					MAX(CASE WHEN est_jour_hospitalisation = '1' THEN heure_debut ELSE -1 END) AS heure_dernier
				FROM activite.p_mouvements_sejour
				GROUP BY 1,2
				HAVING (
					MAX(nb_entrees_directes) = 1 OR 
					MAX(nb_sorties_directes) = 1
					) AND
					(
						MIN(heure_debut) <> MIN(CASE WHEN est_jour_hospitalisation = '1' THEN heure_debut ELSE 999999 END) OR
						MAX(heure_debut) <> MAX(CASE WHEN est_jour_hospitalisation = '1' THEN heure_debut ELSE -1 END)
					)
				) subview 
				WHERE p_mouvements_sejour.no_sejour = subview.no_sejour AND
					p_mouvements_sejour.date = subview.date AND
					(
						est_premier_mouvement_jour IS DISTINCT FROM CASE WHEN heure_premier = heure_debut THEN '1' ELSE '0' END OR
						est_dernier_mouvement_jour IS DISTINCT FROM CASE WHEN heure_dernier = heure_debut THEN '1' ELSE '0' END
					);
			
				-- Transformation UF selon type eclatement
				SELECT activite.cti_transform_uf();

                -- Mises à jour mouvements selon présence prestation (hdj)
				SELECT activite[PX].cti_calcul_hdj_mouvements();

				-- Calcul des journées dans la table des mouvements
				SELECT activite[PX].cti_calcul_journees_mouvements();
				
			]]></sqlcmd>

		</NODE>

		<NODE label="Compléments séjour">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
            
                -- Finess séjour
				UPDATE activite.p_sejours
				SET finess = t_finess.code
				FROM activite.t_lieux
				JOIN activite.t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid
				JOIN base.t_finess On t_services_facturation.finess_id = t_finess.oid
				WHERE lieu_sortie_id = t_lieux.oid AND
					p_sejours.finess IS DISTINCT FROM t_finess.code AND
					t_services_facturation.finess_id <> 0
				;
				
				WITH finess as (
					SELECT MAX(t_finess.code) AS code
					FROM base.t_finess 
					WHERE secondaire = '0'
					HAVING count(*) = 1
				), empty_sejours as (
					SELECT p_sejours.oid, finess.code as finess_code, lieu_sortie_id
					FROM activite.p_sejours
					JOIN finess ON 1=1
					WHERE p_sejours.finess = '' OR p_sejours.finess = '000000000'
				), update_sejours as (
					SELECT empty_sejours.oid, finess_code FROM empty_sejours
					JOIN activite.t_lieux ON empty_sejours.lieu_sortie_id = t_lieux.oid
					JOIN activite.t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid
					WHERE t_services_facturation.finess_id = 0
				)				
				UPDATE activite.p_sejours
					SET finess = finess_code
				FROM update_sejours
				WHERE update_sejours.oid = p_sejours.oid
				AND finess IS DISTINCT FROM finess_code
				;
				
				UPDATE activite.p_sejours
				SET finess = subview.code
				FROM
				(
				SELECT MAX(code) AS code
				FROM base.t_finess
				WHERE secondaire = '0'
				HAVING count(DISTINCT code) = 1
				) subview
				WHERE p_sejours.finess = '' OR 
					p_sejours.finess = '000000000'
				;
				
				-- Médecin séjour selon service
				UPDATE activite.p_sejours
				SET medecin_sejour_id = 
					CASE 
						WHEN COALESCE(t_services_facturation.medecin_force_id,0) > 0 THEN t_services_facturation.medecin_force_id 
						WHEN COALESCE(t_services_facturation.medecin_par_defaut_id,0) > 0 AND p_sejours.medecin_sejour_id = 0 THEN t_services_facturation.medecin_par_defaut_id
						ELSE p_sejours.medecin_sejour_id END
				FROM activite.t_lieux
				JOIN activite.t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid
				WHERE lieu_sortie_id = t_lieux.oid AND
					(
						t_services_facturation.medecin_force_id <> 0 OR
						t_services_facturation.medecin_par_defaut_id <> 0
					)
				;
            
                -- Correction date sortie dans séjours pour externes et ambu présents
                UPDATE activite.p_sejours
				SET date_sortie = subview.date_sortie, heure_sortie = subview.heure_sortie
				FROM
				(
				SELECT p_sejours.no_sejour, MAX(date) AS date_sortie, (MAX(Array[date::text, heure_fin::text]))[2]::numeric AS heure_sortie
				FROM activite.p_sejours
				JOIN activite.p_mouvements_sejour ON p_sejours.no_sejour = p_mouvements_sejour.no_sejour
				WHERE p_sejours.type_sejour IN ('2','3') AND
					p_sejours.code_sorti <> '1' AND
					(
					p_mouvements_sejour.nb_ambulatoires = 1 OR 
					p_mouvements_sejour.nb_externes = 1
					)
				GROUP BY 1
				) subview
				WHERE p_sejours.no_sejour = subview.no_sejour
                ;
            
               
				-- Chambre particuliere demandee si facturee
				
				DROP TABLE IF EXISTS w_factures_lignes_c_cp;
									
				CREATE TEMP TABLE w_factures_lignes_c_cp AS
				SELECT p_factures.no_sejour
				FROM activite[PX].p_factures_lignes_c
					JOIN activite[PX].p_factures ON p_factures.no_facture = p_factures_lignes_c.no_facture
					JOIN activite[PX].p_sejours ON p_sejours.no_sejour = p_factures.no_sejour AND p_sejours.code_cp_demandee <> '1'
					JOIN activite[PX].v_listes_3 ON liste_code = 'CTI_SHO_R' AND rubrique_facturation_id = to_id
				WHERE p_factures_lignes_c.montant_facture <> 0 
				GROUP BY 1
				HAVING SUM(nb_rubrique) > 0;


				ALTER TABLE w_factures_lignes_c_cp ADD CONSTRAINT w_factures_lignes_c_cp_pkey PRIMARY KEY(no_sejour);

				UPDATE activite[PX].p_sejours
				SET code_cp_demandee = '1'
				FROM w_factures_lignes_c_cp 
				WHERE p_sejours.no_sejour = w_factures_lignes_c_cp.no_sejour AND
					code_cp_demandee <> '1';
					
				-- GHS esthétique
				UPDATE activite[PX].p_sejours SET
					ghs_id = (SELECT oid FROM base.t_ghs WHERE code = 9999)
				WHERE ghs_id <= 0 AND
					ghm_id IN (SELECT oid FROM base.t_ghm WHERE code LIKE '09Z02%' OR code LIKE '23Z03%');
											
				-- GHS 
				UPDATE activite[PX].p_sejours SET
					date_groupage = '20991231'::date,	
					ghs_id = 
						CASE
							WHEN p_sejours.particularite_t2a::bpchar = 'SE1'::bpchar THEN - 9991::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE2'::bpchar THEN - 9992::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE3'::bpchar THEN - 9993::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE4'::bpchar THEN - 9994::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE5'::bpchar THEN - 9997::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE6'::bpchar THEN - 9998::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'ATU'::bpchar THEN - 9995::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'FFM'::bpchar THEN - 9996::bigint
							WHEN t_services_facturation.type_t2a <> '1'::bpchar THEN - 9990::bigint
							WHEN p_sejours.type_sejour NOT IN ('1','2','5','6') THEN - 9990::bigint
							WHEN p_sejours.code_sorti <> 1::numeric THEN - 9980::bigint
							WHEN p_sejours.date_groupage = '2099-12-31'::date THEN - 9981::bigint
							ELSE - 9981::bigint
						END,
					ghm_id = 
						CASE
							WHEN p_sejours.particularite_t2a::bpchar = 'SE1'::bpchar THEN - 9991::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE2'::bpchar THEN - 9992::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE3'::bpchar THEN - 9993::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE4'::bpchar THEN - 9994::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE5'::bpchar THEN - 9997::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE6'::bpchar THEN - 9998::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'ATU'::bpchar THEN - 9995::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'FFM'::bpchar THEN - 9996::bigint
							WHEN t_services_facturation.type_t2a <> '1'::bpchar THEN - 9990::bigint
							WHEN p_sejours.type_sejour NOT IN ('1','2','5','6') THEN - 9990::bigint
							WHEN p_sejours.code_sorti <> 1::numeric THEN - 9980::bigint
							WHEN p_sejours.date_groupage = '2099-12-31'::date THEN - 9981::bigint
							ELSE - 9981::bigint
						END
				FROM activite[PX].t_lieux 
					JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
				WHERE p_sejours.lieu_sortie_id = t_lieux.oid AND
					ghs_id <= 0 AND 
					gmt_id <= 0 AND 
					(
					date_groupage IS DISTINCT FROM '20991231'::date
					OR
					ghm_id IS DISTINCT FROM 
						CASE
							WHEN p_sejours.particularite_t2a::bpchar = 'SE1'::bpchar THEN - 9991::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE2'::bpchar THEN - 9992::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE3'::bpchar THEN - 9993::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE4'::bpchar THEN - 9994::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE5'::bpchar THEN - 9997::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE6'::bpchar THEN - 9998::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'ATU'::bpchar THEN - 9995::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'FFM'::bpchar THEN - 9996::bigint
							WHEN t_services_facturation.type_t2a <> '1'::bpchar THEN - 9990::bigint
							WHEN p_sejours.type_sejour NOT IN ('1','2','5','6') THEN - 9990::bigint
							WHEN p_sejours.code_sorti <> 1::numeric THEN - 9980::bigint
							WHEN p_sejours.date_groupage = '2099-12-31'::date THEN - 9981::bigint
							ELSE - 9981::bigint
						END
					OR
					ghs_id IS DISTINCT FROM 
						CASE
							WHEN p_sejours.particularite_t2a::bpchar = 'SE1'::bpchar THEN - 9991::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE2'::bpchar THEN - 9992::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE3'::bpchar THEN - 9993::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'SE4'::bpchar THEN - 9994::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'ATU'::bpchar THEN - 9995::bigint
							WHEN p_sejours.particularite_t2a::bpchar = 'FFM'::bpchar THEN - 9996::bigint
							WHEN t_services_facturation.type_t2a <> '1'::bpchar THEN - 9990::bigint
							WHEN p_sejours.type_sejour NOT IN ('1','2','5','6') THEN - 9990::bigint
							WHEN p_sejours.code_sorti <> 1::numeric THEN - 9980::bigint
							WHEN p_sejours.date_groupage = '2099-12-31'::date THEN - 9981::bigint
							ELSE - 9981::bigint
						END
					)
						;
				
				-- Calcul des ages en années (date_entre - date_naissance ou -1 si une des deux dates absente)
				
				UPDATE activite.p_sejours SET age = NULL;
				
				-- Court séjour
				UPDATE activite.p_sejours set
					age = extract(year from age(date_entree, date_naissance))
				FROM 
					activite.p_patients 
				WHERE 
					p_patients.no_patient = p_sejours.no_patient
					and (p_sejours.age = 0 OR p_sejours.age is null OR p_sejours.age = -1)
					and date_naissance >= '1890-01-01'::date
					and date_entree >= '2000-01-01'::date
					AND 
						(
						code_sorti = '1' AND date_sortie - date_entree < 180 OR
						code_sorti <> '1' AND date(now()) - date_entree < 180
						)
					and date_naissance <= date_sortie
 					and extract(year from age(date_entree, date_naissance)) <= 120
				;

 				-- longs sejours (> 6mois) age selondébut d'année
				UPDATE activite.p_sejours set
					age = extract(year from age(date_trunc('year',CASE WHEN code_sorti = '1' THEN date_sortie ELSE now() END), date_naissance))
				FROM 
					activite.p_patients 
				WHERE 
					p_patients.no_patient = p_sejours.no_patient
					and (p_sejours.age = 0 OR p_sejours.age is null OR p_sejours.age = -1)
					and date_naissance >= '1890-01-01'::date
					AND 
						(
						code_sorti = '1' AND date_sortie - date_entree >= 180 OR
						code_sorti <> '1' AND date(now()) - date_entree >= 180
						)
					and date_naissance <= date_sortie
 					and extract(year from age(date_trunc('year',CASE WHEN code_sorti = '1' THEN date_sortie ELSE now() END), date_naissance)) <= 120
				;

					
                UPDATE activite.p_sejours SET
                    age = -1
                WHERE p_sejours.age is null OR age < -1
                ;
					
				-- Codes de mode d'entree obsolètes
				UPDATE activite[PX].p_sejours SET
					mode_entree = CASE
									WHEN mode_entree = 'T' THEN '7'
									WHEN mode_entree = 'I' THEN '6'
									ELSE '8' END
				WHERE
					mode_entree IN ('D', 'T', 'I');
					
				-- Codes de modes de sortie obsolètes
				UPDATE activite[PX].p_sejours SET
					mode_sortie = CASE
									WHEN mode_sortie = 'T' THEN '7'
									WHEN mode_sortie = 'I' THEN '6'
									ELSE '8' END
				WHERE
					mode_sortie IN ('D', 'T', 'I');				
				
				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_factures_lignes_c_cp CASCADE;
				
				
				-- Compléments séjours (type pmsi)
				SELECT activite.cti_reorganize_sejours('activite.p_sejours');
				
			]]></sqlcmd>

		</NODE>

		<NODE label="Compléments clients (solde auto)">
			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
			
				 SELECT activite.cti_solde_auto()
                 ;

			]]></sqlcmd>
		</NODE>

		<NODE label="Compléments factures (BG)">
			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
			
				-- Factures BG récupérées depuis PMSI -> date facture = date groupage
				UPDATE activite.p_factures
				SET date_facture = p_sejours.date_groupage
				FROM activite.p_sejours
				WHERE p_factures.type_facture = 'G' AND
					p_factures.no_sejour = p_sejours.no_sejour AND
					p_sejours.date_groupage > p_factures.date_facture AND
					p_sejours.date_groupage <> '20991231';

				-- Factures BG récupérées depuis PMSI -> date facture = date derniere facture TP1 hbg
				UPDATE activite.p_factures
				SET date_facture = p_factures_x.date_facture
				FROM activite.p_factures p_factures_x
					JOIN activite.p_sejours ON p_factures_x.no_sejour = p_sejours.no_sejour
				WHERE p_factures.type_facture = 'G' AND
					p_factures_x.no_sejour = p_factures.no_sejour AND
					p_factures_x.no_facture <> p_factures.no_facture AND
					p_factures_x.type_facture <> 'G' AND
					p_factures_x.date_facture > p_factures.date_facture AND
					p_factures_x.code_facture = '1' AND
					p_factures_x.montant_facture_1_c > 0 AND
					p_factures_x.date_facture <> '20991231'
                ;
                

			]]></sqlcmd>
		</NODE>

		<NODE label="Compléments factures">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
			
				-- Ajustement date de fin des prestations non facturées si JS non compris
				UPDATE activite.p_factures_lignes_non_facturees_c
				SET date_fin = date_fin - interval '1 day'
				FROM activite.t_prestations
				WHERE prestation_id = t_prestations.oid AND
					(
					t_prestations.code IN ('CPC') OR
					type_ventilation_jour = '1'
					) AND
					(date_fin - date_debut) = nb_rubrique
				;

				-- Eclatement des lignes non facturées si une ligne pour plusieurs jours
				DROP TABLE IF EXISTS w_factures_lignes_non_facturees_c_jour;
				CREATE TEMP TABLE w_factures_lignes_non_facturees_c_jour AS
				SELECT p_factures_lignes_non_facturees_c.*, 
					p_factures_lignes_non_facturees_c.CTID AS fromCTID
				FROM activite.p_factures_lignes_non_facturees_c
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				WHERE nb_rubrique > 1 AND
					(
					t_prestations.code IN ('CPC') OR
					type_ventilation_jour = '1'
					) AND
					(date_fin - date_debut + 1) = nb_rubrique
				;

				UPDATE activite.p_factures_lignes_non_facturees_c SET
					nb_rubrique = 1, 
					date_fin = p_factures_lignes_non_facturees_c.date_debut,
					montant_encours = p_factures_lignes_non_facturees_c.montant_encours / p_factures_lignes_non_facturees_c.nb_rubrique
				FROM w_factures_lignes_non_facturees_c_jour
				WHERE p_factures_lignes_non_facturees_c.CTID = fromCTID
				;
				
				DROP TABLE IF EXISTS w_factures_lignes_non_facturees_c_jour_to;
				CREATE TEMP TABLE w_factures_lignes_non_facturees_c_jour_to AS
				SELECT w_factures_lignes_non_facturees_c_jour.*,
					p_calendrier.date AS to_date
				FROM w_factures_lignes_non_facturees_c_jour
				JOIN base.p_calendrier ON p_calendrier.date > w_factures_lignes_non_facturees_c_jour.date_debut AND p_calendrier.date <= w_factures_lignes_non_facturees_c_jour.date_fin
				;

				UPDATE w_factures_lignes_non_facturees_c_jour_to SET
					nb_rubrique = 1, 
					date_debut = to_date,
					date_fin = to_date,
					montant_encours = montant_encours / nb_rubrique
				;

				ALTER TABLE w_factures_lignes_non_facturees_c_jour_to DROP COLUMN fromCTID;
				ALTER TABLE w_factures_lignes_non_facturees_c_jour_to DROP COLUMN to_date;
				
				-- Dans la table w_factures_lignes_non_facturees_c_jour_to, les lignes sont maintenant ventilees jour/jour
				-- Pour les factures SSR (facturation intermediaires), il se peut que certaines lignes soient affectées à la mauvaise 
				-- facture intermédiaire
				-- La sequence qui suit permet de reaffecter la bonne facture
				ANALYSE w_factures_lignes_non_facturees_c_jour_to
				;

				DROP TABLE IF EXISTS w_factures_lignes_non_facturees_c_reaffect
				;
				CREATE TEMP TABLE w_factures_lignes_non_facturees_c_reaffect AS
				SELECT 
					w_factures_lignes_non_facturees_c_jour_to.no_facture,
					w_factures_lignes_non_facturees_c_jour_to.date_debut,
					MAX(p_factures_cible.no_facture) AS no_facture_cible
				FROM w_factures_lignes_non_facturees_c_jour_to
				JOIN activite.p_factures ON w_factures_lignes_non_facturees_c_jour_to.no_facture = p_factures.no_facture
				JOIN activite.t_lieux ON w_factures_lignes_non_facturees_c_jour_to.lieu_id = t_lieux.oid
				JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
				LEFT JOIN activite.p_factures p_factures_cible ON 
					p_factures_cible.no_sejour = p_factures.no_sejour AND
					w_factures_lignes_non_facturees_c_jour_to.date_debut BETWEEN p_factures_cible.date_debut AND p_factures_cible.date_fin AND
					p_factures_cible.type_facture = 'E'
				WHERE avec_facturation_intermediaire = '1' AND
					w_factures_lignes_non_facturees_c_jour_to.date_debut NOT BETWEEN p_factures.date_debut AND p_factures.date_fin
				GROUP BY 1,2
				;

				ANALYSE w_factures_lignes_non_facturees_c_reaffect
				;

				UPDATE w_factures_lignes_non_facturees_c_jour_to
				SET no_facture = no_facture_cible
				FROM w_factures_lignes_non_facturees_c_reaffect
				WHERE w_factures_lignes_non_facturees_c_jour_to.no_facture = w_factures_lignes_non_facturees_c_reaffect.no_facture AND
					w_factures_lignes_non_facturees_c_jour_to.date_debut = w_factures_lignes_non_facturees_c_reaffect.date_debut AND
					no_facture_cible IS NOT NULL
				;
				
				-- Suppression des lignes sans facture cible
				DELETE FROM w_factures_lignes_non_facturees_c_jour_to
				USING w_factures_lignes_non_facturees_c_reaffect
				WHERE w_factures_lignes_non_facturees_c_jour_to.no_facture = w_factures_lignes_non_facturees_c_reaffect.no_facture AND
					w_factures_lignes_non_facturees_c_jour_to.date_debut = w_factures_lignes_non_facturees_c_reaffect.date_debut AND
					no_facture_cible IS NULL
				;

				INSERT INTO activite.p_factures_lignes_non_facturees_c
				SELECT *
				FROM w_factures_lignes_non_facturees_c_jour_to
				;
			
				SELECT base.cti_vacuum_table('activite','p_factures');
				SELECT base.cti_vacuum_table('activite','p_sejours');

                -- suppression des FJ pour les services maternite (idem encours CTI)
                DELETE
                FROM activite.p_factures_lignes_non_facturees_c
                USING activite.t_lieux,
                    activite.t_services_facturation,
                    activite.t_prestations
                WHERE lieu_id = t_lieux.oid AND
                    t_services_facturation.oid = t_lieux.service_facturation_id AND
                    t_services_facturation.particularites_encours = 'MAT' AND
                    t_prestations.oid = prestation_id AND
                    t_prestations.code IN ('FJ','FJA','FJS','FJR')
                    ;
				
				-- Recalculer totaux facture
				UPDATE activite.p_factures SET
					montant_facture_c = subview.montant_facture,
					montant_facture_0_c = subview.montant_facture_0,
					montant_facture_1_c = subview.montant_facture_1,
					montant_facture_2_c = subview.montant_facture_2,
					montant_facture_22_c = subview.montant_facture_22,
					montant_comptabilise_budget_global_c = subview.montant_comptabilise_budget_global_c
				FROM (
					SELECT p_factures.no_facture, 
						SUM(COALESCE(CASE WHEN origine_facturation_id = 1 THEN p_factures_lignes_c.montant_facture ELSE 0 END,0)) AS montant_facture, 
						MAX(p_factures.montant_facture_c), 
						SUM(COALESCE(CASE WHEN origine_facturation_id = 1 THEN p_factures_lignes_c.montant_facture_0 ELSE 0 END,0)) AS montant_facture_0, 
						MAX(p_factures.montant_facture_0_c), 
						SUM(COALESCE(CASE WHEN origine_facturation_id = 1 THEN p_factures_lignes_c.montant_facture_1 ELSE 0 END,0)) AS montant_facture_1, 
						MAX(p_factures.montant_facture_1_c), 
						SUM(COALESCE(CASE WHEN origine_facturation_id = 1 THEN p_factures_lignes_c.montant_facture_2 ELSE 0 END,0)) AS montant_facture_2, 
						MAX(p_factures.montant_facture_2_c), 
						SUM(COALESCE(CASE WHEN origine_facturation_id = 1 THEN p_factures_lignes_c.montant_facture_22 ELSE 0 END,0)) AS montant_facture_22, 
						MAX(p_factures.montant_facture_22_c), 
						SUM(COALESCE(p_factures_lignes_c.montant_comptabilise_budget_global_1,0)) AS montant_comptabilise_budget_global_c, 
						MAX(p_factures.montant_comptabilise_budget_global_c)
					FROM activite.p_factures
					LEFT JOIN activite.p_factures_lignes_c on p_factures_lignes_c.no_facture = p_factures.no_facture
					GROUP BY 1
					HAVING 
						(
							SUM(COALESCE(CASE WHEN origine_facturation_id = 1 THEN p_factures_lignes_c.montant_facture ELSE 0 END,0)) <> MAX(p_factures.montant_facture_c) OR
							SUM(COALESCE(CASE WHEN origine_facturation_id = 1 THEN p_factures_lignes_c.montant_facture_0 ELSE 0 END,0)) <> MAX(p_factures.montant_facture_0_c) OR
							SUM(COALESCE(CASE WHEN origine_facturation_id = 1 THEN p_factures_lignes_c.montant_facture_1 ELSE 0 END,0)) <> MAX(p_factures.montant_facture_1_c) OR
							SUM(COALESCE(CASE WHEN origine_facturation_id = 1 THEN p_factures_lignes_c.montant_facture_2 ELSE 0 END,0)) <> MAX(p_factures.montant_facture_2_c) OR
							SUM(COALESCE(CASE WHEN origine_facturation_id = 1 THEN p_factures_lignes_c.montant_facture_22 ELSE 0 END,0)) <> MAX(p_factures.montant_facture_22_c) OR
							SUM(COALESCE(p_factures_lignes_c.montant_comptabilise_budget_global_1,0)) <> MAX(p_factures.montant_comptabilise_budget_global_c)
						)
					) subview
				WHERE p_factures.no_facture = subview.no_facture;
			
				-- Recalculer facture de référence
				DROP TABLE IF EXISTS w_sejours_facture_reference;

				CREATE TEMP TABLE w_sejours_facture_reference AS
				SELECT 
					p_sejours.no_sejour,
					CASE WHEN avec_facturation_intermediaire IS DISTINCT FROM '1' THEN p_sejours.date_sortie ELSE p_factures.date_fin END AS date_fin,
					MIN(CASE WHEN avec_facturation_intermediaire IS DISTINCT FROM '1' THEN p_sejours.date_entree ELSE p_factures.date_debut END) AS date_debut,
					MAX(p_factures.no_facture) AS no_facture_last,
					MAX(CASE WHEN p_factures.no_facture NOT LIKE '%.DMA' AND type_facture <> '1' AND type_facture <> 'X' AND type_facture <> 'P' THEN p_factures.no_facture ELSE null END) AS no_facture_reference_last,
					(MAX(ARRAY[to_char(
						CASE
							WHEN p_factures.no_facture NOT LIKE '%.DMA' AND type_facture <> '1' AND type_facture <> 'X' AND type_facture <> 'P' AND (t_prestations.code IN ('GHS','GHT','PJ') OR (p_factures.no_facture LIKE '%BG' AND p_sejours.type_sejour IN ('1','2','5','6'))) THEN p_factures_lignes_c.taux_1
							ELSE 0 END
							,'FM00000'),
						CASE 
							WHEN p_factures.no_facture NOT LIKE '%.DMA' AND type_facture <> '1' AND type_facture <> 'X' AND type_facture <> 'P' AND (t_prestations.code IN ('GHS','GHT','PJ') OR (p_factures.no_facture LIKE '%BG' AND p_sejours.type_sejour IN ('1','2','5','6'))) THEN p_factures.no_facture 
							ELSE NULL END
							]
					))[2] AS no_facture_reference_sejour_last,
					COUNT(DISTINCT p_factures.no_facture) AS nb_factures,
					MAX(avec_facturation_intermediaire) AS avec_facturation_intermediaire
				FROM activite.p_factures
					JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
					JOIN activite.t_lieux ON p_sejours.lieu_sortie_id = t_lieux.oid
					JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
					LEFT JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
					LEFT JOIN activite.t_prestations ON p_factures_lignes_c.prestation_id = t_prestations.oid AND t_prestations.code IN ('GHS','GHT','PJ')
				GROUP BY 1,2;


				CREATE INDEX w_sejours_facture_reference_i1
								  ON w_sejours_facture_reference
								  USING btree
								  (no_sejour);
				
				-- Cas d'une facture, d'un avoir et dune autre facture, il faut privilégier l'autre facture
				UPDATE w_sejours_facture_reference
				SET no_facture_reference_sejour_last = subview.no_facture_reference
				FROM
				(
				SELECT p_factures.no_sejour, 
					CASE WHEN avec_facturation_intermediaire IS DISTINCT FROM '1' THEN p_sejours.date_sortie ELSE p_factures.date_fin END AS date_fin,
					MAX(CASE WHEN type_facture <> '1' AND type_facture <> 'X' THEN no_facture ELSE NULL END) AS no_facture_reference
				FROM activite.p_factures
				JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				JOIN activite.t_lieux ON p_sejours.lieu_sortie_id = t_lieux.oid
				JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
				WHERE p_factures.no_facture NOT LIKE '%.DMA'
				GROUP BY 1,2
				HAVING SUM(CASE WHEN type_facture <> '1' AND type_facture <> 'X' THEN 1 ELSE 0 END) = 1 AND
					SUM(CASE WHEN type_facture = '1' THEN 1 ELSE 0 END) = SUM(CASE WHEN type_facture = 'X' THEN 1 ELSE 0 END) AND
					SUM(CASE WHEN type_facture = 'X' THEN 1 ELSE 0 END) > 0
				) subview
				WHERE w_sejours_facture_reference.no_sejour = subview.no_sejour AND
					w_sejours_facture_reference.date_fin = subview.date_fin AND
					no_facture_reference_sejour_last IS DISTINCT FROM subview.no_facture_reference
				;

				UPDATE activite.p_factures
				SET no_facture_reference = COALESCE(no_facture_reference_sejour_last, no_facture_reference_last, no_facture_last)
				FROM w_sejours_facture_reference
				JOIN activite.p_sejours ON p_sejours.no_sejour = w_sejours_facture_reference.no_sejour
				WHERE p_factures.no_sejour = w_sejours_facture_reference.no_sejour AND
					(
						p_factures.date_fin = w_sejours_facture_reference.date_fin OR
						p_factures.date_fin = p_sejours.date_sortie AND avec_facturation_intermediaire IS DISTINCT FROM '1'

					) AND
					p_factures.no_facture_reference <> COALESCE(no_facture_reference_sejour_last, no_facture_reference_last, no_facture_last);
						
				UPDATE activite.p_factures
				SET facture_reference_id = p_factures_references.oid
				FROM activite.p_factures p_factures_references
				WHERE p_factures.no_facture_reference = p_factures_references.no_facture
					AND p_factures.facture_reference_id <> p_factures_references.oid;
					
				
				--Report Sur Encours
				UPDATE activite.p_factures_encours
				SET no_facture_reference = subview.no_facture_reference
				FROM 
					(SELECT no_sejour, MAX(no_facture_reference) AS no_facture_reference
					FROM activite.p_factures
					GROUP BY 1
					HAVING count(distinct no_facture_reference)  = 1
					) subview
				WHERE p_factures_encours.no_sejour = subview.no_sejour AND
					p_factures_encours.no_facture_reference <> subview.no_facture_reference;
					
					

			
			
				-- Supprimer les factures de référence nulles sur séjours budget global
				DROP TABLE IF EXISTS w_factures_references;
				CREATE TEMP TABLE w_factures_references AS
				SELECT p_factures.no_facture_reference
				FROM activite.p_factures
				JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				JOIN activite.t_lieux ON lieu_sortie_id = t_lieux.oid
				JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
				JOIN activite.p_factures_reference ON p_factures_reference.no_facture_reference = p_factures.no_facture_reference
				WHERE p_factures_reference.nb_non_calcules > 0 AND
					t_services_facturation.est_sans_facturation = '2'
				GROUP BY 1
				HAVING SUM(CASE WHEN p_factures.code_facture = '1' AND p_factures.no_facture LIKE '%BG' THEN 1 ELSE 0 END) > 0 AND
					SUM(CASE WHEN p_factures.code_facture = '0' AND 
						p_factures.montant_facture_c = 0 AND 
						p_factures.montant_facture_h = 0 AND
						p_factures.montant_regle_c = 0 AND 
						p_factures.montant_regle_h = 0
						THEN 1 ELSE 0 END) > 0 
				ORDER BY 1;

				DELETE FROM activite.p_factures
				USING w_factures_references
				WHERE w_factures_references.no_facture_reference = p_factures.no_facture_reference AND
					p_factures.code_facture = '0' AND 
					p_factures.montant_facture_c = 0 AND 
					p_factures.montant_facture_h = 0 AND
					p_factures.montant_regle_c = 0 AND 
					p_factures.montant_regle_h = 0;
			
				-- Reporter ghs sur factures
				UPDATE activite.p_factures
				SET ghs_id = p_sejours.ghs_id
				FROM activite.p_sejours
				WHERE p_factures.no_sejour = p_sejours.no_sejour AND p_factures.ghs_id IS DISTINCT FROM p_sejours.ghs_id;
				
				UPDATE activite.p_sejours 
				SET date_groupage = date_facture 
				WHERE (date_groupage IS null OR date_groupage = '20991231' OR date_groupage = '00010101') AND 
					date_facture <> '2099-12-31' AND ghs_id > 0;
                    
                    
                -- Cas spécial de deux factures additives non facturées (pour génération encours)
                UPDATE activite.p_factures
				SET type_facture = '0'
				WHERE no_facture IN
				(
					SELECT no_facture_reference
					FROM
					(
					SELECT no_sejour, MAX(no_facture_reference) AS no_facture_reference
					FROM activite.p_factures
					WHERE code_facture = '0'
					GROUP BY 1
					HAVING count(*) > 1 AND
						SUM(CASE WHEN type_facture = '2' AND code_facture = '0' THEN 1 ELSE 0 END) = count(*) 
						) subview 
				)
				;

				

				
			]]></sqlcmd>

		</NODE>

		<NODE label="Compléments factures séances (BG)">
			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
			
                -- Eclatement seances pour séjours à l'année (GHM Grenoble)
				
				DROP TABLE IF EXISTS w_factures_seances_bg;
				CREATE TEMP TABLE w_factures_seances_bg AS
				SELECT p_factures.*, 
					GREATEST(p_calendrier_mois.date_debut,p_factures.date_debut) AS date_seance_debut, 
					LEAST(p_calendrier_mois.date_fin,p_factures.date_fin) AS date_seance_fin, 
					0::numeric AS nb_seances,  
					0::numeric AS nb_seances_facturees, 
					no_facture AS no_facture_original
				FROM activite.p_factures
				JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour 
				LEFT JOIN base.t_ghm ON p_sejours.ghm_id = t_ghm.oid
				JOIN base.p_calendrier_mois ON p_calendrier_mois.date_debut <= p_factures.date_fin AND p_calendrier_mois.date_fin >= p_factures.date_debut
				WHERE no_facture LIKE '%BG' AND 
					type_sejour = '5' AND 
					COALESCE(t_ghm.code,'') NOT IN ('28Z19Z', '28Z20Z') AND
					date_trunc('month',p_factures.date_fin) > date_trunc('month',p_factures.date_debut)
				;
				
				SELECT setval('activite.s_factures', COALESCE((SELECT MAX(oid) FROM activite.p_factures),0)+1, true)
				;
				
				UPDATE w_factures_seances_bg
				SET date_debut = date_seance_debut, 
					date_fin = date_seance_fin,
					no_facture = CASE WHEN w_factures_seances_bg.date_debut = date_seance_debut THEN w_factures_seances_bg.no_facture_original ELSE replace(no_facture_original,'BG','') || to_char(date_seance_fin,'YYMM') || '.BG' END,
					oid = CASE WHEN w_factures_seances_bg.date_debut = date_seance_debut THEN w_factures_seances_bg.oid ELSE nextval('activite.s_factures'::regclass) END
					;

				UPDATE w_factures_seances_bg SET
					no_facture_reference = no_facture,
					facture_reference_id = oid
				;

				ANALYSE w_factures_seances_bg;

				CREATE INDEX i_w_factures_seances_bg_1
				  ON w_factures_seances_bg
				  USING btree
				  (no_facture_original);

				  
				CREATE INDEX i_w_factures_seances_bg_2
				  ON w_factures_seances_bg
				  USING btree
				  (no_sejour);

				UPDATE w_factures_seances_bg
				SET nb_seances = subview.nb_seances
				FROM 
					(
					SELECT no_facture, COUNT(DISTINCT date) AS nb_seances
					  FROM activite.p_mouvements_sejour
					  JOIN  w_factures_seances_bg ON
						p_mouvements_sejour.no_sejour = w_factures_seances_bg.no_sejour AND
						p_mouvements_sejour.date BETWEEN w_factures_seances_bg.date_debut AND w_factures_seances_bg.date_fin AND
						p_mouvements_sejour.nb_seances > 0
						GROUP BY 1
					) subview
				WHERE subview.no_facture = w_factures_seances_bg.no_facture AND
					subview.nb_seances > 0
				;




				UPDATE w_factures_seances_bg
				SET nb_seances_facturees =  subview.nb_seances
				FROM
				(
					SELECT w_factures_seances_bg.no_facture, COUNT(DISTINCT p_factures_lignes_c.date_debut) AS nb_seances
					  FROM activite.p_factures_lignes_c
					  JOIN  w_factures_seances_bg ON
						p_factures_lignes_c.no_facture = w_factures_seances_bg.no_facture_original AND
						p_factures_lignes_c.date_debut BETWEEN w_factures_seances_bg.date_debut AND w_factures_seances_bg.date_fin AND
						p_factures_lignes_c.montant_facture > 0
						GROUP BY 1
					) subview
				WHERE subview.no_facture = w_factures_seances_bg.no_facture AND
				subview.nb_seances > 0
				;


				UPDATE w_factures_seances_bg SET
					code_facture = CASE WHEN nb_seances_facturees > 0 THEN '1' WHEN nb_seances = 0 THEN '1' ELSE '0' END,
					date_facture = CASE WHEN nb_seances_facturees > 0 THEN date_fin WHEN nb_seances = 0 THEN date_fin ELSE '20991231' END,
					code_vente = CASE WHEN nb_seances_facturees > 0 THEN '1' WHEN nb_seances = 0 THEN '1' ELSE '0' END,
					date_vente = CASE WHEN nb_seances_facturees > 0 THEN date_fin WHEN nb_seances = 0 THEN date_fin ELSE '20991231' END,
					mois_vente = to_char(CASE WHEN nb_seances_facturees > 0 THEN date_fin WHEN nb_seances = 0 THEN date_fin ELSE '20991231' END,'YYYMM')::numeric
				;
	


				UPDATE activite.p_factures_lignes_c
				SET no_facture = w_factures_seances_bg.no_facture, facture_id = w_factures_seances_bg.oid
				FROM w_factures_seances_bg
				WHERE p_factures_lignes_c.no_facture = w_factures_seances_bg.no_facture_original AND
					p_factures_lignes_c.date_debut BETWEEN w_factures_seances_bg.date_debut AND w_factures_seances_bg.date_fin AND
					p_factures_lignes_c.no_facture <> w_factures_seances_bg.no_facture
				;

				UPDATE activite.p_factures_lignes_h
				SET no_facture = w_factures_seances_bg.no_facture, facture_id = w_factures_seances_bg.oid
				FROM w_factures_seances_bg
				WHERE p_factures_lignes_h.no_facture = w_factures_seances_bg.no_facture_original AND
					p_factures_lignes_h.date_debut BETWEEN w_factures_seances_bg.date_debut AND w_factures_seances_bg.date_fin AND
					p_factures_lignes_h.no_facture <> w_factures_seances_bg.no_facture
				;

				UPDATE w_factures_seances_bg SET
					montant_facture_c = subview.montant_facture, 
					montant_facture_1_c = subview.montant_facture, 
					montant_comptabilise_budget_global_c = subview.montant_facture
				FROM
				(
				SELECT w_factures_seances_bg.no_facture, SUM(COALESCE(montant_facture,0)) AS montant_facture
				FROM w_factures_seances_bg
				LEFT JOIN activite.p_factures_lignes_c ON
					p_factures_lignes_c.no_facture = w_factures_seances_bg.no_facture AND
					p_factures_lignes_c.date_debut BETWEEN w_factures_seances_bg.date_debut AND w_factures_seances_bg.date_fin AND
					p_factures_lignes_c.montant_facture > 0
				GROUP BY 1
				) subview
				WHERE subview.no_facture = w_factures_seances_bg.no_facture AND
					w_factures_seances_bg.montant_facture_c <> subview.montant_facture
				;


				DELETE
				FROM activite.p_factures 
				WHERE no_facture IN (SELECT no_facture_original FROM w_factures_seances_bg)
				;

				ALTER TABLE w_factures_seances_bg DROP COLUMN nb_seances;
				ALTER TABLE w_factures_seances_bg DROP COLUMN nb_seances_facturees;
				ALTER TABLE w_factures_seances_bg DROP COLUMN date_seance_debut;
				ALTER TABLE w_factures_seances_bg DROP COLUMN date_seance_fin;
				ALTER TABLE w_factures_seances_bg DROP COLUMN no_facture_original;

				INSERT INTO activite.p_factures
				SELECT * FROM w_factures_seances_bg
				;
                
                UPDATE activite.p_factures SET
					no_facture_reference = p_factures_bg.no_facture, facture_reference_id = p_factures_bg.oid
				FROM activite.p_factures p_factures_bg 
				JOIN activite.p_sejours ON p_factures_bg.no_sejour = p_sejours.no_sejour AND p_sejours.type_sejour = '5'
				WHERE 
					p_factures.no_sejour = p_factures_bg.no_sejour AND
					p_factures.no_facture NOT LIKE '%BG' AND
					p_factures.no_facture_reference LIKE '%BG' AND
					p_factures_bg.no_facture LIKE '%BG' AND
					p_factures.date_fin BETWEEN p_factures_bg.date_debut AND p_factures_bg.date_fin AND
					p_factures.no_facture_reference <> p_factures_bg.no_facture
				;
				

			]]></sqlcmd>
		</NODE>

		<NODE label="Compléments lignes factures">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[

				-- Suppression des prestations comptées en double (présentes dans la facture initiale et dans la facture BG)
				DROP TABLE IF EXISTS w_dejafac_bg
				;
				CREATE TEMP TABLE w_dejafac_bg AS
				SELECT 
					p_factures.no_sejour
					,p_factures_lignes_c.prestation_id
				FROM activite.p_factures_lignes_c
					JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
				WHERE p_factures_lignes_c.no_facture LIKE '%BG'
				GROUP BY 
					p_factures.no_sejour,
					p_factures_lignes_c.prestation_id
				;

				ANALYZE w_dejafac_bg
				;

				DROP TABLE IF EXISTS w_dejafac_hbg
				;
				CREATE TEMP TABLE w_dejafac_hbg AS
				SELECT 
					p_factures.no_facture
					,p_factures_lignes_c.prestation_id
				FROM activite.p_factures_lignes_c
					JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
					JOIN w_dejafac_bg 
						ON p_factures.no_sejour = w_dejafac_bg.no_sejour 
						AND p_factures_lignes_c.prestation_id = w_dejafac_bg.prestation_id
				WHERE p_factures_lignes_c.no_facture NOT LIKE '%BG' 
					AND p_factures_lignes_c.montant_facture = 0 
					AND p_factures_lignes_c.montant_comptabilise = 0  
					AND p_factures_lignes_c.montant_encours = 0
				GROUP BY 
					p_factures.no_facture,
					p_factures_lignes_c.prestation_id
				;

				ANALYZE w_dejafac_hbg
				;

				DELETE FROM activite.p_factures_lignes_c
				USING w_dejafac_hbg
				WHERE p_factures_lignes_c.no_facture = w_dejafac_hbg.no_facture 
					AND p_factures_lignes_c.prestation_id = w_dejafac_hbg.prestation_id 
					AND p_factures_lignes_c.montant_facture = 0 
					AND p_factures_lignes_c.montant_comptabilise = 0  
					AND p_factures_lignes_c.montant_encours = 0
				;

			
				-- Lieu des lignes de factures (en tenant compte des absences) 
                DROP TABLE IF EXISTS w_mouvements_sejour_lieu_jour;
                CREATE TEMP TABLE w_mouvements_sejour_lieu_jour AS
                SELECT no_sejour, 
                    date,
                    (MAX(CASE WHEN est_absence <> '1' THEN Array[heure_fin, lieu_id] ELSE NULL END))[2] AS lieu_id,
                    (MAX(Array[heure_fin, lieu_id]))[2] AS lieu_id_avec_absence
                FROM activite.p_mouvements_sejour
                JOIN activite.t_lieux ON lieu_id = t_lieux.oid
                JOIN activite.t_services_facturation On service_facturation_id = t_services_facturation.oid
                GROUP BY 1,2
				HAVING (MAX(CASE WHEN est_absence <> '1' THEN Array[heure_fin, lieu_id] ELSE NULL END))[2] IS DISTINCT FROM (MAX(Array[heure_fin, lieu_id]))[2]
                ;

                UPDATE activite.p_factures_lignes_c 
				SET lieu_id = COALESCE(w_mouvements_sejour_lieu_jour.lieu_id,w_mouvements_sejour_lieu_jour.lieu_id_avec_absence)
				FROM activite.p_factures, w_mouvements_sejour_lieu_jour
				WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
					p_factures.no_sejour = w_mouvements_sejour_lieu_jour.no_sejour AND
					p_factures_lignes_c.date_fin = w_mouvements_sejour_lieu_jour.date AND
					p_factures_lignes_c.lieu_id <> COALESCE(w_mouvements_sejour_lieu_jour.lieu_id,w_mouvements_sejour_lieu_jour.lieu_id_avec_absence)
                ;
                
                UPDATE activite.p_factures_lignes_h 
				SET lieu_id = COALESCE(w_mouvements_sejour_lieu_jour.lieu_id,w_mouvements_sejour_lieu_jour.lieu_id_avec_absence)
				FROM activite.p_factures, w_mouvements_sejour_lieu_jour
				WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND
					p_factures.no_sejour = w_mouvements_sejour_lieu_jour.no_sejour AND
					p_factures_lignes_h.date_fin = w_mouvements_sejour_lieu_jour.date AND
					p_factures_lignes_h.lieu_id <> COALESCE(w_mouvements_sejour_lieu_jour.lieu_id,w_mouvements_sejour_lieu_jour.lieu_id_avec_absence)
                ;
		
				-- Dans le cas des ESPIC les prestations peuvent être facturées en partie sur la facture BG (part AMO) et et partie dans la GAP (part AMC/PATIENT)
				-- Dans ce cas afin de ne pas doubler le nombre de prestations -> mise à 0 des coefficient (quantités) des prestations venant dans de la GAP si prestation identique venant de la facture BG
				WITH prestations_importees_pmsi as (
					SELECT
						p_factures.no_facture_reference,
						t_prestations.oid as prestation_id
					FROM activite.p_factures_lignes_c
					JOIN activite.p_factures ON p_factures.no_facture = p_factures_lignes_c.no_facture
					JOIN activite.p_sejours ON p_sejours.no_sejour = p_factures.no_sejour													-- Jointure sur séjour pour récupérer finess
					JOIN base.t_finess ON t_finess.code = p_sejours.finess																	-- Jointure sur finess pour limiter l'impact aux espics
					JOIN activite.t_prestations ON t_prestations.oid = p_factures_lignes_c.prestation_id 
						AND t_prestations.code IN ('PJ', 'FJ', 'SSM', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO')			-- filtre sur les prestations souhaitées
					WHERE p_factures.no_facture = no_facture_reference
					AND p_factures.no_facture ilike '%BG'																					-- ne conserver que les factures provenant du PMSI (BG)
					AND taux_1 < 100																										-- Exclure les lignes à 100% BG -> 100% AMO
					AND type_etablissement IN ('2','3')																						-- Filtre sur espic
					GROUP BY 1,2
				)
				UPDATE activite.p_factures_lignes_c
					SET coefficient = 0																										-- Mettre la quantité à 0
				FROM activite.p_factures, prestations_importees_pmsi
				WHERE 1=1 
					AND p_factures.no_facture = p_factures_lignes_c.no_facture
					AND prestations_importees_pmsi.no_facture_reference = p_factures.no_facture_reference AND p_factures_lignes_c.prestation_id = prestations_importees_pmsi.prestation_id -- Si ligne avec prestation identique sur même facture de référence
					AND p_factures.no_facture NOT LIKE '%BG'																				-- Ne pas mettre à jour ce qui vient du PMSI
					AND ((taux_2 > 0 AND taux_2 < 100) OR (taux_0 > 0 AND taux_0 < 100));									-- Seulement si lignes n'est pas à 100% patient/AMC
				
			]]></sqlcmd>
		</NODE>

		<NODE label="Compléments encours">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
			
					ANALYSE activite.p_sejours;
					
					ANALYSE activite.p_mouvements_sejour;
					
					ANALYSE activite.p_factures;
					
					ANALYSE activite.p_factures_lignes_c;
					
					ANALYSE activite.p_factures_reference;
					
					ANALYSE activite.p_factures_encours;
					
					ANALYSE activite.p_factures_encours_lignes_c;
					
					SELECT activite.valoriser_sejours_groupes_smr();
					
					SELECT activite.calcul_encours(NULL,'');
			
					SELECT activite.cti_ajust_encours();
										
					-- Ajustement dotation
					SELECT activite.cti_gen_dotation();
				
			]]></sqlcmd>
		</NODE>

		<NODE label="Factures de référence">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
		
		
				DROP TABLE IF EXISTS w_factures_reference;
				CREATE TEMP TABLE w_factures_reference AS
				SELECT
					p_sejours.oid AS sejour_id,
					p_sejours.no_sejour,
					p_sejours.date_entree,
					p_sejours.date_sortie,
					p_sejours.code_sorti,
					p_sejours.type_sejour,
					facture_reference_id,
					no_facture_reference,
					CASE WHEN p_sejours.type_sejour IN ('1','2','5') THEN type_t2a ELSE '0' END AS type_t2a,
					MIN(CASE 
                        WHEN p_sejours.type_sejour = '3' THEN p_sejours.date_entree
						WHEN p_sejours.type_sejour IN ('5') AND no_facture_reference LIKE '%BG' THEN date_debut
                        WHEN p_sejours.type_sejour IN ('1','2','5') AND type_t2a = '1' THEN p_sejours.date_entree
						WHEN p_sejours.type_sejour IN ('1','2','5') AND avec_facturation_intermediaire <> '1' THEN p_sejours.date_entree
                        ELSE date_debut END) AS date_debut_facture,
					MAX(CASE 
                        WHEN p_sejours.type_sejour = '3' THEN p_sejours.date_sortie
						WHEN p_sejours.type_sejour IN ('5') AND no_facture_reference LIKE '%BG' THEN date_fin
                        WHEN p_sejours.type_sejour IN ('1','2','5') AND type_t2a = '1' THEN p_sejours.date_sortie
                        WHEN p_sejours.type_sejour IN ('1','2','5') AND avec_facturation_intermediaire <> '1' THEN p_sejours.date_sortie
                        ELSE date_fin END) AS date_fin_facture,
					MAX(CASE WHEN no_facture = no_facture_reference THEN p_factures.type_facture ELSE NULL END) AS type_facture,
					MAX(date_groupage) AS date_groupage,
					NULL::numeric AS delai_groupage,
					0::numeric AS retard_groupage,
					0::numeric AS nb_groupe,
					0::numeric AS nb_non_groupe,
					0::numeric AS nb_calculable,
					MAX(CASE WHEN no_facture = no_facture_reference THEN GREATEST(p_factures.ghs_id,0) ELSE 0 END) AS ghs_id,
					MAX(CASE WHEN no_facture = no_facture_reference THEN p_factures.ghs_bebe1_id ELSE 0 END) AS ghs_bebe1_id,
					MAX(CASE WHEN no_facture = no_facture_reference THEN p_factures.ghs_bebe2_id ELSE 0 END) AS ghs_bebe2_id,
					MAX(CASE WHEN no_facture = no_facture_reference THEN p_factures.ghs_bebe3_id ELSE 0 END) AS ghs_bebe3_id,
					MAX(CASE WHEN no_facture = no_facture_reference THEN GREATEST(p_factures.gmt_id,0) ELSE 0 END) AS gmt_id,
					MAX(CASE WHEN no_facture = no_facture_reference THEN p_factures.tiers_payant_0_id ELSE 0 END) AS tiers_payant_0_id,
					MAX(CASE WHEN no_facture = no_facture_reference THEN p_factures.tiers_payant_1_id ELSE 0 END) AS tiers_payant_1_id,
					MAX(CASE WHEN no_facture = no_facture_reference THEN p_factures.tiers_payant_2_id ELSE 0 END) AS tiers_payant_2_id,
					MAX(CASE WHEN no_facture = no_facture_reference THEN p_factures.tiers_payant_22_id ELSE 0 END) AS tiers_payant_22_id,
					MAX(CASE WHEN no_facture = no_facture_reference AND p_factures.code_facture IN ('1', '2') THEN '1' ELSE '0' END) AS code_facture,
					MAX(CASE WHEN no_facture = no_facture_reference THEN p_factures.date_facture ELSE '00010101' END) AS date_facture,
					NULL::numeric AS delai_facture,
					0::numeric AS retard_facture,
					MAX(CASE WHEN no_facture = no_facture_reference THEN p_factures.code_vente ELSE '0' END) AS code_vente,
					MAX(CASE WHEN no_facture = no_facture_reference THEN p_factures.date_vente ELSE '00010101' END) AS date_vente,
					COUNT(*) AS nb_factures,
					MAX(CASE 
						WHEN p_sejours.code_sorti <> '1' AND avec_facturation_intermediaire <> '1' THEN 0
						WHEN p_factures.type_facture NOT IN ('P', 'G') AND p_factures.code_facture NOT IN ('1','2') THEN 1 
						ELSE 0 END) AS nb_non_calcules,
                    COALESCE(MAX(CASE 
						WHEN p_sejours.code_sorti <> '1' AND avec_facturation_intermediaire <> '1' THEN 0
						WHEN p_factures.type_facture NOT IN ('P', 'G') AND p_factures.no_facture NOT LIKE '%BG' AND p_factures.code_facture NOT IN ('1','2') THEN 1 
						ELSE 0 END),0) AS nb_non_calcules_horsbg,
					COALESCE(MAX(CASE 
						WHEN p_sejours.code_sorti <> '1' AND avec_facturation_intermediaire <> '1' THEN 0
						WHEN p_factures.type_facture NOT IN ('P', 'G') AND p_factures.no_facture LIKE '%BG' AND p_factures.code_facture NOT IN ('1','2') THEN 1 
						ELSE 0 END),0) AS nb_non_calcules_bg,
					SUM(CASE
					    WHEN p_factures.type_facture = '0'::bpchar THEN 0
					    WHEN p_factures.type_facture = 'P'::bpchar THEN 0
					    WHEN p_factures.type_facture = 'E'::bpchar THEN 0
					    WHEN p_factures.type_facture = 'X'::bpchar THEN 0
					    ELSE 1
					END) AS nb_factures_regularisation,
					SUM(p_factures.nb_rejets) AS nb_rejets,

					'1'::text AS code_expedie_0,
					MAX(CASE WHEN no_facture = no_facture_reference AND p_factures.code_expedie_1 = '1' THEN p_factures.code_expedie_1 ELSE '0' END) AS code_expedie_1,
					MAX(p_factures.code_expedie_2) AS code_expedie_2,
					MAX(CASE WHEN no_facture = no_facture_reference THEN p_factures.date_expedition ELSE '00010101' END) AS date_expedition,
					MAX(CASE WHEN p_factures.code_expedie_0 = '1' AND p_factures.date_expedition_0 < '20991231' THEN p_factures.date_expedition_0 ELSE '00010101' END) AS date_expedition_0,
					MAX(CASE WHEN no_facture = no_facture_reference AND p_factures.code_expedie_1 = '1' THEN p_factures.date_expedition_1 ELSE '00010101' END) AS date_expedition_1,
					MAX(CASE WHEN p_factures.code_expedie_2 = '1' AND p_factures.date_expedition_2 < '20991231' THEN p_factures.date_expedition_2 ELSE '00010101' END) AS date_expedition_2,
					MAX(CASE WHEN p_factures.code_expedie_0 = '1' AND p_factures.date_expedition_0 < '20991231' THEN no_bordereau_0 ELSE '' END) AS no_bordereau_0,
					MAX(CASE WHEN no_facture = no_facture_reference AND code_expedie_1 = '1' THEN no_bordereau_1 ELSE '' END) AS no_bordereau_1,
					MAX(CASE WHEN p_factures.code_expedie_2 = '1' AND p_factures.date_expedition_2 < '20991231'  THEN no_bordereau_2 ELSE '' END) AS no_bordereau_2,
					NULL::numeric AS delai_expedition,
					NULL::numeric AS delai_expedition_0,
					NULL::numeric AS delai_expedition_1,
					NULL::numeric AS delai_expedition_2,
					0::numeric AS nb_non_expedie,
					0::numeric AS nb_non_expedie_c,
					0::numeric AS nb_non_expedie_h,
					0::numeric AS nb_non_expedie_0,
					0::numeric AS nb_non_expedie_0_c,
					0::numeric AS nb_non_expedie_0_h,
					0::numeric AS nb_non_expedie_1,
					0::numeric AS nb_non_expedie_1_c,
					0::numeric AS nb_non_expedie_1_h,
					0::numeric AS nb_non_expedie_2,
					0::numeric AS nb_non_expedie_2_c,
					0::numeric AS nb_non_expedie_2_h,
					
					SUM(p_factures.montant_facture_c + p_factures.montant_facture_h) AS montant_facture,
					SUM(p_factures.montant_facture_c) AS montant_facture_c,
					SUM(p_factures.montant_facture_h) AS montant_facture_h,
					SUM(p_factures.montant_facture_0_c + p_factures.montant_facture_0_h) AS montant_facture_0,
					SUM(p_factures.montant_facture_0_c) AS montant_facture_0_c,
					SUM(p_factures.montant_facture_0_h) AS montant_facture_0_h,
					SUM(p_factures.montant_facture_1_c + p_factures.montant_facture_1_h) AS montant_facture_1,
					SUM(p_factures.montant_facture_1_c) AS montant_facture_1_c,
					SUM(p_factures.montant_facture_1_h) AS montant_facture_1_h,
					SUM(p_factures.montant_facture_2_c + p_factures.montant_facture_2_h + p_factures.montant_facture_22_c + p_factures.montant_facture_22_h) AS montant_facture_2,
					SUM(p_factures.montant_facture_2_c + p_factures.montant_facture_22_c) AS montant_facture_2_c,
					SUM(p_factures.montant_facture_2_h + p_factures.montant_facture_22_h) AS montant_facture_2_h,
					SUM(p_factures.montant_facture_c_actes_inclus_dans_sejour) AS montant_facture_c_actes_inclus_dans_sejour,
					SUM(p_factures.montant_facture_h_actes_inclus_dans_sejour) AS montant_facture_h_actes_inclus_dans_sejour,

					SUM(p_factures.montant_encours_c + p_factures.montant_encours_h) AS montant_encours,
					SUM(p_factures.montant_encours_c) AS montant_encours_c,
					SUM(p_factures.montant_encours_h) AS montant_encours_h,
					SUM(p_factures.montant_encours_0_c + p_factures.montant_encours_0_h) AS montant_encours_0,
					SUM(p_factures.montant_encours_0_c) AS montant_encours_0_c,
					SUM(p_factures.montant_encours_0_h) AS montant_encours_0_h,
					SUM(p_factures.montant_encours_1_c + p_factures.montant_encours_1_h) AS montant_encours_1,
					SUM(p_factures.montant_encours_1_c) AS montant_encours_1_c,
					SUM(p_factures.montant_encours_1_h) AS montant_encours_1_h,
					SUM(p_factures.montant_encours_2_c + p_factures.montant_encours_2_h + p_factures.montant_encours_22_c + p_factures.montant_encours_22_h) AS montant_encours_2,
					SUM(p_factures.montant_encours_2_c + p_factures.montant_encours_22_c) AS montant_encours_2_c,
					SUM(p_factures.montant_encours_2_h + p_factures.montant_encours_22_h) AS montant_encours_2_h,

					SUM(p_factures.montant_comptabilise_c + p_factures.montant_comptabilise_h) AS montant_comptabilise,
					SUM(p_factures.montant_comptabilise_c) AS montant_comptabilise_c,
					SUM(p_factures.montant_comptabilise_h) AS montant_comptabilise_h,
					SUM(p_factures.montant_comptabilise_0_c + p_factures.montant_comptabilise_0_h) AS montant_comptabilise_0,
					SUM(p_factures.montant_comptabilise_0_c) AS montant_comptabilise_0_c,
					SUM(p_factures.montant_comptabilise_0_h) AS montant_comptabilise_0_h,
					SUM(p_factures.montant_comptabilise_1_c + p_factures.montant_comptabilise_1_h) AS montant_comptabilise_1,
					SUM(p_factures.montant_comptabilise_1_c) AS montant_comptabilise_1_c,
					SUM(p_factures.montant_comptabilise_1_h) AS montant_comptabilise_1_h,
					SUM(p_factures.montant_comptabilise_2_c + p_factures.montant_comptabilise_2_h + p_factures.montant_comptabilise_22_c + p_factures.montant_comptabilise_22_h) AS montant_comptabilise_2,
					SUM(p_factures.montant_comptabilise_2_c + p_factures.montant_comptabilise_22_c) AS montant_comptabilise_2_c,
					SUM(p_factures.montant_comptabilise_2_h + p_factures.montant_comptabilise_22_h) AS montant_comptabilise_2_h,
					SUM(p_factures.montant_comptabilise_budget_global_c) AS montant_comptabilise_budget_global_c,
					
					SUM(p_factures.montant_regle_c + p_factures.montant_regle_h) AS montant_regle,
					SUM(p_factures.montant_regle_c) AS montant_regle_c,
					SUM(p_factures.montant_regle_h) AS montant_regle_h,
					SUM(p_factures.montant_regle_0_c + p_factures.montant_regle_0_h) AS montant_regle_0,
					SUM(p_factures.montant_regle_0_c) AS montant_regle_0_c,
					SUM(p_factures.montant_regle_0_h) AS montant_regle_0_h,
					SUM(p_factures.montant_regle_1_c + p_factures.montant_regle_1_h) AS montant_regle_1,
					SUM(p_factures.montant_regle_1_c) AS montant_regle_1_c,
					SUM(p_factures.montant_regle_1_h) AS montant_regle_1_h,
					SUM(p_factures.montant_regle_2_c + p_factures.montant_regle_2_h + p_factures.montant_regle_22_c + p_factures.montant_regle_22_h) AS montant_regle_2,
					SUM(p_factures.montant_regle_2_c + p_factures.montant_regle_22_c) AS montant_regle_2_c,
					SUM(p_factures.montant_regle_2_h + p_factures.montant_regle_22_h) AS montant_regle_2_h,

					COALESCE(
						CASE 
							WHEN SUM(p_factures.montant_regle_c) >= SUM(p_factures.montant_comptabilise_c) AND SUM(p_factures.montant_regle_h) >= SUM(p_factures.montant_comptabilise_h) THEN 
								MAX(CASE WHEN p_factures.date_solde < '20991231' AND p_factures.date_solde > '00010101' THEN p_factures.date_solde ELSE NULL END) 
							ELSE NULL END
						,'20991231') AS date_solde,
					COALESCE(
						CASE 
							WHEN SUM(p_factures.montant_regle_c) >= SUM(p_factures.montant_comptabilise_c) THEN 
								MAX(CASE WHEN p_factures.date_solde_c < '20991231' AND p_factures.date_solde_c > '00010101' THEN p_factures.date_solde_c ELSE NULL END) 
							ELSE NULL END
						,'20991231') AS date_solde_c,
					COALESCE(
						CASE 
							WHEN SUM(p_factures.montant_regle_h) >= SUM(p_factures.montant_comptabilise_h) THEN 
								MAX(CASE WHEN p_factures.date_solde_h < '20991231' AND p_factures.date_solde_h > '00010101' THEN p_factures.date_solde_h ELSE NULL END) 
							ELSE NULL END
						,'20991231') AS date_solde_h,
					NULL::date AS date_solde_0,
					COALESCE(
						CASE 
							WHEN SUM(p_factures.montant_regle_0_c) >= SUM(p_factures.montant_comptabilise_0_c) THEN 
								MAX(CASE WHEN p_factures.date_solde_0_c < '20991231' AND p_factures.date_solde_0_c > '00010101' THEN p_factures.date_solde_0_c ELSE NULL END) 
							ELSE NULL END
						,'20991231') AS date_solde_0_c,
					COALESCE(
						CASE 
							WHEN SUM(p_factures.montant_regle_0_h) >= SUM(p_factures.montant_comptabilise_0_h) THEN 
								MAX(CASE WHEN p_factures.date_solde_0_h < '20991231' AND p_factures.date_solde_0_h > '00010101' THEN p_factures.date_solde_0_h ELSE NULL END) 
							ELSE NULL END
						,'20991231') AS date_solde_0_h,
					NULL::date AS date_solde_1,
					COALESCE(
						CASE 
							WHEN SUM(p_factures.montant_regle_1_c) >= SUM(p_factures.montant_comptabilise_1_c) THEN 
								MAX(CASE WHEN p_factures.date_solde_1_c < '20991231' AND p_factures.date_solde_1_c > '00010101' THEN p_factures.date_solde_1_c ELSE NULL END) 
							ELSE NULL END
						,'20991231') AS date_solde_1_c,
					COALESCE(
						CASE 
							WHEN SUM(p_factures.montant_regle_1_h) >= SUM(p_factures.montant_comptabilise_1_h) THEN 
								MAX(CASE WHEN p_factures.date_solde_1_h < '20991231' AND p_factures.date_solde_1_h > '00010101' THEN p_factures.date_solde_1_h ELSE NULL END) 
							ELSE NULL END
						,'20991231') AS date_solde_1_h,
					NULL::date AS date_solde_2,
					COALESCE(
						CASE 
							WHEN SUM(p_factures.montant_regle_2_c) >= SUM(p_factures.montant_comptabilise_2_c) THEN 
								MAX(CASE WHEN p_factures.date_solde_2_c < '20991231' AND p_factures.date_solde_2_c > '00010101' THEN p_factures.date_solde_2_c ELSE NULL END) 
							ELSE NULL END
						,'20991231') AS date_solde_2_c,
					COALESCE(
						CASE 
							WHEN SUM(p_factures.montant_regle_2_h) >= SUM(p_factures.montant_comptabilise_2_h) THEN 
								MAX(CASE WHEN p_factures.date_solde_2_h < '20991231' AND p_factures.date_solde_2_h > '00010101' THEN p_factures.date_solde_2_h ELSE NULL END) 
							ELSE NULL END
						,'20991231') AS date_solde_2_h,
						
					0::numeric AS delai_solde,
					0::numeric AS delai_solde_c,
					0::numeric AS delai_solde_h,
					0::numeric AS delai_solde_0,
					0::numeric AS delai_solde_0_c,
					0::numeric AS delai_solde_0_h,
					0::numeric AS delai_solde_1,
					0::numeric AS delai_solde_1_c,
					0::numeric AS delai_solde_1_h,
					0::numeric AS delai_solde_2,
					0::numeric AS delai_solde_2_c,
					0::numeric AS delai_solde_2_h,
					0::numeric AS nb_non_solde,
					0::numeric AS nb_non_solde_c,
					0::numeric AS nb_non_solde_h,
					0::numeric AS nb_non_solde_0,
					0::numeric AS nb_non_solde_0_c,
					0::numeric AS nb_non_solde_0_h,
					0::numeric AS nb_non_solde_1,
					0::numeric AS nb_non_solde_1_c,
					0::numeric AS nb_non_solde_1_h,
					0::numeric AS nb_non_solde_2,
					0::numeric AS nb_non_solde_2_c,
					0::numeric AS nb_non_solde_2_h,
					MAX(CASE WHEN p_factures.montant_comptabilise_c <> p_factures.montant_regle_c OR p_factures.montant_comptabilise_h <> p_factures.montant_regle_h THEN 1 ELSE 0 END) AS nb_non_cloture,
					MAX(CASE WHEN p_factures.montant_comptabilise_c <> p_factures.montant_regle_c THEN 1 ELSE 0 END) AS nb_non_cloture_c,
					MAX(CASE WHEN p_factures.montant_comptabilise_h <> p_factures.montant_regle_h THEN 1 ELSE 0 END) AS nb_non_cloture_h,
					MAX(CASE WHEN p_factures.montant_comptabilise_0_c <> p_factures.montant_regle_0_c OR p_factures.montant_comptabilise_0_h <> p_factures.montant_regle_0_h THEN 1 ELSE 0 END) AS nb_non_cloture_0,
					MAX(CASE WHEN p_factures.montant_comptabilise_0_c <> p_factures.montant_regle_0_c THEN 1 ELSE 0 END) AS nb_non_cloture_0_c,
					MAX(CASE WHEN p_factures.montant_comptabilise_0_h <> p_factures.montant_regle_0_h THEN 1 ELSE 0 END) AS nb_non_cloture_0_h,
					MAX(CASE WHEN p_factures.montant_comptabilise_1_c <> p_factures.montant_regle_1_c OR p_factures.montant_comptabilise_1_h <> p_factures.montant_regle_1_h THEN 1 ELSE 0 END) AS nb_non_cloture_1,
					MAX(CASE WHEN p_factures.montant_comptabilise_1_c <> p_factures.montant_regle_1_c THEN 1 ELSE 0 END) AS nb_non_cloture_1_c,
					MAX(CASE WHEN p_factures.montant_comptabilise_1_h <> p_factures.montant_regle_1_h THEN 1 ELSE 0 END) AS nb_non_cloture_1_h,
					MAX(CASE WHEN p_factures.montant_comptabilise_2_c <> p_factures.montant_regle_2_c OR p_factures.montant_comptabilise_2_h <> p_factures.montant_regle_2_h OR p_factures.montant_comptabilise_22_c <> p_factures.montant_regle_22_c OR p_factures.montant_comptabilise_22_h <> p_factures.montant_regle_22_h THEN 1 ELSE 0 END) AS nb_non_cloture_2,
					MAX(CASE WHEN p_factures.montant_comptabilise_2_c <> p_factures.montant_regle_2_c OR p_factures.montant_comptabilise_22_c <> p_factures.montant_regle_22_c THEN 1 ELSE 0 END) AS nb_non_cloture_2_c,
					MAX(CASE WHEN p_factures.montant_comptabilise_2_h <> p_factures.montant_regle_2_h OR p_factures.montant_comptabilise_22_h <> p_factures.montant_regle_22_h THEN 1 ELSE 0 END) AS nb_non_cloture_2_h,
					0::numeric AS nb_rubriques_c,
					0::numeric AS nb_rubriques_h
				FROM activite.p_sejours
					JOIN activite.p_factures ON p_factures.no_sejour = p_sejours.no_sejour
					JOIN activite.t_lieux ON p_sejours.lieu_sortie_id = t_lieux.oid
					JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
				WHERE t_services_facturation.est_sans_facturation IS DISTINCT FROM '1' AND
					code_prevu <> 1
				GROUP BY 1,2,3,4,5,6,7,8,9;
                
                -- Cas des seances avec un séjour sur l'année (découpées en mois au GHM Grenoble)
				UPDATE w_factures_reference
				SET date_debut_facture = p_factures.date_debut, date_fin_facture = p_factures.date_fin
				FROM activite.p_factures
				JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				WHERE w_factures_reference.no_facture_reference = p_factures.no_facture AND
					w_factures_reference.no_facture_reference LIKE '%BG' AND
					p_sejours.type_sejour = '5'
				;
                
				-- Cas des séjours SSR avec plusieurs factures de references 'recuperationde la bonne date de debut de facture'
				UPDATE w_factures_reference
				SET date_debut_facture = p_factures.date_debut, date_fin_facture = p_factures.date_fin
				FROM activite.p_factures
				JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				WHERE w_factures_reference.no_facture_reference = p_factures.no_facture 
                AND type_t2a = '2' ;
				
				-- comptage des rubriques dans les lignes clinique avant généaration des lignes cliniques 0ETS
				WITH w_fac AS
				(
					SELECT 
						p_factures.no_sejour,
						COUNT(DISTINCT p_factures_lignes_c.rubrique_facturation_id) as nb_rubriques_c
					FROM
						activite.p_factures
						JOIN activite.p_factures_lignes_c ON p_factures_lignes_c.no_facture = p_factures.no_facture
					GROUP BY 1
				)
				UPDATE w_factures_reference SET
					nb_rubriques_c = w_fac.nb_rubriques_c
				FROM
					w_fac
				WHERE
					w_fac.no_sejour = w_factures_reference.no_sejour;
				
				-- idem avec les lignes honoraires
				WITH w_fac AS
				(
					SELECT 
						p_factures.no_sejour,
						COUNT(DISTINCT p_factures_lignes_h.rubrique_facturation_id) as nb_rubriques_h
					FROM
						activite.p_factures
						JOIN activite.p_factures_lignes_h ON p_factures_lignes_h.no_facture = p_factures.no_facture
					GROUP BY 1
				)
				UPDATE w_factures_reference SET
					nb_rubriques_h = w_fac.nb_rubriques_h
				FROM
					w_fac
				WHERE
					w_fac.no_sejour = w_factures_reference.no_sejour;

				-- Mise à jour des dates	
					
				UPDATE w_factures_reference
				SET date_facture = date_fin_facture 
				WHERE date_facture < date_fin_facture;


				UPDATE w_factures_reference
				SET date_groupage = date_facture 
				WHERE date_groupage < date_sortie AND
					date_groupage <> '20991231' AND
					code_sorti = '1' AND
					ghs_id <> 0;



				UPDATE w_factures_reference
				SET date_groupage = date_facture 
				WHERE date_groupage > date_facture AND
					date_groupage <> '20991231' AND
					ghs_id <> 0;


				UPDATE w_factures_reference
				SET date_facture = '20991231'
				WHERE nb_non_calcules = 1 AND date_facture <> '20991231';



				UPDATE w_factures_reference SET
					date_expedition = CASE WHEN date_expedition < '15000101' THEN '20991231' ELSE date_expedition END,
					date_expedition_0 = CASE WHEN date_expedition_0 < '15000101' THEN '20991231' ELSE date_expedition_0 END,
					date_expedition_1 = CASE WHEN date_expedition_1 < '15000101' THEN '20991231' ELSE date_expedition_1 END,
					date_expedition_2 = CASE WHEN date_expedition_2 < '15000101' THEN '20991231' ELSE date_expedition_2 END,
					date_solde = CASE WHEN date_solde < '15000101' THEN '20991231' ELSE date_solde END,
					date_solde_c = CASE WHEN date_solde_c < '15000101' THEN '20991231' ELSE date_solde_c END,
					date_solde_0_c = CASE WHEN date_solde_0_c < '15000101' THEN '20991231' ELSE date_solde_0_c END,
					date_solde_1_c = CASE WHEN date_solde_1_c < '15000101' THEN '20991231' ELSE date_solde_1_c END,
					date_solde_2_c = CASE WHEN date_solde_2_c < '15000101' THEN '20991231' ELSE date_solde_2_c END,
					date_solde_h = CASE WHEN date_solde_h < '15000101' THEN '20991231' ELSE date_solde_h END,
					date_solde_0_h = CASE WHEN date_solde_0_h < '15000101' THEN '20991231' ELSE date_solde_0_h END,
					date_solde_1_h = CASE WHEN date_solde_1_h < '15000101' THEN '20991231' ELSE date_solde_1_h END,
					date_solde_2_h = CASE WHEN date_solde_2_h < '15000101' THEN '20991231' ELSE date_solde_2_h END
				WHERE (
					date_expedition < '15000101' OR
					date_expedition_0 < '15000101' OR
					date_expedition_1 < '15000101' OR
					date_expedition_2 < '15000101' OR
					date_solde < '15000101' OR
					date_solde_c < '15000101' OR
					date_solde_0_c < '15000101' OR
					date_solde_1_c < '15000101' OR
					date_solde_2_c < '15000101' OR
					date_solde_h < '15000101' OR
					date_solde_0_h < '15000101' OR
					date_solde_1_h < '15000101' OR
					date_solde_2_h < '15000101'
					);


				UPDATE w_factures_reference SET
					date_expedition = CASE WHEN date_expedition < date_facture THEN date_facture ELSE date_expedition END,
					date_expedition_0 = CASE WHEN date_expedition_0 < date_facture AND code_expedie_0 = '1' THEN date_facture ELSE date_expedition_0 END,
					date_expedition_1 = CASE WHEN date_expedition_1 < date_facture AND code_expedie_1 = '1' THEN date_facture ELSE date_expedition_1 END,
					date_expedition_2 = CASE WHEN date_expedition_2 < date_facture AND code_expedie_2 = '1' THEN date_facture ELSE date_expedition_2 END
				WHERE date_expedition < date_facture OR
					date_expedition_0 < date_facture AND code_expedie_0 = '1' OR
					date_expedition_1 < date_facture AND code_expedie_1 = '1' OR
					date_expedition_2 < date_facture AND code_expedie_2 = '1' ;
					
				
				-- Ajustement dates de solde 				
				DROP TABLE IF EXISTS w_correction_date_c;
				CREATE TEMP TABLE w_correction_date_c AS
				SELECT p_factures.no_facture_reference, p_factures.no_sejour,
					MAX(p_factures_reference.date_solde_0_c) AS date_solde_0_c_old,
					MAX(p_factures_reference.date_solde_1_c) AS date_solde_1_c_old,
					MAX(p_factures_reference.date_solde_2_c) AS date_solde_2_c_old,
					MAX(CASE 
						WHEN p_factures_reference.montant_comptabilise_0_c = 0 THEN '00010101' 
						WHEN p_factures_reference.montant_comptabilise_0_c = p_factures_reference.montant_regle_0_c AND 
							p_factures_reference.date_solde_0_c = '20991231' AND 
							p_factures_reference.montant_comptabilise_0_c <> 0 AND 
							p_factures_soldes_c.montant_regle_0 <> 0 
							THEN date_comptable 
						ELSE NULL END) AS date_solde_0_c_new,
					MAX(CASE 
						WHEN p_factures_reference.montant_comptabilise_1_c = 0 THEN '00010101' 
						WHEN p_factures_reference.montant_comptabilise_1_c = p_factures_reference.montant_regle_1_c AND 
							p_factures_reference.date_solde_1_c = '20991231' AND 
							p_factures_reference.montant_comptabilise_1_c <> 0 AND 
							p_factures_reference.date_solde_1_c = '20991231' AND 
							p_factures_soldes_c.montant_regle_1 <> 0 
							THEN date_comptable 
						ELSE NULL END) AS date_solde_1_c_new,
					MAX(CASE 
						WHEN p_factures_reference.montant_comptabilise_2_c = 0 THEN '00010101' 
						WHEN p_factures_reference.montant_comptabilise_2_c = p_factures_reference.montant_regle_2_c AND 
							p_factures_reference.date_solde_2_c = '20991231' AND 
							p_factures_reference.montant_comptabilise_2_c <> 0 AND 
							p_factures_reference.date_solde_2_c = '20991231' AND 
							p_factures_soldes_c.montant_regle_2 <> 0 
							THEN date_comptable 
						ELSE NULL END) AS date_solde_2_c_new
				FROM activite.p_factures
				JOIN w_factures_reference p_factures_reference ON p_factures.no_facture_reference = p_factures_reference.no_facture_reference
				LEFT JOIN activite.p_factures_soldes_c ON p_factures.no_facture = p_factures_soldes_c.no_facture AND p_factures_soldes_c.montant_regle <> 0 
				GROUP BY 1,2
				;

		  
				UPDATE w_factures_reference p_factures_reference SET
					date_solde_c = 
						CASE WHEN GREATEST(COALESCE(date_solde_0_c_new,date_solde_0_c),COALESCE(date_solde_1_c_new,date_solde_1_c),COALESCE(date_solde_2_c_new,date_solde_2_c)) <> '00010101' 
						THEN GREATEST(COALESCE(date_solde_0_c_new,date_solde_0_c),COALESCE(date_solde_1_c_new,date_solde_1_c),COALESCE(date_solde_2_c_new,date_solde_2_c)) 
						ELSE '20991231' END,
					date_solde_0_c = CASE WHEN COALESCE(date_solde_0_c_new,date_solde_0_c) <> '00010101' THEN COALESCE(date_solde_0_c_new,date_solde_0_c) ELSE '20991231' END,
					date_solde_1_c = CASE WHEN COALESCE(date_solde_1_c_new,date_solde_1_c) <> '00010101' THEN COALESCE(date_solde_1_c_new,date_solde_1_c) ELSE '20991231' END,
					date_solde_2_c = CASE WHEN COALESCE(date_solde_2_c_new,date_solde_2_c) <> '00010101' THEN COALESCE(date_solde_2_c_new,date_solde_2_c) ELSE '20991231' END
				FROM w_correction_date_c
				WHERE p_factures_reference.no_facture_reference = w_correction_date_c.no_facture_reference AND
					(
					date_solde_c <> CASE WHEN GREATEST(COALESCE(date_solde_0_c_new,date_solde_0_c),COALESCE(date_solde_1_c_new,date_solde_1_c),COALESCE(date_solde_2_c_new,date_solde_2_c)) <> '00010101' 
						THEN GREATEST(COALESCE(date_solde_0_c_new,date_solde_0_c),COALESCE(date_solde_1_c_new,date_solde_1_c),COALESCE(date_solde_2_c_new,date_solde_2_c)) 
						ELSE '20991231' END OR
					date_solde_0_c <> CASE WHEN COALESCE(date_solde_0_c_new,date_solde_0_c) <> '00010101' THEN COALESCE(date_solde_0_c_new,date_solde_0_c) ELSE '20991231' END OR
					date_solde_1_c <> CASE WHEN COALESCE(date_solde_1_c_new,date_solde_1_c) <> '00010101' THEN COALESCE(date_solde_1_c_new,date_solde_1_c) ELSE '20991231' END OR
					date_solde_2_c <> CASE WHEN COALESCE(date_solde_2_c_new,date_solde_2_c) <> '00010101' THEN COALESCE(date_solde_2_c_new,date_solde_2_c) ELSE '20991231' END
					)
				;
				
				-- Ajustement dates de solde 				
				DROP TABLE IF EXISTS w_correction_date_h;
				CREATE TEMP TABLE w_correction_date_h AS
				SELECT p_factures.no_facture_reference, p_factures.no_sejour,
					MAX(p_factures_reference.date_solde_0_h) AS date_solde_0_h_old,
					MAX(p_factures_reference.date_solde_1_h) AS date_solde_1_h_old,
					MAX(p_factures_reference.date_solde_2_h) AS date_solde_2_h_old,
					MAX(CASE 
						WHEN p_factures_reference.montant_comptabilise_0_h = 0 THEN '00010101' 
						WHEN p_factures_reference.montant_comptabilise_0_h = p_factures_reference.montant_regle_0_h AND 
							p_factures_reference.date_solde_0_h = '20991231' AND 
							p_factures_reference.montant_comptabilise_0_h <> 0 AND 
							p_factures_soldes_h.montant_regle_0 <> 0 
							THEN date_comptable 
						ELSE NULL END) AS date_solde_0_h_new,
					MAX(CASE 
						WHEN p_factures_reference.montant_comptabilise_1_h = 0 THEN '00010101' 
						WHEN p_factures_reference.montant_comptabilise_1_h = p_factures_reference.montant_regle_1_h AND 
							p_factures_reference.date_solde_1_h = '20991231' AND 
							p_factures_reference.montant_comptabilise_1_h <> 0 AND 
							p_factures_reference.date_solde_1_h = '20991231' AND 
							p_factures_soldes_h.montant_regle_1 <> 0 
							THEN date_comptable 
						ELSE NULL END) AS date_solde_1_h_new,
					MAX(CASE 
						WHEN p_factures_reference.montant_comptabilise_2_h = 0 THEN '00010101' 
						WHEN p_factures_reference.montant_comptabilise_2_h = p_factures_reference.montant_regle_2_h AND 
							p_factures_reference.date_solde_2_h = '20991231' AND 
							p_factures_reference.montant_comptabilise_2_h <> 0 AND 
							p_factures_reference.date_solde_2_h = '20991231' AND 
							p_factures_soldes_h.montant_regle_2 <> 0 
							THEN date_comptable 
						ELSE NULL END) AS date_solde_2_h_new
				FROM activite.p_factures
				JOIN w_factures_reference p_factures_reference ON p_factures.no_facture_reference = p_factures_reference.no_facture_reference
				LEFT JOIN activite.p_factures_soldes_h ON p_factures.no_facture = p_factures_soldes_h.no_facture AND p_factures_soldes_h.montant_regle <> 0 
				GROUP BY 1,2
				;

		  
				UPDATE w_factures_reference p_factures_reference SET
					date_solde_h = 
						CASE WHEN GREATEST(COALESCE(date_solde_0_h_new,date_solde_0_h),COALESCE(date_solde_1_h_new,date_solde_1_h),COALESCE(date_solde_2_h_new,date_solde_2_h)) <> '00010101' 
						THEN GREATEST(COALESCE(date_solde_0_h_new,date_solde_0_h),COALESCE(date_solde_1_h_new,date_solde_1_h),COALESCE(date_solde_2_h_new,date_solde_2_h)) 
						ELSE '20991231' END,
					date_solde_0_h = CASE WHEN COALESCE(date_solde_0_h_new,date_solde_0_h) <> '00010101' THEN COALESCE(date_solde_0_h_new,date_solde_0_h) ELSE '20991231' END,
					date_solde_1_h = CASE WHEN COALESCE(date_solde_1_h_new,date_solde_1_h) <> '00010101' THEN COALESCE(date_solde_1_h_new,date_solde_1_h) ELSE '20991231' END,
					date_solde_2_h = CASE WHEN COALESCE(date_solde_2_h_new,date_solde_2_h) <> '00010101' THEN COALESCE(date_solde_2_h_new,date_solde_2_h) ELSE '20991231' END
				FROM w_correction_date_h
				WHERE p_factures_reference.no_facture_reference = w_correction_date_h.no_facture_reference AND
					(
					date_solde_h <> CASE WHEN GREATEST(COALESCE(date_solde_0_h_new,date_solde_0_h),COALESCE(date_solde_1_h_new,date_solde_1_h),COALESCE(date_solde_2_h_new,date_solde_2_h)) <> '00010101' 
						THEN GREATEST(COALESCE(date_solde_0_h_new,date_solde_0_h),COALESCE(date_solde_1_h_new,date_solde_1_h),COALESCE(date_solde_2_h_new,date_solde_2_h)) 
						ELSE '20991231' END OR
					date_solde_0_h <> CASE WHEN COALESCE(date_solde_0_h_new,date_solde_0_h) <> '00010101' THEN COALESCE(date_solde_0_h_new,date_solde_0_h) ELSE '20991231' END OR
					date_solde_1_h <> CASE WHEN COALESCE(date_solde_1_h_new,date_solde_1_h) <> '00010101' THEN COALESCE(date_solde_1_h_new,date_solde_1_h) ELSE '20991231' END OR
					date_solde_2_h <> CASE WHEN COALESCE(date_solde_2_h_new,date_solde_2_h) <> '00010101' THEN COALESCE(date_solde_2_h_new,date_solde_2_h) ELSE '20991231' END
					)
				;


				UPDATE w_factures_reference SET
					date_solde_0 = COALESCE(GREATEST(CASE WHEN montant_facture_0_c <> 0 THEN date_solde_0_c ELSE NULL END,CASE WHEN montant_facture_0_h <> 0 THEN date_solde_0_h ELSE NULL END),'20991231'),
					date_solde_1 = COALESCE(GREATEST(CASE WHEN montant_facture_1_c <> 0 THEN date_solde_1_c ELSE NULL END,CASE WHEN montant_facture_1_h <> 0 THEN date_solde_1_h ELSE NULL END),'20991231'),
					date_solde_2 = COALESCE(GREATEST(CASE WHEN montant_facture_2_c <> 0 THEN date_solde_2_c ELSE NULL END,CASE WHEN montant_facture_2_h <> 0 THEN date_solde_2_h ELSE NULL END),'20991231');

				

				UPDATE w_factures_reference SET
					nb_groupe = CASE WHEN type_t2a = '1' AND type_sejour IN ('1','2','5') AND ghs_id > 0 THEN 1 ELSE 0 END,
					nb_non_groupe = CASE WHEN type_t2a = '1' AND ghs_id = 0 AND nb_non_calcules = 1 THEN 1 ELSE 0 END,
					nb_calculable = CASE WHEN type_t2a = '1' AND ghs_id > 0 AND nb_non_calcules = 1 THEN 1 
								WHEN type_t2a <> '1' AND nb_non_calcules = 1 THEN 1 
								ELSE 0 END,
					nb_non_expedie = CASE WHEN montant_comptabilise_0 > montant_regle_0 AND code_expedie_0 <> '1' THEN 1 
								WHEN montant_comptabilise_1 > montant_regle_1 AND code_expedie_1 <> '1' THEN 1 	
								WHEN montant_comptabilise_2 > montant_regle_2 AND code_expedie_2 <> '1' THEN 1 
						ELSE 0 END,
					nb_non_expedie_c = CASE WHEN montant_comptabilise_0_c > montant_regle_0_c AND code_expedie_0 <> '1' THEN 1 
								WHEN montant_comptabilise_1_c > montant_regle_1_c AND code_expedie_1 <> '1' THEN 1 	
								WHEN montant_comptabilise_2_c > montant_regle_2_c AND code_expedie_2 <> '1' THEN 1 
						ELSE 0 END,
					nb_non_expedie_h = CASE WHEN montant_comptabilise_0_h > montant_regle_0_h AND code_expedie_0 <> '1' THEN 1 
								WHEN montant_comptabilise_1_h > montant_regle_1_h AND code_expedie_1 <> '1' THEN 1 	
								WHEN montant_comptabilise_2_h > montant_regle_2_h AND code_expedie_2 <> '1' THEN 1 
						ELSE 0 END,
					nb_non_expedie_0 = CASE WHEN montant_comptabilise_0 > montant_regle_0 AND code_expedie_0 <> '1' THEN 1 
						ELSE 0 END,
					nb_non_expedie_0_c = CASE WHEN montant_comptabilise_0_c > montant_regle_0_c AND code_expedie_0 <> '1' THEN 1 
						ELSE 0 END,
					nb_non_expedie_0_h = CASE WHEN montant_comptabilise_0_h > montant_regle_0_h AND code_expedie_0 <> '1' THEN 1 
						ELSE 0 END,
					nb_non_expedie_1 = CASE WHEN montant_comptabilise_1 > montant_regle_1 AND code_expedie_1 <> '1' THEN 1 
						ELSE 0 END,
					nb_non_expedie_1_c = CASE WHEN montant_comptabilise_1_c > montant_regle_1_c AND code_expedie_1 <> '1' THEN 1 
						ELSE 0 END,
					nb_non_expedie_1_h = CASE WHEN montant_comptabilise_1_h > montant_regle_1_h AND code_expedie_1 <> '1' THEN 1 
						ELSE 0 END,
					nb_non_expedie_2 = CASE WHEN montant_comptabilise_2 > montant_regle_2 AND code_expedie_2 <> '1' THEN 1 
						ELSE 0 END,
					nb_non_expedie_2_c = CASE WHEN montant_comptabilise_2_c > montant_regle_2_c AND code_expedie_2 <> '1' THEN 1 
						ELSE 0 END,
					nb_non_expedie_2_h = CASE WHEN montant_comptabilise_2_h > montant_regle_2_h AND code_expedie_2 <> '1' THEN 1 
						ELSE 0 END
				;




				UPDATE w_factures_reference SET
					delai_groupage = CASE
						    WHEN type_t2a = '1' AND ghs_id > 0 AND date_groupage <> '2099-12-31' AND code_sorti = '1' THEN date_groupage - date_sortie
						    ELSE NULL END,
					delai_facture = CASE
						    WHEN date_facture <> '2099-12-31' THEN date_facture - date_fin_facture
						    ELSE NULL END,
					delai_expedition = CASE
						    WHEN montant_facture_c + montant_facture_c <> 0 AND date_expedition <> '2099-12-31' THEN date_expedition - date_fin_facture
						    ELSE NULL END,
					delai_expedition_0 = CASE
						    WHEN montant_facture_0_c + montant_facture_0_h <> 0 AND date_expedition_0 <> '2099-12-31'THEN date_expedition_0 - date_fin_facture
						    ELSE NULL END,
					delai_expedition_1 = CASE
						    WHEN montant_facture_1_c + montant_facture_1_h <> 0 AND date_expedition_1 <> '2099-12-31'THEN date_expedition_1 - date_fin_facture
						    ELSE NULL END,
					delai_expedition_2 = CASE
						    WHEN montant_facture_2_c + montant_facture_2_h <> 0 AND date_expedition_2 <> '2099-12-31'THEN date_expedition_2 - date_fin_facture
						    ELSE NULL END,
					delai_solde = CASE
						    WHEN montant_comptabilise_c + montant_comptabilise_h <> 0 AND date_solde <> '2099-12-31' THEN date_solde - date_fin_facture
						    ELSE NULL END,
					delai_solde_c = CASE
						    WHEN montant_comptabilise_c <> 0 AND date_solde_c <> '2099-12-31' THEN date_solde_c - date_fin_facture
						    ELSE NULL END,
					delai_solde_h = CASE
						    WHEN montant_comptabilise_h <> 0 AND date_solde_h <> '2099-12-31' THEN date_solde_h - date_fin_facture
						    ELSE NULL END,
					delai_solde_0 = CASE
						    WHEN montant_comptabilise_0 <> 0 AND date_solde_0 <> '2099-12-31' THEN date_solde_0 - date_fin_facture
						    ELSE NULL END,
					delai_solde_0_c = CASE
						    WHEN montant_comptabilise_0_c <> 0 AND date_solde_0_c <> '2099-12-31' THEN date_solde_0_c - date_fin_facture
						    ELSE NULL END,
					delai_solde_0_h = CASE
						    WHEN montant_comptabilise_0_h <> 0 AND date_solde_0_h <> '2099-12-31' THEN date_solde_0_h - date_fin_facture
						    ELSE NULL END,
					delai_solde_1 = CASE
						    WHEN montant_comptabilise_1 <> 0 AND date_solde_1 <> '2099-12-31' THEN date_solde_1 - date_fin_facture
						    ELSE NULL END,
					delai_solde_1_c = CASE
						    WHEN montant_comptabilise_1_c <> 0 AND date_solde_1_c <> '2099-12-31' THEN date_solde_1_c - date_fin_facture
						    ELSE NULL END,
					delai_solde_1_h = CASE
						    WHEN montant_comptabilise_1_h <> 0 AND date_solde_1_h <> '2099-12-31' THEN date_solde_1_h - date_fin_facture
						    ELSE NULL END,
					delai_solde_2 = CASE
						    WHEN montant_comptabilise_2 <> 0 AND date_solde_2 <> '2099-12-31' THEN date_solde_2 - date_fin_facture
						    ELSE NULL END,
					delai_solde_2_c = CASE
						    WHEN montant_comptabilise_2_c <> 0 AND date_solde_2_c <> '2099-12-31' THEN date_solde_2_c - date_fin_facture
						    ELSE NULL END,
					delai_solde_2_h = CASE
						    WHEN montant_comptabilise_2_h <> 0 AND date_solde_2_h <> '2099-12-31' THEN date_solde_2_h - date_fin_facture
						    ELSE NULL END,
					nb_non_solde = CASE
						    WHEN code_facture <> '1'::bpchar THEN 0
						    WHEN montant_comptabilise_0_c <> montant_regle_0_c THEN 1
						    WHEN montant_comptabilise_0_h <> montant_regle_0_h THEN 1
						    WHEN montant_comptabilise_1_c <> montant_regle_1_c THEN 1
						    WHEN montant_comptabilise_1_h <> montant_regle_1_h THEN 1
						    WHEN montant_comptabilise_2_c <> montant_regle_2_c THEN 1
						    WHEN montant_comptabilise_2_h <> montant_regle_2_h THEN 1
						    ELSE 0
						END,
					nb_non_solde_c = CASE
						    WHEN code_facture <> '1'::bpchar THEN 0
						    WHEN montant_comptabilise_0_c <> montant_regle_0_c THEN 1
						    WHEN montant_comptabilise_1_c <> montant_regle_1_c THEN 1
						    WHEN montant_comptabilise_2_c <> montant_regle_2_c THEN 1
						    ELSE 0
						END,
					nb_non_solde_h = CASE
						    WHEN code_facture <> '1'::bpchar THEN 0
						    WHEN montant_comptabilise_0_h <> montant_regle_0_h THEN 1
						    WHEN montant_comptabilise_1_h <> montant_regle_1_h THEN 1
						    WHEN montant_comptabilise_2_h <> montant_regle_2_h THEN 1
						    ELSE 0
						END,
					nb_non_solde_0 = CASE
						    WHEN code_facture <> '1'::bpchar THEN 0
						    WHEN montant_comptabilise_0_c <> montant_regle_0_c THEN 1
						    WHEN montant_comptabilise_0_h <> montant_regle_0_h THEN 1
						    ELSE 0
						END,
					nb_non_solde_0_c = CASE
						    WHEN code_facture <> '1'::bpchar THEN 0
						    WHEN montant_comptabilise_0_c <> montant_regle_0_c THEN 1
						    ELSE 0
						END,
					nb_non_solde_0_h = CASE
						    WHEN code_facture <> '1'::bpchar THEN 0
						    WHEN montant_comptabilise_0_h <> montant_regle_0_h THEN 1
						    ELSE 0
						END,
					nb_non_solde_1 = CASE
						    WHEN code_facture <> '1'::bpchar THEN 0
						    WHEN montant_comptabilise_1_c <> montant_regle_1_c THEN 1
						    WHEN montant_comptabilise_1_h <> montant_regle_1_h THEN 1
						    ELSE 0
						END,
					nb_non_solde_1_c = CASE
						    WHEN code_facture <> '1'::bpchar THEN 0
						    WHEN montant_comptabilise_1_c <> montant_regle_1_c THEN 1
						    ELSE 0
						END,
					nb_non_solde_1_h = CASE
						    WHEN code_facture <> '1'::bpchar THEN 0
						    WHEN montant_comptabilise_1_h <> montant_regle_1_h THEN 1
						    ELSE 0
						END,
					nb_non_solde_2 = CASE
						    WHEN code_facture <> '1'::bpchar THEN 0
						    WHEN montant_comptabilise_2_c <> montant_regle_2_c THEN 1
						    WHEN montant_comptabilise_2_h <> montant_regle_2_h THEN 1
						    ELSE 0
						END,
					nb_non_solde_2_c = CASE
						    WHEN code_facture <> '1'::bpchar THEN 0
						    WHEN montant_comptabilise_2_c <> montant_regle_2_c THEN 1
						    ELSE 0
						END,
					nb_non_solde_2_h = CASE
						    WHEN code_facture <> '1'::bpchar THEN 0
						    WHEN montant_comptabilise_2_h <> montant_regle_2_h THEN 1
						    ELSE 0
						END;
						
						
				-- Retard de groupage et de facturation
				
				-- Période en semaine pleine pour calcul coefficients
				DROP TABLE IF EXISTS w_periode;
				CREATE TABLE w_periode AS
				SELECT 
					MAX(CASE WHEN jour_semaine = 1 AND date <= date(t_divers.valeur_date - interval '1 year') THEN date ELSE NULL END) AS date_debut_periode,
					MAX(CASE WHEN jour_semaine = 7 AND date <= t_divers.valeur_date THEN date ELSE NULL END) AS date_fin_periode,
					(MAX(CASE WHEN jour_semaine = 7 AND date <= t_divers.valeur_date THEN date ELSE NULL END) - 
						MAX(CASE WHEN jour_semaine = 1 AND date <= date(t_divers.valeur_date - interval '1 year') THEN date ELSE NULL END) 
						+ 1) AS duree_periode
				FROM base.p_calendrier
				JOIN activite.t_divers ON t_divers.code = 'NOW' AND p_calendrier.date <= t_divers.valeur_date;

				-- Calcul durée groupage par dossier (coeff journalier)
				DROP TABLE IF EXISTS w_retard_groupage_coefficient;
				CREATE TEMP TABLE w_retard_groupage_coefficient AS
				SELECT
					MAX(date_debut_periode) AS date_debut_periode,
					MAX(duree_periode) AS duree_periode,
					SUM(CASE WHEN type_sejour NOT IN ('2','5') THEN v_factures_reference_1.nb_groupe ELSE 0 END) AS nb_groupe_h,
					SUM(CASE WHEN type_sejour NOT IN ('2','5') THEN v_factures_reference_1.delai_groupage ELSE 0 END) AS delai_groupe_h,
					SUM(CASE WHEN type_sejour IN ('2','5') THEN v_factures_reference_1.nb_groupe ELSE 0 END) AS nb_groupe_a,
					SUM(CASE WHEN type_sejour IN ('2','5') THEN v_factures_reference_1.delai_groupage ELSE 0 END) AS delai_groupe_a,
					0::numeric AS coefficient_groupage_h,
					0::numeric AS coefficient_groupage_a
				FROM w_factures_reference v_factures_reference_1
					JOIN w_periode ON
						(
						v_factures_reference_1.date_groupage BETWEEN w_periode.date_debut_periode AND w_periode.date_fin_periode
						) 
				WHERE nb_groupe = 1;
						

				UPDATE w_retard_groupage_coefficient SET
						coefficient_groupage_h = base.cti_division(base.cti_division(duree_periode, nb_groupe_h + nb_groupe_a) * base.cti_division(delai_groupe_h, nb_groupe_h)
							, base.cti_division(delai_groupe_a + delai_groupe_h, nb_groupe_a + nb_groupe_h)),
						coefficient_groupage_a = base.cti_division(base.cti_division(duree_periode, nb_groupe_h + nb_groupe_a) * base.cti_division(delai_groupe_a, nb_groupe_a)
							, base.cti_division(delai_groupe_a + delai_groupe_h, nb_groupe_a + nb_groupe_h))
						;
                        
                -- Code sortie uniquement sur dernière facture si facturations intermédiaires
                UPDATE w_factures_reference p_factures_reference
                SET code_sorti = '0'
                FROM activite.p_sejours 
                JOIN (SELECT no_sejour, (MAX(Array[date_fin_facture::text,no_facture_reference]))[2] AS no_facture_last FROM activite.p_factures_reference WHERE code_sorti = '1' GROUP BY 1 HAVING count(*) > 1) subview ON p_sejours.no_sejour = subview.no_sejour
                WHERE p_factures_reference.no_sejour = p_sejours.no_sejour AND
                    p_factures_reference.code_sorti = '1' AND
                    p_sejours.type_sejour <> '3' AND
                    p_factures_reference.no_facture_reference <> no_facture_last
                    ;


				-- Mise à jour dans table
				UPDATE w_factures_reference
				SET retard_groupage = 
					CASE WHEN type_sejour NOT IN ('2','5') THEN coefficient_groupage_h ELSE coefficient_groupage_a END
				FROM w_retard_groupage_coefficient
				WHERE nb_non_groupe = 1 AND date_sortie >= date_debut_periode;
				
				
				-- Calcul durée facturation par dossier (coeff journalier)
				DROP TABLE IF EXISTS w_retard_facture_coefficient;
				CREATE TEMP TABLE w_retard_facture_coefficient AS
				SELECT
					MAX(date_debut_periode) AS date_debut_periode,
					MAX(duree_periode) AS duree_periode,
					SUM(CASE WHEN type_sejour NOT IN ('2','3','5') THEN 1 ELSE 0 END) AS nb_facture_h,
					SUM(CASE WHEN type_sejour NOT IN ('2','3','5') THEN v_factures_reference_1.delai_facture ELSE 0 END) AS delai_facture_h,
					SUM(CASE WHEN type_sejour IN ('2','5') THEN 1 ELSE 0 END) AS nb_facture_a,
					SUM(CASE WHEN type_sejour IN ('2','5') THEN v_factures_reference_1.delai_facture ELSE 0 END) AS delai_facture_a,
					SUM(CASE WHEN type_sejour IN ('3') THEN 1 ELSE 0 END) AS nb_facture_x,
					SUM(CASE WHEN type_sejour IN ('3') THEN v_factures_reference_1.delai_facture ELSE 0 END) AS delai_facture_x,

					0::numeric AS coefficient_facture_h,
					0::numeric AS coefficient_facture_a,
					0::numeric AS coefficient_facture_x
					
				FROM w_factures_reference v_factures_reference_1
					JOIN w_periode ON
						(
						v_factures_reference_1.date_facture BETWEEN w_periode.date_debut_periode AND w_periode.date_fin_periode
						) 
				WHERE v_factures_reference_1.nb_non_calcules = 0;

				UPDATE w_retard_facture_coefficient SET
					coefficient_facture_h = base.cti_division(base.cti_division(duree_periode, nb_facture_h + nb_facture_a + nb_facture_x) * base.cti_division(delai_facture_h, nb_facture_h)
						, base.cti_division(delai_facture_a + delai_facture_h + delai_facture_x, nb_facture_a + nb_facture_h + nb_facture_x)),
					coefficient_facture_a = base.cti_division(base.cti_division(duree_periode, nb_facture_h + nb_facture_a + nb_facture_x) * base.cti_division(delai_facture_a, nb_facture_a)
						, base.cti_division(delai_facture_a + delai_facture_h + delai_facture_x, nb_facture_a + nb_facture_h + nb_facture_x)),
					coefficient_facture_x = base.cti_division(duree_periode, nb_facture_h + nb_facture_a + nb_facture_x) * 
						base.cti_division(base.cti_division(delai_facture_x, nb_facture_x), base.cti_division(delai_facture_a + delai_facture_h + delai_facture_x, nb_facture_a + nb_facture_h + nb_facture_x))
					;
				
				-- Mise à jour dans table

				UPDATE w_factures_reference
				SET retard_facture = 
					CASE WHEN type_sejour IN ('2','5') THEN coefficient_facture_a WHEN type_sejour IN ('3') THEN coefficient_facture_x ELSE coefficient_facture_h END
				FROM w_retard_facture_coefficient
				WHERE nb_non_calcules = 1 AND date_sortie >= date_debut_periode;

				-- Validation données
				SELECT base.cti_disable_index('activite', 'i_factures_reference_1');
				SELECT base.cti_disable_index('activite', 'i_factures_reference_2');
				SELECT base.cti_disable_index('activite', 'i_factures_reference_3');
				SELECT base.cti_disable_index('activite', 'i_factures_reference_4');

				TRUNCATE activite.p_factures_reference;

				INSERT INTO activite.p_factures_reference (
					sejour_id,
					no_sejour,
					date_entree,
					date_sortie,
					code_sorti,
					facture_reference_id,
					no_facture_reference,
					type_t2a,
					date_debut_facture,
					date_fin_facture,
					type_facture,
					date_groupage,
					retard_groupage,
					delai_groupage,
					nb_groupe,
					nb_non_groupe,
					nb_calculable,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					gmt_id,
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					code_facture,
					date_facture,
					retard_facture,
					delai_facture,
					code_vente,
					date_vente,
					nb_factures,
					nb_non_calcules,
                    nb_non_calcules_horsbg,
					nb_non_calcules_bg,
					nb_factures_regularisation,
					nb_rejets,
					code_expedie_0,
					code_expedie_1,
					code_expedie_2,
					date_expedition,
					date_expedition_0,
					date_expedition_1,
					date_expedition_2,
					no_bordereau_0,
					no_bordereau_1,
					no_bordereau_2,
					delai_expedition,
					delai_expedition_0,
					delai_expedition_1,
					delai_expedition_2,
					nb_non_expedie,
					nb_non_expedie_c,
					nb_non_expedie_h,
					nb_non_expedie_0,
					nb_non_expedie_0_c,
					nb_non_expedie_0_h,
					nb_non_expedie_1,
					nb_non_expedie_1_c,
					nb_non_expedie_1_h,
					nb_non_expedie_2,
					nb_non_expedie_2_c,
					nb_non_expedie_2_h,
					montant_facture,
					montant_facture_c,
					montant_facture_h,
					montant_facture_0,
					montant_facture_0_c,
					montant_facture_0_h,
					montant_facture_1,
					montant_facture_1_c,
					montant_facture_1_h,
					montant_facture_2,
					montant_facture_2_c,
					montant_facture_2_h,
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour,
					montant_encours,
					montant_encours_c,
					montant_encours_h,
					montant_encours_0,
					montant_encours_0_c,
					montant_encours_0_h,
					montant_encours_1,
					montant_encours_1_c,
					montant_encours_1_h,
					montant_encours_2,
					montant_encours_2_c,
					montant_encours_2_h,
					montant_comptabilise,
					montant_comptabilise_c,
					montant_comptabilise_h,
					montant_comptabilise_0,
					montant_comptabilise_0_c,
					montant_comptabilise_0_h,
					montant_comptabilise_1,
					montant_comptabilise_1_c,
					montant_comptabilise_1_h,
					montant_comptabilise_2,
					montant_comptabilise_2_c,
					montant_comptabilise_2_h,
					montant_comptabilise_budget_global_c,
					montant_regle,
					montant_regle_c,
					montant_regle_h,
					montant_regle_0,
					montant_regle_0_c,
					montant_regle_0_h,
					montant_regle_1,
					montant_regle_1_c,
					montant_regle_1_h,
					montant_regle_2,
					montant_regle_2_c,
					montant_regle_2_h,
					date_solde,
					date_solde_c,
					date_solde_h,
					date_solde_0,
					date_solde_0_c,
					date_solde_0_h,
					date_solde_1,
					date_solde_1_c,
					date_solde_1_h,
					date_solde_2,
					date_solde_2_c,
					date_solde_2_h,
					delai_solde,
					delai_solde_c,
					delai_solde_h,
					delai_solde_0,
					delai_solde_0_c,
					delai_solde_0_h,
					delai_solde_1,
					delai_solde_1_c,
					delai_solde_1_h,
					delai_solde_2,
					delai_solde_2_c,
					delai_solde_2_h,
					nb_non_solde,
					nb_non_solde_c,
					nb_non_solde_h,
					nb_non_solde_0,
					nb_non_solde_0_c,
					nb_non_solde_0_h,
					nb_non_solde_1,
					nb_non_solde_1_c,
					nb_non_solde_1_h,
					nb_non_solde_2,
					nb_non_solde_2_c,
					nb_non_solde_2_h,
					nb_non_cloture,
					nb_non_cloture_c,
					nb_non_cloture_h,
					nb_non_cloture_0,
					nb_non_cloture_0_c,
					nb_non_cloture_0_h,
					nb_non_cloture_1,
					nb_non_cloture_1_c,
					nb_non_cloture_1_h,
					nb_non_cloture_2,
					nb_non_cloture_2_c,
					nb_non_cloture_2_h,
					nb_rubriques_c,
					nb_rubriques_h
					)
				SELECT 
					sejour_id,
					no_sejour,
					date_entree,
					date_sortie,
					code_sorti,
					facture_reference_id,
					no_facture_reference,
					type_t2a,
					date_debut_facture,
					date_fin_facture,
					type_facture,
					date_groupage,
					retard_groupage,
					delai_groupage,
					nb_groupe,
					nb_non_groupe,
					nb_calculable,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					gmt_id,
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					code_facture,
					date_facture,
					retard_facture,
					delai_facture,
					code_vente,
					date_vente,
					nb_factures,
					nb_non_calcules,
                    nb_non_calcules_horsbg,
					nb_non_calcules_bg,
					nb_factures_regularisation,
					nb_rejets,
					code_expedie_0,
					code_expedie_1,
					code_expedie_2,
					date_expedition,
					date_expedition_0,
					date_expedition_1,
					date_expedition_2,
					no_bordereau_0,
					no_bordereau_1,
					no_bordereau_2,
					delai_expedition,
					delai_expedition_0,
					delai_expedition_1,
					delai_expedition_2,
					nb_non_expedie,
					nb_non_expedie_c,
					nb_non_expedie_h,
					nb_non_expedie_0,
					nb_non_expedie_0_c,
					nb_non_expedie_0_h,
					nb_non_expedie_1,
					nb_non_expedie_1_c,
					nb_non_expedie_1_h,
					nb_non_expedie_2,
					nb_non_expedie_2_c,
					nb_non_expedie_2_h,
					montant_facture,
					montant_facture_c,
					montant_facture_h,
					montant_facture_0,
					montant_facture_0_c,
					montant_facture_0_h,
					montant_facture_1,
					montant_facture_1_c,
					montant_facture_1_h,
					montant_facture_2,
					montant_facture_2_c,
					montant_facture_2_h,
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour,
					montant_encours,
					montant_encours_c,
					montant_encours_h,
					montant_encours_0,
					montant_encours_0_c,
					montant_encours_0_h,
					montant_encours_1,
					montant_encours_1_c,
					montant_encours_1_h,
					montant_encours_2,
					montant_encours_2_c,
					montant_encours_2_h,
					montant_comptabilise,
					montant_comptabilise_c,
					montant_comptabilise_h,
					montant_comptabilise_0,
					montant_comptabilise_0_c,
					montant_comptabilise_0_h,
					montant_comptabilise_1,
					montant_comptabilise_1_c,
					montant_comptabilise_1_h,
					montant_comptabilise_2,
					montant_comptabilise_2_c,
					montant_comptabilise_2_h,
					montant_comptabilise_budget_global_c,
					montant_regle,
					montant_regle_c,
					montant_regle_h,
					montant_regle_0,
					montant_regle_0_c,
					montant_regle_0_h,
					montant_regle_1,
					montant_regle_1_c,
					montant_regle_1_h,
					montant_regle_2,
					montant_regle_2_c,
					montant_regle_2_h,
					date_solde,
					date_solde_c,
					date_solde_h,
					date_solde_0,
					date_solde_0_c,
					date_solde_0_h,
					date_solde_1,
					date_solde_1_c,
					date_solde_1_h,
					date_solde_2,
					date_solde_2_c,
					date_solde_2_h,
					delai_solde,
					delai_solde_c,
					delai_solde_h,
					delai_solde_0,
					delai_solde_0_c,
					delai_solde_0_h,
					delai_solde_1,
					delai_solde_1_c,
					delai_solde_1_h,
					delai_solde_2,
					delai_solde_2_c,
					delai_solde_2_h,
					nb_non_solde,
					nb_non_solde_c,
					nb_non_solde_h,
					nb_non_solde_0,
					nb_non_solde_0_c,
					nb_non_solde_0_h,
					nb_non_solde_1,
					nb_non_solde_1_c,
					nb_non_solde_1_h,
					nb_non_solde_2,
					nb_non_solde_2_c,
					nb_non_solde_2_h,
					nb_non_cloture,
					nb_non_cloture_c,
					nb_non_cloture_h,
					nb_non_cloture_0,
					nb_non_cloture_0_c,
					nb_non_cloture_0_h,
					nb_non_cloture_1,
					nb_non_cloture_1_c,
					nb_non_cloture_1_h,
					nb_non_cloture_2,
					nb_non_cloture_2_c,
					nb_non_cloture_2_h,
					nb_rubriques_c,
					nb_rubriques_h
				FROM w_factures_reference;
				
				ANALYSE activite.p_factures_reference
				;


				SELECT base.cti_enable_index('activite', 'i_factures_reference_1');
				SELECT base.cti_enable_index('activite', 'i_factures_reference_2');
				SELECT base.cti_enable_index('activite', 'i_factures_reference_3');
				SELECT base.cti_enable_index('activite', 'i_factures_reference_4');


				

				SELECT base.cti_disable_index('activite', 'i_factures_reference_tiers_1');
				SELECT base.cti_disable_index('activite', 'i_factures_reference_tiers_2');
				SELECT base.cti_disable_index('activite', 'i_factures_reference_tiers_3');
				SELECT base.cti_disable_index('activite', 'i_factures_reference_tiers_4');


				TRUNCATE activite.p_factures_reference_tiers;


				INSERT INTO activite.p_factures_reference_tiers (
					sejour_id,
					no_sejour,
					date_entree,
					date_sortie,
					code_sorti,
					facture_reference_id,
					no_facture_reference,
					type_t2a,
					date_debut_facture,
					date_fin_facture,
					type_facture,
					date_groupage,
					retard_groupage,
					delai_groupage,
					nb_groupe,
					nb_non_groupe,
					nb_calculable,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					gmt_id,
					tiers_payant_id,
					code_facture,
					date_facture,
					retard_facture,
					delai_facture,
					code_vente,
					date_vente,
					nb_factures,
					nb_non_calcules,
                    nb_non_calcules_horsbg,
					nb_non_calcules_bg,
					nb_factures_regularisation,
					nb_rejets,
					code_expedie_0,
					code_expedie_1,
					code_expedie_2,
					date_expedition,
					date_expedition_0,
					date_expedition_1,
					date_expedition_2,
					no_bordereau_0,
					no_bordereau_1,
					no_bordereau_2,
					delai_expedition,
					delai_expedition_0,
					delai_expedition_1,
					delai_expedition_2,
					nb_non_expedie,
					nb_non_expedie_c,
					nb_non_expedie_h,
					nb_non_expedie_0,
					nb_non_expedie_0_c,
					nb_non_expedie_0_h,
					nb_non_expedie_1,
					nb_non_expedie_1_c,
					nb_non_expedie_1_h,
					nb_non_expedie_2,
					nb_non_expedie_2_c,
					nb_non_expedie_2_h,
					montant_facture,
					montant_facture_c,
					montant_facture_h,
					montant_facture_0,
					montant_facture_0_c,
					montant_facture_0_h,
					montant_facture_1,
					montant_facture_1_c,
					montant_facture_1_h,
					montant_facture_2,
					montant_facture_2_c,
					montant_facture_2_h,
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour,
					montant_encours,
					montant_encours_c,
					montant_encours_h,
					montant_encours_0,
					montant_encours_0_c,
					montant_encours_0_h,
					montant_encours_1,
					montant_encours_1_c,
					montant_encours_1_h,
					montant_encours_2,
					montant_encours_2_c,
					montant_encours_2_h,
					montant_comptabilise,
					montant_comptabilise_c,
					montant_comptabilise_h,
					montant_comptabilise_0,
					montant_comptabilise_0_c,
					montant_comptabilise_0_h,
					montant_comptabilise_1,
					montant_comptabilise_1_c,
					montant_comptabilise_1_h,
					montant_comptabilise_2,
					montant_comptabilise_2_c,
					montant_comptabilise_2_h,
					montant_comptabilise_budget_global_c,
					montant_regle,
					montant_regle_c,
					montant_regle_h,
					montant_regle_0,
					montant_regle_0_c,
					montant_regle_0_h,
					montant_regle_1,
					montant_regle_1_c,
					montant_regle_1_h,
					montant_regle_2,
					montant_regle_2_c,
					montant_regle_2_h,
					date_solde,
					date_solde_c,
					date_solde_h,
					date_solde_0,
					date_solde_0_c,
					date_solde_0_h,
					date_solde_1,
					date_solde_1_c,
					date_solde_1_h,
					date_solde_2,
					date_solde_2_c,
					date_solde_2_h,
					delai_solde,
					delai_solde_c,
					delai_solde_h,
					delai_solde_0,
					delai_solde_0_c,
					delai_solde_0_h,
					delai_solde_1,
					delai_solde_1_c,
					delai_solde_1_h,
					delai_solde_2,
					delai_solde_2_c,
					delai_solde_2_h,
					nb_non_solde,
					nb_non_solde_c,
					nb_non_solde_h,
					nb_non_solde_0,
					nb_non_solde_0_c,
					nb_non_solde_0_h,
					nb_non_solde_1,
					nb_non_solde_1_c,
					nb_non_solde_1_h,
					nb_non_solde_2,
					nb_non_solde_2_c,
					nb_non_solde_2_h,
					nb_non_cloture,
					nb_non_cloture_c,
					nb_non_cloture_h,
					nb_non_cloture_0,
					nb_non_cloture_0_c,
					nb_non_cloture_0_h,
					nb_non_cloture_1,
					nb_non_cloture_1_c,
					nb_non_cloture_1_h,
					nb_non_cloture_2,
					nb_non_cloture_2_c,
					nb_non_cloture_2_h
					)
				SELECT 
					sejour_id,
					no_sejour,
					date_entree,
					date_sortie,
					code_sorti,
					facture_reference_id,
					no_facture_reference,
					type_t2a,
					date_debut_facture,
					date_fin_facture,
					type_facture,
					date_groupage,
					CASE WHEN tiers_payant_1_id = 0 AND tiers_payant_2_id = 0 THEN retard_groupage ELSE 0 END,
					delai_groupage,
					nb_groupe,
					nb_non_groupe,
					nb_calculable,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					gmt_id,
					tiers_payant_0_id AS tiers_payant_id,
					code_facture,
					date_facture,
					CASE WHEN tiers_payant_1_id = 0 AND tiers_payant_2_id = 0 THEN retard_facture ELSE 0 END,
					delai_facture,
					code_vente,
					date_vente,
					nb_factures,
					nb_non_calcules,
                    nb_non_calcules_horsbg,
					nb_non_calcules_bg,
					nb_factures_regularisation,
					nb_rejets,
					code_expedie_0 AS code_expedie_0,
					'0' AS code_expedie_1,
					'0' AS code_expedie_2,
					date_expedition_0 AS date_expedition,
					date_expedition_0,
					NULL::date AS date_expedition_1,
					NULL::date AS date_expedition_2,
					no_bordereau_0,
					'' AS no_bordereau_1,
					'' AS no_bordereau_2,
					delai_expedition_0 AS delai_expedition,
					delai_expedition_0,
					NULL::numeric AS delai_expedition_1,
					NULL::numeric AS delai_expedition_2,
					nb_non_expedie_0 AS nb_non_expedie,
					nb_non_expedie_0_c AS nb_non_expedie_c,
					nb_non_expedie_0_h AS nb_non_expedie_h,
					nb_non_expedie_0,
					nb_non_expedie_0_c,
					nb_non_expedie_0_h,
					0 AS nb_non_expedie_1,
					0 AS nb_non_expedie_1_c,
					0 AS nb_non_expedie_1_h,
					0 AS nb_non_expedie_2,
					0 AS nb_non_expedie_2_c,
					0 AS nb_non_expedie_2_h,
					montant_facture_0 AS montant_facture,
					montant_facture_0_c AS montant_facture_c,
					montant_facture_0_h AS montant_facture_h,
					montant_facture_0,
					montant_facture_0_c,
					montant_facture_0_h,
					0 AS montant_facture_1,
					0 AS montant_facture_1_c,
					0 AS montant_facture_1_h,
					0 AS montant_facture_2,
					0 AS montant_facture_2_c,
					0 AS montant_facture_2_h,
					0 AS montant_facture_c_actes_inclus_dans_sejour,
					0 AS montant_facture_h_actes_inclus_dans_sejour,
					montant_encours_0 AS montant_encours,
					montant_encours_0_c AS montant_encours_c,
					montant_encours_0_h AS montant_encours_h,
					montant_encours_0,
					montant_encours_0_c,
					montant_encours_0_h,
					0 AS montant_encours_1,
					0 AS montant_encours_1_c,
					0 AS montant_encours_1_h,
					0 AS montant_encours_2,
					0 AS montant_encours_2_c,
					0 AS montant_encours_2_h,
					montant_comptabilise_0 AS montant_comptabilise,
					montant_comptabilise_0_c AS montant_comptabilise_c,
					montant_comptabilise_0_h AS montant_comptabilise_h,
					montant_comptabilise_0,
					montant_comptabilise_0_c,
					montant_comptabilise_0_h,
					0 AS montant_comptabilise_1,
					0 AS montant_comptabilise_1_c,
					0 AS montant_comptabilise_1_h,
					0 AS montant_comptabilise_2,
					0 AS montant_comptabilise_2_c,
					0 AS montant_comptabilise_2_h,
					0 AS montant_comptabilise_budget_global_c,
					montant_regle_0 AS montant_regle,
					montant_regle_0_c AS montant_regle_c,
					montant_regle_0_h AS montant_regle_h,
					montant_regle_0,
					montant_regle_0_c,
					montant_regle_0_h,
					0 AS montant_regle_1,
					0 AS montant_regle_1_c,
					0 AS montant_regle_1_h,
					0 AS montant_regle_2,
					0 AS montant_regle_2_c,
					0 AS montant_regle_2_h,
					date_solde_0 AS date_solde,
					date_solde_0_c AS date_solde_c,
					date_solde_0_h AS date_solde_h,
					date_solde_0,
					date_solde_0_c,
					date_solde_0_h,
					NULL::date AS date_solde_1,
					NULL::date AS date_solde_1_c,
					NULL::date AS date_solde_1_h,
					NULL::date AS date_solde_2,
					NULL::date AS date_solde_2_c,
					NULL::date AS date_solde_2_h,
					delai_solde_0 AS delai_solde,
					delai_solde_0_c AS delai_solde_c,
					delai_solde_0_h AS delai_solde_h,
					delai_solde_0,
					delai_solde_0_c,
					delai_solde_0_h,
					NULL::numeric AS delai_solde_1,
					NULL::numeric AS delai_solde_1_c,
					NULL::numeric AS delai_solde_1_h,
					NULL::numeric AS delai_solde_2,
					NULL::numeric AS delai_solde_2_c,
					NULL::numeric AS delai_solde_2_h,
					nb_non_solde_0 AS nb_non_solde,
					nb_non_solde_0_c AS nb_non_solde_c,
					nb_non_solde_0_h AS nb_non_solde_h,
					nb_non_solde_0,
					nb_non_solde_0_c,
					nb_non_solde_0_h,
					0 AS nb_non_solde_1,
					0 AS nb_non_solde_1_c,
					0 AS nb_non_solde_1_h,
					0 AS nb_non_solde_2,
					0 AS nb_non_solde_2_c,
					0 AS nb_non_solde_2_h,
					nb_non_cloture_0 AS nb_non_cloture,
					nb_non_cloture_0_c AS nb_non_cloture_c,
					nb_non_cloture_0_h AS nb_non_cloture_h,
					nb_non_cloture_0,
					nb_non_cloture_0_c,
					nb_non_cloture_0_h,
					0 AS nb_non_cloture_1,
					0 AS nb_non_cloture_1_c,
					0 AS nb_non_cloture_1_h,
					0 AS nb_non_cloture_2,
					0 AS nb_non_cloture_2_c,
					0 AS nb_non_cloture_2_h
			FROM w_factures_reference
			WHERE tiers_payant_0_id <> 0
                AND
                  (
                  montant_facture_0 <> 0 OR
                  montant_comptabilise_0 <> 0 OR
                  montant_regle_0 <> 0 OR
                  montant_encours <> 0
                  )
            ;


			INSERT INTO activite.p_factures_reference_tiers (
					sejour_id,
					no_sejour,
					date_entree,
					date_sortie,
					code_sorti,
					facture_reference_id,
					no_facture_reference,
					type_t2a,
					date_debut_facture,
					date_fin_facture,
					type_facture,
					date_groupage,
					retard_groupage,
					delai_groupage,
					nb_groupe,
					nb_non_groupe,
					nb_calculable,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					gmt_id,
					tiers_payant_id,
					code_facture,
					date_facture,
					retard_facture,
					delai_facture,
					code_vente,
					date_vente,
					nb_factures,
					nb_non_calcules,
                    nb_non_calcules_horsbg,
					nb_non_calcules_bg,
					nb_factures_regularisation,
					nb_rejets,
					code_expedie_0,
					code_expedie_1,
					code_expedie_2,
					date_expedition,
					date_expedition_0,
					date_expedition_1,
					date_expedition_2,
					no_bordereau_0,
					no_bordereau_1,
					no_bordereau_2,
					delai_expedition,
					delai_expedition_0,
					delai_expedition_1,
					delai_expedition_2,
					nb_non_expedie,
					nb_non_expedie_c,
					nb_non_expedie_h,
					nb_non_expedie_0,
					nb_non_expedie_0_c,
					nb_non_expedie_0_h,
					nb_non_expedie_1,
					nb_non_expedie_1_c,
					nb_non_expedie_1_h,
					nb_non_expedie_2,
					nb_non_expedie_2_c,
					nb_non_expedie_2_h,
					montant_facture,
					montant_facture_c,
					montant_facture_h,
					montant_facture_0,
					montant_facture_0_c,
					montant_facture_0_h,
					montant_facture_1,
					montant_facture_1_c,
					montant_facture_1_h,
					montant_facture_2,
					montant_facture_2_c,
					montant_facture_2_h,
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour,
					montant_encours,
					montant_encours_c,
					montant_encours_h,
					montant_encours_0,
					montant_encours_0_c,
					montant_encours_0_h,
					montant_encours_1,
					montant_encours_1_c,
					montant_encours_1_h,
					montant_encours_2,
					montant_encours_2_c,
					montant_encours_2_h,
					montant_comptabilise,
					montant_comptabilise_c,
					montant_comptabilise_h,
					montant_comptabilise_0,
					montant_comptabilise_0_c,
					montant_comptabilise_0_h,
					montant_comptabilise_1,
					montant_comptabilise_1_c,
					montant_comptabilise_1_h,
					montant_comptabilise_2,
					montant_comptabilise_2_c,
					montant_comptabilise_2_h,
					montant_comptabilise_budget_global_c,
					montant_regle,
					montant_regle_c,
					montant_regle_h,
					montant_regle_0,
					montant_regle_0_c,
					montant_regle_0_h,
					montant_regle_1,
					montant_regle_1_c,
					montant_regle_1_h,
					montant_regle_2,
					montant_regle_2_c,
					montant_regle_2_h,
					date_solde,
					date_solde_c,
					date_solde_h,
					date_solde_0,
					date_solde_0_c,
					date_solde_0_h,
					date_solde_1,
					date_solde_1_c,
					date_solde_1_h,
					date_solde_2,
					date_solde_2_c,
					date_solde_2_h,
					delai_solde,
					delai_solde_c,
					delai_solde_h,
					delai_solde_0,
					delai_solde_0_c,
					delai_solde_0_h,
					delai_solde_1,
					delai_solde_1_c,
					delai_solde_1_h,
					delai_solde_2,
					delai_solde_2_c,
					delai_solde_2_h,
					nb_non_solde,
					nb_non_solde_c,
					nb_non_solde_h,
					nb_non_solde_0,
					nb_non_solde_0_c,
					nb_non_solde_0_h,
					nb_non_solde_1,
					nb_non_solde_1_c,
					nb_non_solde_1_h,
					nb_non_solde_2,
					nb_non_solde_2_c,
					nb_non_solde_2_h,
					nb_non_cloture,
					nb_non_cloture_c,
					nb_non_cloture_h,
					nb_non_cloture_0,
					nb_non_cloture_0_c,
					nb_non_cloture_0_h,
					nb_non_cloture_1,
					nb_non_cloture_1_c,
					nb_non_cloture_1_h,
					nb_non_cloture_2,
					nb_non_cloture_2_c,
					nb_non_cloture_2_h
					)
				SELECT 
					sejour_id,
					no_sejour,
					date_entree,
					date_sortie,
					code_sorti,
					facture_reference_id,
					no_facture_reference,
					type_t2a,
					date_debut_facture,
					date_fin_facture,
					type_facture,
					date_groupage,
					CASE WHEN tiers_payant_1_id <> 0 THEN retard_groupage ELSE 0 END,
					delai_groupage,
					nb_groupe,
					nb_non_groupe,
					nb_calculable,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					gmt_id,
					tiers_payant_1_id AS tiers_payant_id,
					code_facture,
					date_facture,
					CASE WHEN tiers_payant_1_id <> 0 THEN retard_facture ELSE 0 END,
					delai_facture,
					code_vente,
					date_vente,
					nb_factures,
					nb_non_calcules,
                    nb_non_calcules_horsbg,
					nb_non_calcules_bg,
					nb_factures_regularisation,
					nb_rejets,
					'0' AS code_expedie_0,
					code_expedie_1,
					'0' AS code_expedie_2,
					date_expedition_1 AS date_expedition,
					NULL::date AS date_expedition_0,
					date_expedition_1,
					NULL::date AS date_expedition_2,
					'' AS no_bordereau_0,
					no_bordereau_1,
					'' AS no_bordereau_2,
					delai_expedition_1 AS delai_expedition,
					NULL::numeric AS delai_expedition_0,
					delai_expedition_1,
					NULL::numeric AS delai_expedition_2,
					nb_non_expedie_1 AS nb_non_expedie,
					nb_non_expedie_1_c AS nb_non_expedie_c,
					nb_non_expedie_1_h AS nb_non_expedie_h,
					0 AS nb_non_expedie_0,
					0 AS nb_non_expedie_0_c,
					0 AS nb_non_expedie_0_h,
					nb_non_expedie_1,
					nb_non_expedie_1_c,
					nb_non_expedie_1_h,
					0 AS nb_non_expedie_2,
					0 AS nb_non_expedie_2_c,
					0 AS nb_non_expedie_2_h,
					montant_facture_1 AS montant_facture,
					montant_facture_1_c AS montant_facture_c,
					montant_facture_1_h AS montant_facture_h,
					0 AS montant_facture_0,
					0 AS montant_facture_0_c,
					0 AS montant_facture_0_h,
					montant_facture_1,
					montant_facture_1_c,
					montant_facture_1_h,
					0 AS montant_facture_2,
					0 AS montant_facture_2_c,
					0 AS montant_facture_2_h,
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour,
					montant_encours_1 AS montant_encours,
					montant_encours_1_c AS montant_encours_c,
					montant_encours_1_h AS montant_encours_h,
					0 AS montant_encours_0,
					0 AS montant_encours_0_c,
					0 AS montant_encours_0_h,
					montant_encours_1,
					montant_encours_1_c,
					montant_encours_1_h,
					0 AS montant_encours_2,
					0 AS montant_encours_2_c,
					0 AS montant_encours_2_h,
					montant_comptabilise_1 AS montant_comptabilise,
					montant_comptabilise_1_c AS montant_comptabilise_c,
					montant_comptabilise_1_h AS montant_comptabilise_h,
					0 AS montant_comptabilise_0,
					0 AS montant_comptabilise_0_c,
					0 AS montant_comptabilise_0_h,
					montant_comptabilise_1,
					montant_comptabilise_1_c,
					montant_comptabilise_1_h,
					0 AS montant_comptabilise_2,
					0 AS montant_comptabilise_2_c,
					0 AS montant_comptabilise_2_h,
					montant_comptabilise_budget_global_c,
					montant_regle_1 AS montant_regle,
					montant_regle_1_c AS montant_regle_c,
					montant_regle_1_h AS montant_regle_h,
					0 AS montant_regle_0,
					0 AS montant_regle_0_c,
					0 AS montant_regle_0_h,
					montant_regle_1,
					montant_regle_1_c,
					montant_regle_1_h,
					0 AS montant_regle_2,
					0 AS montant_regle_2_c,
					0 AS montant_regle_2_h,
					date_solde_1 AS date_solde,
					date_solde_1_c AS date_solde_c,
					date_solde_1_h AS date_solde_h,
					NULL::date AS date_solde_0,
					NULL::date AS date_solde_0_c,
					NULL::date AS date_solde_0_h,
					date_solde_1,
					date_solde_1_c,
					date_solde_1_h,
					NULL::date AS date_solde_2,
					NULL::date AS date_solde_2_c,
					NULL::date AS date_solde_2_h,
					delai_solde_1 AS delai_solde,
					delai_solde_1_c AS delai_solde_c,
					delai_solde_1_h AS delai_solde_h,
					NULL::numeric AS delai_solde_0,
					NULL::numeric AS delai_solde_0_c,
					NULL::numeric AS delai_solde_0_h,
					delai_solde_1,
					delai_solde_1_c,
					delai_solde_1_h,
					NULL::numeric AS delai_solde_2,
					NULL::numeric AS delai_solde_2_c,
					NULL::numeric AS delai_solde_2_h,
					nb_non_solde_1 AS nb_non_solde,
					nb_non_solde_1_c AS nb_non_solde_c,
					nb_non_solde_1_h AS nb_non_solde_h,
					0 AS nb_non_solde_0,
					0 AS nb_non_solde_0_c,
					0 AS nb_non_solde_0_h,
					nb_non_solde_1,
					nb_non_solde_1_c,
					nb_non_solde_1_h,
					0 AS nb_non_solde_2,
					0 AS nb_non_solde_2_c,
					0 AS nb_non_solde_2_h,
					nb_non_cloture_1 AS nb_non_cloture,
					nb_non_cloture_1_c AS nb_non_cloture_c,
					nb_non_cloture_1_h AS nb_non_cloture_h,
					0 AS nb_non_cloture_0,
					0 AS nb_non_cloture_0_c,
					0 AS nb_non_cloture_0_h,
					nb_non_cloture_1,
					nb_non_cloture_1_c,
					nb_non_cloture_1_h,
					0 AS nb_non_cloture_2,
					0 AS nb_non_cloture_2_c,
					0 AS nb_non_cloture_2_h
			FROM w_factures_reference
			WHERE tiers_payant_1_id <> 0
                AND
                  (
                  montant_facture_1 <> 0 OR
                  montant_comptabilise_1 <> 0 OR
                  montant_regle_1 <> 0 OR
                  montant_encours <> 0
                  )
            ;


			INSERT INTO activite.p_factures_reference_tiers (
					sejour_id,
					no_sejour,
					date_entree,
					date_sortie,
					code_sorti,
					facture_reference_id,
					no_facture_reference,
					type_t2a,
					date_debut_facture,
					date_fin_facture,
					type_facture,
					date_groupage,
					retard_groupage,
					delai_groupage,
					nb_groupe,
					nb_non_groupe,
					nb_calculable,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					gmt_id,
					tiers_payant_id,
					code_facture,
					date_facture,
					retard_facture,
					delai_facture,
					code_vente,
					date_vente,
					nb_factures,
					nb_non_calcules,
                    nb_non_calcules_horsbg,
					nb_non_calcules_bg,
					nb_factures_regularisation,
					nb_rejets,
					code_expedie_0,
					code_expedie_1,
					code_expedie_2,
					date_expedition,
					date_expedition_0,
					date_expedition_1,
					date_expedition_2,
					no_bordereau_0,
					no_bordereau_1,
					no_bordereau_2,
					delai_expedition,
					delai_expedition_0,
					delai_expedition_1,
					delai_expedition_2,
					nb_non_expedie,
					nb_non_expedie_c,
					nb_non_expedie_h,
					nb_non_expedie_0,
					nb_non_expedie_0_c,
					nb_non_expedie_0_h,
					nb_non_expedie_1,
					nb_non_expedie_1_c,
					nb_non_expedie_1_h,
					nb_non_expedie_2,
					nb_non_expedie_2_c,
					nb_non_expedie_2_h,
					montant_facture,
					montant_facture_c,
					montant_facture_h,
					montant_facture_0,
					montant_facture_0_c,
					montant_facture_0_h,
					montant_facture_1,
					montant_facture_1_c,
					montant_facture_1_h,
					montant_facture_2,
					montant_facture_2_c,
					montant_facture_2_h,
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour,
					montant_encours,
					montant_encours_c,
					montant_encours_h,
					montant_encours_0,
					montant_encours_0_c,
					montant_encours_0_h,
					montant_encours_1,
					montant_encours_1_c,
					montant_encours_1_h,
					montant_encours_2,
					montant_encours_2_c,
					montant_encours_2_h,
					montant_comptabilise,
					montant_comptabilise_c,
					montant_comptabilise_h,
					montant_comptabilise_0,
					montant_comptabilise_0_c,
					montant_comptabilise_0_h,
					montant_comptabilise_1,
					montant_comptabilise_1_c,
					montant_comptabilise_1_h,
					montant_comptabilise_2,
					montant_comptabilise_2_c,
					montant_comptabilise_2_h,
					montant_comptabilise_budget_global_c,
					montant_regle,
					montant_regle_c,
					montant_regle_h,
					montant_regle_0,
					montant_regle_0_c,
					montant_regle_0_h,
					montant_regle_1,
					montant_regle_1_c,
					montant_regle_1_h,
					montant_regle_2,
					montant_regle_2_c,
					montant_regle_2_h,
					date_solde,
					date_solde_c,
					date_solde_h,
					date_solde_0,
					date_solde_0_c,
					date_solde_0_h,
					date_solde_1,
					date_solde_1_c,
					date_solde_1_h,
					date_solde_2,
					date_solde_2_c,
					date_solde_2_h,
					delai_solde,
					delai_solde_c,
					delai_solde_h,
					delai_solde_0,
					delai_solde_0_c,
					delai_solde_0_h,
					delai_solde_1,
					delai_solde_1_c,
					delai_solde_1_h,
					delai_solde_2,
					delai_solde_2_c,
					delai_solde_2_h,
					nb_non_solde,
					nb_non_solde_c,
					nb_non_solde_h,
					nb_non_solde_0,
					nb_non_solde_0_c,
					nb_non_solde_0_h,
					nb_non_solde_1,
					nb_non_solde_1_c,
					nb_non_solde_1_h,
					nb_non_solde_2,
					nb_non_solde_2_c,
					nb_non_solde_2_h,
					nb_non_cloture,
					nb_non_cloture_c,
					nb_non_cloture_h,
					nb_non_cloture_0,
					nb_non_cloture_0_c,
					nb_non_cloture_0_h,
					nb_non_cloture_1,
					nb_non_cloture_1_c,
					nb_non_cloture_1_h,
					nb_non_cloture_2,
					nb_non_cloture_2_c,
					nb_non_cloture_2_h
					)
				SELECT 
					sejour_id,
					no_sejour,
					date_entree,
					date_sortie,
					code_sorti,
					facture_reference_id,
					no_facture_reference,
					type_t2a,
					date_debut_facture,
					date_fin_facture,
					type_facture,
					date_groupage,
					CASE WHEN tiers_payant_1_id = 0 AND tiers_payant_2_id <> 0 THEN retard_groupage ELSE 0 END,
					delai_groupage,
					nb_groupe,
					nb_non_groupe,
					nb_calculable,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					gmt_id,
					tiers_payant_2_id AS tiers_payant_id,
					code_facture,
					date_facture,
					CASE WHEN tiers_payant_1_id = 0 AND tiers_payant_2_id <> 0 THEN retard_facture ELSE 0 END,
					delai_facture,
					code_vente,
					date_vente,
					nb_factures,
					nb_non_calcules,
                    nb_non_calcules_horsbg,
					nb_non_calcules_bg,
					nb_factures_regularisation,
					nb_rejets,
					'0' AS code_expedie_0,
					'0' AS code_expedie_1,
					code_expedie_2,
					date_expedition_2 AS date_expedition,
					NULL::date AS date_expedition_0,
					NULL::date AS date_expedition_1,
					date_expedition_2,
					'' AS no_bordereau_0,
					'' AS no_bordereau_1,
					no_bordereau_2,
					delai_expedition_2 AS delai_expedition,
					NULL::numeric AS delai_expedition_0,
					NULL::numeric AS delai_expedition_1,
					delai_expedition_2,
					nb_non_expedie_2 AS nb_non_expedie,
					nb_non_expedie_2_c AS nb_non_expedie_c,
					nb_non_expedie_2_h AS nb_non_expedie_h,
					0 AS nb_non_expedie_0,
					0 AS nb_non_expedie_0_c,
					0 AS nb_non_expedie_0_h,
					0 AS nb_non_expedie_1,
					0 AS nb_non_expedie_1_c,
					0 AS nb_non_expedie_1_h,
					nb_non_expedie_2,
					nb_non_expedie_2_c,
					nb_non_expedie_2_h,
					montant_facture_2 AS montant_facture,
					montant_facture_2_c AS montant_facture_c,
					montant_facture_2_h AS montant_facture_h,
					0 AS montant_facture_0,
					0 AS montant_facture_0_c,
					0 AS montant_facture_0_h,
					0 AS montant_facture_1,
					0 AS montant_facture_1_c,
					0 AS montant_facture_1_h,
					montant_facture_2,
					montant_facture_2_c,
					montant_facture_2_h,
					0 AS montant_facture_c_actes_inclus_dans_sejour,
					0 AS montant_facture_h_actes_inclus_dans_sejour,
					montant_encours_2 AS montant_encours,
					montant_encours_2_c AS montant_encours_c,
					montant_encours_2_h AS montant_encours_h,
					0 AS montant_encours_0,
					0 AS montant_encours_0_c,
					0 AS montant_encours_0_h,
					0 AS montant_encours_1,
					0 AS montant_encours_1_c,
					0 AS montant_encours_1_h,
					montant_encours_2,
					montant_encours_2_c,
					montant_encours_2_h,
					montant_comptabilise_2 AS montant_comptabilise,
					montant_comptabilise_2_c AS montant_comptabilise_c,
					montant_comptabilise_2_h AS montant_comptabilise_h,
					0 AS montant_comptabilise_0,
					0 AS montant_comptabilise_0_c,
					0 AS montant_comptabilise_0_h,
					0 AS montant_comptabilise_1,
					0 AS montant_comptabilise_1_c,
					0 AS montant_comptabilise_1_h,
					montant_comptabilise_2,
					montant_comptabilise_2_c,
					montant_comptabilise_2_h,
					0 AS montant_comptabilise_budget_global_c,
					montant_regle_2 AS montant_regle,
					montant_regle_2_c AS montant_regle_c,
					montant_regle_2_h AS montant_regle_h,
					0 AS montant_regle_0,
					0 AS montant_regle_0_c,
					0 AS montant_regle_0_h,
					0 AS montant_regle_1,
					0 AS montant_regle_1_c,
					0 AS montant_regle_1_h,
					montant_regle_2,
					montant_regle_2_c,
					montant_regle_2_h,
					date_solde_2 AS date_solde,
					date_solde_2_c AS date_solde_c,
					date_solde_2_h AS date_solde_h,
					NULL::date AS date_solde_0,
					NULL::date AS date_solde_0_c,
					NULL::date AS date_solde_0_h,
					NULL::date AS date_solde_1,
					NULL::date AS date_solde_1_c,
					NULL::date AS date_solde_1_h,
					date_solde_2,
					date_solde_2_c,
					date_solde_2_h,
					delai_solde_2 AS delai_solde,
					delai_solde_2_c AS delai_solde_c,
					delai_solde_2_h AS delai_solde_h,
					NULL::numeric AS delai_solde_0,
					NULL::numeric AS delai_solde_0_c,
					NULL::numeric AS delai_solde_0_h,
					NULL::numeric AS delai_solde_1,
					NULL::numeric AS delai_solde_1_c,
					NULL::numeric AS delai_solde_1_h,
					delai_solde_2,
					delai_solde_2_c,
					delai_solde_2_h,
					nb_non_solde_2 AS nb_non_solde,
					nb_non_solde_2_c AS nb_non_solde_c,
					nb_non_solde_2_h AS nb_non_solde_h,
					0 AS nb_non_solde_0,
					0 AS nb_non_solde_0_c,
					0 AS nb_non_solde_0_h,
					0 AS nb_non_solde_1,
					0 AS nb_non_solde_1_c,
					0 AS nb_non_solde_1_h,
					nb_non_solde_2,
					nb_non_solde_2_c,
					nb_non_solde_2_h,
					nb_non_cloture_2 AS nb_non_cloture,
					nb_non_cloture_2_c AS nb_non_cloture_c,
					nb_non_cloture_2_h AS nb_non_cloture_h,
					0 AS nb_non_cloture_0,
					0 AS nb_non_cloture_0_c,
					0 AS nb_non_cloture_0_h,
					0 AS nb_non_cloture_1,
					0 AS nb_non_cloture_1_c,
					0 AS nb_non_cloture_1_h,
					nb_non_cloture_2,
					nb_non_cloture_2_c,
					nb_non_cloture_2_h
			FROM w_factures_reference
			WHERE tiers_payant_2_id <> 0
                AND
                  (
                  montant_facture_2 <> 0 OR
                  montant_comptabilise_2 <> 0 OR
                  montant_regle_2 <> 0 OR
                  montant_encours <> 0
                  )
            ;

			ANALYSE activite.p_factures_reference_tiers
			;            

			SELECT base.cti_enable_index('activite', 'i_factures_reference_tiers_1');
			SELECT base.cti_enable_index('activite', 'i_factures_reference_tiers_2');
			SELECT base.cti_enable_index('activite', 'i_factures_reference_tiers_3');
			SELECT base.cti_enable_index('activite', 'i_factures_reference_tiers_4');
            
            
            
            UPDATE activite.p_factures
            SET date_fin = date_fin_facture
            FROM activite.p_factures_reference 
            WHERE p_factures.no_facture_reference = p_factures_reference.no_facture_reference AND
                p_factures.date_fin <> p_factures_reference.date_fin_facture
                ;


			-- Suppression des tables de travail non utilisées après
			DROP TABLE IF EXISTS w_factures_reference CASCADE;	
            
            -- Report motifs de non facturation
			
			-- Annulation si facture OK
			UPDATE activite.p_factures
			SET motif_non_facturation_id = 0, motif_non_facturation_comment = ''
			FROM activite.p_factures_reference
			WHERE p_factures_reference.no_facture_reference = p_factures.no_facture_reference AND
				p_factures.motif_non_facturation_id <> 0 AND
				nb_non_calcules = 0
				;

			UPDATE activite.p_factures_reference
			SET motif_non_facturation_id = subview.motif_non_facturation_id, 
				motif_non_facturation_comment = subview.motif_non_facturation_comment
			FROM 
				(
				SELECT no_facture_reference, 
					MAX(motif_non_facturation_id) AS motif_non_facturation_id,
					MAX(motif_non_facturation_comment) AS motif_non_facturation_comment
				FROM activite.p_factures 
				WHERE motif_non_facturation_id <> 0 
				GROUP BY 1
				) subview
			WHERE p_factures_reference.no_facture_reference = subview.no_facture_reference AND
				nb_non_calcules = 1
			;
			UPDATE activite.p_factures_reference_tiers
			SET motif_non_facturation_id = subview.motif_non_facturation_id, 
				motif_non_facturation_comment = subview.motif_non_facturation_comment
			FROM 
				(
				SELECT no_facture_reference, 
					MAX(motif_non_facturation_id) AS motif_non_facturation_id,
					MAX(motif_non_facturation_comment) AS motif_non_facturation_comment
				FROM activite.p_factures 
				WHERE motif_non_facturation_id <> 0 
				GROUP BY 1
				) subview
			WHERE p_factures_reference_tiers.no_facture_reference = subview.no_facture_reference AND
				nb_non_calcules = 1
			;
			
			
			UPDATE activite.p_factures_reference
			SET motif_non_facturation_id = t_motif_non_facturation.oid
			FROM activite.t_motif_non_facturation
			WHERE t_motif_non_facturation.code_original = '*CTING' AND
				nb_non_calcules = 1 AND
				nb_non_groupe = 1 AND
				motif_non_facturation_id = 0
			;

			UPDATE activite.p_factures
			SET motif_non_facturation_id = p_factures_reference.motif_non_facturation_id
			FROm activite.p_factures_reference
			WHERE p_factures_reference.no_facture_reference = p_factures.no_facture_reference AND
				p_factures.motif_non_facturation_id IS DISTINCT FROM p_factures_reference.motif_non_facturation_id
			;

			UPDATE activite.p_factures_reference_tiers
			SET motif_non_facturation_id = p_factures_reference.motif_non_facturation_id
			FROM activite.p_factures_reference
			WHERE p_factures_reference.no_facture_reference = p_factures_reference_tiers.no_facture_reference AND
				p_factures_reference_tiers.motif_non_facturation_id IS DISTINCT FROM p_factures_reference.motif_non_facturation_id AND
				p_factures_reference_tiers.nb_non_calcules = 1
			;
			
			
			-- Pointer les journées facturées dans occupation
			DROP TABLE IF EXISTS w_sejours_non_factures;
			CREATE TEMP TABLE w_sejours_non_factures AS
			SELECT p_sejours.no_sejour, 
				COALESCE(p_factures_reference.date_entree, p_sejours.date_entree) AS date_debut, 
				COALESCE(p_factures_reference.date_sortie, p_sejours.date_sortie) AS date_fin
			FROM activite.p_sejours
			LEFT JOIN activite.p_factures_reference ON p_sejours.no_sejour = p_factures_reference.no_sejour
			WHERE p_factures_reference.nb_non_calcules <> 0
			ORDER BY p_sejours.no_sejour, p_factures_reference.date_sortie;

			CREATE INDEX w_sejours_non_factures_i1 ON w_sejours_non_factures USING btree (no_sejour);

			UPDATE activite.p_mouvements_sejour
			SET est_facture = '0'
			WHERE p_mouvements_sejour.est_mouvement_previsionnel = '1' AND
				 est_facture IS DISTINCT FROM '0';

			UPDATE activite.p_mouvements_sejour
			SET est_facture = '0'
			FROM w_sejours_non_factures
			WHERE p_mouvements_sejour.no_sejour = w_sejours_non_factures.no_sejour AND
				p_mouvements_sejour.date BETWEEN w_sejours_non_factures.date_debut AND w_sejours_non_factures.date_fin;
				
				
				
			-- Code facture complet dans séjours
			DROP TABLE IF EXISTS w_sejours_etat_factures;
			CREATE TEMP TABLE w_sejours_etat_factures AS
			SELECT p_sejours.no_sejour, 
				MIN(CASE WHEN nb_non_calcules = 0 THEN '1' ELSE '0' END) AS code_facture_reference,
				MAX(CASE WHEN nb_non_calcules = 0 THEN p_factures_reference.date_facture ELSE '20991231' END) AS date_facture_reference,
				MIN(CASE WHEN p_sejours.date_facture < '2099-12-31'THEN '1' ELSE '0' END) AS code_facture_sejour
			FROM activite.p_sejours
			LEFT JOIN activite.p_factures_reference ON p_sejours.no_sejour = p_factures_reference.no_sejour
			GROUP BY 1
			HAVING MIN(CASE WHEN nb_non_calcules = 0 THEN '1' ELSE '0' END) <> MIN(CASE WHEN p_sejours.date_facture < '2099-12-31'THEN '1' ELSE '0' END)
			ORDER BY p_sejours.no_sejour;

			CREATE INDEX w_sejours_etat_factures_i1 ON w_sejours_etat_factures USING btree (no_sejour);

			UPDATE activite.p_sejours
			SET date_facture = date_facture_reference
			FROM w_sejours_etat_factures
			WHERE p_sejours.no_sejour = w_sejours_etat_factures.no_sejour;
			
			
			-- Actualisation facture de référence des encours
			UPDATE activite.p_factures_encours
			SET no_facture_reference = p_factures.no_facture
			FROM activite.p_factures
			WHERE p_factures_encours.no_sejour = p_factures.no_sejour AND
				p_factures_encours.date_debut BETWEEN p_factures.date_debut AND p_factures.date_fin AND
				p_factures.no_facture = p_factures.no_facture_reference AND
				p_factures_encours.no_facture_reference <> p_factures.no_facture;
      
            -- Etat des séjours
            
            DROP  TABLE IF EXISTS w_sejours_1;
            CREATE TEMP TABLE w_sejours_1 as
            SELECT  
                p_sejours.no_sejour,
                SUM(CASE WHEN p_factures_reference.date_facture != '2099-12-31' THEN 1 ELSE 0 END) AS nb_facturation_partielle,
                MAX(nb_non_groupe) AS nb_non_groupe,
                MAX(nb_non_calcules) AS nb_non_calcules,
                MAX(nb_non_solde) AS nb_non_solde
            FROM activite.p_sejours
            LEFT JOIN activite.p_factures_reference ON p_factures_reference.no_sejour = p_sejours.no_sejour
            GROUP BY 1;

            ANALYSE w_sejours_1
            ;

            -- UPDATE Etat des séjours 
            
            UPDATE activite.p_sejours SET etat_sejour = 
                CASE 
                    WHEN  type_sejour = 9  THEN '9' -- Fictif
					
					WHEN  est_sans_facturation ='1'  THEN '8' -- Non facturable ou recuse
    
                    WHEN  code_prevu = 1 THEN '0' -- prévu
                    
                    WHEN  code_sorti <> 1 THEN CASE WHEN nb_facturation_partielle > 0 THEN '2' ELSE '1' END -- Présent(1) et présent avec faturation partielle (2)
                    
                    WHEN  code_sorti = 1 AND nb_non_groupe = 1   THEN '3' -- sorti non groupé 

                    WHEN  code_sorti = 1 AND nb_non_calcules = 1 AND date_groupage IS NULL THEN '3' -- Sorti non groupé dans le cas où il y a un pré-groupage mais pas de validation DIM
                    
                    WHEN  code_sorti = 1 AND nb_non_calcules = 1  THEN CASE WHEN nb_facturation_partielle > 0 THEN '5' ELSE '4' END-- sorti non facturé(4)  et sorti non facturé avec facturation partielle (5)
                    
                    WHEN  nb_non_solde = 0   THEN '7' -- soldé
                    
                    WHEN  nb_non_calcules = 0 AND nb_non_solde = 1   THEN '6' -- Facturé non soldé

                    ELSE '?'
                END
            FROM w_sejours_1
            WHERE w_sejours_1.no_sejour = p_sejours.no_sejour;

			]]></sqlcmd>
		</NODE>
		<NODE label="Etat des dossiers PMSI">

			<condition><![CDATA[
				"[PX]" == "" && "[ENV_WITHPMSI]" == "1"
			]]></condition>

			<sqlcmd><![CDATA[

			WITH w_sejours AS (
			  SELECT
				  p_sejours.no_sejour
				  ,p_sejour_pmsi.rss_id
				  ,SUM(CASE WHEN p_factures_reference.nb_non_calcules = 0 THEN 1 ELSE 0 END) AS nb_facturation_partielle
				  ,MAX(p_factures_reference.nb_non_groupe)  AS nb_non_groupe
				  ,MAX(p_factures_reference.nb_non_calcules) AS nb_non_calcules
				  ,MAX(p_factures_reference.nb_non_solde)   AS nb_non_solde
				  ,MAX(p_sejours.type_sejour) AS type_sejour
				  ,MAX(p_sejours.code_sorti) AS code_sorti
				  ,MAX(p_sejours.date_groupage) AS date_groupage
			  FROM activite.p_sejours
			  	JOIN activite.p_sejour_pmsi ON p_sejour_pmsi.sejour_id = p_sejours.oid
			  	LEFT JOIN activite.p_factures_reference  ON p_factures_reference.no_sejour = p_sejours.no_sejour
			  	GROUP BY p_sejours.no_sejour, p_sejour_pmsi.rss_id
			),
			w_sejours_cal AS (
			  SELECT
				w_sejours.no_sejour
				,w_sejours.rss_id
				,CASE
				  WHEN w_sejours.type_sejour = 9 THEN '9'
				  WHEN w_sejours.code_sorti = 1 AND w_sejours.nb_non_groupe   = 1 THEN '3'
				  WHEN w_sejours.code_sorti = 1 AND w_sejours.nb_non_calcules = 1 AND w_sejours.date_groupage IS NULL THEN '3'
				  WHEN w_sejours.code_sorti = 1 AND w_sejours.nb_non_calcules = 1 THEN CASE WHEN w_sejours.nb_facturation_partielle > 0 THEN '5' ELSE '4' END
				  WHEN w_sejours.nb_non_solde = 0 THEN '7'
				  WHEN w_sejours.nb_non_calcules = 0 AND w_sejours.nb_non_solde = 1 THEN '6'
				  ELSE '0'
				END AS etat_new
			  FROM w_sejours
			 )
			UPDATE pmsi.p_rss
			SET etat_sejour = w_sejours_cal.etat_new
			FROM w_sejours_cal
			WHERE p_rss.oid = w_sejours_cal.rss_id
			  AND p_rss.etat_sejour IS DISTINCT FROM w_sejours_cal.etat_new
			  ;
            
            UPDATE pmsi.p_rss SET etat_sejour = '8'
                WHERE  etat_sejour is null or etat_sejour = '?';

            -- Update champ transmission e-pmsi MCO,SSR,PSY,HAD,HORS PMSI
            WITH sej_pmsi AS (
            	SELECT DISTINCT no_sejour
            		   ,traitement_epmsi
            		   ,en_cours_pmsi FROM activite.p_sejour_pmsi
			)
			UPDATE activite.p_sejours
			SET traitement_epmsi_id = CASE
										WHEN type_pmsi not in ('1','2','3','4') THEN 5
										WHEN type_pmsi = '1' AND sej_pmsi.en_cours_pmsi = '0' AND sej_pmsi.traitement_epmsi in ('11', '12', '13', '14', '15', '21', '22', '23', '24', '25', '26', '30', '31', '32', '33') THEN 11
									  ELSE 10 END
			FROM sej_pmsi
				WHERE sej_pmsi.no_sejour = p_sejours.no_sejour;
			]]></sqlcmd>
		</NODE>

		<NODE label="MAJ GHM-GME dans p_sejours">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[ 

		   	-- MAJ sejours externe MCO
   
           UPDATE activite[PX].p_sejours  
		   SET ghmgme_id = t_ghmgme_c.ghmgme_id
		   FROM activite[PX].t_ghmgme_c
		   where t_ghmgme_c.ghmgme_id = p_sejours.ghm_id 
		   AND p_sejours.ghm_id in (-9991,-9992,-9993,-9994,-9995,-9996,-9990,-9980,-9981)
		   ;
		   
		   	-- MAJ sejours externe SSR

           UPDATE activite[PX].p_sejours  
		   SET ghmgme_id = t_ghmgme_c.ghmgme_id
		   FROM activite[PX].t_ghmgme_c
		   where t_ghmgme_c.ghmgme_id = p_sejours.gme_id 
		   AND p_sejours.gme_id in (-9991,-9992,-9993,-9994,-9995,-9996,-9990,-9980,-9981)
		   ;

			-- MAJ p_sejours.ghmgme_id pour le champ ghm
    
           UPDATE activite[PX].p_sejours  
		   SET ghmgme_id = t_ghmgme_c.ghmgme_id
		   FROM activite[PX].t_ghmgme_c
		   where t_ghmgme_c.ghmgme_id = p_sejours.ghm_id 
		   AND p_sejours.ghm_id > 0
		   ;

			-- MAJ p_sejours.ghmgme_id pour le champ gme
   
           UPDATE activite[PX].p_sejours  
		   SET ghmgme_id = t_ghmgme_c.ghmgme_id
		   FROM activite[PX].t_ghmgme_c
		   where t_ghmgme_c.ghmgme_id = p_sejours.gme_id + 10000
		   AND p_sejours.gme_id > 0
		   ;

			]]></sqlcmd>
		</NODE>

		<NODE label="Compléments lignes factures">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
		
				
				-- Ajustement PMSI fil de l'eau
				SELECT activite.cti_ajust_fildeleau();
                
                -- Modification facturation jour de sortie CP
                INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'TRANSCPJS',
					'Transformation lignes de facture pour CP jour de sortie',
					'0',
					'1=Si Rubrique CP avec date fin > date entrée et nombre à 1 et date début = date entrée et date fin = date sortie alors date début = date fin'
				WHERE 'TRANSCPJS' NOT IN (SELECT code FROM activite.t_divers);
                ;
                
                UPDATE activite.p_factures_lignes_c
                SET date_debut = p_factures_lignes_c.date_fin
                FROM activite.p_factures
                JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                JOIN activite.t_divers ON t_divers.code = 'TRANSCPJS' AND t_divers.valeur = '1'
                WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
                    (
                    nb_rubrique = 1 OR 
                    nb_rubrique = -1
                    ) AND
                    p_factures_lignes_c.date_fin > p_factures_lignes_c.date_debut AND
                    p_factures_lignes_c.date_fin = date_sortie AND
                    p_factures_lignes_c.date_debut = date_entree AND
                    rubrique_facturation_id IN
                    (SELECT to_id
                        FROM activite.t_listes
                        JOIN activite.t_listes_contenu ON liste_id = t_listes.oid
                        WHERE code = 'CTI_SHO_R'
                        )
                ;				
				
				-- Compte produit
				
				-- Forcage depuis parametrage
				UPDATE activite[PX].p_factures_lignes_c
				SET compte_produit_id = 
					CASE 
						WHEN est_compte_force = '1' THEN t_service_rubrique.compte_id
						WHEN p_factures_lignes_c.compte_produit_id = 0 THEN t_service_rubrique.compte_id
						ELSE p_factures_lignes_c.compte_produit_id END
				FROM activite[PX].t_lieux,
					activite[PX].t_service_rubrique
				WHERE lieu_id = t_lieux.oid AND
					t_service_rubrique.service_facturation_id = t_lieux.service_facturation_id AND
					t_service_rubrique.rubrique_facturation_id = p_factures_lignes_c.rubrique_facturation_id AND
					t_service_rubrique.compte_id <> 0 AND
					p_factures_lignes_c.compte_produit_id IS DISTINCT FROM 
					CASE 
						WHEN est_compte_force = '1' THEN t_service_rubrique.compte_id
						WHEN p_factures_lignes_c.compte_produit_id = 0 THEN t_service_rubrique.compte_id
						ELSE p_factures_lignes_c.compte_produit_id END
					;
					
				-- Déduction depuis historique service rubrique
				DROP TABLE IF EXISTS w_factures_lignes_c_compte_serrub;
				CREATE TEMP TABLE w_factures_lignes_c_compte_serrub AS
				SELECT rubrique_facturation_id, service_facturation_id, (MAX(Array[date_vente::text || to_char(nb,'FM000000000000'), compte_produit_id::text]))[2]::bigint AS compte_produit_id
				FROM
				(
				SELECT rubrique_facturation_id, service_facturation_id, date(date_trunc('month',date_vente)) AS date_vente, compte_produit_id, count(*) AS nb
				FROM activite.p_factures_lignes_c
				JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
				JOIN activite.t_lieux ON p_factures_lignes_c.lieu_id = t_lieux.oid
				WHERE compte_produit_id <> 0 AND date_vente < '20991231'
				GROUP BY 1,2,3,4
				) subview
				GROUP BY 1,2;
                
                CREATE INDEX w_factures_lignes_c_compte_serrub_i1
				  ON w_factures_lignes_c_compte_serrub
				  USING btree
				  (rubrique_facturation_id);


				UPDATE activite.p_factures_lignes_c
				SET compte_produit_id = w_factures_lignes_c_compte_serrub.compte_produit_id
				FROM w_factures_lignes_c_compte_serrub,
					activite.t_lieux
				WHERE p_factures_lignes_c.compte_produit_id = 0 AND
					p_factures_lignes_c.lieu_id = t_lieux.oid AND
					p_factures_lignes_c.rubrique_facturation_id = w_factures_lignes_c_compte_serrub.rubrique_facturation_id AND
					t_lieux.service_facturation_id = w_factures_lignes_c_compte_serrub.service_facturation_id;
                    
                -- Déduction depuis historique service prestation
                DROP TABLE IF EXISTS w_factures_lignes_c_compte_serpre;
				CREATE TEMP TABLE w_factures_lignes_c_compte_serpre AS
				SELECT prestation_id, service_facturation_id, (MAX(Array[date_vente::text || to_char(nb,'FM000000000000'), compte_produit_id::text]))[2]::bigint AS compte_produit_id
				FROM
				(
				SELECT prestation_id, service_facturation_id, date(date_trunc('month',date_vente)) AS date_vente, compte_produit_id, count(*) AS nb
				FROM activite.p_factures_lignes_c
				JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
				JOIN activite.t_lieux ON p_factures_lignes_c.lieu_id = t_lieux.oid
				WHERE compte_produit_id <> 0 AND date_vente < '20991231'
				GROUP BY 1,2,3,4
				) subview
				GROUP BY 1,2;
                
                CREATE INDEX w_factures_lignes_c_compte_serpre_i1
				  ON w_factures_lignes_c_compte_serpre
				  USING btree
				  (prestation_id);

				UPDATE activite.p_factures_lignes_c
				SET compte_produit_id = w_factures_lignes_c_compte_serpre.compte_produit_id
				FROM w_factures_lignes_c_compte_serpre,
					activite.t_lieux
				WHERE p_factures_lignes_c.compte_produit_id = 0 AND
					p_factures_lignes_c.lieu_id = t_lieux.oid AND
					p_factures_lignes_c.prestation_id = w_factures_lignes_c_compte_serpre.prestation_id AND
					t_lieux.service_facturation_id = w_factures_lignes_c_compte_serpre.service_facturation_id;

                -- Déduction depuis historique rubrique uniquement
				DROP TABLE IF EXISTS w_factures_lignes_c_compte_rub;
				CREATE TEMP TABLE w_factures_lignes_c_compte_rub AS
				SELECT rubrique_facturation_id,  (MAX(Array[date_vente::text || to_char(nb,'FM000000000000'), compte_produit_id::text]))[2]::bigint AS compte_produit_id
				FROM
				(
				SELECT rubrique_facturation_id,  date(date_trunc('month',date_vente)) AS date_vente, compte_produit_id, count(*) AS nb
				FROM activite.p_factures_lignes_c
				JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
				WHERE compte_produit_id <> 0 AND date_vente < '20991231'
				GROUP BY 1,2,3
				) subview
				GROUP BY 1;

				CREATE INDEX w_factures_lignes_c_compte_rub_i1
				  ON w_factures_lignes_c_compte_rub
				  USING btree
				  (rubrique_facturation_id);


				UPDATE activite.p_factures_lignes_c
				SET compte_produit_id = w_factures_lignes_c_compte_rub.compte_produit_id
				FROM w_factures_lignes_c_compte_rub				
				WHERE p_factures_lignes_c.compte_produit_id = 0 AND
					p_factures_lignes_c.rubrique_facturation_id = w_factures_lignes_c_compte_rub.rubrique_facturation_id;
					
					
					
				-- Forcage depuis parametrage
				UPDATE activite[PX].p_factures_encours_lignes_c
				SET compte_produit_id = 
					CASE 
						WHEN est_compte_force = '1' THEN t_service_rubrique.compte_id
						WHEN p_factures_encours_lignes_c.compte_produit_id = 0 THEN t_service_rubrique.compte_id
						ELSE p_factures_encours_lignes_c.compte_produit_id END
				FROM activite[PX].t_lieux,
					activite[PX].t_service_rubrique
				WHERE lieu_id = t_lieux.oid AND
					t_service_rubrique.service_facturation_id = t_lieux.service_facturation_id AND
					t_service_rubrique.rubrique_facturation_id = p_factures_encours_lignes_c.rubrique_facturation_id AND
					t_service_rubrique.compte_id <> 0 AND
					p_factures_encours_lignes_c.compte_produit_id IS DISTINCT FROM 
					CASE 
						WHEN est_compte_force = '1' THEN t_service_rubrique.compte_id
						WHEN p_factures_encours_lignes_c.compte_produit_id = 0 THEN t_service_rubrique.compte_id
						ELSE p_factures_encours_lignes_c.compte_produit_id END
					;
					
				-- Déduction depuis historiques service rubrique
				UPDATE activite[PX].p_factures_encours_lignes_c
				SET compte_produit_id = w_factures_lignes_c_compte_serrub.compte_produit_id
				FROM w_factures_lignes_c_compte_serrub,
					activite[PX].t_lieux
				WHERE (p_factures_encours_lignes_c.compte_produit_id = 0 OR p_factures_encours_lignes_c.compte_produit_id IS NULL) AND
					p_factures_encours_lignes_c.lieu_id = t_lieux.oid AND
					p_factures_encours_lignes_c.rubrique_facturation_id = w_factures_lignes_c_compte_serrub.rubrique_facturation_id AND
					t_lieux.service_facturation_id = w_factures_lignes_c_compte_serrub.service_facturation_id;
                    
                -- Déduction depuis historiques service prestation  
                UPDATE activite.p_factures_encours_lignes_c
				SET compte_produit_id = w_factures_lignes_c_compte_serpre.compte_produit_id
				FROM w_factures_lignes_c_compte_serpre,
					activite.t_lieux
				WHERE p_factures_encours_lignes_c.compte_produit_id = 0 AND
					p_factures_encours_lignes_c.lieu_id = t_lieux.oid AND
					p_factures_encours_lignes_c.prestation_id = w_factures_lignes_c_compte_serpre.prestation_id AND
					t_lieux.service_facturation_id = w_factures_lignes_c_compte_serpre.service_facturation_id;
				
                -- Déduction depuis historiques rubrique uniquement
				UPDATE activite[PX].p_factures_encours_lignes_c
				SET compte_produit_id = w_factures_lignes_c_compte_rub.compte_produit_id
				FROM w_factures_lignes_c_compte_rub
				WHERE (p_factures_encours_lignes_c.compte_produit_id = 0 OR p_factures_encours_lignes_c.compte_produit_id IS NULL) AND
					p_factures_encours_lignes_c.rubrique_facturation_id = w_factures_lignes_c_compte_rub.rubrique_facturation_id;
                    
                
				
				
				-- Maintenance rubrique_facturation CTI
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('activite[PX].p_factures_lignes_c');
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('activite[PX].p_factures_encours_lignes_c');
				
				
				-- Valorisation des actes gratuits
				UPDATE activite.p_factures_lignes_h
				SET montant_non_facture = round(p_factures_lignes_h.prix_unitaire * p_factures_lignes_h.nb_prestation * p_factures_lignes_h.coefficient * p_factures_lignes_h.coefficient_mco, 2)
				FROM base.t_actes,
					activite.p_factures
					JOIN activite.p_sejours ON p_sejours.no_sejour = p_factures.no_sejour
				WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND
					p_factures_lignes_h.acte_id = t_actes.oid AND
					p_factures_lignes_h.montant_facture = 0 AND
					(p_sejours.est_budget_global IS DISTINCT FROM '1' OR p_factures.code_facture <> '0') AND
					COALESCE(p_factures_lignes_h.montant_facture_actes_inclus_dans_sejour, 0) = 0;
					
					
					
					
				-- Regroupement des lignes de CP (cas de rubriques facturées deux fois sur même date pour pb tarif patient/mutuelle
				DROP TABLE IF EXISTS w_cp_double;
				CREATE TEMP TABLE w_cp_double AS
				SELECT
					no_facture, date_debut, date_fin, prestation_id, rubrique_facturation_id, nb_rubrique, nb_prestation, coefficient, 
					SUM(prix_unitaire) AS prix_unitaire,
					round(base.cti_division(SUM(montant_facture_1),SUM(montant_facture))*100.00,0) AS taux_1,
					round(base.cti_division(SUM(montant_facture_2),SUM(montant_facture))*100.00,0) AS taux_2,
					round(base.cti_division(SUM(montant_facture_22),SUM(montant_facture))*100.00,0) AS taux_22,
					round(base.cti_division(SUM(montant_facture_0),SUM(montant_facture))*100.00,0) AS taux_0,
					SUM(montant_facture) AS montant_facture,
					SUM(montant_facture_0) AS montant_facture_0,
					SUM(montant_facture_1) AS montant_facture_1,
					SUM(montant_facture_2) AS montant_facture_2,
					SUM(montant_facture_22) AS montant_facture_22,
					SUM(montant_comptabilise) AS montant_comptabilise,
					SUM(montant_comptabilise_0) AS montant_comptabilise_0,
					SUM(montant_comptabilise_1) AS montant_comptabilise_1,
					SUM(montant_comptabilise_2) AS montant_comptabilise_2,
					SUM(montant_comptabilise_22) AS montant_comptabilise_22,
					SUM(montant_encours) AS montant_encours,
					SUM(montant_encours_0) AS montant_encours_0,
					SUM(montant_encours_1) AS montant_encours_1,
					SUM(montant_encours_2) AS montant_encours_2,
					SUM(montant_encours_22) AS montant_encours_22,
					
					MIN(p_factures_lignes_c.CTID) AS keepCTID
				FROM activite.p_factures_lignes_c
				WHERE rubrique_facturation_id IN (SELECT to_id FROM activite.v_listes_3 WHERE liste_code = 'CTI_SHO_R') AND 
					montant_facture <> 0
				GROUP BY 1,2,3,4,5,6,7,8
				HAVING count(*) > 1;


				INSERT INTO w_cp_double
				SELECT
					no_facture, date_debut, date_fin, MAX(prestation_id) AS prestation_id, rubrique_facturation_id, 1 AS nb_rubrique, 1 AS nb_prestation, 1 AS coefficient,
					SUM(montant_encours) AS prix_unitaire,
					round(base.cti_division(SUM(montant_facture_1),SUM(montant_facture))*100.00,0) AS taux_1,
					round(base.cti_division(SUM(montant_facture_2),SUM(montant_facture))*100.00,0) AS taux_2,
					round(base.cti_division(SUM(montant_facture_22),SUM(montant_facture))*100.00,0) AS taux_22,
					round(base.cti_division(SUM(montant_facture_0),SUM(montant_facture))*100.00,0) AS taux_0,
					SUM(montant_facture) AS montant_facture,
					SUM(montant_facture_0) AS montant_facture_0,
					SUM(montant_facture_1) AS montant_facture_1,
					SUM(montant_facture_2) AS montant_facture_2,
					SUM(montant_facture_22) AS montant_facture_22,
					SUM(montant_comptabilise) AS montant_comptabilise,
					SUM(montant_comptabilise_0) AS montant_comptabilise_0,
					SUM(montant_comptabilise_1) AS montant_comptabilise_1,
					SUM(montant_comptabilise_2) AS montant_comptabilise_2,
					SUM(montant_comptabilise_22) AS montant_comptabilise_22,
					SUM(montant_encours) AS montant_encours,
					SUM(montant_encours_0) AS montant_encours_0,
					SUM(montant_encours_1) AS montant_encours_1,
					SUM(montant_encours_2) AS montant_encours_2,
					SUM(montant_encours_22) AS montant_encours_22,
					
					MIN(p_factures_lignes_c.CTID) AS keepCTID
				FROM activite.p_factures_lignes_c
				WHERE rubrique_facturation_id IN (SELECT to_id FROM activite.v_listes_3 WHERE liste_code = 'CTI_SHO_R') AND 
					montant_encours <> 0
				GROUP BY 1,2,3,5,6,7
				HAVING count(*) > 1;
                
                UPDATE w_cp_double 
				SET taux_0 = CASE WHEN taux_0 < 0 THEN 0 WHEN taux_0 > 100 THEN 100 ELSE taux_0 END
				WHERE taux_0 <> CASE WHEN taux_0 < 0 THEN 0 WHEN taux_0 > 100 THEN 100 ELSE taux_0 END
				;
				UPDATE w_cp_double 
				SET taux_1 = CASE WHEN taux_1 < 0 THEN 0 WHEN taux_1 > 100 THEN 100 ELSE taux_1 END
				WHERE taux_1 <> CASE WHEN taux_1 < 0 THEN 0 WHEN taux_1 > 100 THEN 100 ELSE taux_1 END
				;
				UPDATE w_cp_double 
				SET taux_2 = CASE WHEN taux_2 < 0 THEN 0 WHEN taux_2 > 100 THEN 100 ELSE taux_2 END
				WHERE taux_2 <> CASE WHEN taux_2 < 0 THEN 0 WHEN taux_2 > 100 THEN 100 ELSE taux_2 END
				;
				UPDATE w_cp_double 
				SET taux_22 = CASE WHEN taux_22 < 0 THEN 0 WHEN taux_22 > 100 THEN 100 ELSE taux_22 END
				WHERE taux_22 <> CASE WHEN taux_22 < 0 THEN 0 WHEN taux_22 > 100 THEN 100 ELSE taux_22 END
				;


				UPDATE w_cp_double
				SET prestation_id = subview.prestation_id
				FROM
					(
					SELECT rubrique_facturation_id, (MAX(ARRAY[nb,prestation_id]))[2] AS prestation_id
					FROM
						(
						SELECT rubrique_facturation_id, prestation_id, count(*) AS nb 
						FROM w_cp_double
						GROUP BY 1,2) subview
					GROUP BY 1
					) subview
				WHERE w_cp_double.rubrique_facturation_id = subview.rubrique_facturation_id AND
					w_cp_double.prestation_id <> subview.prestation_id;

				

				CREATE INDEX w_cp_double_i1
						  ON w_cp_double
						  USING btree
						  (no_facture);

				DELETE FROM activite.p_factures_lignes_c
				USING w_cp_double 
				WHERE p_factures_lignes_c.no_facture = w_cp_double.no_facture AND
					p_factures_lignes_c.date_debut = w_cp_double.date_debut AND
					p_factures_lignes_c.date_fin = w_cp_double.date_fin AND
					(p_factures_lignes_c.prestation_id = w_cp_double.prestation_id OR w_cp_double.montant_encours <> 0) AND
					p_factures_lignes_c.rubrique_facturation_id = w_cp_double.rubrique_facturation_id AND
					(p_factures_lignes_c.nb_rubrique = w_cp_double.nb_rubrique OR w_cp_double.montant_encours <> 0) AND
					(p_factures_lignes_c.nb_prestation = w_cp_double.nb_prestation OR w_cp_double.montant_encours <> 0) AND
					(p_factures_lignes_c.coefficient = w_cp_double.coefficient OR w_cp_double.montant_encours <> 0) AND
					p_factures_lignes_c.CTID <> keepCTID;
					

				UPDATE activite.p_factures_lignes_c SET
					prestation_id = w_cp_double.prestation_id,
					nb_rubrique = w_cp_double.nb_rubrique,
					nb_prestation = w_cp_double.nb_prestation,
					coefficient = w_cp_double.coefficient,
					prix_unitaire = w_cp_double.prix_unitaire,
					taux_0 = w_cp_double.taux_0,
					taux_1 = w_cp_double.taux_1,
					taux_2 = w_cp_double.taux_2,
					taux_22 = w_cp_double.taux_22,
					montant_facture = w_cp_double.montant_facture,
					montant_facture_0 = w_cp_double.montant_facture_0,
					montant_facture_1 = w_cp_double.montant_facture_1,
					montant_facture_2 = w_cp_double.montant_facture_2,
					montant_facture_22 = w_cp_double.montant_facture_22,
					montant_comptabilise = w_cp_double.montant_comptabilise,
					montant_comptabilise_0 = w_cp_double.montant_comptabilise_0,
					montant_comptabilise_1 = w_cp_double.montant_comptabilise_1,
					montant_comptabilise_2 = w_cp_double.montant_comptabilise_2,
					montant_comptabilise_22 = w_cp_double.montant_comptabilise_22,
					montant_encours = w_cp_double.montant_encours,
					montant_encours_0 = w_cp_double.montant_encours_0,
					montant_encours_1 = w_cp_double.montant_encours_1,
					montant_encours_2 = w_cp_double.montant_encours_2,
					montant_encours_22 = w_cp_double.montant_encours_22
				FROM w_cp_double
				WHERE p_factures_lignes_c.no_facture = w_cp_double.no_facture AND
					p_factures_lignes_c.date_debut = w_cp_double.date_debut AND
					p_factures_lignes_c.date_fin = w_cp_double.date_fin AND
					(p_factures_lignes_c.prestation_id = w_cp_double.prestation_id OR w_cp_double.montant_encours <> 0) AND
					p_factures_lignes_c.rubrique_facturation_id = w_cp_double.rubrique_facturation_id AND
					(p_factures_lignes_c.nb_rubrique = w_cp_double.nb_rubrique OR w_cp_double.montant_encours <> 0) AND
					(p_factures_lignes_c.nb_prestation = w_cp_double.nb_prestation OR w_cp_double.montant_encours <> 0) AND
					(p_factures_lignes_c.coefficient = w_cp_double.coefficient OR w_cp_double.montant_encours <> 0);
				
				-- Report sur le lieu de sortie de sortie en cas d'absence
				UPDATE activite.p_factures_lignes_c 
				SET lieu_id = p_sejours.lieu_sortie_id
				FROM activite.p_factures, activite.p_mouvements_sejour, activite.p_sejours
				WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
					p_factures.no_sejour = p_mouvements_sejour.no_sejour AND
					p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
					activite.p_factures_lignes_c.date_debut = p_mouvements_sejour.date AND 
					(p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.nb_sorties_directes = 1) AND
					p_factures_lignes_c.lieu_id IN (SELECT oid FROM activite.t_lieux_c WHERE unite_fonctionnelle_id IN (SELECT oid FROM activite.t_unites_fonctionnelles WHERE code = '*ABS'))
				;

			]]></sqlcmd>

		</NODE>



		<NODE label="Compléments clients">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
            
                -- Factures sans toiers payant
                INSERT INTO activite.t_tiers_payant(code, code_original, texte, texte_court, type_tiers_payant)
                SELECT 'NR1', '*CTINR1', 'Caisse non renseignée', 'Caisse non renseignée', '1'
                WHERE '*CTINR1' NOT IN (SELECT code_original FROM activite.t_tiers_payant WHERE code_original IS NOT NULL)
                ;

                INSERT INTO activite.t_tiers_payant(code, code_original, texte, texte_court, type_tiers_payant)
                SELECT 'NR2', '*CTINR2', 'Mutuelle non renseignée', 'Mutuelle non renseignée', '2'
                WHERE '*CTINR2' NOT IN (SELECT code_original FROM activite.t_tiers_payant WHERE code_original IS NOT NULL)
                ;

                UPDATE activite.p_factures
                SET tiers_payant_1_id = t_tiers_payant.oid
                FROM activite.t_tiers_payant
                WHERE t_tiers_payant.code_original = '*CTINR1' AND
                tiers_payant_1_id = 0 AND
                    (montant_facture_1_c <> 0 OR montant_facture_1_h <> 0)
                ;
		
                UPDATE activite.p_factures
                SET tiers_payant_2_id = t_tiers_payant.oid
                FROM activite.t_tiers_payant
                WHERE t_tiers_payant.code_original = '*CTINR2' AND
                tiers_payant_2_id = 0 AND
                    (montant_facture_2_c <> 0 OR montant_facture_2_h <> 0)
                ;

			
				-- Nouvelle table des clients en attendant le dvp natif
				
				SELECT base.cti_disable_index('activite', 'i_facture_solde_tiers_c_1');
				SELECT base.cti_disable_index('activite', 'i_facture_solde_tiers_c_2');
				SELECT base.cti_disable_index('activite', 'i_facture_solde_tiers_c_3');
				SELECT base.cti_disable_index('activite', 'i_facture_solde_tiers_c_4');
				SELECT base.cti_disable_index('activite', 'i_facture_solde_tiers_c_5');
				SELECT base.cti_disable_index('activite', 'i_facture_solde_tiers_c_8');
			
				INSERT INTO activite.p_facture_solde_tiers_c
					(
					facture_id, 
					no_facture, 
					date_comptable, 
					rubrique_comptabilisation_id, 
					prestation_id, 
					tiers_payant_id,
					montant_comptabilise, 
					montant_regle, 
					montant_comptabilise_0, 
					montant_regle_0, 
					od_avoir,
                    od_non_comptabilise
					)
				SELECT
					facture_id, 
					p_factures_soldes_c.no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					tiers_payant_0_id AS tiers_payant_id,
					montant_comptabilise_0, 
					montant_regle_0, 
					montant_comptabilise_0, 
					montant_regle_0, 
					od_avoir,
                    od_non_comptabilise
				FROM activite.p_factures_soldes_c
				JOIN activite.p_factures ON p_factures_soldes_c.no_facture = p_factures.no_facture
				WHERE p_factures.tiers_payant_0_id > 0 AND
					(
					p_factures_soldes_c.montant_comptabilise_0 <> 0 OR
					p_factures_soldes_c.montant_regle_0 <> 0
					);

				INSERT INTO activite.p_facture_solde_tiers_c
					(
					facture_id, 
					no_facture, 
					date_comptable, 
					rubrique_comptabilisation_id, 
					prestation_id, 
					tiers_payant_id,
					montant_comptabilise, 
					montant_regle, 
					montant_comptabilise_1, 
					montant_regle_1, 
					od_avoir,
                    od_non_comptabilise
					)
				SELECT
					facture_id, 
					p_factures_soldes_c.no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					tiers_payant_1_id AS tiers_payant_id,
					montant_comptabilise_1, 
					montant_regle_1, 
					montant_comptabilise_1, 
					montant_regle_1, 
					od_avoir,
                    od_non_comptabilise
				FROM activite.p_factures_soldes_c
				JOIN activite.p_factures ON p_factures_soldes_c.no_facture = p_factures.no_facture
				WHERE p_factures.tiers_payant_1_id > 0 AND
					(
					p_factures_soldes_c.montant_comptabilise_1 <> 0 OR
					p_factures_soldes_c.montant_regle_1 <> 0
					);

				INSERT INTO activite.p_facture_solde_tiers_c
					(
					facture_id, 
					no_facture, 
					date_comptable, 
					rubrique_comptabilisation_id, 
					prestation_id, 
					tiers_payant_id,
					montant_comptabilise, 
					montant_regle, 
					montant_comptabilise_2, 
					montant_regle_2,
					od_avoir,
                    od_non_comptabilise
					)
				SELECT
					facture_id, 
					p_factures_soldes_c.no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					tiers_payant_2_id AS tiers_payant_id,
					montant_comptabilise_2, 
					montant_regle_2, 
					montant_comptabilise_2, 
					montant_regle_2,
					od_avoir,
                    od_non_comptabilise
				FROM activite.p_factures_soldes_c
				JOIN activite.p_factures ON p_factures_soldes_c.no_facture = p_factures.no_facture
				WHERE p_factures.tiers_payant_2_id > 0 AND
					(
					p_factures_soldes_c.montant_comptabilise_2 <> 0 OR
					p_factures_soldes_c.montant_regle_2 <> 0
					);

				INSERT INTO activite.p_facture_solde_tiers_c
					(
					facture_id, 
					no_facture, 
					date_comptable, 
					rubrique_comptabilisation_id, 
					prestation_id, 
					tiers_payant_id,
					montant_comptabilise, 
					montant_regle, 
					montant_comptabilise_2, 
					montant_regle_2,
					od_avoir,
                    od_non_comptabilise
					)
				SELECT
					facture_id, 
					p_factures_soldes_c.no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					tiers_payant_22_id AS tiers_payant_id,
					montant_comptabilise_22, 
					montant_regle_22, 
					montant_comptabilise_22, 
					montant_regle_22, 
					od_avoir,
                    od_non_comptabilise
				FROM activite.p_factures_soldes_c
				JOIN activite.p_factures ON p_factures_soldes_c.no_facture = p_factures.no_facture
				WHERE p_factures.tiers_payant_22_id > 0 AND
					(
					p_factures_soldes_c.montant_comptabilise_22 <> 0 OR
					p_factures_soldes_c.montant_regle_22 <> 0
					);

				SELECT base.cti_enable_index('activite', 'i_facture_solde_tiers_c_1');
				SELECT base.cti_enable_index('activite', 'i_facture_solde_tiers_c_2');
				SELECT base.cti_enable_index('activite', 'i_facture_solde_tiers_c_3');
				SELECT base.cti_enable_index('activite', 'i_facture_solde_tiers_c_4');
				SELECT base.cti_enable_index('activite', 'i_facture_solde_tiers_c_5');
				SELECT base.cti_enable_index('activite', 'i_facture_solde_tiers_c_8');

		-- Nouvelle table des honoraires
				
				SELECT base.cti_disable_index('activite', 'i_facture_solde_tiers_h_1');
				SELECT base.cti_disable_index('activite', 'i_facture_solde_tiers_h_2');
				SELECT base.cti_disable_index('activite', 'i_facture_solde_tiers_h_3');
				SELECT base.cti_disable_index('activite', 'i_facture_solde_tiers_h_4');
				SELECT base.cti_disable_index('activite', 'i_facture_solde_tiers_h_5');
				SELECT base.cti_disable_index('activite', 'i_facture_solde_tiers_h_8');
			
				INSERT INTO activite.p_facture_solde_tiers_h
					(
					facture_id, 
					no_facture, 
					date_comptable, 
					rubrique_comptabilisation_id, 
					prestation_id, 
					tiers_payant_id,
					montant_comptabilise, 
					montant_regle, 
					montant_comptabilise_0, 
					montant_regle_0, 
					od_avoir,
                    od_non_comptabilise
					)
				SELECT
					facture_id, 
					p_factures_soldes_h.no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					tiers_payant_0_id AS tiers_payant_id,
					montant_comptabilise_0, 
					montant_regle_0, 
					montant_comptabilise_0, 
					montant_regle_0, 
					od_avoir,
                    od_non_comptabilise
				FROM activite.p_factures_soldes_h
				JOIN activite.p_factures ON p_factures_soldes_h.no_facture = p_factures.no_facture
				WHERE p_factures.tiers_payant_0_id > 0 AND
					(
					p_factures_soldes_h.montant_comptabilise_0 <> 0 OR
					p_factures_soldes_h.montant_regle_0 <> 0
					);

				INSERT INTO activite.p_facture_solde_tiers_h
					(
					facture_id, 
					no_facture, 
					date_comptable, 
					rubrique_comptabilisation_id, 
					prestation_id, 
					tiers_payant_id,
					montant_comptabilise, 
					montant_regle, 
					montant_comptabilise_1, 
					montant_regle_1, 
					od_avoir,
                    od_non_comptabilise
					)
				SELECT
					facture_id, 
					p_factures_soldes_h.no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					tiers_payant_1_id AS tiers_payant_id,
					montant_comptabilise_1, 
					montant_regle_1, 
					montant_comptabilise_1, 
					montant_regle_1, 
					od_avoir,
                    od_non_comptabilise
				FROM activite.p_factures_soldes_h
				JOIN activite.p_factures ON p_factures_soldes_h.no_facture = p_factures.no_facture
				WHERE p_factures.tiers_payant_1_id > 0 AND
					(
					p_factures_soldes_h.montant_comptabilise_1 <> 0 OR
					p_factures_soldes_h.montant_regle_1 <> 0
					);

				INSERT INTO activite.p_facture_solde_tiers_h
					(
					facture_id, 
					no_facture, 
					date_comptable, 
					rubrique_comptabilisation_id, 
					prestation_id, 
					tiers_payant_id,
					montant_comptabilise, 
					montant_regle, 
					montant_comptabilise_2, 
					montant_regle_2,
					od_avoir,
                    od_non_comptabilise
					)
				SELECT
					facture_id, 
					p_factures_soldes_h.no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					tiers_payant_2_id AS tiers_payant_id,
					montant_comptabilise_2, 
					montant_regle_2, 
					montant_comptabilise_2, 
					montant_regle_2,
					od_avoir,
                    od_non_comptabilise
				FROM activite.p_factures_soldes_h
				JOIN activite.p_factures ON p_factures_soldes_h.no_facture = p_factures.no_facture
				WHERE p_factures.tiers_payant_2_id > 0 AND
					(
					p_factures_soldes_h.montant_comptabilise_2 <> 0 OR
					p_factures_soldes_h.montant_regle_2 <> 0
					);

				INSERT INTO activite.p_facture_solde_tiers_h
					(
					facture_id, 
					no_facture, 
					date_comptable, 
					rubrique_comptabilisation_id, 
					prestation_id, 
					tiers_payant_id,
					montant_comptabilise, 
					montant_regle, 
					montant_comptabilise_2, 
					montant_regle_2,
					od_avoir,
                    od_non_comptabilise
					)
				SELECT
					facture_id, 
					p_factures_soldes_h.no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					tiers_payant_22_id AS tiers_payant_id,
					montant_comptabilise_22, 
					montant_regle_22, 
					montant_comptabilise_22, 
					montant_regle_22, 
					od_avoir,
                    od_non_comptabilise
				FROM activite.p_factures_soldes_h
				JOIN activite.p_factures ON p_factures_soldes_h.no_facture = p_factures.no_facture
				WHERE p_factures.tiers_payant_22_id > 0 AND
					(
					p_factures_soldes_h.montant_comptabilise_22 <> 0 OR
					p_factures_soldes_h.montant_regle_22 <> 0
					);

				SELECT base.cti_enable_index('activite', 'i_facture_solde_tiers_h_1');
				SELECT base.cti_enable_index('activite', 'i_facture_solde_tiers_h_2');
				SELECT base.cti_enable_index('activite', 'i_facture_solde_tiers_h_3');
				SELECT base.cti_enable_index('activite', 'i_facture_solde_tiers_h_4');
				SELECT base.cti_enable_index('activite', 'i_facture_solde_tiers_h_5');
				SELECT base.cti_enable_index('activite', 'i_facture_solde_tiers_h_8');
				
		]]></sqlcmd>
		</NODE>

		<NODE label="Interventions">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_intervention;
				
				CREATE TEMP TABLE w_intervention AS
				SELECT 
					sejour_id,
					p_factures_lignes_h.date_debut,
					p_factures_lignes_h.heure_debut,
					(MAX(CASE WHEN t_prestations.code IN ('ADC','ACO') THEN Array[icr_1,COALESCE(acte_id,0)] ELSE null END))[2] AS acte_id,
					(MAX(CASE WHEN t_prestations.code IN ('ADC','ACO') THEN Array[icr_1,medecin_facture_id] ELSE NULL END))[2] AS medecin_chirurgien_id,
					(MAX(CASE WHEN t_prestations.code IN ('ADA') THEN Array[icr_1,medecin_facture_id] ELSE NULL END))[2] AS medecin_anesthesiste_id
				FROM 
					activite[PX].p_factures_lignes_h
					JOIN activite[PX].p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture
					JOIN base.t_actes ON acte_id = t_actes.oid
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				WHERE 
					t_prestations.code IN ('ADC', 'ACO', 'ADA') AND
					t_actes.code NOT LIKE 'YYYY%'
				GROUP BY 1,2,3
				HAVING MAX(CASE WHEN t_prestations.code IN ('ADC','ACO') THEN acte_id ELSE 0 END) > 0 AND
						SUM(nb_prestation) <> 0
				ORDER BY 1,2,3;

				INSERT INTO w_intervention 
				SELECT 
					sejour_id,
					p_factures_lignes_non_facturees_h.date_debut,
					p_factures_lignes_non_facturees_h.heure_debut,
					(MAX(CASE WHEN t_prestations.code IN ('ADC','ACO') THEN Array[icr_1,COALESCE(acte_id,0)] ELSE null END))[2] AS acte_id,
					(MAX(CASE WHEN t_prestations.code IN ('ADC','ACO') THEN Array[icr_1,medecin_facture_id] ELSE NULL END))[2] AS medecin_chirurgien_id,
					(MAX(CASE WHEN t_prestations.code IN ('ADA') THEN Array[icr_1,medecin_facture_id] ELSE NULL END))[2] AS medecin_anesthesiste_id
				FROM 
					activite.p_factures_lignes_non_facturees_h
					JOIN activite.p_factures ON p_factures_lignes_non_facturees_h.no_facture = p_factures.no_facture
					JOIN base.t_actes ON acte_id = t_actes.oid
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				WHERE 
					t_prestations.code IN ('ADC', 'ACO', 'ADA') AND
					t_actes.code NOT LIKE 'YYYY%' AND
					sejour_id NOT IN (SELECT sejour_id FROM w_intervention)
				GROUP BY 1,2,3
				HAVING MAX(CASE WHEN t_prestations.code IN ('ADC','ACO') THEN acte_id ELSE 0 END) > 0
				ORDER BY 1,2,3;

				TRUNCATE activite.p_intervention;
				
				-- Ajout des conditions "sejour_id != 0 AND date_debut IS DISTINCT FROM NULL" pour dégager les lignes sans date de début et sans référence à un séjour existant
				-- CLA 05/05/14
				
				INSERT INTO activite.p_intervention (
					sejour_id, 
					date_debut,
					heure_debut, 
					salle_id, 
					medecin_chirurgien_id, 
					medecin_anesthesiste_id, 
					acte_id
					)
				SELECT 
					sejour_id, 
					date_debut,
					heure_debut, 
					0::bigint AS salle_id, 
					COALESCE(medecin_chirurgien_id,0), 
					COALESCE(medecin_anesthesiste_id,0), 
					acte_id
				FROM w_intervention
				WHERE
					sejour_id != 0 AND date_debut IS DISTINCT FROM NULL;
				
				
				-- Ventilation selon date intervention
				SELECT activite.cti_ventilation_lignes('activite.p_factures_lignes_c');
				
				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_intervention CASCADE;	
				
				
			]]></sqlcmd>
		</NODE>

		<NODE label="Budget">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
			
                    SELECT activite.cti_budget_generate_keys();
					SELECT activite.cti_budget_execute_rules();
				
				
			]]></sqlcmd>
		</NODE>

		<NODE label="Lien PMSI">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
			
					SELECT activite.cti_reorganize_sejour_pmsi();
                    SELECT activite.cti_gen_dma_ssr();
					
					-- mise à jour potentielle à partir des lots pour être cohérent (prioritaires dans pmsi)
					SELECT base.cti_execute(
					'UPDATE activite.p_sejours_transferts
					SET 
						destination_id = etablissement_destination_id
					FROM activite.p_sejour_pmsi
						JOIN pmsi.p_rss_transferts ON p_sejour_pmsi.rss_id = p_rss_transferts.rss_id
						JOIN base.t_etablissements ON etablissement_destination_id = t_etablissements.oid
					WHERE p_sejours_transferts.sejour_id = p_sejour_pmsi.sejour_id AND
						etablissement_destination_id > 0 AND
						destination_id <> etablissement_destination_id AND
						length(t_etablissements.code) = 9
					.,
					
					INSERT INTO activite.p_sejours_transferts(sejour_id, provenance_id, destination_id)
					SELECT
						sejour_id,
						MAX(etablissement_provenance_id),
						MAX(etablissement_destination_id)
					FROM activite.p_sejour_pmsi
						JOIN pmsi.p_rss_transferts ON p_sejour_pmsi.rss_id = p_rss_transferts.rss_id
					WHERE
						sejour_id NOT IN (SELECT sejour_id FROM activite.p_sejours_transferts)
					GROUP BY 1
					HAVING
					(
						MAX(etablissement_provenance_id) > 0 OR
						MAX(etablissement_destination_id) > 0
					)
					',1)
					WHERE 'p_rss' IN (SELECT tablename FROM pg_tables WHERE schemaname = 'pmsi' AND tablename = 'p_rss')
					;
					
					-- Ajustement chiffre d'affaire fil de l'eau PMSI
					SELECT activite.cti_ajust_fildeleau_rsf()
					;
					
					

			]]></sqlcmd>
		</NODE>

		<NODE label="Corrections séjours">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>
			<sqlcmd><![CDATA[
			
				-- Etablissements transfert vide
				INSERT INTO activite.p_sejours_transferts(sejour_id, provenance_id,destination_id)
				SELECT oid, 0, 0
				FROM activite.p_sejours
				WHERE p_sejours.oid NOT IN (SELECT sejour_id FROM activite.p_sejours_transferts)
				;
			
				-- Màj des médecins séjour d'après les médecins actes si pas encore de médecin RSS dans p_séjours 
				-- et qu'il y a des exécutants renseignés dans p_factures_lignes_h
				-- On prend l'exécutant de l'acte avec le plus fort ICR
				DROP TABLE IF EXISTS w_executants;
				CREATE TEMP TABLE w_executants AS
				SELECT
					p_sejours.oid AS sejour_id, 
					(MAX(ARRAY[t_actes.icr_1, p_factures_lignes_h.montant_facture+p_factures_lignes_h.montant_encours,p_factures_lignes_h.medecin_facture_id]))[3] as medecin_id
				FROM activite.p_factures_lignes_h
					JOIN activite.p_factures on p_factures.oid = p_factures_lignes_h.facture_id
					JOIN activite.p_sejours on p_sejours.no_sejour = p_factures.no_sejour
					JOIN base.t_actes ON acte_id = t_actes.oid
				WHERE acte_id <> 0
					AND medecin_sejour_id = 0
                    AND activite_ccam <> '4'
					AND medecin_facture_id != 0
					AND type_sejour IN ('2','3','4')
				GROUP BY 1;
	
				UPDATE activite.p_sejours SET
					medecin_sejour_id = w_executants.medecin_id
				FROM w_executants
				WHERE 1=1
					AND w_executants.sejour_id = p_sejours.oid
					AND p_sejours.medecin_sejour_id = 0;
                    
                UPDATE activite.p_mouvements_sejour
				SET medecin_sejour_id = p_sejours.medecin_sejour_id
				FROM activite.p_sejours
				WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
					p_sejours.medecin_sejour_id  <> p_mouvements_sejour.medecin_sejour_id
				;

			]]></sqlcmd>
		</NODE>

		<NODE label="Chiffrier CTI">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>
			<sqlcmd><![CDATA[

				TRUNCATE activite[PX].p_chiffrier
				;

				INSERT INTO activite[PX].p_chiffrier (mois)
				SELECT mois
				FROM (
					SELECT DISTINCT to_char(date_sortie, 'YYYYMM')::numeric AS mois FROM activite[PX].p_sejours
					WHERE date_sortie >= 20100101 AND to_char(date_sortie, 'YYYYMM')::numeric <= to_char(now() + interval '1 month', 'YYYYMM')::numeric
				) subview
				;

				DELETE FROM activite[PX].p_chiffrier WHERE mois > to_char(now() + interval '1 month', 'YYYYMM')::numeric
				;

			]]></sqlcmd>
		</NODE>

		<NODE label="Calculs divers">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>
			<sqlcmd><![CDATA[
            
                -- Génération lignes fictive clinique pour facturation uniquement honoraires
				SELECT activite.cti_gen_0ets();

                
                -- Calcule moyen 12 derniers mois glissants
				DROP TABLE IF EXISTS w_chiffrier;
					CREATE TEMP TABLE w_chiffrier AS
					SELECT 
						date(date_trunc('month',date_comptable) + interval '1 month' - interval '1 day') AS date_comptable,
						SUM(montant_comptabilise) AS montant_comptabilise,
						SUM(montant_regle) AS montant_regle,
						COUNT(DISTINCT CASE WHEN date_trunc('month', p_factures.date_vente) = date_trunc('month', date_comptable) THEN p_factures.no_sejour ELSE null END) AS nb_sejour,
						0::numeric AS montant_solde,
						0::numeric AS montant_encours_cti,
						0::numeric AS montant_encours_prs,
						0::numeric AS montant_report_encours_cti,
						0::numeric AS montant_report_encours_prs
					FROM activite.p_factures_soldes_c p_factures_soldes
						JOIN activite.p_factures ON p_factures_soldes.no_facture = p_factures.no_facture
					WHERE date_comptable <= date(date_trunc('month',now()) + interval '1 month' - interval '1 day')
					GROUP BY 1
					ORDER BY 1;
					
					UPDATE w_chiffrier
					SET montant_solde = 
						(SELECT SUM(montant_comptabilise - montant_regle) 
						FROM w_chiffrier w_chiffrier_histo 
						WHERE w_chiffrier_histo.date_comptable <= w_chiffrier.date_comptable);
					
					-- Reprise des encours
					
					UPDATE w_chiffrier SET
						montant_encours_cti = subview.montant_encours_cti,
						montant_encours_prs = subview.montant_encours_prs
					FROM
					(
					SELECT 
						date(date_trunc('month',date_encours) + interval '1 month' - interval '1 day') AS date_comptable, 
						SUM(CASE WHEN code_origine = 'C' THEN montant_encours_c ELSE 0 END) AS montant_encours_cti, 
						SUM(CASE WHEN code_origine = 'P' THEN montant_encours_c ELSE 0 END) AS montant_encours_prs
					FROM activite.p_factures_encours
					GROUP BY 1
					) subview
					WHERE w_chiffrier.date_comptable = subview.date_comptable;

					UPDATE w_chiffrier SET
						montant_report_encours_cti = w_chiffrier_2.montant_encours_cti
					FROM w_chiffrier w_chiffrier_2
					WHERE date_trunc('month',w_chiffrier.date_comptable) - interval '1 month' =
						date_trunc('month',w_chiffrier_2.date_comptable)
					;				
					
				-- occupation
					DROP TABLE IF EXISTS w_chiffrier_dt_occ;
					CREATE TEMP TABLE w_chiffrier_dt_occ AS
					SELECT 
						date(date_trunc('month',date_fin) + interval '1 month' - interval '1 day') AS date_occupation,
						SUM(v_factures_lignes_c_5.montant_facture) +  SUM(v_factures_lignes_c_5.montant_encours) AS montant_comptabilise_dt_occ,
						COUNT(DISTINCT  v_factures_lignes_c_5.no_sejour ) AS nb_sejour_dt_occ
					FROM  activite.v_factures_lignes_c_5
					JOIN activite.v_factures_reference_1  ON (v_factures_lignes_c_5.no_sejour = v_factures_reference_1.no_sejour)
					where date(date_trunc('month',date_fin) + interval '1 month' - interval '1 day')  <= (select max(valeur) from activite.t_divers where code ilike 'NOWCLOTURE')
					GROUP BY 1
					ORDER BY 1;	
					
				--sortie
					DROP TABLE IF EXISTS w_chiffrier_dt_sor;
					CREATE TEMP TABLE w_chiffrier_dt_sor AS
					SELECT 
						date(date_trunc('month',date_fin_facture) + interval '1 month' - interval '1 day') AS date_sortie,
						SUM(v_factures_reference_1.montant_facture_c) + SUM(v_factures_reference_1.montant_encours_c) AS montant_comptabilise_dt_sor,
						COUNT(DISTINCT  v_factures_reference_1 ) AS nb_sejour_dt_sor
					FROM  activite.v_factures_reference_1
					where date(date_trunc('month',date_fin_facture) + interval '1 month' - interval '1 day')  <= (select max(valeur) from activite.t_divers where code ilike 'NOWCLOTURE')
					GROUP BY 1
					ORDER BY 1;				
				--groupage
					DROP TABLE IF EXISTS w_chiffrier_dt_grp;
					CREATE TEMP TABLE w_chiffrier_dt_grp AS
					SELECT 
						date(date_trunc('month',date_groupage) + interval '1 month' - interval '1 day') AS date_groupage,
						SUM(v_factures_reference_1.montant_facture_c) + SUM(v_factures_reference_1.montant_encours_c) AS montant_comptabilise_dt_grp,
						COUNT(DISTINCT  v_factures_reference_1 ) AS nb_sejour_dt_grp
					FROM  activite.v_factures_reference_1
					where date(date_trunc('month',date_groupage) + interval '1 month' - interval '1 day')  <= (select max(valeur) from activite.t_divers where code ilike 'NOWCLOTURE')
					GROUP BY 1
					ORDER BY 1;
				--  table resultat_glob
					DROP TABLE IF EXISTS activite.p_chiffrier_data_calcule_gliss;
					CREATE  TABLE activite.p_chiffrier_data_calcule_gliss AS
					select * from w_chiffrier 
					LEFT JOIN w_chiffrier_dt_occ ON w_chiffrier_dt_occ.date_occupation = w_chiffrier.date_comptable
					LEFT JOIN w_chiffrier_dt_sor ON w_chiffrier_dt_sor.date_sortie = w_chiffrier.date_comptable
					LEFT JOIN w_chiffrier_dt_grp ON w_chiffrier_dt_grp.date_groupage = w_chiffrier.date_comptable;
				
					DROP TABLE IF EXISTS activite.p_chiffrier_resultat_calcule_gliss;
					CREATE  TABLE activite.p_chiffrier_resultat_calcule_gliss AS	
					
					select p_chiffrier_data_calcule_gliss.date_comptable as date_comptable,
						mois_texte ||' '|| iso_annee as texte,
						('Du '|| (select mois_texte ||' '||iso_annee from base.p_calendrier where date = (p_chiffrier_data_calcule_gliss.date_comptable - interval '1 year' + interval '1 day')::date) || ' au ' || (mois_texte ||' '||iso_annee)) as periode,
						AVG(w_chiffrier_glis.montant_comptabilise) as mt_cpt,
						AVG(w_chiffrier_glis.montant_comptabilise)/20 as mt_cpt_j,
						AVG(w_chiffrier_glis.montant_regle) as mt_reg,
						AVG(w_chiffrier_glis.montant_regle)/20 as mt_reg_j,
						AVG(w_chiffrier_glis.nb_sejour) as nb_sej,
						AVG(w_chiffrier_glis.nb_sejour)/20 as nb_sej_j,
						AVG(w_chiffrier_glis.montant_solde) as mt_sol,
						AVG(w_chiffrier_glis.montant_solde)/20 as mt_sol_j,
						AVG(w_chiffrier_glis.montant_comptabilise + w_chiffrier_glis.montant_encours_cti - w_chiffrier_glis.montant_report_encours_cti  )  as mt_act_cpt,
						AVG(w_chiffrier_glis.montant_comptabilise + w_chiffrier_glis.montant_encours_cti - w_chiffrier_glis.montant_report_encours_cti  )/20  as mt_act_cpt_j,
						AVG(w_chiffrier_glis.nb_sejour_dt_occ) as nb_sej_dt_occ,
						AVG(w_chiffrier_glis.nb_sejour_dt_occ)/20 as nb_sej_dt_occ_j,
						AVG(w_chiffrier_glis.montant_comptabilise_dt_occ) as mt_cpt_occ,
						AVG(w_chiffrier_glis.montant_comptabilise_dt_occ)/20 as mt_cpt_occ_j,
						AVG(w_chiffrier_glis.nb_sejour_dt_sor) as nb_sej_dt_sor,
						AVG(w_chiffrier_glis.nb_sejour_dt_sor)/20 as nb_sej_dt_sor_j,
						AVG(w_chiffrier_glis.montant_comptabilise_dt_sor) as mt_cpt_sor,
						AVG(w_chiffrier_glis.montant_comptabilise_dt_sor)/20 as mt_cpt_sor_j,
						
						AVG(w_chiffrier_glis.nb_sejour_dt_grp) as nb_sej_dt_grp,
						AVG(w_chiffrier_glis.nb_sejour_dt_grp)/20 as nb_sej_dt_grp_j,
						AVG(w_chiffrier_glis.montant_comptabilise_dt_grp) as mt_cpt_grp,
						AVG(w_chiffrier_glis.montant_comptabilise_dt_grp)/20 as mt_cpt_grp_j
						
					from activite.p_chiffrier_data_calcule_gliss 
					JOIN base.p_calendrier ON p_chiffrier_data_calcule_gliss.date_comptable = p_calendrier.date
					LEFT JOIN activite.p_chiffrier_data_calcule_gliss w_chiffrier_glis on w_chiffrier_glis.date_comptable between p_chiffrier_data_calcule_gliss.date_comptable - interval '1 year' + interval '1 day' and p_chiffrier_data_calcule_gliss.date_comptable 
					where p_chiffrier_data_calcule_gliss.date_comptable BETWEEN 2012 AND EXTRACT(YEAR FROM NOW()) + 1
					AND p_chiffrier_data_calcule_gliss.date_comptable  <= (select max(valeur) from activite.t_divers where code ilike 'NOWCLOTURE')

					group by 1,2 order by 1	;	
                    
                -- Calcul effet prix GHS
                SELECT activite.cti_gen_sejour_effet_tarif();
                
                -- Calcule durée d'occupation par SERVICE/UF/UM/ETAGE/LIT
                SELECT activite.cti_calc_duree_occupation();

			]]></sqlcmd>
		</NODE>

		<NODE label="Correction table des mouvements">
			<condition><![CDATA[
                "[PX]" == ""
            ]]></condition>

			<sqlcmd><![CDATA[
            
                --Selon les prestataires le sejour_id est vide
                
                UPDATE activite[PX].p_mouvements_sejour
                    SET sejour_id = p_sejours.oid
                FROM activite[PX].p_sejours
                WHERE true 
                    AND p_mouvements_sejour.no_sejour = p_sejours.no_sejour
                    AND p_mouvements_sejour.sejour_id = 0 
                    AND p_sejours.oid != 0
                ;
            
            ]]></sqlcmd>
		</NODE>

		<NODE label="Formes d'activité">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
			
					SELECT activite.cti_reorganize_forme_activite()
					;
					
					SELECT activite.cti_filiere_soin_execute_rule()
					;
					
					SELECT activite.cti_execute_compte_produit_analytique_rule()
					;

			]]></sqlcmd>
		</NODE>


		<NODE label="Référencements">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
			
				
				-- Oids
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'dursej', date_sortie - date_entree 
				FROM activite[PX].p_sejours 
				WHERE date_sortie - date_entree NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'dursej')
				AND date_sortie >= date_entree 
				AND date_sortie < '2099-12-31'::date
				GROUP BY 2
				ORDER BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'c_postaux', code_postal_id 
				FROM activite[PX].p_sejours 
				WHERE code_postal_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'c_postaux')
				GROUP BY 2;
                
                INSERT INTO activite.p_oids (code_table, oid) 
                SELECT 'forme_activite', forme_activite_id 
                FROM activite.p_sejours 
                WHERE forme_activite_id NOT IN (SELECT oid FROM activite.p_oids WHERE code_table = 'forme_activite')
                GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'medecin_s', medecin_sejour_id 
				FROM activite[PX].p_sejours 
				WHERE medecin_sejour_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'medecin_s')
				GROUP BY 2;
								
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'medecin_s', medecin_sejour_id 
				FROM activite[PX].p_mouvements_sejour 
				WHERE medecin_sejour_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'medecin_s')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'ghs', ghs_id 
				FROM activite[PX].p_sejours 
				WHERE ghs_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'ghs')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'ghm', ghm_id 
				FROM activite[PX].p_sejours 
				WHERE ghm_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'ghm')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'ghs', ghs_id 
				FROM activite[PX].p_factures 
				WHERE ghs_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'ghs')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'medecin_x', medecin_facture_id 
				FROM activite[PX].p_factures_lignes_h 
				WHERE medecin_facture_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'medecin_x')
				GROUP BY 2;
                
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'gme', gme_id 
				FROM activite[PX].p_sejours 
				WHERE gme_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'gme')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'ghmgme', ghmgme_id 
				FROM activite[PX].p_sejours 
				WHERE ghmgme_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'ghmgme')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'rubrique_c', rubrique_facturation_id
				FROM activite[PX].p_factures_lignes_c WHERE rubrique_facturation_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'rubrique_c')
				GROUP BY 2;
	
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'rubrique_c', rubrique_comptabilisation_id
				FROM activite[PX].p_factures_lignes_c WHERE rubrique_comptabilisation_id NOT IN (SELECT oid	FROM activite[PX].p_oids WHERE code_table = 'rubrique_c')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'rubrique_c', rubrique_facturation_id
				FROM activite[PX].p_factures_encours_lignes_c WHERE rubrique_facturation_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'rubrique_c')
				GROUP BY 2;
	
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'rubrique_c', rubrique_comptabilisee_id
				FROM activite[PX].p_factures_soldes_c WHERE rubrique_comptabilisee_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'rubrique_c')
				GROUP BY 2;
	
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'prestation_c', prestation_id
				FROM activite[PX].p_factures_lignes_c WHERE prestation_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'prestation_c')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'prestation_c', prestation_id
				FROM activite[PX].p_factures_encours_lignes_c WHERE prestation_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'prestation_c')
				GROUP BY 2;
				
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'lpp', lpp_id
				FROM activite[PX].p_factures_lignes_c WHERE lpp_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'lpp')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'ucd', ucd_id
				FROM activite[PX].p_factures_lignes_c WHERE ucd_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'ucd')
				GROUP BY 2;
				
				
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'prestation_c', prestation_id
				FROM activite[PX].p_factures_soldes_c WHERE prestation_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'prestation_c')
				GROUP BY 2;
				
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'prestation_h', prestation_id
				FROM activite[PX].p_factures_lignes_h WHERE prestation_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'prestation_h')
				GROUP BY 2;
				
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'acte_h', acte_id
				FROM activite[PX].p_factures_lignes_h WHERE acte_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'acte_h')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'protocole_h', protocole_id
				FROM activite[PX].p_factures_lignes_h WHERE protocole_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'protocole_h')
				GROUP BY 2;
				
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'tiers_payant', tiers_payant_0_id
				FROM activite[PX].p_factures WHERE tiers_payant_0_id <> 0 AND tiers_payant_0_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'tiers_payant')
				GROUP BY 2;
				
				
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'tiers_payant', tiers_payant_1_id
				FROM activite[PX].p_factures WHERE tiers_payant_1_id <> 0 AND tiers_payant_1_id NOT IN (SELECT oid
				FROM activite[PX].p_oids WHERE code_table = 'tiers_payant')
				GROUP BY 2;
				
				
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'tiers_payant', tiers_payant_2_id
				FROM activite[PX].p_factures WHERE tiers_payant_2_id <> 0 AND tiers_payant_2_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'tiers_payant')
				GROUP BY 2;
				
				
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'tiers_payant', tiers_payant_22_id
				FROM activite[PX].p_factures WHERE tiers_payant_22_id <> 0 AND tiers_payant_22_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'tiers_payant')
				GROUP BY 2;
				
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'mode_traitement', t_services_facturation.mode_traitement_id
				FROM activite[PX].t_lieux JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
				WHERE 
					t_services_facturation.mode_traitement_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'mode_traitement' AND oid IS NOT NULL) AND t_services_facturation.mode_traitement_id IS NOT NULL
				GROUP BY 2;
	
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'lit', lit_id
				FROM activite[PX].t_lieux WHERE lit_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'lit')
				GROUP BY 2;
				

					
				INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'service', service_facturation_id
				FROM activite[PX].t_lieux WHERE service_facturation_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'service')
				GROUP BY 2;
                
                INSERT INTO activite[PX].p_oids (code_table, oid)
				SELECT 'activite', activite_id
				FROM activite[PX].t_lieux WHERE activite_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'activite')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
						SELECT 'etage', etage_id
				FROM activite[PX].t_lieux, activite[PX].t_lits WHERE lit_id = t_lits.oid AND etage_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'etage')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
						SELECT 'compte', compte_produit_id
				FROM activite[PX].p_factures_lignes_c WHERE compte_produit_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'compte')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
						SELECT 'compte', compte_produit_analytique_id
				FROM activite[PX].p_factures_lignes_c WHERE compte_produit_analytique_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'compte')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'uf', unite_fonctionnelle_id
				FROM activite[PX].t_lieux WHERE unite_fonctionnelle_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'uf')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'um', unite_medicale_id
				FROM activite[PX].t_lieux WHERE unite_medicale_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'um')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'medecin_t', medecin_traitant_id 
				FROM activite[PX].p_sejours 
				WHERE medecin_traitant_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'medecin_t')
				GROUP BY 2;
				
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'filiere_soin', filiere_soin_principale_id 
				FROM activite[PX].p_sejours 
				WHERE filiere_soin_principale_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'filiere_soin')
				GROUP BY 2;
																	
			]]></sqlcmd>
		</NODE>

		<NODE label="Tables répliquées">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
				
				SELECT activite[PX].cti_reorganize_ghs_c();
				
				SELECT activite[PX].cti_reorganize_ghm_c();
				
				SELECT activite[PX].cti_reorganize_gmt_c();
				
				SELECT activite[PX].cti_reorganize_gme_c();
				
				SELECT activite[PX].cti_reorganize_actes_c();
				
				SELECT activite[PX].cti_reorganize_lieux_c();
				
				SELECT activite[PX].cti_reorganize_medecins_administratifs_c();
				
				SELECT activite[PX].cti_reorganize_tiers_payant();
				
				SELECT activite[PX].cti_reorganize_ages_c();
				
				SELECT base.cti_reorganize_codes_postaux_c('activite');
				
				SELECT activite[PX].cti_reorganize_durees_sejour_c();
				
				SELECT activite.cti_reorganize_finess_c();
								
				SELECT activite.cti_reorganize_ucd_lpp_c();
				
				SELECT activite[PX].cti_reorganize_controle_chiffrier();
				
				SELECT activite[PX].cti_update_schema_classes('*ALL');
				
                SELECT activite.cti_now('NOW','FORCE');
                SELECT activite.cti_now('NOWCLOTURE','FORCE');

			]]></sqlcmd>

		</NODE>

		<NODE label="Poles">

			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[
					
					SELECT activite.cti_reorganize_pole()
					;

					INSERT INTO activite.p_oids (code_table, oid) 
					SELECT 'pole', pole_id 
					FROM activite.p_mouvements_sejour
					WHERE pole_id NOT IN (SELECT oid FROM activite.p_oids WHERE code_table = 'pole')
					GROUP BY 2;
									
					INSERT INTO activite.p_oids (code_table, oid) 
					SELECT 'pole', pole_id 
					FROM activite.p_factures_lignes_c
					WHERE pole_id NOT IN (SELECT oid FROM activite.p_oids WHERE code_table = 'pole')
					GROUP BY 2;

			]]></sqlcmd>
		</NODE>

	</NODE>

	<NODE name="VACUUM" label="REORGANISATION BASE DE DONNEES">

		<condition><![CDATA[
			"[PX]" == ""
		]]></condition>

		<NODE label="Réorganisation tables">

			<sqlcmd><![CDATA[
			
				ANALYSE activite[PX].p_chiffrier_comptable;
				ANALYSE activite[PX].p_chiffrier_shs;
				ANALYSE activite[PX].p_ecriture_comptable;
				VACUUM ANALYSE activite[PX].p_factures;
				ANALYSE activite[PX].p_factures_comptables;
				VACUUM ANALYSE activite[PX].p_factures_encours;
				ANALYSE activite[PX].p_factures_encours_lignes_c;
				ANALYSE activite[PX].p_factures_lignes_c;
				ANALYSE activite[PX].p_factures_lignes_h;
				ANALYSE activite[PX].p_factures_lignes_non_facturees_c;
				ANALYSE activite[PX].p_factures_lignes_non_facturees_h;
				ANALYSE activite[PX].p_factures_rejets;
				ANALYSE activite[PX].p_factures_soldes_c;
				ANALYSE activite[PX].p_factures_soldes_h;
				ANALYSE activite[PX].p_intervention;
				ANALYSE activite[PX].p_mouvements_sejour;
				ANALYSE activite[PX].p_oids;
				ANALYSE activite[PX].p_patients;
				VACUUM ANALYSE activite[PX].p_sejours;
				REINDEX TABLE activite[PX].p_sejours;
				ANALYSE activite[PX].p_sejours_assurance;
				ANALYSE activite[PX].t_activites;
				ANALYSE activite[PX].t_classes;
				ANALYSE activite[PX].t_classes_sections;
				ANALYSE activite[PX].t_classes_sections_elements;
				ANALYSE activite[PX].t_etages;
				ANALYSE activite[PX].t_ghs_c;
				ANALYSE activite[PX].t_indicateurs;
				ANALYSE activite[PX].t_lieux;
				ANALYSE activite[PX].t_lieux_c;
				ANALYSE activite[PX].t_listes;
				ANALYSE activite[PX].t_listes_contenu;
				ANALYSE activite[PX].t_listes_tables;
				ANALYSE activite[PX].t_lits;
				ANALYSE activite[PX].t_medecins_administratifs;
				ANALYSE activite[PX].t_medecins_administratifs_c;
				ANALYSE activite[PX].t_prestations;
				ANALYSE activite[PX].t_rapports;
				ANALYSE activite[PX].t_rapports_rubriques;
				ANALYSE activite[PX].t_rejets_noemie;
				ANALYSE activite[PX].t_rubriques_facturation;
				ANALYSE activite[PX].t_services_facturation;
				ANALYSE activite[PX].t_specialites_medecin;
				ANALYSE activite[PX].t_tiers_payant;
				ANALYSE activite[PX].t_types_tiers_payant;
				ANALYSE activite[PX].t_unites_fonctionnelles;
				ANALYSE activite[PX].t_unites_medicales;
				
				VACUUM ANALYSE activite[PX].p_bloc_occupation;
				VACUUM ANALYSE activite[PX].p_coordonnees_patient;
				VACUUM ANALYSE activite[PX].t_controle_chiffrier;
				VACUUM ANALYSE activite[PX].t_etages;
				VACUUM ANALYSE activite[PX].t_etages_historique;
				VACUUM ANALYSE activite[PX].t_expert_controle;
				VACUUM ANALYSE activite[PX].t_forme_activite_rule;
				VACUUM ANALYSE activite[PX].t_lieux;
				VACUUM ANALYSE activite[PX].t_rapport_group;
				VACUUM ANALYSE activite[PX].t_services_facturation;
				VACUUM ANALYSE activite[PX].t_services_facturation_historique;
				VACUUM ANALYSE activite[PX].t_unites_fonctionnelles_historique;
				VACUUM ANALYSE activite[PX].t_unites_medicales_historique;
			
				-- indexes
				REINDEX TABLE activite.p_factures;
				REINDEX TABLE activite.p_factures_encours_lignes_c;
				REINDEX TABLE activite.p_patients;
				REINDEX TABLE activite.p_sejour_effet_tarif;
				REINDEX TABLE activite.p_ecriture_comptable;
			]]></sqlcmd>
		</NODE>

		<NODE label="Vide cache">
			<sqlcmd><![CDATA[
			
				SELECT cti_cache_reload as log from cache.cti_cache_reload('iCTI_activite', true);
				
			]]></sqlcmd>
		</NODE>


	</NODE>

	<NODE name="RAZ" label="RAZ BASE">

		<NODE label="Parametres">
			<sqlcmd><![CDATA[
							
					SELECT activite[PX].cti_initialize_tables()
                    ;
                    SELECT base.cti_verify_sequences('activite')
                    ;
                    
                    -- Initialisation table des prestations / ccam
                    INSERT INTO activite.t_prestations (code, texte, texte_court)
                    SELECT code, texte, texte
                    FROM base.t_ccam_regroupements
                    WHERE code NOT IN (SELECT code FROM activite.t_prestations) AND
                        code NOT IN ('NGAP','CCAM','CDAM') AND
                        length(code) = 3 AND
                        oid IN (SELECT ccam_regroupement_id_1 FROM base.t_actes) AND
                        code <> ''
                    ;

        
				
			]]></sqlcmd>
		</NODE>


		<NODE label="Nettoyage des tables">
			<sqlcmd><![CDATA[
			
				TRUNCATE activite[PX].p_chiffrier_comptable;
				
				TRUNCATE activite[PX].p_factures_comptables;
				
				TRUNCATE activite[PX].p_ecriture_comptable;

				TRUNCATE activite[PX].p_patients;
				
				TRUNCATE activite[PX].p_coordonnees_patient;
				
				TRUNCATE activite[PX].p_sejours;
				
				TRUNCATE activite[PX].p_sejours_groupes_smr;
				
				TRUNCATE activite[PX].p_sejours_assurance;
				
				TRUNCATE activite[PX].p_sejours_transferts;
				
				ALTER SEQUENCE activite[PX].s_sejours RESTART WITH 1;

				TRUNCATE activite[PX].p_mouvements_sejour;
				
				TRUNCATE activite[PX].p_intervention;
				
				-- Les Lieux ne sont plus effacés mais attention aux clés en double
				--TRUNCATE activite[PX].t_lieux;
				
				DROP TABLE IF EXISTS w_lieux
				;
				CREATE TEMP TABLE w_lieux AS
					with lieux as (
						SELECT
							code_original_1,
							code_original_2,
							code_original_3,
							code_original_4,
							code_original_5,
							code_original_6, 
							MIN(t_lieux.oid) AS keep_oid,
							array_agg(oid) AS all_oid
						FROM activite[PX].t_lieux
						GROUP BY 1,2,3,4,5,6
						HAVING count(*) > 1
					)
					select
						keep_oid,
						unnest(all_oid) as all_oid
					from lieux
				;
				
				ANALYSE w_lieux
				;
                
                UPDATE activite[PX].p_factures_encours SET
				 lieu_sortie_id = keep_oid
				FROM w_lieux
				WHERE 1=1
					AND lieu_sortie_id = all_oid
					AND lieu_sortie_id != keep_oid
                ;

				UPDATE activite[PX].p_factures_encours_lignes_c SET
					lieu_id = keep_oid
				FROM w_lieux
				WHERE 1=1
					AND lieu_id = all_oid
					AND lieu_id != keep_oid
                ;
				
				-- Report sur justificatif encours
				UPDATE activite.p_facture_encours_ligne_valorise_c
				SET lieu_id = p_factures_encours_lignes_c.lieu_id
				FROM activite.p_factures_encours_lignes_c
				WHERE p_facture_encours_ligne_valorise_c.no_facture = p_factures_encours_lignes_c.no_facture AND
					p_facture_encours_ligne_valorise_c.date_debut = p_factures_encours_lignes_c.date_debut AND
					p_facture_encours_ligne_valorise_c.prestation_id = p_factures_encours_lignes_c.prestation_id AND
					p_facture_encours_ligne_valorise_c.lieu_id <> p_factures_encours_lignes_c.lieu_id
				;

				DELETE FROM activite[PX].t_lieux
				USING w_lieux
				WHERE 1=1
					AND t_lieux.oid = w_lieux.all_oid
					AND w_lieux.keep_oid != t_lieux.oid
				;
				
				--ALTER SEQUENCE activite[PX].s_lieux RESTART WITH 1;
				
				TRUNCATE activite[PX].p_factures;
				
				ALTER SEQUENCE activite[PX].s_factures RESTART WITH 1;

				TRUNCATE activite[PX].p_factures_lignes_non_facturees_c;
				
				TRUNCATE activite[PX].p_factures_lignes_non_facturees_h;
				
				TRUNCATE activite[PX].p_factures_lignes_c;
				
				TRUNCATE activite[PX].p_factures_lignes_h;
				
				TRUNCATE activite[PX].p_factures_rejets;
				
				TRUNCATE activite[PX].p_factures_soldes_c;
				TRUNCATE activite[PX].p_facture_solde_tiers_c;
				
				TRUNCATE activite[PX].p_factures_soldes_h;
				TRUNCATE activite[PX].p_facture_solde_tiers_h;
				
				TRUNCATE activite[PX].p_factures_comptables;
				
				TRUNCATE activite[PX].p_factures_reference;
				TRUNCATE activite[PX].p_factures_reference_tiers;
				
				TRUNCATE activite[PX].p_intervention;
										
			]]></sqlcmd>
		</NODE>

		<NODE label="Pré-initialisation">
			<sqlcmd><![CDATA[ 
				
				
				
			]]></sqlcmd>
		</NODE>

	</NODE>





</ROOT>
