<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
	
	
	<NODE name="INIT" label="INITIALISATIONS">

		<NODE label="Tests initiaux">
			<sqlcmd><![CDATA[
		
			]]></sqlcmd>
		</NODE>
	
		<NODE label="Identification des séjours">
			<sqlcmd><![CDATA[
            
                DROP TABLE IF EXISTS w_periode;
				CREATE TEMP TABLE w_periode AS
				SELECT 
                    greatest(max_reg,max_sej) AS date_extraction
                FROM 
                    (SELECT max(date) as max_reg FROM prod_mederi.KRGLDET WHERE DATE <= now() AND DATE >= '[ENV_ADM_ANNEEDEBUT]0101') sub,
                    (SELECT greatest(
                        max(CASE WHEN DATEENTREE <= now() THEN DATEENTREE ELSE '1900-01-01' END),
                        max(CASE WHEN  DATESORTIE <= now() THEN DATESORTIE ELSE '1900-01-01' END))
                    as max_sej FROM prod_mederi.KDOSSIER WHERE TYPDOS != 4
                    AND DATEENTREE >= '[ENV_ADM_ANNEEDEBUT]0101'
                ) sub2;
				
				-- Corrections TP
				UPDATE prod_mederi.KDOSSIER
				SET COORGDEST = subview.COORGDEST
				FROM (SELECT substr(COORGDEST,1,10) AS COORGDEST10, MAX(COORGDEST) AS COORGDEST, count(*)  FROM prod_mederi.KORGDEST WHERE LENGTH(COORGDEST) > 10 GROUP BY 1) subview
				WHERE KDOSSIER.COORGDEST = subview.COORGDEST10
				;
				UPDATE prod_mederi.KDOSSIER
				SET COORGDEST = 'PATIENT'
				WHERE COALESCE(COORGDEST,'') = '' AND 'PATIENT' IN (SELECT trim(COORGDEST) FROM prod_mederi.KORGDEST WHERE  COORGDEST LIKE 'PAT%')
				;
				
				-- Corrections RSS
				DROP TABLE IF EXISTS w_KRSS;
				CREATE TEMP TABLE w_KRSS AS
				SELECT *
				FROM prod_mederi.KRSS 
				;

				ANALYSE w_KRSS
				;

				DELETE FROM w_KRSS
				USING
				(
				SELECT K5CLEUNIK, count(*),
					(MAX(ARRAY[RSSCMDGHM, RSSSORT::text, CTID::text]))[3]::TID AS keep_CTID
				FROM w_KRSS
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE w_KRSS.K5CLEUNIK = subview.K5CLEUNIK AND
					w_KRSS.CTID <> subview.keep_CTID
				;

				DELETE FROM w_KRSS
				USING
				(
				SELECT NODOSSIER, count(*),
					(MAX(ARRAY[RSSCMDGHM, RSSSORT::text, K5CLEUNIK::text, CTID::text]))[4]::TID AS keep_CTID
				FROM w_KRSS
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE w_KRSS.NODOSSIER = subview.NODOSSIER AND
					w_KRSS.CTID <> subview.keep_CTID
				;

                        
                -- vérifications des séjours
			
				
				DROP TABLE IF EXISTS w_DOSSIER;
				CREATE TEMP TABLE w_DOSSIER AS
				SELECT 
                    date_extraction,
					NOFITNESS,	
					KDOSSIER.* ,
					COALESCE(DATESORTIE, '20991231') AS date_sortie,
					'N'::text AS CTI_OK,
					''::text AS dup_type_sejour,
					'0'::text AS dup_code_prevu,
					0::bigint AS dup_sejour_id,
					0::bigint AS dup_medecin_sejour_id,
					''::text AS dup_etat,
					rank() OVER (PARTITION BY KDOSSIER.NODOSSIER ORDER BY DATESORTIE, HEURESOR, K5CLEUNIK) as rank,
					K5CLEUNIK
				FROM w_periode,prod_mederi.KDOSSIER
                    LEFT JOIN w_KRSS KRSS ON KDOSSIER.NODOSSIER = KRSS.NODOSSIER
					, prod_mederi.ETABLI --LEFT JOIN prod_mederi.ETABLI ON KDOSSIER.NOETABLI = ETABLI.NOETABLI
                WHERE KDOSSIER.NODOSSIER IS NOT NULL AND
					DATEENTREE IS NOT NULL AND
                    (
                    COALESCE(DATESORTIE,RSSSORT,'20991231') >=  '[ENV_ADM_ANNEEDEBUT]0101' OR
                    KDOSSIER.NODOSSIER IN (SELECT NODOSSIER FROM w_KFACTURE KFACTURE WHERE DATEFAC >= '[ENV_ADM_ANNEEDEBUT]0101' OR DATECOMPTA >=  '[ENV_ADM_ANNEEDEBUT]0101' OR DATECOMPTA IS NULL) OR
                    KDOSSIER.NODOSSIER IN (SELECT NODOSSIER FROM w_KREGL KREGL WHERE DATE >= '[ENV_ADM_ANNEEDEBUT]0101' OR DATECOMPTA >=  '[ENV_ADM_ANNEEDEBUT]0101' )
                    ) 
                ORDER BY NODOSSIER, K5CLEUNIK;
				
				ANALYSE w_DOSSIER
				;
				
				
				-- Suppression des séjours sans mouvemlent, sans facture, sans reglement
				DELETE
				FROM w_dossier
				WHERE NODOSSIER NOT IN (SELECT KSEJOUR.NODOSSIER FROM prod_mederi.KSEJOUR WHERE KSEJOUR.NODOSSIER IS NOT NULL) AND
					NODOSSIER NOT IN (SELECT KFACTURE.NODOSSIER FROM prod_mederi.KFACTURE WHERE KFACTURE.NODOSSIER IS NOT NULL) AND
					NODOSSIER NOT  IN (SELECT KRGLDET.NODOSSIER FROM prod_mederi.KRGLDET WHERE KRGLDET.NODOSSIER IS NOT NULL)
				;
				
				
				-- Heure entrée non saisie
				UPDATE w_DOSSIER 
				SET HEUREENT = '08:00:00'
				WHERE HEUREENT IS NULL AND
					DATEENTREE = DATESORTIE AND
					HEURESOR > '08:00:00'
				;
				UPDATE w_DOSSIER 
				SET HEUREENT = '07:00:00'
				WHERE HEUREENT IS NULL AND
					DATEENTREE = DATESORTIE AND
					HEURESOR >= '07:00:00'
				;

                -- date entrée > datedeb 
                UPDATE w_DOSSIER 
                SET
                    DATEENTREE = KSEJOUR.DATEDEB,
                    HEUREENT = KSEJOUR.HEUREDEB
                FROM prod_mederi.KSEJOUR
                WHERE 
                    DATEENTREE > w_DOSSIER.DATEDEB
                    AND KSEJOUR.NODOSSIER = w_DOSSIER.NODOSSIER
                    AND w_DOSSIER.DATEDEB = KSEJOUR.DATEDEB;

                
                UPDATE w_DOSSIER 
                SET
                    NODOSSIER = NODOSSIER || '_' || rank
                WHERE rank != 1;
                
                -- modification de la table des rss pour prendre en compte les rss multiples par séjour
                
                UPDATE w_KRSS KRSS
                SET 
                    NODOSSIER = w_DOSSIER.NODOSSIER 
                FROM w_DOSSIER
                WHERE KRSS.K5CLEUNIK = w_DOSSIER.K5CLEUNIK
                ;
                
				CREATE INDEX  w_dossier_i1
				  ON  w_dossier
				  USING btree
				  (NODOSSIER);
				
				ANALYSE W_DOSSIER;
				
				-- Numéros de factures en double
				

				
			]]></sqlcmd>
		</NODE>
					
		<NODE label="Correstions">
			<sqlcmd><![CDATA[
				
				-- N° facture en double
				
				
				
		
			]]></sqlcmd>
		</NODE>
		
	</NODE>

	<NODE name="SEJOUR" label="RECUPERATION DES SEJOURS">
	
		<NODE label="Patients">
			<sqlcmd><![CDATA[

			
				-- Source des patients : KNIP ou KDOSSIER (il arrive que les deux tables soient décorélées, 
				-- privilégier alors le NIP de KDOSSIER)
				
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'MEDERI_PATIENTS',
					'Source patients MEDERI',
					'NIP',
					'Prendre les patients dans les dossies (DOS) ou dans les patients (NIP)'
				WHERE 'MEDERI_PATIENTS' NOT IN (SELECT code FROM activite.t_divers);
				;
					
				DROP TABLE IF EXISTS w_prod_mederi_knip 
				;
				CREATE TEMP TABLE w_prod_mederi_knip (
					NIP text,
					NOMPAT text, 
					PRENOMPAT text,
					NOMJFILLE text, 
					SEXE text, 
					DATENAIS text, 
					NOMUSUEL text, 
					NIPEXT text, 
					NOSS text, 
					CLESS text, 
					INSC text,
					NICLEUNIK text
				);
					
				-- Patients selon table des patients (paramètre t_divers)
				INSERT INTO w_prod_mederi_knip (
					NIP,
					NOMPAT, 
					PRENOMPAT,
					NOMJFILLE, 
					SEXE, 
					DATENAIS, 
					NOMUSUEL, 
					NIPEXT, 
					NOSS, 
					CLESS, 
					INSC,
					NICLEUNIK
				)
				SELECT 
					NIP,
					NOMPAT, 
					PRENOMPAT,
					MAX(NOMJFILLE) AS NOMJFILLE, 
					SEXE, 
					DATENAIS, 
					NOMUSUEL, 
					MAX(NIPEXT) AS NIPEXT, 
					NOSS, 
					CLESS, 
					INSC,
					MAX(NICLEUNIK) AS NICLEUNIK
				FROM prod_mederi.KNIP
					JOIN activite.t_divers ON t_divers.code = 'MEDERI_PATIENTS'
				WHERE 
					t_divers.valeur = 'NIP'
				GROUP BY NIP,
					NOMPAT, 
					PRENOMPAT,  
					SEXE, 
					DATENAIS, 
					NOMUSUEL, 
					NOSS, 
					CLESS, 
					INSC
				;
				
				-- Patients selon table des dossiers (paramètre t_divers)
				INSERT INTO w_prod_mederi_knip (
					NIP,
					NOMPAT, 
					PRENOMPAT,
					NOMJFILLE, 
					SEXE, 
					DATENAIS, 
					NOMUSUEL, 
					NIPEXT, 
					NOSS, 
					CLESS, 
					INSC,
					NICLEUNIK
				)
				WITH w_knip AS (
					SELECT
						NIP, 
						MAX(KNIP.NOMPAT) AS NOMPAT, 
						MAX(KNIP.PRENOMPAT) AS PRENOMPAT,
						MAX(KNIP.NOMJFILLE) AS NOMJFILLE, 
						MAX(KNIP.SEXE) AS SEXE, 
						MAX(KNIP.DATENAIS) AS DATENAIS, 
						MAX(KNIP.NOMUSUEL) AS NOMUSUEL, 
						MAX(KNIP.NIPEXT) AS NIPEXT, 
						MAX(KNIP.NOSS) AS NOSS, 
						MAX(KNIP.CLESS) AS CLESS, 
						MAX(KNIP.INSC) AS INSC,
						MAX(NICLEUNIK) AS NICLEUNIK
					FROM prod_mederi.KNIP
					GROUP BY KNIP.NIP
				)
				SELECT
					KDOSSIER.NIP,
					MAX(COALESCE(w_knip.NOMPAT, KDOSSIER.NOMPAT)) AS NOMPAT, 
					MAX(COALESCE(w_knip.PRENOMPAT,KDOSSIER.PRENOMPAT)) AS PRENOMPAT,
					MAX(COALESCE(w_knip.NOMJFILLE, KDOSSIER.NOMJFPAT)) AS NOMJFILLE, 
					MAX(COALESCE(w_knip.SEXE, KDOSSIER.SEXE)) AS SEXE, 
					MAX(COALESCE(w_knip.DATENAIS, KDOSSIER.DATENAIS)) AS DATENAIS, 
					MAX(w_knip.NOMUSUEL) AS NOMUSUEL, 
					MAX(w_knip.NIPEXT) AS NIPEXT, 
					MAX(w_knip.NOSS) AS NOSS, 
					MAX(w_knip.CLESS) AS CLESS, 
					MAX(w_knip.INSC) AS INSC,
					MAX(w_knip.NICLEUNIK) AS NICLEUNIK
				FROM prod_mederi.KDOSSIER
					LEFT JOIN w_knip ON w_knip.NIP = KDOSSIER.NIP
					JOIN activite.t_divers ON t_divers.code = 'MEDERI_PATIENTS'
				WHERE 
					t_divers.valeur = 'DOS'
				GROUP BY KDOSSIER.NIP
				;
				
				UPDATE  w_prod_mederi_knip 
				SET NOMPAT = NOMUSUEL
				FROM activite.t_divers
				WHERE 1=1
					AND t_divers.valeur = 'NIP'
					AND t_divers.code = 'MEDERI_PATIENTS'
					AND (NOMUSUEL IS NOT NULL OR NOMUSUEL <> '')
				;

				DROP TABLE IF EXISTS w_prod_mederi_knip_2 
				;
				
				CREATE TEMP TABLE w_prod_mederi_knip_2 AS
				SELECT 
					NIP,
					NOMPAT, 
					PRENOMPAT, 
					MAX(NOMJFILLE) AS NOMJFILLE, 
					SEXE, 
					DATENAIS, 
					NOMUSUEL, 
					MAX(NIPEXT) AS NIPEXT, 
					NOSS, 
					CLESS, 
					INSC,
					MAX(NICLEUNIK) AS NICLEUNIK
				FROM w_prod_mederi_knip				
				GROUP BY NIP,
					NOMPAT, 
					PRENOMPAT,  
					SEXE, 
					DATENAIS, 
					NOMUSUEL, 
					NOSS, 
					CLESS, 
					INSC
				;

				DROP TABLE IF EXISTS w_prod_mederi_knip_3 
				;
				
				CREATE TEMP TABLE w_prod_mederi_knip_3 AS
				SELECT
					NIP,
					NIP AS NIP2, 
					NOMPAT,
					PRENOMPAT, 
					NOMJFILLE, 
					SEXE,
					DATENAIS, 
					NOMUSUEL, 
					NIPEXT, 
					NOSS, 
					CLESS, 
					INSC,
					MAX(NICLEUNIK) AS NICLEUNIK 
				FROM w_prod_mederi_knip_2
				GROUP BY NIP,
					NOMPAT, 
					PRENOMPAT,  
					NOMJFILLE,
					SEXE, 
					DATENAIS, 
					NOMUSUEL, 
					NIPEXT, 
					NOSS, 
					CLESS, 
					INSC
				;	

                UPDATE w_prod_mederi_knip_3 
				SET NOMUSUEL = NOMPAT
				WHERE NOMUSUEL IS NULL
				;      
				
				-- Cas de NIP en double
				UPDATE w_prod_mederi_knip_3
				SET NIP2 = subview.to_NIP2
				FROM
				(
				SELECT NIP2, MAX(NICLEUNIK) AS NICLEUNIK, MAX(NIP)||'-'||count(*)::text AS to_NIP2
				FROM w_prod_mederi_knip_3
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE w_prod_mederi_knip_3.NICLEUNIK = subview.NICLEUNIK
				;
		
			
				INSERT INTO activite[PX].p_patients(finess, no_patient, nom, prenom, date_naissance, code_sexe)
				SELECT '', NIP2, MAX(NOMUSUEL), max(PRENOMPAT), date(MAX(DATENAIS)), MAX(sexe)				
				FROM w_prod_mederi_knip_3
					LEFT JOIN activite[PX].p_patients ON (NIP = p_patients.no_patient)
				WHERE p_patients.no_patient IS NULL and NIP IS NOT NULL
				GROUP BY 2
				;
				
				
				
					
				UPDATE activite[PX].p_patients
				SET nom = NOMUSUEL, 
					prenom = PRENOM, 
					date_naissance = date(DATENAIS), 
					code_sexe = SEXE
				FROM w_prod_mederi_knip_3
				WHERE p_patients.no_patient = NIP2
					AND (
						p_patients.nom IS DISTINCT FROM NOMUSUEL OR 
						p_patients.prenom IS DISTINCT FROM PRENOMPAT OR
						p_patients.date_naissance IS DISTINCT FROM date(DATENAIS) OR
						p_patients.code_sexe IS DISTINCT FROM SEXE
					);	
							
										
			]]></sqlcmd>
		</NODE>
				
		<NODE label="Séjours">
			<sqlcmd><![CDATA[

					DROP TABLE IF EXISTS w_PEC_DOSSIER;
					CREATE TEMP TABLE w_PEC_DOSSIER AS
					SELECT NODOSSIER, 
						COALESCE(MAX(t_tiers_payant_0.oid),0)::bigint AS tiers_payant_0_id, 
						COALESCE(MAX(t_tiers_payant_1.oid),0)::bigint AS tiers_payant_1_id, 
						COALESCE(MAX(t_tiers_payant_2.oid),0)::bigint AS tiers_payant_2_id, 
						0::bigint AS tiers_payant_22_id,
						COALESCE(MAX(NOSS)) AS matricule_1,
						COALESCE(MAX(INSC)) AS matricule_2
					FROM w_DOSSIER
						LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_1 ON (w_DOSSIER.COORGDEST = t_tiers_payant_1.code_original)
						LEFT JOIN w_prod_mederi_knip_3 ON w_DOSSIER.NIP = w_prod_mederi_knip_3.NIP
						LEFT JOIN prod_mederi.ORGMUT ON w_DOSSIER.NOMUTUELLE = ORGMUT.NOMUTUELLE
						LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON (w_DOSSIER.NOMUTUELLE = t_tiers_payant_2.code_original)
						LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_0 ON (t_tiers_payant_0.type_tiers_payant = '0' AND t_tiers_payant_0.oid <> 0)
					GROUP BY 1;
					
					ALTER TABLE w_PEC_DOSSIER ADD CONSTRAINT w_PEC_DOSSIER_pkey PRIMARY KEY(NODOSSIER);			
					
					DROP TABLE IF EXISTS w_sejours;
					CREATE TEMP TABLE w_sejours AS
					SELECT 
						CASE WHEN DATEENTREE > now() THEN 'W' || w_DOSSIER.NODOSSIER ELSE w_DOSSIER.NODOSSIER END as no_sejour, 
						w_DOSSIER.NODOSSIER as code_original, 
						NIP as no_patient, 
						DATEENTREE as date_entree, 
						replace(HEUREENT,':','')::bigint as heure_entree, 
						CASE WHEN DATESORTIE IS NOT NULL THEN DATESORTIE ELSE '20991231'::date END as date_sortie, 
						replace(HEURESOR,':','')::numeric  as heure_sortie, 
						w_DOSSIER.SEXE as code_sexe, 
						0 AS age, 
						CASE WHEN DATESORTIE <= date(now()) THEN 1 ELSE 0 END as code_sorti, 
						CASE WHEN TYPDOS = 4 OR DATEENTREE > now() THEN 1 ELSE 0 END as code_prevu,
						CASE 
							WHEN TYPDOS = 1 THEN 1::int
                            WHEN TYPDOS = 2 THEN 3::int
                            WHEN TYPDOS = 3 THEN CASE WHEN RSSCMDGHM LIKE '28%' THEN 5::int ELSE 2::int END
                            WHEN TYPDOS = 6 THEN 3::int
                            WHEN TYPDOS = 4 AND DATEENTREE = DATEPREV THEN 9::int
                            WHEN TYPDOS = 4 AND DATEENTREE != DATEPREV THEN 9::int
                            ELSE 1::int END as type_sejour,
						COALESCE(t_medecins_administratifs.oid,0) as medecin_sejour_id,
						0 as ghs_id,
						'20991231'::date as date_groupage,
						CASE WHEN DUREECP > 1 THEN 1 ELSE 0 END AS code_cp_demandee,
						0 as mode_traitement_id,
						'8'::character(1) as mode_entree,
						'0'::character(1) as provenance,
						'8'::character(1) as mode_sortie,
						'0'::character(1) as destination,
						COALESCE(tiers_payant_0_id,0) AS tiers_payant_0_id,
						COALESCE(tiers_payant_1_id,0) AS tiers_payant_1_id,
						COALESCE(tiers_payant_2_id,0) AS tiers_payant_2_id,
						0 AS tiers_payant_22_id,
						0 AS est_budget_global, -- seulement pour privé pour l'instant
                        w_DOSSIER.NOFITNESS as finess
					FROM w_DOSSIER
                            LEFT JOIN w_KRSS KRSS ON w_DOSSIER.NODOSSIER = KRSS.NODOSSIER
							LEFT JOIN activite[PX].t_medecins_administratifs ON w_DOSSIER.NOPRAT = t_medecins_administratifs.code_original
                            JOIN w_PEC_DOSSIER ON w_PEC_DOSSIER.NODOSSIER = w_DOSSIER.NODOSSIER
						;
						
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_2');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_3');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_4');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_5');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_6');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_7');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_8');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_9');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_10');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_11');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_12');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_13');
					
					-- Forcage type selon séjour
					UPDATE w_sejours
					SET type_sejour = t_sejour.type_sejour::int
					FROM activite.t_sejour
					WHERE t_sejour.no_sejour = w_sejours.no_sejour AND
						t_sejour.type_sejour IN ('1','2','3','4','5','6','9')
						AND t_sejour.type_sejour is not NULL ;
						
					UPDATE activite[PX].p_sejours SET
						code_original = w_sejours.code_original, 
						no_patient = w_sejours.no_patient, 
						date_entree = w_sejours.date_entree, 
						heure_entree = w_sejours.heure_entree, 
						date_sortie = w_sejours.date_sortie, 
						heure_sortie = w_sejours.heure_sortie, 
						code_sexe = w_sejours.code_sexe, 
						age = w_sejours.age, 
						code_sorti = w_sejours.code_sorti, 
						code_prevu = w_sejours.code_prevu, 
						type_sejour = w_sejours.type_sejour::int, 
						medecin_sejour_id = w_sejours.medecin_sejour_id,
						code_cp_demandee = w_sejours.code_cp_demandee,
						mode_traitement_id = w_sejours.mode_traitement_id,
						mode_entree = w_sejours.mode_entree,
						provenance = w_sejours.provenance,
						mode_sortie = w_sejours.mode_sortie,
						destination = w_sejours.destination,
						tiers_payant_0_id = w_sejours.tiers_payant_0_id,
						tiers_payant_1_id = w_sejours.tiers_payant_1_id,
						tiers_payant_2_id = w_sejours.tiers_payant_2_id,
						tiers_payant_22_id = w_sejours.tiers_payant_22_id,
						est_budget_global = w_sejours.est_budget_global,
                        finess = w_sejours.finess                        
					FROM w_sejours
					WHERE w_sejours.no_sejour = p_sejours.no_sejour
					AND (
						w_sejours.code_original IS DISTINCT FROM p_sejours.code_original OR
						w_sejours.no_patient IS DISTINCT FROM p_sejours.no_patient OR
						w_sejours.date_entree IS DISTINCT FROM p_sejours.date_entree OR
						w_sejours.heure_entree IS DISTINCT FROM p_sejours.heure_entree OR
						w_sejours.date_sortie IS DISTINCT FROM p_sejours.date_sortie OR
						w_sejours.heure_sortie IS DISTINCT FROM p_sejours.heure_sortie OR
						w_sejours.code_sexe IS DISTINCT FROM p_sejours.code_sexe OR
						w_sejours.age IS DISTINCT FROM p_sejours.age OR
						w_sejours.code_sorti IS DISTINCT FROM p_sejours.code_sorti OR
						w_sejours.code_prevu IS DISTINCT FROM p_sejours.code_prevu OR
						w_sejours.type_sejour IS DISTINCT FROM p_sejours.type_sejour OR
						w_sejours.medecin_sejour_id IS DISTINCT FROM p_sejours.medecin_sejour_id OR
						w_sejours.code_cp_demandee IS DISTINCT FROM p_sejours.code_cp_demandee OR
						w_sejours.mode_traitement_id IS DISTINCT FROM p_sejours.mode_traitement_id OR
						w_sejours.mode_entree IS DISTINCT FROM p_sejours.mode_entree OR
						w_sejours.provenance IS DISTINCT FROM p_sejours.provenance OR 
						w_sejours.mode_sortie IS DISTINCT FROM p_sejours.mode_sortie OR 
						w_sejours.destination IS DISTINCT FROM p_sejours.destination OR 
						w_sejours.tiers_payant_0_id IS DISTINCT FROM p_sejours.tiers_payant_0_id OR
						w_sejours.tiers_payant_1_id IS DISTINCT FROM p_sejours.tiers_payant_1_id OR
						w_sejours.tiers_payant_2_id IS DISTINCT FROM p_sejours.tiers_payant_2_id OR
						w_sejours.tiers_payant_22_id IS DISTINCT FROM p_sejours.tiers_payant_22_id OR
						w_sejours.est_budget_global IS DISTINCT FROM p_sejours.est_budget_global OR
                        w_sejours.finess IS DISTINCT FROM p_sejours.finess                                                                      
					);
					
				INSERT INTO activite[PX].p_sejours (
					no_sejour, 
					code_original, 
					no_patient, 
					date_entree, 
					heure_entree, 
					date_sortie, 
					heure_sortie, 
					code_sexe, 
					age, 
					code_sorti, 
					code_prevu, 
					type_sejour, 
					medecin_sejour_id,
					ghs_id,
					date_groupage,
					code_cp_demandee,
					mode_traitement_id,
					mode_entree,
					provenance,
					mode_sortie,
					destination,
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					est_budget_global,
                    finess
				) 
				SELECT 
					
					w_sejours.no_sejour, 
					w_sejours.code_original,
					w_sejours.no_patient, 
					w_sejours.date_entree, 
					w_sejours.heure_entree, 
					w_sejours.date_sortie, 
					w_sejours.heure_sortie, 
				    w_sejours.code_sexe::char(1),
					w_sejours.age, 
					w_sejours.code_sorti, 
					w_sejours.code_prevu, 
                    w_sejours.type_sejour::char(1), 
					w_sejours.medecin_sejour_id,
					w_sejours.ghs_id,
					w_sejours.date_groupage,
                    w_sejours.type_sejour::char(1), 
					w_sejours.mode_traitement_id,
					w_sejours.mode_entree::char(1),
					w_sejours.provenance::char(1),
					w_sejours.mode_sortie::char(1),
					w_sejours.destination::char(1),
					w_sejours.tiers_payant_0_id,
					w_sejours.tiers_payant_1_id,
					w_sejours.tiers_payant_2_id,
					w_sejours.tiers_payant_22_id,
					w_sejours.est_budget_global,
                    w_sejours.finess
				FROM w_sejours LEFT JOIN activite[PX].p_sejours ON (w_sejours.no_sejour = p_sejours.no_sejour)
				WHERE p_sejours.no_sejour IS NULL;
				
				
				DELETE FROM activite[PX].p_sejours 
				USING activite[PX].p_sejours AS p_sejours_i LEFT JOIN w_sejours ON (w_sejours.no_sejour = p_sejours_i.no_sejour)
				WHERE 
					p_sejours.no_sejour = p_sejours_i.no_sejour AND 
					w_sejours.no_sejour IS NULL;

				-- Modes es  selon mouvements (1:entree, 10: sortie 2,11,3) a priori 1 seul enregistrement avec 1 ou 10 mais au cas ou...
				UPDATE activite[PX].p_sejours
				SET mode_entree = MPMSI::text,
                    provenance = CASE WHEN char_length(CPMSI) > 1 THEN '0' ELSE CPMSI END
				FROM prod_mederi.KSEJOUR_MVT
                WHERE no_sejour = NODOSSIER
                AND TYPEMVT = 1;

                UPDATE activite[PX].p_sejours
				SET mode_sortie = MPMSI::text,
                    destination = CASE WHEN char_length(CPMSI) > 1 THEN '0' ELSE CPMSI END
				FROM prod_mederi.KSEJOUR_MVT
                WHERE no_sejour = NODOSSIER
                AND TYPEMVT = 10;
                
				-- Modes entrée sortie selon PMSI MCO		
				UPDATE activite[PX].p_sejours
				SET 
                    mode_entree = KRUM.MODEENTREE,
                    provenance = RIGHT(KRUM.PROVENANCE,1)
				FROM prod_mederi.KRUM
				WHERE no_sejour = NODOSSIER
                AND RSSNO = '01';

               DROP TABLE IF EXISTS w_mode_sortie;
               CREATE TEMP TABLE w_mode_sortie AS
               SELECT
                    NODOSSIER,
                    (MAX(Array[RSSNO::text, RIGHT(MODESORTIE::text,1)]))[2] as mode,
                    (MAX(Array[RSSNO::text, RIGHT(KRUM.DESTINATION,1)]))[2] as des
				FROM prod_mederi.KRUM
                GROUP BY NODOSSIER;
				
                UPDATE activite[PX].p_sejours
				SET 
                    mode_sortie = mode,
                    destination = des
                FROM w_mode_sortie
                WHERE no_sejour = NODOSSIER;
                
				-- Etablissements de provenance et destination
				-- insertion nouveaux etablissements
				DROP TABLE IF EXISTS w_ETAB;
				CREATE TEMP TABLE w_ETAB AS
					SELECT HOPITAL.*,t_etablissements.code FROM prod_mederi.HOPITAL LEFT JOIN base.t_etablissements ON CODEHOPIT = t_etablissements.code
					WHERE CODEHOPIT = ANY(array(SELECT NOANEST FROM w_DOSSIER)::text[])
						OR CODEHOPIT = ANY(array(SELECT HOPITSORTIE FROM w_DOSSIER)::text[]);
						
				INSERT INTO base.t_etablissements
				(
					code,
					texte,
					texte_court
				)
				SELECT 
					CODEHOPIT,
					NOM,
					NOM
				FROM w_ETAB
				WHERE code IS NULL;

                -- rechargements des etablissements
				DROP TABLE IF EXISTS w_ETAB;
				CREATE TEMP TABLE w_ETAB AS
					SELECT CODEHOPIT, t_etablissements.* FROM prod_mederi.HOPITAL LEFT JOIN base.t_etablissements ON CODEHOPIT = code
                    ;
						
                -- insertion des données de correspondances (pas d'update car les tables sont vidées avant import)
                DROP TABLE IF EXISTS w_TRANS;
				CREATE TEMP TABLE w_TRANS AS
					SELECT 
						CASE WHEN DATEENTREE > now() THEN 'W' || NODOSSIER ELSE NODOSSIER END as no_sejour, 
						pro.oid as oid_pro,
						des.oid as oid_des						
					FROM w_DOSSIER
						LEFT JOIN w_ETAB as pro ON w_DOSSIER.NOANEST = pro.CODEHOPIT
						LEFT JOIN w_ETAB as des ON w_DOSSIER.HOPITSORTIE = des.CODEHOPIT
					WHERE NOANEST IS NOT NULL OR HOPITSORTIE IS NOT NULL;
				
				INSERT INTO activite[PX].p_sejours_transferts(
					sejour_id,
					provenance_id,
					destination_id
					)
					SELECT
						p_sejours.oid,
						oid_pro,
						oid_des						
					FROM  activite[PX].p_sejours 
						JOIN w_TRANS ON w_TRANS.no_sejour = p_sejours.no_sejour;		
			
				-- ghm et ghs
                DROP TABLE IF EXISTS w_KRSSLOG;
                CREATE TEMP TABLE w_KRSSLOG AS
                SELECT 
                    KRSS.NODOSSIER,
                    COALESCE(MIN(CASE WHEN KRSSLOG.GHM <> '' AND PMSI_DEXPORT >= RSSSORT AND KRSSLOG.GHM = KRSS.RSSCMDGHM THEN date(PMSI_DEXPORT) ELSE NULL END),'20991231') AS PMSI_DEXPORT,
                    (MAX(Array[PMSI_DEXPORT::text, VERROUAP::text]))[2]  AS VERROUAP,
                    (MAX(Array[PMSI_DEXPORT::text, GHM::text]))[2]  AS GHM
                FROM prod_mederi.KRSSLOG
                JOIN w_KRSS KRSS ON KRSS.RSSNR = KRSSLOG.RSSNR
                GROUP BY 1
                ;

                UPDATE activite[PX].p_sejours SET
					ghs_id =  COALESCE(t_ghs.oid,0),
					ghm_id = COALESCE(t_ghm.oid,0),
					date_groupage = CASE WHEN GHM IS NOT NULL THEN date(PMSI_DEXPORT) ELSE '20991231' END
				FROM w_DOSSIER
                    JOIN w_KRSSLOG ON w_DOSSIER.NODOSSIER = w_KRSSLOG.NODOSSIER
					LEFT JOIN base.t_ghs ON VERROUAP = t_ghs.code
					LEFT JOIN base.t_ghm ON GHM = t_ghm.code AND t_ghm.code NOT LIKE '90%'
				WHERE 
					p_sejours.code_original = w_DOSSIER.NODOSSIER AND 
					(
						p_sejours.ghs_id IS DISTINCT FROM COALESCE(t_ghs.oid,0) OR
						p_sejours.ghm_id IS DISTINCT FROM COALESCE(t_ghm.oid,0) OR
						p_sejours.date_groupage IS DISTINCT FROM CASE WHEN GHM IS NULL THEN date(PMSI_DEXPORT) ELSE '20991231' END
					)
				;
				
				-- Code postal ?
				UPDATE activite[PX].p_sejours
				SET code_postal_id = t_codes_postaux.oid
				FROM w_DOSSIER
                JOIN base.t_codes_postaux ON CPPAT = t_codes_postaux.code
				WHERE code_original = NODOSSIER AND
					p_sejours.code_postal_id IS DISTINCT FROM t_codes_postaux.oid;
				
				-- Type séance d'après GHM (dans création directement)
	

				-- Séjours ignorés
				UPDATE activite[PX].p_sejours
				SET etat = 'I'
				FROM activite.t_sejour
				WHERE t_sejour.no_sejour = p_sejours.no_sejour AND
					est_ignore = '1' AND
					etat <> 'I' AND
					'[PX]' = '';

				UPDATE activite[PX].p_sejours
				SET etat = ''
				WHERE etat = 'I' AND 
					no_sejour NOT IN (SELECT no_sejour FROM activite.t_sejour WHERE est_ignore = '1') AND
					'[PX]' = '';
				
				-- Médecin séjour forcé
				UPDATE activite[PX].p_sejours
				SET medecin_sejour_id = t_sejour.medecin_sejour_id
				FROM activite.t_sejour
				WHERE t_sejour.no_sejour = p_sejours.no_sejour AND
					t_sejour.medecin_sejour_id <> 0 AND
					p_sejours.medecin_sejour_id IS DISTINCT FROM t_sejour.medecin_sejour_id AND
					'[PX]' = '';
			
			
				-- recréation index
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_9');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_10');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_11');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_12');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_13');
				
				
				-- assurance
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_4');
				
				INSERT INTO activite[PX].p_sejours_assurance(
					sejour_id, 
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					matricule_1, 
					tiers_payant_2_id, 
					matricule_2, 
					tiers_payant_22_id, 
					matricule_22)
				SELECT
					oid AS sejour_id,
					p_sejours.tiers_payant_0_id, 
					p_sejours.tiers_payant_1_id, 
					substr(w_PEC_DOSSIER.matricule_1,1,30),
					p_sejours.tiers_payant_2_id, 
					substr(w_PEC_DOSSIER.matricule_2,1,30),
					p_sejours.tiers_payant_22_id, 
					''::text AS matricule_22
				FROM w_PEC_DOSSIER
					JOIN activite[PX].p_sejours ON code_original = NODOSSIER AND p_sejours.etat = '';
					
				
				
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_4');
				
				
				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_PEC_DOSSIER;
				
			]]></sqlcmd>
		</NODE>

		<NODE label="Mouvements">
			<sqlcmd><![CDATA[
		
				-- tous les séjours = dernier service
				DROP TABLE IF EXISTS w_SER_principal;
				CREATE TEMP TABLE w_SER_principal AS
				SELECT NODOSSIER, 
					(MAX(Array[DATEDEB::text, NOSERVINT::text]))[2] as NOSERVINT
				FROM prod_mederi.KSEJOUR
				JOIN activite[PX].p_sejours ON NODOSSIER = p_sejours.code_original
				GROUP BY 1;
    
                -- mise à jour des services séjour et dmt d'après les mouvements
                UPDATE activite[PX].p_sejours
                SET
                    mode_traitement_id = t_modes_traitement.oid,
					type_sejour = CASE WHEN t_services_facturation.type_sejour IN ('1','2','3','5','6','9') THEN t_services_facturation.type_sejour ELSE p_sejours.type_sejour END
                FROM w_SER_principal
                    JOIN activite[PX].t_services_facturation ON NOSERVINT = t_services_facturation.code_original
					JOIN base.t_modes_traitement ON t_services_facturation.mode_traitement_id = t_modes_traitement.oid
                    JOIN base.t_dmt ON t_services_facturation.dmt_id = t_dmt.oid
                WHERE NODOSSIER = no_sejour;
    
				-- Traitement des mouvements
				DROP SEQUENCE IF EXISTS w_MOUVEMENT_seq;
				CREATE TEMP SEQUENCE w_MOUVEMENT_seq
					INCREMENT 1
					MINVALUE 1
					MAXVALUE 9223372036854775807
					START 1
					CACHE 1;
                
                -- Prendre tous les mouvements
                DROP TABLE IF EXISTS w_KSEJOUR ;
                CREATE TEMP TABLE w_KSEJOUR AS
                SELECT *
                FROM prod_mederi.KSEJOUR
                ;

                -- Ajouter les mouvements manquant
				INSERT INTO w_KSEJOUR(
				    secleunik,
				    nodossier,
				    datedeb,
				    datefin,
				    heuredeb,
				    heurefin,
				    noservint,
				    nochambre,
				    sho,
				    datesho,
				    dureesho,
				    etat,
				    etatsej,
				    noacte,
				    noprat,
				    nosae,
				    annulfactudj)
				SELECT
				    '*'||NODOSSIER AS SECLEUNIK,
				    NODOSSIER,
				    DATEENTREE AS DATEDEB,
				    DATESORTIE AS DATEFIN,
				    HEUREENT AS HEUREDEB,
				    HEURESOR AS HEUREFIN,
				    ''::text AS NOSERVINT,
				    ''::text AS NOCHAMBRE,
				    ''::text AS SHO,
				    NULL::DATE AS DATESHO,
				    '0'::text AS DUREESHO,
				    '0'::text AS ETAT,
				    '0'::text AS ETATSEJ,
				    ''::text AS NOACTE,
				    NOPRAT,
				    ''::text AS NOSAE,
				    '0'::text AS ANNULFACTUDJ
				FROM prod_mederi.KDOSSIER
				WHERE NODOSSIER NOT IN (SELECT NODOSSIER FROM prod_mederi.KSEJOUR)
                ;
                
                CREATE INDEX  w_KSEJOUR_i1
				  ON w_KSEJOUR
				  USING btree
				  (NODOSSIER);
                  
                CREATE INDEX  w_KSEJOUR_i2
				  ON w_KSEJOUR
				  USING btree
				  (NOSERVINT);
				  
				UPDATE w_KSEJOUR
				SET HEUREDEB = '08:00:00'
				WHERE HEUREDEB IS NULL AND 
					HEUREFIN > '08:00:00'
				;
				UPDATE w_KSEJOUR
				SET HEUREDEB = '07:00:00'
				WHERE HEUREDEB IS NULL AND 
					HEUREFIN > '07:00:00'
				;
				
				-- Correction heures dossier nulles
				UPDATE w_DOSSIER KDOSSIER
				SET HEUREENT = subview.HEUREDEB
				FROM
				(
				SELECT KDOSSIER.NODOSSIER, MIN(KSEJOUR.HEUREDEB) AS HEUREDEB
				FROM w_DOSSIER KDOSSIER
				JOIN w_KSEJOUR KSEJOUR ON 
					KDOSSIER.NODOSSIER = KSEJOUR.NODOSSIER AND
					KDOSSIER.DATEENTREE = KSEJOUR.DATEDEB
				WHERE HEUREENT IS NULL AND
					HEUREDEB IS NOT NULL
				GROUP BY 1
				) subview
				WHERE KDOSSIER.NODOSSIER = subview.NODOSSIER
				;
				
				UPDATE w_DOSSIER KDOSSIER
				SET HEURESOR = subview.HEUREFIN
				FROM
				(
				SELECT KDOSSIER.NODOSSIER, MAX(KSEJOUR.HEUREFIN) AS HEUREFIN
				FROM w_DOSSIER KDOSSIER
				JOIN w_KSEJOUR KSEJOUR ON 
					KDOSSIER.NODOSSIER = KSEJOUR.NODOSSIER AND
					KDOSSIER.DATESORTIE = KSEJOUR.DATEFIN
				WHERE HEURESOR IS NULL AND
					HEUREFIN IS NOT NULL
				GROUP BY 1
				) subview
				WHERE KDOSSIER.NODOSSIER = subview.NODOSSIER
				;
                
                -- L'heure de début du premier mouvement et l'heure de fin du dernier mouvement sont parfois différentes de l'heure d'entrée et de sortie du dossier. 
                -- On les fait correspondre
                UPDATE w_ksejour SET
                	datefin = subview.datefin,
                	heurefin = subview.heurefin
                FROM 
                (
                SELECT 
                	ksejour.nodossier, 
                	((MAX(ARRAY[ksejour.datefin::text, ksejour.heurefin, secleunik])))[3]::numeric AS secleunik,
                	MAX(KDOSSIER.datesortie) AS datefin,
                	((MAX(ARRAY[KDOSSIER.datesortie::text, KDOSSIER.heuresor])))[2] AS heurefin
                FROM prod_mederi.KDOSSIER
                JOIN w_ksejour ksejour ON KDOSSIER.nodossier = ksejour.nodossier
                WHERE heurefin IS NOT NULL
                GROUP BY 1
                HAVING MAX(kdossier.datesortie) <> MAX(ksejour.datefin) OR
                	((MAX(ARRAY[datefin::text, heurefin])))[2] <> ((MAX(ARRAY[ksejour.datefin::text, ksejour.heurefin])))[2]
                ) subview
                WHERE w_ksejour.secleunik = subview.secleunik
                ;

                UPDATE w_ksejour SET
                	datedeb = subview.dateentree,
                	heuredeb = subview.heureent
                FROM
                (
                SELECT 
                	ksejour.nodossier, 
                	((MIN(ARRAY[ksejour.datedeb::text, ksejour.heuredeb, secleunik])))[3]::numeric AS secleunik,
                	MIN(KDOSSIER.dateentree) AS dateentree, 
                	((MIN(ARRAY[KDOSSIER.dateentree::text, KDOSSIER.heureent])))[2] AS heureent
                FROM prod_mederi.KDOSSIER
                JOIN w_ksejour ksejour ON KDOSSIER.nodossier = ksejour.nodossier
                GROUP BY 1
                HAVING MIN(KDOSSIER.dateentree) <> MIN(ksejour.datedeb) OR
                	((MIN(ARRAY[dateentree::text, heureent])))[2] <> ((MIN(ARRAY[ksejour.datedeb::text, ksejour.heuredeb])))[2]
                ) subview
                WHERE w_ksejour.secleunik = subview.secleunik
                ;
                    
				DROP TABLE IF EXISTS w_MOUVEMENT;
				CREATE TEMP TABLE w_MOUVEMENT AS
				SELECT row_number() OVER (PARTITION BY 1 ORDER BY KSEJOUR.NODOSSIER,KSEJOUR.DATEDEB, KSEJOUR.HEUREDEB) AS sequence, 
					KSEJOUR.NODOSSIER,
					0 as RSSBEBE,
					(to_char(KSEJOUR.DATEDEB,'YYYY-MM-DD ') || KSEJOUR.HEUREDEB::text)::timestamp AS DATEDEB,
					date(KSEJOUR.DATEDEB) AS DATEDEB_DAT,
					replace(KSEJOUR.HEUREDEB,':','')::numeric(6,0)  AS HEUREDEB,
					(to_char(COALESCE(KSEJOUR.DATEFIN,'20991231'),'YYYY-MM-DD ') || COALESCE(KSEJOUR.HEUREFIN,'240000')::text)::timestamp AS DATEFIN,
					COALESCE(KSEJOUR.DATEFIN,'20991231') AS DATEFIN_DAT,
					replace(COALESCE(KSEJOUR.HEUREFIN,'240000'),':','')::numeric(6,0)  AS HEUREFIN,
                    CASE 
                        WHEN KSEJOUR.DATEDEB = DATEENTREE AND KSEJOUR.HEUREDEB = HEUREENT THEN 'E' 
                        WHEN KSEJOUR.DATEFIN = DATESORTIE AND KSEJOUR.HEUREFIN = HEURESOR THEN 'S'
                        ELSE '0' END AS TYPEMVT,
					w_SER_principal.NOSERVINT AS NOSERVINT_SEJ,
                    KSEJOUR.NOSERVINT,
					NOSERVSS,
                    CODEUM,
                    CASE 
						WHEN NOCHAMBRE IS NULL THEN KSERVINT.NOSERVINT::text || '-0'
						ELSE replace(NOCHAMBRE,' ','') END AS NOLIT,
                    SHO,
                    '0'::text AS TYPEMVT_before,
					'0'::text AS NOSERVINT_before, 
					'0'::text AS NOSERVSS_before, 
					0::text AS NOLIT_before,
					'0'::text AS TYPEMVT_next,
					'0'::text AS NOSERVINT_next, 
					'0'::text AS NOSERVSS_next, 
					0::text AS NOLIT_next
				FROM w_KSEJOUR KSEJOUR
					JOIN activite[PX].p_sejours ON KSEJOUR.NODOSSIER = p_sejours.code_original
					JOIN w_DOSSIER ON w_DOSSIER.NODOSSIER = KSEJOUR.NODOSSIER
  					JOIN w_SER_principal ON w_DOSSIER.NODOSSIER = w_SER_principal.NODOSSIER
                    LEFT JOIN prod_mederi.KSERVINT ON KSEJOUR.NOSERVINT = KSERVINT.NOSERVINT
                    
				ORDER BY CASE WHEN DATEENTREE > now() THEN 'W' || w_DOSSIER.NODOSSIER ELSE w_DOSSIER.NODOSSIER END, KSEJOUR.DATEDEB
                ;
	
				CREATE INDEX  w_MOUVEMENT_i1
				  ON  w_MOUVEMENT
				  USING btree
				  (SEQUENCE);
				  
				 CREATE INDEX  w_MOUVEMENT_i2
				  ON  w_MOUVEMENT
				  USING btree
				  (NODOSSIER);
				
				ANALYSE w_MOUVEMENT;
			
				-- calcul date fin
                UPDATE w_MOUVEMENT SET
                    DATEDEB = w_MOUVEMENT_B.DATEFIN + INTERVAL '1 second'
                FROM w_MOUVEMENT w_MOUVEMENT_B 
                WHERE w_MOUVEMENT.NODOSSIER = w_MOUVEMENT_B.NODOSSIER AND
                    w_MOUVEMENT.sequence = w_MOUVEMENT_B.sequence +1 AND
                    w_MOUVEMENT.HEUREDEB = 0 AND
                    w_MOUVEMENT_B.HEUREFIN <> 0;
                    
                UPDATE w_MOUVEMENT SET
                    DATEFIN = w_MOUVEMENT_A.DATEDEB - INTERVAL '1 second'
                FROM w_MOUVEMENT w_MOUVEMENT_A
                WHERE w_MOUVEMENT.NODOSSIER = w_MOUVEMENT_A.NODOSSIER AND
                    w_MOUVEMENT.sequence = w_MOUVEMENT_A.sequence -1 AND
                    w_MOUVEMENT.HEUREFIN = 0;

                UPDATE w_MOUVEMENT SET
                    HEUREDEB = to_char(DATEDEB,'HH24MISS')::numeric,
                    DATEDEB_DAT = date(DATEDEB),
                    HEUREFIN = to_char(DATEFIN,'HH24MISS')::numeric,
                    DATEFIN_DAT = date(DATEFIN)
                WHERE HEUREDEB = 0 OR HEUREFIN = 0
                ;

				UPDATE w_MOUVEMENT
				SET DATEFIN = CASE WHEN w_MOUVEMENT_next.TYPEMVT <> 'S' THEN w_MOUVEMENT_next.DATEDEB - interval '1 second' ELSE w_MOUVEMENT_next.DATEDEB_DAT END,
					DATEFIN_DAT = date(CASE WHEN w_MOUVEMENT_next.TYPEMVT <> 'S' THEN w_MOUVEMENT_next.DATEDEB - interval '1 second' ELSE w_MOUVEMENT_next.DATEDEB END),
					HEUREFIN = extract('hour' FROM CASE WHEN w_MOUVEMENT_next.TYPEMVT <> 'S' THEN w_MOUVEMENT_next.DATEDEB - interval '1 second' ELSE w_MOUVEMENT.DATEDEB END) * 10000 + 
							extract('minute' FROM CASE WHEN w_MOUVEMENT_next.TYPEMVT <> 'S' THEN w_MOUVEMENT_next.DATEDEB - interval '1 second' ELSE w_MOUVEMENT.DATEDEB END) * 100 + 
							extract('second' FROM CASE WHEN w_MOUVEMENT_next.TYPEMVT <> 'S' THEN w_MOUVEMENT_next.DATEDEB - interval '1 second' ELSE w_MOUVEMENT.DATEDEB END),
					TYPEMVT_next = w_MOUVEMENT_next.TYPEMVT,
					NOSERVINT_next = w_MOUVEMENT_next.NOSERVINT,
					NOSERVSS_next = w_MOUVEMENT_next.NOSERVSS,
					NOLIT_next = w_MOUVEMENT_next.NOLIT
				FROM w_MOUVEMENT w_MOUVEMENT_next
				WHERE w_MOUVEMENT.NODOSSIER = w_MOUVEMENT_next.NODOSSIER
					AND w_MOUVEMENT.sequence = w_MOUVEMENT_next.sequence - 1;
					
					
				-- Si hopital de jour sans journée,
				UPDATE w_MOUVEMENT
				SET TYPEMVT_next = 'C'
				FROM activite[PX].p_sejours,
					activite[PX].t_services_facturation
					JOIN base.t_modes_traitement on t_services_facturation.mode_traitement_id = t_modes_traitement.oid
				WHERE NODOSSIER = p_sejours.code_original AND
					code_prevu <> '1' AND
					TYPEMVT = 'E' AND
					NOSERVSS = t_services_facturation.code_original AND
					(TYPEMVT_NEXT = '' OR TYPEMVT_NEXT = 'S' AND date_entree <> date_sortie) AND
					t_modes_traitement.code = '04' AND
					t_services_facturation.type_t2a = '2';
	



				-- calcul mvt avant

				UPDATE w_MOUVEMENT
				SET 
					TYPEMVT_before = w_MOUVEMENT_before.TYPEMVT,
					NOSERVINT_before = w_MOUVEMENT_before.NOSERVINT,
					NOSERVSS_before = w_MOUVEMENT_before.NOSERVSS,
					NOLIT_before = w_MOUVEMENT_before.NOLIT
				FROM w_MOUVEMENT w_MOUVEMENT_before
				WHERE w_MOUVEMENT.NODOSSIER = w_MOUVEMENT_before.NODOSSIER
					AND w_MOUVEMENT.sequence = w_MOUVEMENT_before.sequence + 1
					AND w_MOUVEMENT.TYPEMVT <> 'S';
	
				-- Absences
				UPDATE w_MOUVEMENT
				SET NOSERVINT = 'ABS'
				WHERE TYPEMVT = 'A';
				
				-- Hopital de jour Dernière séance avant dans sortie -- pas sur (c'est quoi P)
				UPDATE w_MOUVEMENT SET
					DATEDEB = DATEFIN,
					DATEDEB_DAT = DATEFIN_DAT,
					HEUREDEB = HEUREFIN
				WHERE TYPEMVT = 'P' AND TYPEMVT_next = 'S' AND
					DATEFIN <> DATEDEB;

				-- Hopital de jour Première séance après date entree
				UPDATE w_MOUVEMENT SET
					DATEFIN = DATEDEB,
					DATEFIN_DAT = DATEDEB_DAT,
					HEUREFIN = HEUREDEB
				WHERE TYPEMVT = 'E' AND TYPEMVT_next = 'C' AND
					DATEDEB <> DATEFIN;

				
				-- creation mouvements par jour

				DROP TABLE IF EXISTS w_mouvements_sejour;
				CREATE TEMP TABLE w_mouvements_sejour AS
				SELECT 
					w_MOUVEMENT.NODOSSIER AS no_sejour,
					p_sejours.oid AS sejour_id,
					sequence,
					p_calendrier.date, 
					p_calendrier.jour_semaine,
					p_calendrier.is_weekend,
					CASE WHEN p_calendrier.date = DATEDEB_DAT THEN HEUREDEB ELSE 0 END AS heure_debut,
					CASE WHEN p_calendrier.date = DATEFIN_DAT THEN HEUREFIN ELSE 240000 END AS heure_fin,
					CASE WHEN p_calendrier.date = DATEDEB_DAT AND TYPEMVT = 'E' AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_entrees_directes,
					CASE WHEN p_calendrier.date = DATEFIN_DAT AND (TYPEMVT = 'S' OR (TYPEMVT = 'E' AND DATEFIN_DAT = p_sejours.date_sortie)) AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_sorties_directes,
					CASE WHEN p_calendrier.date = DATEDEB_DAT AND TYPEMVT = 'E' AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_entree,
					CASE WHEN p_calendrier.date = DATEFIN_DAT AND  (TYPEMVT = 'S' OR (TYPEMVT = 'E' AND DATEFIN_DAT = p_sejours.date_sortie)) AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_sortie,
					CASE WHEN p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_hospitalisation,
					CASE WHEN p_calendrier.date = DATEDEB_DAT AND TYPEMVT = 'E' AND p_sejours.type_sejour = '2' THEN 1 ELSE 0 END AS nb_ambulatoires,
					CASE WHEN p_calendrier.date = DATEDEB_DAT AND TYPEMVT = 'E' AND p_sejours.type_sejour = '3' THEN 1 ELSE 0 END AS nb_externes,
					CASE WHEN p_calendrier.date = DATEDEB_DAT AND TYPEMVT = 'E' AND p_sejours.type_sejour <> '9' AND t_dmt.code IN ('303', '307', '308', '401', '402', '403', '404', '405', '406', '407', '408', '409') THEN 1 ELSE 0 END AS nb_urgences,
					0 as nb_seances,

					CASE WHEN p_calendrier.date = DATEDEB_DAT AND TYPEMVT <> 'E' AND p_sejours.type_sejour = '1' AND NOSERVSS <> NOSERVSS_before THEN 1 ELSE 0 END AS nb_entrees_mutation_service,
					CASE WHEN p_calendrier.date = DATEFIN_DAT AND TYPEMVT <> 'E'  AND p_sejours.type_sejour = '1' AND NOSERVSS <> NOSERVSS_next THEN 1 ELSE 0 END AS nb_sorties_mutation_service,
					CASE WHEN p_calendrier.date = DATEDEB_DAT AND TYPEMVT <> 'E'  AND p_sejours.type_sejour = '1' AND NOSERVINT <> NOSERVINT_before THEN 1 ELSE 0 END AS nb_entrees_mutation_etage,
					CASE WHEN p_calendrier.date = DATEFIN_DAT AND TYPEMVT <> 'E'  AND p_sejours.type_sejour = '1' AND NOSERVINT <> NOSERVINT_next THEN 1 ELSE 0 END AS nb_sorties_mutation_etage,
					0 AS nb_entrees_mutation_activite,
					0 AS nb_sorties_mutation_activite,
					0 AS nb_entrees_mutation_unite_medicale,
					0 AS nb_sorties_mutation_unite_medicale,

					CASE WHEN p_sejours.type_sejour = '1' AND (p_calendrier.date <> DATEFIN_DAT OR TYPEMVT_next = 'S') THEN 1 ELSE 0 END AS nb_jours_js_inclus,
					CASE WHEN p_sejours.type_sejour = '1' AND p_calendrier.date <> DATEFIN_DAT THEN 1 ELSE 0 END AS nb_jours_js_non_inclus,

					CASE WHEN p_sejours.type_sejour = '1' AND (t_lits.chambre_particuliere = 'O' OR SHO != 0) THEN '1' ELSE '0' END AS est_chambre_particuliere,
					CASE WHEN p_sejours.type_sejour = '1' AND (t_lits.chambre_particuliere = 'O' OR SHO != 0) AND (p_calendrier.date <> DATEFIN_DAT OR TYPEMVT_next = 'S') THEN 1 ELSE 0 END AS nb_chambres_particulieres,

					CASE WHEN p_calendrier.date = DATEDEB_DAT AND TYPEMVT = 'E' AND (COALESCE(w_MOUVEMENT.RSSBEBE) > 0) THEN 1 ELSE 0 END AS nb_bebes,
                    
                    NOSERVINT,
					NOSERVINT_SEJ,
					NOSERVSS,
					NOLIT,
                    CODEUM,
                    
					COALESCE(t_lieux.oid,0) AS lieu_id,

					p_sejours.medecin_sejour_id as medecin_sejour_id,

					CASE WHEN p_sejours.code_prevu = '1' OR p_calendrier.date > date(date_extraction) THEN '1' ELSE '0' END AS est_mouvement_previsionnel,

					''::text AS est_premier_mouvement_jour,
					''::text AS est_dernier_mouvement_jour

					
				FROM w_MOUVEMENT 
					LEFT JOIN activite[PX].t_lieux ON 
						t_lieux.code_original_1 = NOSERVINT::text AND 
                        t_lieux.code_original_2 = CODEUM::text AND 
						t_lieux.code_original_4 = NOLIT AND
						t_lieux.code_original_5 = NOSERVSS::text
					JOIN w_DOSSIER ON w_DOSSIER.NODOSSIER = w_MOUVEMENT.NODOSSIER
					JOIN activite[PX].p_sejours ON w_MOUVEMENT.NODOSSIER = p_sejours.no_sejour AND p_sejours.etat = ''
					LEFT JOIN activite[PX].t_lits ON NOLIT = t_lits.code_original
					JOIN activite[PX].t_services_facturation ON NOSERVINT::text = t_services_facturation.code_original
					JOIN base.t_dmt ON t_services_facturation.dmt_id = t_dmt.oid
					JOIN base.p_calendrier ON p_calendrier.date BETWEEN DATEDEB_DAT AND DATEFIN_DAT AND p_calendrier.date <= date(date_extraction) + interval '1 month'
				WHERE 
					(TYPEMVT <> 'P' OR TYPEMVT_next = 'S') AND 
					(p_sejours.type_sejour NOT IN ('2', '3') OR (p_sejours.type_sejour IN ('2', '3') AND TYPEMVT = 'E' AND (p_calendrier.date = DATEDEB_DAT OR p_calendrier.date = DATEFIN_DAT))) AND 
					(p_sejours.code_prevu <> '1' AND p_calendrier.date <= date(date_extraction) OR p_calendrier.date >= date(date_extraction))
				ORDER BY sequence, p_calendrier.date;
                
                UPDATE w_mouvements_sejour SET
                    nb_sorties_mutation_etage = 0,
                    nb_sorties_mutation_service = 0,
                    nb_sorties_mutation_activite = 0,
                    nb_sorties_mutation_unite_medicale = 0
                WHERE nb_sorties_directes = 1 AND (
                    nb_sorties_mutation_etage <> 0 OR
                    nb_sorties_mutation_service <> 0 OR
                    nb_sorties_mutation_activite <> 0 OR
                    nb_sorties_mutation_unite_medicale <> 0
                    )
				;
				-- correction des heure E/S
                
                UPDATE activite[PX].p_sejours SET
                    heure_entree = heure_sortie,
                    heure_sortie = heure_entree
                WHERE 
                    heure_sortie < heure_entree
                    AND date_entree = date_sortie;
                
                UPDATE w_mouvements_sejour SET
                    heure_fin = heure_debut,
                    heure_debut = heure_fin
                FROM activite[PX].p_sejours
                WHERE 
                    w_mouvements_sejour.no_sejour  = p_sejours.no_sejour
                    AND date_entree = date_sortie
                    AND heure_fin < heure_debut;
                                
				DELETE FROM w_mouvements_sejour WHERE heure_fin < heure_debut;
	
				-- Actualisation lieux
				UPDATE activite[PX].t_lieux SET
					service_facturation_id = t_services_facturation.oid,
					mode_traitement_id = t_services_facturation.mode_traitement_id
				FROM activite[PX].t_services_facturation
				WHERE 
					code_original_1 = t_services_facturation.code_original;
	
				UPDATE activite[PX].t_lieux SET
					unite_medicale_id = t_unites_medicales.oid
				FROM activite[PX].t_unites_medicales
				WHERE 
					code_original_2 = t_unites_medicales.code_original;
					
				UPDATE activite[PX].t_lieux SET
					unite_fonctionnelle_id = t_unites_fonctionnelles.oid
				FROM activite[PX].t_unites_fonctionnelles
				WHERE 
					code_original_6 = t_unites_fonctionnelles.code_original;
					
				UPDATE activite[PX].t_lieux SET
					lit_id = t_lits.oid
				FROM activite[PX].t_lits
				WHERE 
					code_original_4 = t_lits.code;
	


				-- creation nouveaux lieux

				INSERT INTO activite[PX].t_lieux(
					code_original_1, 
					code_original_2, 
					code_original_3, 
					code_original_4, 
					code_original_5, 
					code_original_6, 
					code_original_7,
					service_facturation_id, 
					activite_id, 
					lit_id, 
					unite_medicale_id, 
					unite_fonctionnelle_id, 
					mode_traitement_id)
				SELECT DISTINCT 
					NOSERVINT, 
                    CODEUM,
					'',
					NOLIT,
					NOSERVSS,
					'',
					'',
					t_services_facturation.oid,
					COALESCE(t_activites.oid,0),
					COALESCE(t_lits.oid,0),
					COALESCE(t_unites_medicales.oid,0),
					COALESCE(t_unites_fonctionnelles.oid,0),
					t_services_facturation.mode_traitement_id
				FROM w_mouvements_sejour 
                   LEFT JOIN activite[PX].t_lieux ON 
						t_lieux.code_original_1 = NOSERVINT::text AND 
                        t_lieux.code_original_2 = CODEUM::text AND 
						t_lieux.code_original_4 = NOLIT AND
						t_lieux.code_original_5 = NOSERVSS::text
					JOIN activite[PX].t_services_facturation ON w_mouvements_sejour.NOSERVINT::text = t_services_facturation.code_original
                    LEFT JOIN activite[PX].t_unites_medicales ON CODEUM::text = t_unites_medicales.code_original
                    LEFT JOIN activite[PX].t_activites ON NOSERVINT_SEJ = t_activites.code_original
					LEFT JOIN activite[PX].t_lits ON NOLIT = t_lits.code_original
					LEFT JOIN activite[PX].t_unites_fonctionnelles ON NOSERVSS::text = t_unites_fonctionnelles.code_original
				WHERE t_lieux.oid IS NULL;
	



				-- Mise à jour lieux dans futurs mouvements
				UPDATE w_mouvements_sejour SET lieu_id = t_lieux.oid
				FROM activite[PX].t_lieux
				WHERE
                        t_lieux.code_original_1 = NOSERVINT::text AND 
						t_lieux.code_original_4 = NOLIT AND
						t_lieux.code_original_5 = NOSERVSS::text
					AND w_mouvements_sejour.lieu_id = 0;
	
	
	
				-- Médecin séjour

				UPDATE w_mouvements_sejour SET medecin_sejour_id = t_medecins_administratifs.oid
				FROM W_KPRAT, prod_mederi.KSEJOUR, activite[PX].t_medecins_administratifs
				WHERE KSEJOUR.NOPRAT = t_medecins_administratifs.code_original
                    AND KSEJOUR.NODOSSIER = w_mouvements_sejour.no_sejour
					AND date BETWEEN DATEDEB AND DATEFIN
					AND w_mouvements_sejour.medecin_sejour_id <> t_medecins_administratifs.oid
					AND t_medecins_administratifs.oid <> 0;
					
                 -- mise à jour par le code insee (désactivé car Osny veut voir les erreurs de saisie)
--                UPDATE w_mouvements_sejour SET medecin_sejour_id = t_medecins_administratifs.oid
--				FROM W_KPRAT KPRAT, prod_mederi.KSEJOUR, activite[PX].t_medecins_administratifs
--				WHERE 
--                    KSEJOUR.NOPRAT = KPRAT.CODEINSEE
--                    AND KPRAT.NOPRAT = t_medecins_administratifs.code_original
--                    AND KSEJOUR.NODOSSIER = w_mouvements_sejour.no_sejour
--					AND date BETWEEN DATEDEB AND DATEFIN
--                    AND w_mouvements_sejour.medecin_sejour_id <> t_medecins_administratifs.oid
--					AND t_medecins_administratifs.oid <> 0;
--					
					
				-- Unité médicale selon UF
				UPDATE activite[PX].t_lieux
				SET unite_medicale_id = t_unites_medicales.oid,
					code_original_5 = NOSERVSS
				FROM prod_mederi.KSERVINT 
					JOIN activite[PX].t_unites_medicales ON NOSERVSS =t_unites_medicales.code_original
				WHERE NOSERVINT = code_original_6 AND
					(unite_medicale_id IS DISTINCT FROM t_unites_medicales.oid OR
					code_original_5 IS DISTINCT FROM NOSERVSS);
	
				UPDATE activite[PX].t_lieux
				SET unite_medicale_id = t_unites_medicales.oid,
					code_original_5 = '*ABS'
				FROM activite[PX].t_unites_medicales
				WHERE code_original_1 = '*ABS' AND t_unites_medicales.code_original = '*ABS';
					
				-- Unité médicale principale selon UF
				UPDATE activite[PX].t_lieux SET
					activite_id = t_activites.oid,
					code_original_1 = NOSERVINT
				FROM prod_mederi.KSERVINT
					JOIN activite[PX].t_activites ON NOSERVSS = t_activites.code_original
				WHERE NOSERVINT = code_original_1 AND
					activite_id = 0;
					
				
				-- Seances selon GHS pmsi
				DROP TABLE IF EXISTS w_ghs_seances;
				CREATE TEMP TABLE w_ghs_seances AS
				SELECT ghs_id AS oid
				FROM activite[PX].p_sejours
				JOIN base.t_ghm ON p_sejours.ghm_id = t_ghm.oid AND t_ghm.code LIKE '28%'
				JOIN base.t_ghs ON p_sejours.ghs_id = t_ghs.oid AND t_ghs.code <> 9999 AND t_ghs.code > 0
				WHERE ghs_id <> 0
				GROUP BY 1;
				
				DROP TABLE IF EXISTS w_sejours_seances;
				CREATE TEMP TABLE w_sejours_seances AS
				SELECT
					p_sejours.no_sejour,
					date_entree AS date,
					1 AS nb_seances
				FROM activite[PX].p_sejours
					JOIN base.t_ghs ON p_sejours.ghs_id = t_ghs.oid
					JOIN base.t_ghm ON p_sejours.ghm_id = t_ghm.oid
				WHERE date_entree = date_sortie AND
					(ghs_id IN (SELECT oid FROM w_ghs_seances) OR t_ghm.code LIKE '28%');

				CREATE INDEX  w_sejours_seances_i1
				  ON  w_sejours_seances
				  USING btree
				  (no_sejour);
				  
				UPDATE w_mouvements_sejour
				SET nb_seances = w_sejours_seances.nb_seances
				FROM w_sejours_seances
				WHERE w_sejours_seances.no_sejour = w_mouvements_sejour.no_sejour AND 
					w_sejours_seances.date = w_mouvements_sejour.date AND
					w_mouvements_sejour.nb_seances IS DISTINCT FROM w_sejours_seances.nb_seances;			

				-- seances selon RSS
                DROP TABLE IF EXISTS w_SEANCES_RSS;
                CREATE TEMP TABLE w_SEANCES_RSS AS
                SELECT 
                    NODOSSIER,
                    DATEACTE as DATE_SEANCE,
                    count(*) as nb_seances
                FROM prod_mederi.MSEANCES
                    JOIN prod_mederi.KRUM ON KRUM.RSSNR = MSEANCES.RSSNR
                GROUP BY 1,2;
					
                UPDATE w_mouvements_sejour
				SET nb_seances = w_SEANCES_RSS.nb_seances
				FROM w_SEANCES_RSS
				WHERE NODOSSIER = w_mouvements_sejour.no_sejour AND 
					w_SEANCES_RSS.DATE_SEANCE = w_mouvements_sejour.date;
                    
				-- seances selon GHS facturé
				DROP TABLE IF EXISTS w_KACTES_seances;
				CREATE TEMP TABLE  w_KACTES_seances AS
				SELECT
					p_sejours.no_sejour,
					DATEACTE AS date,
					SUM(QTE::int) AS nb_seances
				FROM prod_mederi.KACTES
					JOIN w_KFACTURE KFACTURE ON KFACTURE.NOFAC = KACTES.NOFAC AND est_doublon = '0' -- AND FACPARTIEL <> 9
					JOIN activite[PX].p_sejours ON KFACTURE.NODOSSIER = p_sejours.code_original
					JOIN base.t_ghs ON GHS = t_ghs.code
				WHERE
					t_ghs.oid IN (SELECT oid FROM w_ghs_seances)
				GROUP BY 1,2
				HAVING SUM(QTE::int) > 0;

				CREATE INDEX  w_KACTES_seances_i1
				  ON  w_KACTES_seances
				  USING btree
				  (no_sejour);
				  
				UPDATE w_mouvements_sejour
				SET nb_seances = w_KACTES_seances.nb_seances
				FROM w_KACTES_seances
				WHERE w_KACTES_seances.no_sejour = w_mouvements_sejour.no_sejour AND 
					w_KACTES_seances.date = w_mouvements_sejour.date;
					
					
					
					
				-- seances selon D09, D11 facturé => pas de dialyse dans les actes		

				
				-- seances selon Actes
				DROP TABLE IF EXISTS w_K_seances;
				CREATE TEMP TABLE  w_K_seances AS
				SELECT
					p_sejours.no_sejour,
					DATEACTE AS date,
					SUM(QTE::int) AS nb_seances
				FROM prod_mederi.KACTES
 					JOIN activite[PX].p_sejours ON NODOSSIER = p_sejours.code_original
				WHERE 
					NOACTE = 'K' AND 
					QTE > 0
				GROUP BY 1,2;
				
				UPDATE w_mouvements_sejour
				SET nb_seances = w_K_seances.nb_seances
				FROM w_K_seances
				WHERE w_K_seances.no_sejour = w_mouvements_sejour.no_sejour AND 
					w_K_seances.date = w_mouvements_sejour.date AND
					w_mouvements_sejour.nb_seances = 0;
					
					
					
				-- seances selon D09
								
					
				-- Seances selon type sejour DE = DS
				UPDATE w_mouvements_sejour
				SET nb_seances = 1
				FROM activite[PX].p_sejours
				WHERE p_sejours.no_sejour = w_mouvements_sejour.no_sejour AND 
					p_sejours.type_sejour = '5' AND
					p_sejours.date_entree = p_sejours.date_sortie AND
					p_sejours.date_entree = w_mouvements_sejour.date AND
					w_mouvements_sejour.heure_debut > 0 AND
					w_mouvements_sejour.nb_seances = 0 AND
					w_mouvements_sejour.no_sejour NOT IN (SELECT no_sejour FROM w_mouvements_sejour WHERE nb_seances > 0);	
				
					
	
				-- plusieurs séances le même jour
							
				DROP TABLE IF EXISTS w_seances;
				CREATE TEMP TABLE w_seances as
				SELECT no_sejour, date, MAX(heure_debut) AS heure_debut
				FROM w_mouvements_sejour
				WHERE nb_seances > 0
				GROUP BY 1,2
				HAVING count(DISTINCT heure_debut) > 1;


				UPDATE w_mouvements_sejour
				SET nb_seances = 0 
				FROM w_seances
				WHERE w_mouvements_sejour.no_sejour = w_seances.no_sejour and
					w_mouvements_sejour.date = w_seances.date and
					w_mouvements_sejour.heure_debut <> w_seances.heure_debut;
				
				
				-- Doublons potentiels
				DELETE FROM w_mouvements_sejour
				USING (
				SELECT 				
					no_sejour, date, heure_debut, MAX(CTID) AS fromCTID
				FROM w_mouvements_sejour
				GROUP BY 1,2,3
				HAVING count(*) > 1) subview
				WHERE 1=1
					AND subview.no_sejour = w_mouvements_sejour.no_sejour
					AND subview.date = w_mouvements_sejour.date
					AND subview.heure_debut = w_mouvements_sejour.heure_debut
					AND subview.fromCTID != w_mouvements_sejour.CTID;
				
					
		

				-- Mise en production des mouvements
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_5');
				
--              DROP TABLE IF EXISTS TEMP.w_MOUVEMENT;
--              CREATE TABLE temp.w_MOUVEMENT AS SELECT * FROM w_MOUVEMENT;
                
--              DROP TABLE IF EXISTS TEMP.w_MOUVEMENTS_SEJOUR;
--              CREATE TABLE temp.w_MOUVEMENTS_SEJOUR AS SELECT * FROM w_MOUVEMENTS_SEJOUR;
                
				INSERT INTO activite[PX].p_mouvements_sejour(
							sejour_id, no_sejour, date, est_mouvement_previsionnel, nb_jours_js_non_inclus, 
							lieu_id, nb_entrees_directes, nb_sorties_directes, 
							nb_urgences, nb_externes, nb_ambulatoires, medecin_sejour_id, 
							nb_jours_js_inclus, nb_seances, nb_entrees_mutation_service, 
							nb_sorties_mutation_service, nb_entrees_mutation_activite, nb_sorties_mutation_activite, 
							nb_entrees_mutation_etage, nb_sorties_mutation_etage, nb_chambres_particulieres, 
							heure_debut, heure_fin, est_jour_entree, est_jour_sortie, est_jour_hospitalisation, 
							est_chambre_particuliere, 
							nb_entrees_mutation_unite_medicale, nb_sorties_mutation_unite_medicale, nb_bebes,
							jour_semaine, is_weekend)
				SELECT sejour_id, no_sejour, date, est_mouvement_previsionnel ,nb_jours_js_non_inclus, 
							lieu_id, nb_entrees_directes, nb_sorties_directes, 
							nb_urgences, nb_externes, nb_ambulatoires, medecin_sejour_id, 
							nb_jours_js_inclus, nb_seances, nb_entrees_mutation_service, 
							nb_sorties_mutation_service, nb_entrees_mutation_activite, nb_sorties_mutation_activite, 
							nb_entrees_mutation_etage, nb_sorties_mutation_etage, nb_chambres_particulieres, 
							heure_debut, heure_fin, est_jour_entree, est_jour_sortie, est_jour_hospitalisation, 
							est_chambre_particuliere, 
							nb_entrees_mutation_unite_medicale, nb_sorties_mutation_unite_medicale, nb_bebes,
							jour_semaine, is_weekend
				FROM w_mouvements_sejour
				WHERE heure_fin >= heure_debut
				ORDER BY no_sejour, sequence;
	
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_5');

				-- Lieux de sortie

				UPDATE activite[PX].p_sejours SET lieu_sortie_id = p_mouvements_sejour.lieu_id  
					FROM activite[PX].p_mouvements_sejour 
					WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour  
						AND p_mouvements_sejour.date = p_sejours.date_sortie  
						AND (lieu_sortie_id <> p_mouvements_sejour.lieu_id OR lieu_sortie_id IS NULL);  
	
				UPDATE activite[PX].p_sejours SET lieu_sortie_id = p_mouvements_sejour.lieu_id  
					FROM activite[PX].p_mouvements_sejour 
					WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour  
						AND p_mouvements_sejour.date = p_sejours.date_sortie  AND p_mouvements_sejour.nb_sorties_directes = 1
						AND (lieu_sortie_id <> p_mouvements_sejour.lieu_id OR lieu_sortie_id IS NULL);  

				UPDATE activite[PX].p_sejours SET lieu_sortie_id = p_mouvements_sejour.lieu_id  
					FROM activite[PX].p_mouvements_sejour 
					WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour 
						AND (p_sejours.lieu_sortie_id = 0 OR lieu_sortie_id IS NULL) ;
				
				UPDATE activite[PX].p_sejours SET lieu_sortie_id = 0
					WHERE lieu_sortie_id IS NULL ;
				
				
				UPDATE activite[PX].p_sejours SET lieu_sortie_id = 0
					WHERE p_sejours.code_prevu = '1' AND (p_sejours.lieu_sortie_id = 0 OR lieu_sortie_id IS NULL);
					
					
				UPDATE activite[PX].p_sejours
				SET code_sorti = '1'
				FROM activite[PX].p_mouvements_sejour 
				WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
					code_sorti = '0' AND
					(nb_ambulatoires > 0 OR nb_externes > 0) AND 
					date_sortie <= now();
					
				UPDATE activite[PX].p_sejours
				SET type_sejour = '5'
				WHERE type_sejour <> '5' AND 
					type_sejour <> '1' AND 
					no_sejour IN (
						SELECT no_sejour 
						FROM activite[PX].p_mouvements_sejour 
						WHERE nb_seances > 0);
						
				
				UPDATE activite[PX].p_mouvements_sejour
				SET nb_externes = 0, nb_ambulatoires = 0
				FROM activite[PX].p_sejours
				WHERE p_mouvements_sejour.no_sejour = p_sejours.no_sejour AND
					p_sejours.type_sejour = '5' AND
					(
						nb_externes <> 0 OR
						nb_ambulatoires <> 0
					);
					
					
				
				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_MOUVEMENT;
				DROP TABLE IF EXISTS w_mouvements_sejour;
				DROP TABLE IF EXISTS w_seances;
				DROP TABLE IF EXISTS w_K_seances;
				DROP TABLE IF EXISTS w_KACTES_seances;
										
										
			]]></sqlcmd>
		</NODE>
		
	</NODE>

	<NODE name="FACTURE" label="RECUPERATION DES FACTURES">
	
		<NODE label="Entêtes">

			<sqlcmd><![CDATA[

                
				DROP TABLE IF EXISTS w_sejours_orga CASCADE;
				CREATE TEMP TABLE w_sejours_orga AS
				SELECT 
                    no_sejour,
					p_sejours.oid AS sejour_id,
					p_sejours.code_original,
					p_sejours.date_entree,
                    p_sejours.date_sortie,
					p_sejours.ghs_id,
					p_sejours.lieu_sortie_id,
					p_sejours.tiers_payant_0_id,
					p_sejours.tiers_payant_1_id,
					p_sejours.tiers_payant_2_id,
					p_sejours.tiers_payant_22_id,
					t_tiers_payant_1.code_original as tiers_payant_1_orga_id,
					t_tiers_payant_2.code_original as tiers_payant_2_orga_id,
					t_tiers_payant_22.code_original as tiers_payant_22_orga_id
				FROM activite[PX].p_sejours,activite[PX].t_tiers_payant t_tiers_payant_1, activite[PX].t_tiers_payant t_tiers_payant_2, activite[PX].t_tiers_payant t_tiers_payant_22
				WHERE p_sejours.etat = '' AND
					tiers_payant_1_id = t_tiers_payant_1.oid AND
					tiers_payant_2_id = t_tiers_payant_2.oid AND
					tiers_payant_22_id = t_tiers_payant_22.oid;
	
	
				CREATE INDEX w_sejours_orga_i1
				ON w_sejours_orga
				USING btree
				(code_original);
	
	
	
				-- factures à traiter

				DROP TABLE IF EXISTS w_FAC_FACTURE;
				CREATE TEMP TABLE w_FAC_FACTURE AS
				SELECT KFACTURE.*, 
					w_sejours_orga.*, 
					TYPEETAB,
					'1'::text AS FAC_HON,
                    w_DOSSIER.DATEENTREE AS date_debut_facture,
					COALESCE(KFACTURE.DATEFACPAR, DATESORTIE) AS date_fin_facture,
                    ROW_NUMBER() OVER (
							PARTITION BY KFACTURE.NODOSSIER 
                            ORDER BY COALESCE(CASE WHEN KFACTURE.NOFAC NOT LIKE 'P%' THEN KFACTURE.DATEFACPAR ELSE '20991231' END, DATESORTIE)
							) AS rang_facture
				FROM w_KFACTURE KFACTURE 
					JOIN w_DOSSIER ON KFACTURE.NODOSSIER = w_DOSSIER.NODOSSIER
                    --LEFT JOIN prod_mederi.KENCOURS ON KENCOURS.NOFAC = KFACTURE.NOFAC
					LEFT JOIN prod_mederi.ETABLI ON w_DOSSIER.NOETABLI = ETABLI.NOETABLI
					JOIN w_sejours_orga ON (KFACTURE.NODOSSIER = w_sejours_orga.no_sejour)
				WHERE KFACTURE.NOFAC IS NOT NULL 
                    AND w_sejours_orga.no_sejour = KFACTURE.NODOSSIER
					AND est_doublon = '0'
                   -- AND KENCOURS.NOFAC IS NULL 
                -- AND (FACPARTIEL = 1 OR FACT_DAT_SUP IS NULL)
                ;
                
                UPDATE w_FAC_FACTURE
				SET date_debut_facture = date(w_FAC_FACTURE_p.date_fin_facture + interval '1 day')
				FROM w_FAC_FACTURE w_FAC_FACTURE_p
				WHERE w_FAC_FACTURE.NODOSSIER = w_FAC_FACTURE_p.NODOSSIER AND
					w_FAC_FACTURE.rang_facture = w_FAC_FACTURE_p.rang_facture+1 AND
					w_FAC_FACTURE.NOFAC NOT LIKE 'P%' AND
					date(w_FAC_FACTURE_p.date_fin_facture + interval '1 day') <= w_FAC_FACTURE.date_fin_facture
                ;
			
            
				CREATE INDEX w_FAC_FACTURE_i1
				ON w_FAC_FACTURE
				USING btree
				(NOFAC);
                
                --maj mutuelles différentes sur facture
                DROP TABLE IF EXISTS w_PEC_FACTURE;
				CREATE TEMP TABLE w_PEC_FACTURE AS
				SELECT NOFAC, 
					t_tiers_payant_2.oid::bigint AS tiers_payant_2_id,
                    t_tiers_payant_2.code_original as tiers_payant_2_orga_id
				FROM w_KFACTURE KFACTURE
                    LEFT JOIN prod_mederi.ORGMUT ON KFACTURE.NOMUTUELLE = ORGMUT.NOMUTUELLE
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON (KFACTURE.NOMUTUELLE = t_tiers_payant_2.code_original)
				WHERE NOFAC IS NOT NULL AND est_doublon = '0'
                GROUP BY 1,2;
					
				ALTER TABLE w_PEC_FACTURE ADD CONSTRAINT w_PEC_FACTURE_pkey PRIMARY KEY(NOFAC);		
            
				UPDATE w_FAC_FACTURE
                SET 
                    tiers_payant_2_id = w_PEC_FACTURE.tiers_payant_2_id,
                    tiers_payant_2_orga_id = w_PEC_FACTURE.tiers_payant_2_orga_id
                FROM w_PEC_FACTURE
                WHERE
                    w_FAC_FACTURE.tiers_payant_2_id <> w_PEC_FACTURE.tiers_payant_2_id 
                    AND w_FAC_FACTURE.NOFAC = w_PEC_FACTURE.NOFAC;
                    
				-- En budget global, tous les honoraires ne sont pas facturés (inclus dans GHS) => non utile dans oqn (seul cas traité pour l'instant)

		
				-- Informations montants factures et regles

				DROP TABLE IF EXISTS w_FAC_MONTANTS;
				CREATE TEMP TABLE w_FAC_MONTANTS AS
				SELECT 
                    NOFAC,
                    
                    SUM(CASE WHEN FACPARTIEL != 9 THEN MNTPREST ELSE 0 END) AS montant_facture_c,
					SUM(CASE WHEN FACPARTIEL != 9 THEN MNTPASS ELSE 0 END) AS montant_facture_0_c,
					SUM(CASE WHEN FACPARTIEL != 9 THEN MNTPAM ELSE 0 END) AS montant_facture_1_c,
					SUM(CASE WHEN FACPARTIEL != 9 THEN MNTPMUT ELSE 0 END) AS montant_facture_2_c,
					0 AS montant_facture_22_c,
				
					SUM(CASE WHEN FACPARTIEL != 9 AND DATEFAC IS NOT NULL THEN MNTPREST ELSE 0 END) AS montant_comptabilise_c,
					SUM(CASE WHEN FACPARTIEL != 9 AND DATEFAC IS NOT NULL THEN MNTPASS  ELSE 0 END) AS montant_comptabilise_0_c,
					SUM(CASE WHEN FACPARTIEL != 9 AND DATEFAC IS NOT NULL THEN MNTPAM ELSE 0 END) AS montant_comptabilise_1_c,
                    SUM(CASE WHEN FACPARTIEL != 9 AND DATEFAC IS NOT NULL THEN MNTPMUT ELSE 0 END) AS montant_comptabilise_2_c,
					SUM(CASE WHEN FACPARTIEL != 9 AND DATEFAC IS NOT NULL THEN 0 ELSE 0 END) AS montant_comptabilise_22_c,

					SUM(CASE WHEN FACPARTIEL != 9 THEN MNTPREST - (SLDPAM + SLDPMUT + SLDPASS) ELSE 0 END) AS montant_regle_c,
					SUM(CASE WHEN FACPARTIEL != 9 THEN MNTPASS - SLDPASS ELSE 0 END) AS montant_regle_0_c,
					SUM(CASE WHEN FACPARTIEL != 9 THEN MNTPAM - SLDPAM ELSE 0 END) AS montant_regle_1_c,
                    SUM(CASE WHEN FACPARTIEL != 9 THEN MNTPMUT - SLDPMUT ELSE 0 END) AS montant_regle_2_c,
					SUM(CASE WHEN FACPARTIEL != 9 THEN 0 ELSE 0 END) AS montant_regle_22_c,

					SUM(CASE WHEN FACPARTIEL != 9 THEN MNTHONO ELSE 0 END) AS montant_facture_h,
					SUM(CASE WHEN FACPARTIEL != 9 THEN MNTHASS ELSE 0 END) AS montant_facture_0_h,
					SUM(CASE WHEN FACPARTIEL != 9 THEN MNTHAM ELSE 0 END) AS montant_facture_1_h,
					SUM(CASE WHEN FACPARTIEL != 9 THEN MNTHMUT ELSE 0 END) AS montant_facture_2_h,
					SUM(CASE WHEN FACPARTIEL != 9 THEN 0 ELSE 0 END) AS montant_facture_22_h,
                    
                    SUM(CASE WHEN FACPARTIEL != 9 AND DATEFAC IS NOT NULL THEN MNTHONO ELSE 0 END) AS montant_comptabilise_h,
					SUM(CASE WHEN FACPARTIEL != 9 AND DATEFAC IS NOT NULL THEN MNTHASS ELSE 0 END) AS montant_comptabilise_0_h,
					SUM(CASE WHEN FACPARTIEL != 9 AND DATEFAC IS NOT NULL THEN MNTHAM ELSE 0 END) AS montant_comptabilise_1_h,
                    SUM(CASE WHEN FACPARTIEL != 9 AND DATEFAC IS NOT NULL THEN MNTHMUT ELSE 0 END) AS montant_comptabilise_2_h,
					SUM(CASE WHEN FACPARTIEL != 9 AND DATEFAC IS NOT NULL THEN 0 ELSE 0 END) AS montant_comptabilise_22_h,
					
                    SUM(CASE WHEN FACPARTIEL != 9 THEN MNTHONO - (SLDHAM + SLDHMUT + SLDHASS) ELSE 0 END) AS montant_regle_h,
					SUM(CASE WHEN FACPARTIEL != 9 THEN MNTHASS - SLDHASS ELSE 0 END) AS montant_regle_0_h,
					SUM(CASE WHEN FACPARTIEL != 9 THEN MNTHAM - SLDHAM ELSE 0 END) AS montant_regle_1_h,
                    SUM(CASE WHEN FACPARTIEL != 9 THEN MNTHMUT - SLDHMUT ELSE 0 END) AS montant_regle_2_h,
					SUM(CASE WHEN FACPARTIEL != 9 THEN 0 ELSE 0 END) AS montant_regle_22_h
					
				FROM w_FAC_FACTURE
                WHERE NOFAC IS NOT NULL
				GROUP BY NOFAC;

	
				CREATE INDEX w_FAC_MONTANTS_i1
				ON w_FAC_MONTANTS
				USING btree
				(NOFAC);
	
                UPDATE w_FAC_MONTANTS
                SET 
                    montant_facture_c = -montant_facture_c,
					montant_facture_0_c = -montant_facture_0_c ,
					montant_facture_1_c = -montant_facture_1_c,
					montant_facture_2_c = -montant_facture_2_c,
					montant_facture_22_c = montant_facture_22_c,
				
					montant_comptabilise_c = -montant_comptabilise_c,
					montant_comptabilise_0_c = -montant_comptabilise_0_c,
					montant_comptabilise_1_c = -montant_comptabilise_1_c,
                    montant_comptabilise_2_c = -montant_comptabilise_2_c,
					montant_comptabilise_22_c = -montant_comptabilise_22_c,

					montant_regle_c = -montant_regle_c,
					montant_regle_0_c = -montant_regle_0_c,
					montant_regle_1_c = -montant_regle_1_c,
                    montant_regle_2_c = -montant_regle_2_c,
					montant_regle_22_c = -montant_regle_22_c,

					montant_facture_h = -montant_facture_h,
					montant_facture_0_h = -montant_facture_0_h,
					montant_facture_1_h = -montant_facture_1_h,
					montant_facture_2_h = -montant_facture_2_h,
					montant_facture_22_h = -montant_facture_22_h,
                    
                    montant_comptabilise_h = -montant_comptabilise_h,
					montant_comptabilise_0_h = -montant_comptabilise_0_h,
					montant_comptabilise_1_h = -montant_comptabilise_1_h,
                    montant_comptabilise_2_h = -montant_comptabilise_2_h,
					montant_comptabilise_22_h = -montant_comptabilise_22_h,
					
                    montant_regle_h = -montant_regle_h,
					montant_regle_0_h = -montant_regle_0_h,
					montant_regle_1_h = -montant_regle_1_h,
                    montant_regle_2_h = -montant_regle_2_h,
					montant_regle_22_h = -montant_regle_22_h
                WHERE NOFAC IN (SELECT NOFAC FROM w_KFACTURE KFACTURE WHERE TYPEFAC IN ('2','4'));
	
				-- Informations date dernier reglement

				DROP TABLE IF EXISTS w_FAC_REGLEMENT;
				CREATE TEMP TABLE w_FAC_REGLEMENT AS
				SELECT 
                    KACTES.NODOSSIER,
                    KACTES.NOFAC,
					MAX(CASE WHEN TYPERUB <> 4 AND DEBITEUR = 3 THEN DATE ELSE NULL END) AS date_dernier_reglement_0_c,
					MAX(CASE WHEN TYPERUB <> 4 AND DEBITEUR = 1 THEN DATE ELSE NULL END) AS date_dernier_reglement_1_c,
					MAX(CASE WHEN TYPERUB <> 4 AND DEBITEUR = 2 THEN DATE ELSE NULL END) AS date_dernier_reglement_2_c,
					date(NULL) AS date_dernier_reglement_22_c,
					MAX(CASE WHEN TYPERUB = 4 AND DEBITEUR = 3 THEN DATE ELSE NULL END)  AS date_dernier_reglement_0_h,
					MAX(CASE WHEN TYPERUB = 4 AND DEBITEUR = 1 THEN DATE ELSE NULL END) AS date_dernier_reglement_1_h,
					MAX(CASE WHEN TYPERUB = 4 AND DEBITEUR = 2 THEN DATE ELSE NULL END) AS date_dernier_reglement_2_h,
					date(NULL)  AS date_dernier_reglement_22_h,
					count(DISTINCT date_part('month',DATE)) AS nb_mois_reglement
				FROM w_KRGLDET KRGLDET
                    JOIN prod_mederi.KACTES ON KACTES.ACCLEUNIK = KRGLDET.ACCLEUNIK
                    JOIN w_KFACTURE KFACTURE ON KRGLDET.NOFAC = KFACTURE.NOFAC
				WHERE est_doublon = '0'
				GROUP BY 1,2;

				CREATE INDEX w_FAC_REGLEMENT_i1
				ON w_FAC_REGLEMENT
				USING btree
				(NOFAC);
	
	
				-- Informations date vente (direct dans kfacture)

	  
				-- Informations expedition (factures et avoir)

				DROP TABLE IF EXISTS w_FAC_BORDEREAU;
				CREATE TEMP TABLE w_FAC_BORDEREAU AS
				SELECT NOFAC,
					'0'::text  AS code_expedie_0,
					MAX(CASE WHEN NOBORD != '' AND NOBORD !='X' THEN '1' ELSE '0' END) AS code_expedie_1,
					MAX(CASE WHEN NOBORDM != '' AND NOBORD != 'X' THEN '1' ELSE '0' END) AS code_expedie_2,
					'0' AS code_expedie_22,
					''::text AS no_bordereau_0,
					MAX(CASE WHEN NOBORD != '' AND NOBORD != 'X' THEN NOBORD::bigint ELSE '0' END) AS no_bordereau_1,
					MAX(CASE WHEN NOBORDM != '' AND NOBORDM != 'X' THEN NOBORDM::bigint ELSE '0' END) AS no_bordereau_2,
					NULL AS no_bordereau_22,
					'20991231'::date AS date_expedition_0,
					MIN(CASE WHEN NOBORD != '' AND NOBORD !='X' THEN DATEBORD ELSE '20991231' END) AS date_expedition_1,
					MIN(CASE WHEN NOBORDM != '' AND NOBORDM !='X' THEN DATEBORD ELSE '20991231' END) AS date_expedition_2,
					'20991231'::date AS date_expedition_22
				FROM w_KFACTURE KFACTURE
                WHERE NOFAC IS NOT NULL AND est_doublon = '0'
                GROUP BY 1;

                
				CREATE INDEX w_FAC_BORDEREAU_i1
				ON w_FAC_BORDEREAU
				USING btree
				(NOFAC);
	  
				-- Informations rejets
				
				DROP TABLE IF EXISTS w_FAC_REJET;
				CREATE TEMP TABLE w_FAC_REJET AS
				SELECT FACTURE AS NOFAC,
					COUNT(*) as nb_rejets
				FROM prod_mederi.KNOERJ
				WHERE TRIM(ERRCODE) <> '0001'
				GROUP BY FACTURE;

				CREATE INDEX w_FAC_REJET_i1
				ON w_FAC_REJET
				USING btree
				(NOFAC);
				
				
				-- Ajout des factures
				
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_8');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_9');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_10');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_11');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_12');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_13');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_14');

				INSERT INTO activite[PX].p_factures(
					sejour_id,
					no_sejour, 
					no_facture, 
					date_debut, 
					date_fin, 
					type_facture, 
					code_facture, 
					date_facture, 
					code_vente, 
					date_vente, 
					mois_vente, 
					date_solde, 
					montant_facture_c, 
					montant_facture_h, 
					montant_regle_c, 
					montant_regle_h, 
					delai_facture, 
					delai_solde, 
					date_expedition, 
					delai_expedition, 
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					tiers_payant_2_id, 
					tiers_payant_22_id, 
					date_solde_0_c, 
					date_solde_0_h, 
					date_solde_1_c, 
					date_solde_1_h, 
					date_solde_2_c, 
					date_solde_2_h, 
					date_solde_22_c, 
					date_solde_22_h, 
					date_expedition_0, 
					date_expedition_1, 
					date_expedition_2, 
					date_expedition_22, 
					code_expedie_0, 
					code_expedie_1, 
					code_expedie_2, 
					code_expedie_22, 
					no_bordereau_0, 
					no_bordereau_1, 
					no_bordereau_2, 
					no_bordereau_22, 
					montant_facture_0_c,
					montant_facture_0_h, 
					montant_facture_1_c, 
					montant_facture_1_h, 
					montant_facture_2_c, 
					montant_facture_2_h, 
					montant_facture_22_c, 
					montant_facture_22_h, 
					montant_regle_0_c, 
					montant_regle_0_h, 
					montant_regle_1_c, 
					montant_regle_1_h, 
					montant_regle_2_c, 
					montant_regle_2_h, 
					montant_regle_22_c, 
					montant_regle_22_h, 
					delai_expedition_0, 
					delai_expedition_1, 
					delai_expedition_2, 
					delai_expedition_22, 
					delai_solde_0_c, 
					delai_solde_0_h, 
					delai_solde_1_c, 
					delai_solde_1_h, 
					delai_solde_2_c, 
					delai_solde_2_h, 
					delai_solde_22_c, 
					delai_solde_22_h, 
					ghs_id, 
					particularite_t2a, 
					code_cloture, 
					code_cp_demandee, 
					ghs_bebe1_id, 
					ghs_bebe2_id, 
					ghs_bebe3_id,
					
					montant_comptabilise_c, 
					montant_comptabilise_h, 
					montant_comptabilise_0_c,
					montant_comptabilise_0_h, 
					montant_comptabilise_1_c, 
					montant_comptabilise_1_h, 
					montant_comptabilise_2_c, 
					montant_comptabilise_2_h, 
					montant_comptabilise_22_c, 
					montant_comptabilise_22_h, 
					
					nb_rejets,
					
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour
					)
				SELECT
					sejour_id,
					no_sejour,
					w_FAC_FACTURE.NOFAC AS no_facture,
                    date_debut_facture AS date_debut,
					date_fin_facture AS date_fin,
					CASE 
						WHEN TYPEFAC = '1' THEN '0'
                        WHEN TYPEFAC IN ('2','4') THEN '1'
                        WHEN TYPEFAC IN ('3') THEN 'P'
						ELSE '0' END AS type_facture,
					CASE WHEN FACPARTIEL != 9 THEN '1' ELSE '0' END AS code_facture,
					DATEFAC AS date_facture,
					CASE WHEN DATEFAC IS NOT NULL THEN '1' ELSE '0' END AS code_vente,
					CASE WHEN DATEFAC IS NOT NULL THEN DATEFAC ELSE '20991231'::date END AS date_vente,
					CASE WHEN DATEFAC IS NOT NULL THEN extract('year' FROM DATEFAC) * 100 + extract('month' FROM DATEFAC) ELSE extract('year' FROM '20991231'::date) * 100 + extract('month' FROM '20991231'::date) END AS mois_vente,

					COALESCE(	
					GREATEST(	
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_0_c = 0 THEN date_sortie ELSE date_dernier_reglement_0_c END,
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_0_h = 0 THEN date_sortie ELSE date_dernier_reglement_0_h END,
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_1_c = 0 THEN date_sortie ELSE date_dernier_reglement_1_c END,
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_1_h = 0 THEN date_sortie ELSE date_dernier_reglement_1_h END,	
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_2_c = 0 THEN date_sortie ELSE date_dernier_reglement_2_c END,
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_2_h = 0 THEN date_sortie ELSE date_dernier_reglement_2_h END,	
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_22_c = 0 THEN date_sortie ELSE date_dernier_reglement_22_c END,
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_22_h = 0 THEN date_sortie ELSE date_dernier_reglement_22_h END)
					, '20991231') as date_solde,

						
					w_FAC_MONTANTS.montant_facture_c AS montant_facture_c,
					w_FAC_MONTANTS.montant_facture_h AS montant_facture_h,
					w_FAC_MONTANTS.montant_regle_c AS montant_regle_c,
					w_FAC_MONTANTS.montant_regle_h AS montant_regle_h,
					DATEFAC - date_sortie as delai_facture, 
					0 as delai_solde, 
					LEAST(w_FAC_BORDEREAU.date_expedition_1, w_FAC_BORDEREAU.date_expedition_2) as date_expedition, 
					0 as delai_expedition, 
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,	
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_0_c = 0 THEN date_sortie
						WHEN date_dernier_reglement_0_c IS NOT NULL THEN date_dernier_reglement_0_c ELSE '20991231' END  as date_solde_0_c,
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_0_h = 0 THEN date_sortie
						WHEN date_dernier_reglement_0_h IS NOT NULL THEN date_dernier_reglement_0_h ELSE '20991231' END  as date_solde_0_h,
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_1_c = 0 THEN date_sortie
						WHEN date_dernier_reglement_1_c IS NOT NULL THEN date_dernier_reglement_1_c ELSE '20991231' END  as date_solde_1_c,
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_1_h = 0 THEN date_sortie
						WHEN date_dernier_reglement_1_h IS NOT NULL THEN date_dernier_reglement_1_h ELSE '20991231' END  as date_solde_1_h,	
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_2_c = 0 THEN date_sortie
						WHEN date_dernier_reglement_2_c IS NOT NULL THEN date_dernier_reglement_2_c ELSE '20991231' END  as date_solde_2_c,
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_2_h = 0 THEN date_sortie
						WHEN date_dernier_reglement_2_h IS NOT NULL THEN date_dernier_reglement_2_h ELSE '20991231' END  as date_solde_2_h,	
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_22_c = 0 THEN date_sortie
						WHEN date_dernier_reglement_22_c IS NOT NULL THEN date_dernier_reglement_22_c ELSE '20991231' END  as date_solde_22_c,
					CASE 
						WHEN w_FAC_MONTANTS.montant_comptabilise_22_h = 0 THEN date_sortie
						WHEN date_dernier_reglement_22_h IS NOT NULL THEN date_dernier_reglement_22_h ELSE '20991231' END  as date_solde_22_h,	

					w_FAC_BORDEREAU.date_expedition_0,
					w_FAC_BORDEREAU.date_expedition_1,
					w_FAC_BORDEREAU.date_expedition_2,
					w_FAC_BORDEREAU.date_expedition_22,
					w_FAC_BORDEREAU.code_expedie_0,
					w_FAC_BORDEREAU.code_expedie_1,
					w_FAC_BORDEREAU.code_expedie_2,
					w_FAC_BORDEREAU.code_expedie_22,
					w_FAC_BORDEREAU.no_bordereau_0,
					w_FAC_BORDEREAU.no_bordereau_1,
					w_FAC_BORDEREAU.no_bordereau_2,
					w_FAC_BORDEREAU.no_bordereau_22,

					w_FAC_MONTANTS.montant_facture_0_c AS montant_facture_0_c,
					w_FAC_MONTANTS.montant_facture_0_h AS montant_facture_0_h,
					w_FAC_MONTANTS.montant_facture_1_c AS montant_facture_1_c,
					w_FAC_MONTANTS.montant_facture_1_h AS montant_facture_1_h,
					w_FAC_MONTANTS.montant_facture_2_c AS montant_facture_2_c,
					w_FAC_MONTANTS.montant_facture_2_h AS montant_facture_2_h,
					w_FAC_MONTANTS.montant_facture_22_c AS montant_facture_22_c,
					w_FAC_MONTANTS.montant_facture_22_h AS montant_facture_22_h,

					w_FAC_MONTANTS.montant_regle_0_c AS montant_regle_0_c,
					w_FAC_MONTANTS.montant_regle_0_h AS montant_regle_0_h,
					w_FAC_MONTANTS.montant_regle_1_c AS montant_regle_1_c,
					w_FAC_MONTANTS.montant_regle_1_h AS montant_regle_1_h,
					w_FAC_MONTANTS.montant_regle_2_c AS montant_regle_2_c,
					w_FAC_MONTANTS.montant_regle_2_h AS montant_regle_2_h,
					w_FAC_MONTANTS.montant_regle_22_c AS montant_regle_22_c,
					w_FAC_MONTANTS.montant_regle_22_h AS montant_regle_22_h,


					0 AS delai_expedition_0, 
					0 AS delai_expedition_1, 
					0 AS delai_expedition_2, 
					0 AS delai_expedition_22, 
					0 AS delai_solde_0_c, 
					0 AS delai_solde_0_h, 
					0 AS delai_solde_1_c, 
					0 AS delai_solde_1_h, 
					0 AS delai_solde_2_c, 
					0 AS delai_solde_2_h, 
					0 AS delai_solde_22_c, 
					0 AS delai_solde_22_h, 

					ghs_id,
					'' as particularite_t2a, 

					'0' as code_cloture,
					'0' as code_cp_demandee, 
					0 AS ghs_bebe1_id, 
					0 AS ghs_bebe2_id, 
					0 AS ghs_bebe3_id,
					
					w_FAC_MONTANTS.montant_comptabilise_c, 
					w_FAC_MONTANTS.montant_comptabilise_h, 
					w_FAC_MONTANTS.montant_comptabilise_0_c,
					w_FAC_MONTANTS.montant_comptabilise_0_h, 
					w_FAC_MONTANTS.montant_comptabilise_1_c, 
					w_FAC_MONTANTS.montant_comptabilise_1_h, 
					w_FAC_MONTANTS.montant_comptabilise_2_c, 
					w_FAC_MONTANTS.montant_comptabilise_2_h, 
					w_FAC_MONTANTS.montant_comptabilise_22_c, 
					w_FAC_MONTANTS.montant_comptabilise_22_h, 
					
					COALESCE(w_FAC_REJET.nb_rejets,0),
					
					0,
					0


				FROM w_FAC_FACTURE 
					LEFT JOIN w_FAC_BORDEREAU ON (w_FAC_FACTURE.NOFAC = w_FAC_BORDEREAU.NOFAC)
					LEFT JOIN w_FAC_MONTANTS ON (w_FAC_FACTURE.NOFAC = w_FAC_MONTANTS.NOFAC)
					LEFT JOIN w_FAC_REGLEMENT ON (w_FAC_FACTURE.NOFAC = w_FAC_REGLEMENT.NOFAC)
					LEFT JOIN w_FAC_REJET ON (w_FAC_FACTURE.NOFAC = w_FAC_REJET.NOFAC)
            --       LEFT JOIN prod_mederi.KENCOURS ON w_FAC_FACTURE.NOFAC = KENCOURS.NOFAC   
				ORDER BY 1,2;
				
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_9');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_10');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_11');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_12');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_13');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_14');

	
				-- Séjours sans facture
				
				DROP TABLE IF EXISTS w_factures_trous;
				CREATE TEMP TABLE w_factures_trous AS
				SELECT
					p_sejours.finess,
					p_sejours.no_sejour,
					p_sejours.date_entree,
					p_sejours.tiers_payant_0_id, 
					p_sejours.tiers_payant_1_id, 
					p_sejours.tiers_payant_2_id, 
					p_sejours.tiers_payant_22_id,
					p_sejours.code_cp_demandee,
					p_sejours.ghs_id,
					COALESCE(t_services_facturation.avec_facturation_intermediaire,'') AS avec_facturation_intermediaire,
					p_sejours.code_sorti,
					CASE WHEN code_sorti = '1' THEN date_sortie ELSE date(now()) END AS date_sortie,
					CASE WHEN code_sorti = '1' THEN date_sortie ELSE date(now()) END AS date_fin_encours,
					MAX(CASE WHEN p_factures.date_fin IS NOT NULL AND date_sortie - date_entree < 30 THEN date_sortie ELSE p_factures.date_fin END) AS date_fin_facture,
					date(MAX(COALESCE(CASE WHEN p_factures.date_fin IS NOT NULL AND date_sortie - date_entree < 30 THEN date_sortie ELSE p_factures.date_fin END + interval '1 day', p_sejours.date_entree))) AS date_debut_encours
				FROM activite[PX].p_sejours
					LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND no_facture NOT LIKE 'E%' AND type_facture IS DISTINCT FROM 'P'
					JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
					JOIN activite[PX].t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid
				WHERE p_sejours.etat = '' AND p_sejours.est_sans_facturation IS DISTINCT FROM '1' AND date_entree <= now() AND p_sejours.type_sejour <> '6' AND p_sejours.type_sejour <> '9'
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13;


				INSERT INTO activite[PX].p_factures(
					finess, 
					no_sejour, 
					no_facture, 
					no_facture_reference, 
					type_facture, 
					code_facture, 
					date_facture, 
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					tiers_payant_2_id, 
					tiers_payant_22_id,
					code_cp_demandee, 
					ghs_id,
					date_debut, 
					date_fin)
				SELECT finess, 
					no_sejour, 
					'E' || no_sejour || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || substr(p_calendrier.mois,3,4) ELSE '' END, 
					'E' || no_sejour || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || substr(p_calendrier.mois,3,4) ELSE '' END, 
					'E', 
					'0', 
					'20991231'::date,
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					tiers_payant_2_id, 
					tiers_payant_22_id, 
					code_cp_demandee , 
					ghs_id,
					MIN(GREATEST(date_debut_encours, p_calendrier.date)), 
					MAX(LEAST(date_fin_encours, p_calendrier.date))
				FROM w_factures_trous 
					JOIN base.p_calendrier ON p_calendrier.date  BETWEEN date_debut_encours AND date_fin_encours
				WHERE (date_debut_encours <= date_fin_encours or date_fin_facture is null) 
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13
                HAVING MIN(GREATEST(date_debut_encours, p_calendrier.date)) >= '[ENV_ADM_ANNEEDEBUT]0101'
                ;

				
				
				UPDATE activite[PX].p_factures SET
					date_debut = date_entree,
					date_fin = CASE WHEN code_sorti = '1' THEN date_sortie ELSE date_fin END
				FROM activite[PX].p_sejours 
					JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
					JOIN activite[PX].t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid AND 
						avec_facturation_intermediaire IS DISTINCT FROM '1'
				WHERE p_factures.no_sejour = p_sejours.no_sejour AND
					CASE WHEN code_sorti = '1' THEN date_sortie ELSE date(now()) END - date_entree < 30 AND
					(
					p_factures.date_debut <> date_entree OR
					p_factures.date_fin <> CASE WHEN code_sorti = '1' THEN date_sortie ELSE date_fin END
					);
	
	
				-- Avoirs qui annulent des factures

				UPDATE activite[PX].p_factures SET 
                      no_facture_od_avoir = FAC_FACTURE_AVOIR.NOFAC,
                      type_facture = 'X'
                FROM w_KFACTURE KFACTURE
				JOIN w_KFACTURE FAC_FACTURE_AVOIR ON KFACTURE.NOFAC = FAC_FACTURE_AVOIR.FACAVOIR AND FAC_FACTURE_AVOIR.FACAVOIR != ''
				WHERE p_factures.no_facture = KFACTURE.NOFAC
					AND no_facture_od_avoir IS DISTINCT FROM FAC_FACTURE_AVOIR.NOFAC
					AND KFACTURE.est_doublon = '0'
					AND FAC_FACTURE_AVOIR.est_doublon = '0'
				;

                                    
				DROP TABLE IF EXISTS w_ods_avoir;
				CREATE TEMP TABLE w_ods_avoir AS

                SELECT p_factures.no_facture, p_factures.no_facture_od_avoir, p_factures_avoir.date_facture AS date_od_avoir,
					SUM(p_factures.montant_comptabilise_c + p_factures.montant_comptabilise_h) AS montant_comptabilise,
					SUM(p_factures.montant_regle_c + p_factures.montant_regle_h) AS montant_regle,
					SUM(p_factures_avoir.montant_comptabilise_c + p_factures_avoir.montant_comptabilise_h) AS montant_facture_avoir,
					SUM(p_factures_avoir.montant_regle_c + p_factures_avoir.montant_regle_h) AS montant_regle_avoir
				FROM activite[PX].p_factures JOIN activite[PX].p_factures p_factures_avoir ON p_factures.no_facture = p_factures_avoir.no_facture_od_avoir 
				WHERE p_factures.type_facture = 'X' AND p_factures_avoir.type_facture = '1'
				GROUP BY 1,2,3
				HAVING SUM(p_factures.montant_comptabilise_c + p_factures.montant_comptabilise_h) = 0 - SUM(p_factures_avoir.montant_comptabilise_c + p_factures_avoir.montant_comptabilise_h)
					AND SUM(p_factures.montant_regle_c + p_factures.montant_regle_h) = 0
					AND SUM(p_factures_avoir.montant_regle_c + p_factures_avoir.montant_regle_h) = 0;
	


				UPDATE activite[PX].p_factures SET
					date_solde_c = date_od_avoir,
					date_solde_0_c = date_od_avoir,
					date_solde_1_c = date_od_avoir,
					date_solde_2_c = date_od_avoir,
					date_solde_22_c = date_od_avoir,
					date_solde_h = date_od_avoir,
					date_solde_0_h = date_od_avoir,
					date_solde_1_h = date_od_avoir,
					date_solde_2_h = date_od_avoir,
					date_solde_22_h = date_od_avoir,
					montant_regle_c = montant_comptabilise_c,
					montant_regle_0_c = montant_comptabilise_0_c,
					montant_regle_1_c = montant_comptabilise_1_c,
					montant_regle_2_c = montant_comptabilise_2_c,
					montant_regle_22_c = montant_comptabilise_22_c,
					montant_regle_h = montant_comptabilise_h,
					montant_regle_0_h = montant_comptabilise_0_h,
					montant_regle_1_h = montant_comptabilise_1_h,
					montant_regle_2_h = montant_comptabilise_2_h,
					montant_regle_22_h = montant_comptabilise_22_h
				FROM w_ods_avoir
				WHERE p_factures.no_facture = w_ods_avoir.no_facture;

				UPDATE activite[PX].p_factures SET
					date_solde_c = date_od_avoir,
					date_solde_0_c = date_od_avoir,
					date_solde_1_c = date_od_avoir,
					date_solde_2_c = date_od_avoir,
					date_solde_22_c = date_od_avoir,
					date_solde_h = date_od_avoir,
					date_solde_0_h = date_od_avoir,
					date_solde_1_h = date_od_avoir,
					date_solde_2_h = date_od_avoir,
					date_solde_22_h = date_od_avoir,
					montant_regle_c = montant_comptabilise_c,
					montant_regle_0_c = montant_comptabilise_0_c,
					montant_regle_1_c = montant_comptabilise_1_c,
					montant_regle_2_c = montant_comptabilise_2_c,
					montant_regle_22_c = montant_comptabilise_22_c,
					montant_regle_h = montant_comptabilise_h,
					montant_regle_0_h = montant_comptabilise_0_h,
					montant_regle_1_h = montant_comptabilise_1_h,
					montant_regle_2_h = montant_comptabilise_2_h,
					montant_regle_22_h = montant_comptabilise_22_h
				FROM w_ods_avoir
				WHERE p_factures.no_facture = w_ods_avoir.no_facture_od_avoir;
				
				
				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_sejours_orga CASCADE;
				DROP TABLE IF EXISTS w_FAC_MONTANTS CASCADE;
				DROP TABLE IF EXISTS w_FAC_REGLEMENT CASCADE;
				DROP TABLE IF EXISTS w_FAC_BORDEREAU CASCADE;
				DROP TABLE IF EXISTS w_factures_trous CASCADE;
												
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Rejets">
			<sqlcmd><![CDATA[

				INSERT INTO activite[PX].p_factures_rejets(
					no_facture, date_rejet, rejet_id, rejet_code, rejet_texte)
				SELECT 
					FACTURE , 
					DATEREJET , 
					0,
					TRIM(ERRCODE) ,
					TRIM(ERRLIB)
				FROM prod_mederi.KNOERJ, w_FAC_FACTURE
				WHERE FACTURE = NOFAC
					AND TRIM(ERRCODE) <> '0001' AND TRIM(ERRLIB) <> '';
					
				INSERT INTO activite.t_rejets_noemie (texte, code)
				SELECT rejet_texte, MAX(rejet_code) 
				FROM activite[PX].p_factures_rejets
				LEFT JOIN activite.t_rejets_noemie ON (rejet_texte = t_rejets_noemie.texte)
				WHERE t_rejets_noemie.oid IS NULL
				GROUP BY 1;
				
				UPDATE activite[PX].p_factures_rejets 
				SET rejet_id = t_rejets_noemie.oid
				FROM activite.t_rejets_noemie
				WHERE rejet_texte = t_rejets_noemie.texte;
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lignes non facturées Clinique">
			<sqlcmd><![CDATA[
			
				TRUNCATE activite[PX].p_factures_lignes_non_facturees_c;
				
                
                     
                DROP TABLE IF EXISTS w_KACTES_NF;
                CREATE TEMP TABLE w_KACTES_NF AS
                SELECT
					p_sejours.no_sejour,
					COALESCE(p_factures.no_facture,'') AS no_facture,
					DATEACTE AS date_debut,
                    COALESCE(DATEFIN, DATEACTE) AS date_fin,
                    1 AS nb_rubrique,
                    QTE*KACTES.COEFF AS coefficient,
                    t_rubriques_facturation.oid AS rubrique_facturation_id,
                    t_prestations.oid AS prestation_id,
                    PRIXU::numeric AS prix_unitaire,
                    p_sejours.lieu_sortie_id AS lieu_id
                FROM prod_mederi.KACTES 
				LEFT JOIN prod_mederi.KFACTURE ON KACTES.NOFAC = KFACTURE.NOFAC
				JOIN activite[PX].p_sejours ON KACTES.NODOSSIER = p_sejours.code_original AND p_sejours.etat = ''
				LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND type_facture = 'E' AND
					DATEACTE BETWEEN p_factures.date_debut AND p_factures.date_fin
				JOIN activite[PX].t_rubriques_facturation ON NOACTE = t_rubriques_facturation.code_original
				JOIN prod_mederi.KRUBINT ON KACTES.NOACTE = KRUBINT.NOACTE
				JOIN activite.t_prestations ON NOACTESS = t_prestations.code
				WHERE 
					KACTES.TYPERUB <> 4
					AND KACTES.NOACTE <> 'GHS'
					AND (
						KACTES.NOFAC IS NULL OR
						KFACTURE.NOFAC IS NULL
						)
                    ;

                UPDATE w_KACTES_NF
                    SET no_facture = subview.no_facture
                FROM 
                (
                    SELECT no_sejour, (MAX(Array[date_fin::text,no_facture]))[2] AS no_facture
                    FROM activite[PX].p_factures
                    WHERE type_facture = 'E'
                    GROUP BY 1
                ) subview
                WHERE w_KACTES_NF.no_facture = '' AND
                    w_KACTES_NF.no_sejour = subview.no_sejour
                ;
                
                
                INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
					no_facture, 
					date_debut, 
					date_fin, 
					nb_rubrique, 
					coefficient, 
					rubrique_facturation_id, 
					prestation_id, 
					prix_unitaire, 
					lieu_id)
				SELECT
					no_facture,
					date_debut,
                    date_fin,
					nb_rubrique,
					coefficient,
					rubrique_facturation_id,
					prestation_id,
					prix_unitaire,
					lieu_id
				FROM w_KACTES_NF
                WHERE no_facture <> ''
				;

				
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lignes facturées Clinique">
			<sqlcmd><![CDATA[
			
			
				DROP TABLE IF EXISTS W_KPRAT
				;
				
				CREATE TEMP TABLE W_KPRAT AS
				SELECT * 
				FROM  prod_mederi.KPRAT
				WHERE CTID IN (
							SELECT MAX(CTID)
							from prod_mederi.KPRAT
							GROUP BY NOPRAT
						)
				;
			
				-- comptes associés
				
				INSERT INTO activite[PX].t_compte(oid, code_original, code, texte, texte_court) 
				SELECT 0, 0, '', 'Non renseigné', 'Non renseigné' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_compte);


				INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
				SELECT 
                    NOCOMPTE,
                    NOCOMPTE,
                    array_to_string(array_agg(distinct KACTES.NOACTE),',') ||' service' || CASE WHEN array_length(array_agg(distinct KCPTRUB.NOSERVINT),1) != 1 THEn 's ' ELSE ' ' END || array_to_string(array_agg(distinct KCPTRUB.NOSERVINT),','),
                    array_to_string(array_agg(distinct KACTES.NOACTE),',') ||' service' || CASE WHEN array_length(array_agg(distinct KCPTRUB.NOSERVINT),1) != 1 THEn 's ' ELSE ' ' END || array_to_string(array_agg(distinct KCPTRUB.NOSERVINT),',')
                    FROM prod_mederi.KCPTRUB 
                        JOIN prod_mederi.KACTES ON KACTES.NOACTE = KCPTRUB.NOACTE
				WHERE NOCOMPTE NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code_original IS NOT NULL)
				GROUP BY 1,2
				ORDER BY 1,2;
				
                		
                INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
				SELECT 
                    NOCOMPTES,
                    NOCOMPTES,
                    array_to_string(array_agg(distinct KACTES.NOACTE),',') ||' (tous services)',
                    array_to_string(array_agg(distinct KACTES.NOACTE),',') ||' (tous services)'
                    FROM prod_mederi.KRUBINT 
                      JOIN prod_mederi.KACTES ON KACTES.NOACTE = KRUBINT.NOACTE
				WHERE NOCOMPTES != ''
                    AND NOCOMPTES NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code_original IS NOT NULL)
				GROUP BY 1,2
				ORDER BY 1,2;
                
				-- Extraction lignes

				DROP TABLE IF EXISTS w_FAC_FACTURE_LIGNE_C;
				CREATE TEMP TABLE w_FAC_FACTURE_LIGNE_C AS
				SELECT 
					1::integer AS origine_facturation_id,
					ACCLEUNIK,
					KACTES.NOFAC AS no_facture, 
					DATEACTE AS date_debut, 
					COALESCE(DATEFIN, DATEACTE) AS date_fin, 
					CASE WHEN FACPARTIEL != 9 AND DATEFAC IS NOT NULL THEN DATEFAC ELSE '20991231'::date END AS date_vente,
					lieu_sortie_id,
					CASE WHEN TYPEFAC NOT IN ('2','4') THEN QTE ELSE 0-QTE END AS nb_rubrique,
					CASE WHEN TYPEFAC NOT IN ('2','4') THEN QTE ELSE 0-QTE END AS nb_prestations,
					KACTES.COEFF as coefficient, 
					1::numeric AS coefficient_mco,
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_facturation_id, 
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					COALESCE(t_compte.oid::bigint, 0) AS compte_produit_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id, 
					PRIXU::numeric AS prix_unitaire,

					SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTASS + MNTMUT + MNTSS ELSE - (MNTASS + MNTMUT + MNTSS) END) AS montant_facture,
					SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTASS ELSE - MNTASS END) AS montant_facture_0,
					SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTSS ELSE - MNTSS END) AS montant_facture_1,
					SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTMUT ELSE - MNTMUT END) AS montant_facture_2,
					0  as montant_facture_22,

					0 AS montant_facture_actes_inclus_dans_sejour,
					0 as montant_facture_0_actes_inclus_dans_sejour,
					0 as montant_facture_1_actes_inclus_dans_sejour,
					0 as montant_facture_2_actes_inclus_dans_sejour,
					0 as montant_facture_22_actes_inclus_dans_sejour,

					AVG(100-TAUXSS-TAUXMUT) as taux_0,
					AVG(TAUXSS) as taux_1,
					AVG(TAUXMUT) as taux_2,
					0 as taux_22,
					
                    CASE WHEN MIN(DATEFAC) IS NOT NULL THEN SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTSS + MNTMUT + MNTASS  ELSE - ( MNTSS + MNTMUT + MNTASS)  END) ELSE 0 END AS montant_comptabilise,
					CASE WHEN MIN(DATEFAC) IS NOT NULL THEN SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTASS  ELSE - MNTASS  END)  ELSE 0 END AS montant_comptabilise_0,
					CASE WHEN MIN(DATEFAC) IS NOT NULL THEN SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTSS  ELSE - MNTSS  END)  ELSE 0 END AS montant_comptabilise_1,
                    CASE WHEN MIN(DATEFAC) IS NOT NULL THEN SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTMUT ELSE - MNTMUT END)  ELSE 0 END AS montant_comptabilise_2,
					0 AS montant_comptabilise_22,
					
					0::bigint AS rubrique_facture_id

				FROM prod_mederi.KACTES
					LEFT JOIN activite[PX].t_rubriques_facturation ON (NOACTE = t_rubriques_facturation.code_original)
					JOIN w_FAC_FACTURE ON KACTES.NOFAC = w_FAC_FACTURE.NOFAC
					LEFT JOIN (SELECT NOACTE, NOSERVINT, MAX(NOCOMPTE) AS NOCOMPTE FROM prod_mederi.KCPTRUB GROUP BY 1,2) sub ON KACTES.NOSERVINT = sub.NOSERVINT AND KACTES.NOACTE = sub.NOACTE
					LEFT JOIN prod_mederi.KRUBINT ON KACTES.NOACTE = KRUBINT.NOACTE
					LEFT JOIN activite.t_prestations ON (NOACTESS = t_prestations.code)
                    LEFT JOIN activite[PX].t_compte ON (NOCOMPTE IS NOT NULL AND NOCOMPTE::bigint = t_compte.code_original) OR (NOCOMPTE IS NULL  AND NOCOMPTES::bigint = t_compte.code_original::bigint)
				WHERE 
					FACPARTIEL != 9 AND
                    KACTES.TYPERUB <> 4
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16;
							
				-- Médecin Salarié
				
				INSERT INTO w_FAC_FACTURE_LIGNE_C
				SELECT 
					1::integer AS origine_facturation_id,
					ACCLEUNIK,
					KACTES.NOFAC AS no_facture, 
					date(DATEACTE) AS date_debut, 
					COALESCE(date(DATEFIN),date(DATEACTE)) AS date_fin, 
					CASE WHEN FACPARTIEL != 9 AND KACTES.NOFAC IS NOT NULL THEN DATEFAC ELSE '20991231'::date END AS date_vente,
					lieu_sortie_id,
					CASE WHEN TYPEFAC NOT IN ('2','4') THEN QTE ELSE 0-QTE END AS nb_rubrique,
					CASE WHEN TYPEFAC NOT IN ('2','4') THEN QTE ELSE 0-QTE END AS nb_prestations,
					KACTES.COEFF as coefficient, 
					1 AS coefficient_mco,
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_facturation_id, 
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					MAX(COALESCE(t_compte.oid::bigint, 0)) AS compte_produit_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id, 
					PRIXU AS prix_unitaire,

					0 AS montant_facture,
					0 AS montant_facture_0,
					0 AS montant_facture_1,
					0 AS montant_facture_2,
					0  as montant_facture_22,

					0 AS montant_facture_actes_inclus_dans_sejour,
					0 as montant_facture_0_actes_inclus_dans_sejour,
					0 as montant_facture_1_actes_inclus_dans_sejour,
					0 as montant_facture_2_actes_inclus_dans_sejour,
					0 as montant_facture_22_actes_inclus_dans_sejour,

					AVG(100-TAUXSS-TAUXMUT) as taux_0,
					AVG(TAUXSS) as taux_1,
					AVG(TAUXMUT) as taux_2,
					0 as taux_22,

					SUM(CASE WHEN DATEFAC IS NOT NULL THEN CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTASS + MNTMUT + MNTSS ELSE - (MNTASS + MNTMUT + MNTSS) END ELSE 0 END) AS montant_comptabilise,
					SUM(CASE WHEN DATEFAC IS NOT NULL THEN CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTASS ELSE - MNTASS END ELSE 0 END) AS montant_comptabilise_0,
					SUM(CASE WHEN DATEFAC IS NOT NULL THEN CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTSS ELSE - MNTSS END ELSE 0 END) AS montant_comptabilise_1,
					SUM(CASE WHEN DATEFAC IS NOT NULL THEN CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTMUT ELSE - MNTMUT END ELSE 0 END) AS montant_comptabilise_2,
					0 AS montant_comptabilise_22,
					
					0::bigint AS rubrique_facture_id

				FROM prod_mederi.KACTES
					LEFT JOIN activite[PX].t_rubriques_facturation ON (NOACTE = t_rubriques_facturation.code_original)
					JOIN w_FAC_FACTURE ON KACTES.NOFAC = w_FAC_FACTURE.NOFAC
					LEFT JOIN (SELECT NOACTE, NOSERVINT, MAX(NOCOMPTE) AS NOCOMPTE FROM prod_mederi.KCPTRUB GROUP BY 1,2) sub ON KACTES.NOSERVINT = sub.NOSERVINT AND KACTES.NOACTE = sub.NOACTE
					LEFT JOIN prod_mederi.KRUBINT ON KACTES.NOACTE = KRUBINT.NOACTE
					LEFT JOIN activite.t_prestations ON (NOACTESS = t_prestations.code)
                    LEFT JOIN activite[PX].t_compte ON (NOCOMPTE IS NOT NULL AND NOCOMPTE::bigint = t_compte.code_original) OR (NOCOMPTE IS NULL  AND NOCOMPTES::bigint = t_compte.code_original::bigint)
                    JOIN W_KPRAT KPRAT ON KACTES.NOPRAT = KPRAT.NOPRAT AND KPRAT.CODETAB = 3
					JOIN activite.t_divers ON t_divers.code = 'MEDSAL_COMPTACLI' AND valeur = 1
				WHERE 
					'[ENV_TYPEETS]' NOT IN ('2','3') AND
					FACPARTIEL != 9 AND 
					KACTES.TYPERUB = 4
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,15,16;
			
                
				-- Rubriques internes cti
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('w_FAC_FACTURE_LIGNE_C');

				-- lignes clinique
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_8');

				INSERT INTO activite[PX].p_factures_lignes_c(
					no_facture, 
					date_debut, 
					date_fin, 
					nb_rubrique, 
					nb_prestation, 
					coefficient, 
					coefficient_mco, 
					rubrique_facture_id,
					rubrique_facturation_id, 
					rubrique_comptabilisation_id, 
					compte_produit_id, 
					prestation_id, 
					montant_facture, 
					montant_facture_0, 
					montant_facture_1, 
					montant_facture_2, 
					montant_facture_22, 
					taux_0, 
					taux_1, 
					taux_2, 
					taux_22, 
					prix_unitaire, 
					lieu_id, 
					
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2,
					montant_comptabilise_22, 
					
					montant_encours, 
					montant_encours_0, 
					montant_encours_1, 
					montant_encours_2, 
					montant_encours_22,

					origine_facturation_id,
					montant_facture_actes_inclus_dans_sejour, 
					montant_facture_0_actes_inclus_dans_sejour, 
					montant_facture_1_actes_inclus_dans_sejour, 
					montant_facture_2_actes_inclus_dans_sejour, 
					montant_facture_22_actes_inclus_dans_sejour)

				SELECT 
					no_facture, 
					date_debut, 
					date_fin, 
					nb_rubrique, 
					nb_prestations, 
					coefficient, 
					coefficient_mco, 
					rubrique_facture_id,
					rubrique_facturation_id, 
					rubrique_comptabilisation_id, 
					compte_produit_id, 
					prestation_id, 
					montant_facture, 
					montant_facture_0, 
					montant_facture_1, 
					montant_facture_2, 
					montant_facture_22, 
					taux_0, 
					taux_1, 
					taux_2, 
					taux_22, 
					prix_unitaire, 
					lieu_sortie_id, 
					
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2,
					montant_comptabilise_22, 
					
					0, 
					0, 
					0, 
					0, 
					0,

					origine_facturation_id,
					montant_facture_actes_inclus_dans_sejour, 
					montant_facture_0_actes_inclus_dans_sejour, 
					montant_facture_1_actes_inclus_dans_sejour, 
					montant_facture_2_actes_inclus_dans_sejour, 
					montant_facture_22_actes_inclus_dans_sejour

				FROM w_FAC_FACTURE_LIGNE_C;
				
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_8');

				
				

				UPDATE activite[PX].p_factures_lignes_c
				SET nb_prestation = coefficient * nb_prestation,
					nb_rubrique = coefficient * nb_prestation,
					coefficient = 1
				WHERE coefficient > 1 AND
					prestation_id IN (SELECT oid FROM activite.t_prestations WHERE code IN ('PJ', 'PJ1', 'PJ2', 'FJ', 'PHJ', 'SSM', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO'));
					
				
				-- Eclatement des supplements par jour
				DROP TABLE IF EXISTS w_factures_lignes_sup_c;

				CREATE TEMP TABLE w_factures_lignes_sup_c AS
				SELECT
					p_factures_lignes_c.CTID AS from_CTID, 
					t_prestations.code AS prestation_code,
					CASE WHEN p_sejours.type_sejour <> '5' THEN date(p_sejours.date_entree) ELSE p_factures_lignes_c.date_debut END AS date_debut_ghs,
					CASE WHEN p_sejours.type_sejour <> '5' THEN date(p_sejours.date_sortie - interval '1 day') ELSE p_factures_lignes_c.date_fin END AS date_fin_ghs,
					(date(date_sortie) - date(date_entree)) * CASE WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation_ghs,
					CASE WHEN type_sejour = '5' THEN p_factures_lignes_c.date_debut WHEN t_prestations.code = 'GHS' THEN date(date_entree + interval '1 day') ELSE date(p_factures_lignes_c.date_debut + interval '1 day') END AS date_debut_det,
					CASE WHEN type_sejour = '5' THEN p_factures_lignes_c.date_fin WHEN t_prestations.code = 'GHS' THEN date(p_sejours.date_sortie - interval '1 day') ELSE date(p_factures_lignes_c.date_debut + ((ABS(nb_prestation)-1) || ' day')::interval)  END AS date_fin_det,
					ABS(CASE WHEN type_sejour <> '5' AND t_prestations.code = 'GHS' THEN date(date_sortie) - date(date_entree) ELSE nb_prestation END) AS nb_det,
					p_factures_lignes_c.*
				FROM activite[PX].p_factures_lignes_c
					JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND code IN ('PJ', 'PJ1', 'PJ2', 'FJ', 'SSM', 'GHS', 'EXH', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO') 
				WHERE (nb_prestation > 1 or nb_prestation < -1 OR (type_sejour <> '5' AND t_prestations.code = 'GHS' AND date(date_sortie) - date(date_entree) > 1)) ;

				
				UPDATE w_factures_lignes_sup_c SET 
					date_fin_ghs = date(date_debut_exh - interval '1 day'),
					date_fin_det = date(date_debut_exh - interval '1 day'),
					nb_prestation_ghs = date(date_debut_exh - interval '1 day') - date_debut_ghs + 1,
					nb_det = date(date_debut_exh - interval '1 day') - date_debut_ghs + 1
				FROM (
					SELECT no_facture, date(MIN(date_debut)) AS date_debut_exh
					FROM activite[PX].p_factures_lignes_c
						JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND code = 'EXH'
					GROUP BY 1) subview
				WHERE w_factures_lignes_sup_c.no_facture = subview.no_facture;
				
				CREATE INDEX w_factures_lignes_sup_c_i1
				  ON w_factures_lignes_sup_c
				  USING btree
				  (date_debut);

				DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup;

				CREATE TEMP TABLE w_factures_lignes_sup_c_sup AS
				SELECT
					from_CTID,
					no_facture,
					date AS date_debut,
					date AS date_fin,
					CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_rubrique,
					CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id, 
					prestation_id,
					round(montant_facture / ABS(nb_det),2) AS montant_facture,
					round(montant_facture_0 / ABS(nb_det),2) AS montant_facture_0,
					round(montant_facture_1 / ABS(nb_det),2) AS montant_facture_1,
					round(montant_facture_2 / ABS(nb_det),2) AS montant_facture_2,
					round(montant_facture_22 / ABS(nb_det),2) AS montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					finess,
					prix_unitaire,
					lieu_id,
					round(montant_comptabilise / ABS(nb_det),2) AS montant_comptabilise,
					round(montant_comptabilise_0 / ABS(nb_det),2) AS montant_comptabilise_0,
					round(montant_comptabilise_1 / ABS(nb_det),2) AS montant_comptabilise_1,
					round(montant_comptabilise_2 / ABS(nb_det),2) AS montant_comptabilise_2,
					round(montant_comptabilise_22 / ABS(nb_det),2) AS montant_comptabilise_22,
					round(montant_encours / ABS(nb_det),2) AS montant_encours,
					round(montant_encours_0 / ABS(nb_det),2) AS montant_encours_0,
					round(montant_encours_1 / ABS(nb_det),2) AS montant_encours_1,
					round(montant_encours_2 / ABS(nb_det),2) AS montant_encours_2,
					round(montant_encours_22 / ABS(nb_det),2) AS montant_encours_22,
					round(montant_facture_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_actes_inclus_dans_sejour,
					round(montant_facture_0_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_0_actes_inclus_dans_sejour,
					round(montant_facture_1_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_1_actes_inclus_dans_sejour,
					round(montant_facture_2_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_2_actes_inclus_dans_sejour,
					round(montant_facture_22_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_22_actes_inclus_dans_sejour,
					origine_facturation_id,
					round(montant_comptabilise_budget_global_1 / ABS(nb_det),2) AS montant_comptabilise_budget_global_1,
					facture_id
				FROM w_factures_lignes_sup_c
					JOIN base.p_calendrier ON p_calendrier.date BETWEEN date_debut_det AND date_fin_det 
				;

				DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup_tot;

				CREATE TEMP TABLE w_factures_lignes_sup_c_sup_tot AS

				SELECT from_CTID,
					SUM(nb_rubrique) AS nb_rubrique,
					SUM(nb_prestation) AS nb_prestation,
					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,
					SUM(montant_facture_actes_inclus_dans_sejour) AS montant_facture_actes_inclus_dans_sejour,
					SUM(montant_facture_0_actes_inclus_dans_sejour) AS montant_facture_0_actes_inclus_dans_sejour,
					SUM(montant_facture_1_actes_inclus_dans_sejour) AS montant_facture_1_actes_inclus_dans_sejour,
					SUM(montant_facture_2_actes_inclus_dans_sejour) AS montant_facture_2_actes_inclus_dans_sejour,
					SUM(montant_facture_22_actes_inclus_dans_sejour) AS montant_facture_22_actes_inclus_dans_sejour,
					SUM(montant_comptabilise_budget_global_1) AS montant_comptabilise_budget_global_1
				FROM w_factures_lignes_sup_c_sup
				GROUP BY 1;


				UPDATE activite[PX].p_factures_lignes_c
				SET
					date_fin = p_factures_lignes_c.date_debut,
					nb_rubrique = p_factures_lignes_c.nb_rubrique - w_factures_lignes_sup_c_sup_tot.nb_rubrique,
					nb_prestation = p_factures_lignes_c.nb_prestation - w_factures_lignes_sup_c_sup_tot.nb_prestation,
					montant_facture = p_factures_lignes_c.montant_facture - w_factures_lignes_sup_c_sup_tot.montant_facture,
					montant_facture_0 = p_factures_lignes_c.montant_facture_0 - w_factures_lignes_sup_c_sup_tot.montant_facture_0,
					montant_facture_1 = p_factures_lignes_c.montant_facture_1 - w_factures_lignes_sup_c_sup_tot.montant_facture_1,
					montant_facture_2 = p_factures_lignes_c.montant_facture_2 - w_factures_lignes_sup_c_sup_tot.montant_facture_2,
					montant_facture_22 = p_factures_lignes_c.montant_facture_22 - w_factures_lignes_sup_c_sup_tot.montant_facture_22,
					montant_comptabilise = p_factures_lignes_c.montant_comptabilise - w_factures_lignes_sup_c_sup_tot.montant_comptabilise,
					montant_comptabilise_0 = p_factures_lignes_c.montant_comptabilise_0 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_0,
					montant_comptabilise_1 = p_factures_lignes_c.montant_comptabilise_1 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_1,
					montant_comptabilise_2 = p_factures_lignes_c.montant_comptabilise_2 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_2,
					montant_comptabilise_22 = p_factures_lignes_c.montant_comptabilise_22 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_22,
					montant_encours = p_factures_lignes_c.montant_encours - w_factures_lignes_sup_c_sup_tot.montant_encours,
					montant_encours_0 = p_factures_lignes_c.montant_encours_0 - w_factures_lignes_sup_c_sup_tot.montant_encours_0,
					montant_encours_1 = p_factures_lignes_c.montant_encours_1 - w_factures_lignes_sup_c_sup_tot.montant_encours_1,
					montant_encours_2 = p_factures_lignes_c.montant_encours_2 - w_factures_lignes_sup_c_sup_tot.montant_encours_2,
					montant_encours_22 = p_factures_lignes_c.montant_encours_22 - w_factures_lignes_sup_c_sup_tot.montant_encours_22,
					montant_facture_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_0_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_1_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_2_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_22_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_22_actes_inclus_dans_sejour,
					montant_comptabilise_budget_global_1 = p_factures_lignes_c.montant_comptabilise_budget_global_1 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_budget_global_1
				FROM w_factures_lignes_sup_c_sup_tot
				WHERE p_factures_lignes_c.CTID = from_CTID;
				
				-- Rubriques internes cti
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('w_factures_lignes_sup_c_sup');

				INSERT INTO activite[PX].p_factures_lignes_c(
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					finess,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour,
					origine_facturation_id,
					montant_comptabilise_budget_global_1,
					facture_id)
				SELECT 
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					finess,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour,
					origine_facturation_id,
					montant_comptabilise_budget_global_1,
					facture_id
				FROM w_factures_lignes_sup_c_sup;

	
				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[PX].p_mouvements_sejour
                JOIN activite[PX].t_lieux ON lieu_id = t_lieux.oid
                JOIN activite[PX].t_services_facturation On service_facturation_id = t_services_facturation.oid
                GROUP BY 1,2
                ;

                UPDATE activite[PX].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[PX].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_debut = 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)
                ;

                
		

				DROP TABLE IF EXISTS w_actes_inclus_dans_sejour;
				CREATE TEMP TABLE w_actes_inclus_dans_sejour AS
				SELECT NOFAC AS no_facture, 
					SUM(montant_facture_actes_inclus_dans_sejour) AS montant_facture_actes_inclus_dans_sejour,
					SUM(montant_facture_0_actes_inclus_dans_sejour) AS montant_facture_0_actes_inclus_dans_sejour,
					SUM(montant_facture_1_actes_inclus_dans_sejour) AS montant_facture_1_actes_inclus_dans_sejour,
					SUM(montant_facture_2_actes_inclus_dans_sejour) AS montant_facture_2_actes_inclus_dans_sejour,
					SUM(montant_facture_22_actes_inclus_dans_sejour) AS montant_facture_22_actes_inclus_dans_sejour
				FROM activite[PX].p_factures_lignes_c JOIN w_FAC_FACTURE ON no_facture = NOFAC
				WHERE 
					'[ENV_TYPEETS]' IN ('2','3') AND
					montant_facture_actes_inclus_dans_sejour <> 0 AND 
					origine_facturation_id = 3
				GROUP BY 1;

				DROP TABLE IF EXISTS w_ghs_pj;
				CREATE TEMP TABLE w_ghs_pj AS
				SELECT p_factures_lignes_c.no_facture, 
					p_sejours.no_sejour,
					p_sejours.est_budget_global,
					MIN(p_factures_lignes_c.ctid) AS ctid_min
				FROM activite[PX].p_factures_lignes_c 
					JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				WHERE 
					'[ENV_TYPEETS]' IN ('2','3') AND
					origine_facturation_id = 1 AND 
					(
						prestation_id IN (SELECT oid FROM activite.t_prestations where code IN ('PJ', 'PJ1', 'PJ2', 'GHS', 'AMP5')) OR
						rubrique_facturation_id IN (SELECT oid FROM activite[PX].t_rubriques_facturation where actes_inclus_public = '1')
					)
				GROUP BY 1,2,3;

				

				UPDATE activite[PX].p_factures_lignes_c
				SET 
					montant_facture_actes_inclus_dans_sejour = 0 - w_actes_inclus_dans_sejour.montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour = 0 - w_actes_inclus_dans_sejour.montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour = 0 - w_actes_inclus_dans_sejour.montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour = 0 - w_actes_inclus_dans_sejour.montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour = 0 - w_actes_inclus_dans_sejour.montant_facture_22_actes_inclus_dans_sejour
				FROM w_actes_inclus_dans_sejour, w_ghs_pj
				WHERE 
					'[ENV_TYPEETS]' IN ('2','3') AND
					p_factures_lignes_c.no_facture = w_ghs_pj.no_facture AND p_factures_lignes_c.ctid = w_ghs_pj.ctid_min AND
					w_actes_inclus_dans_sejour.no_facture = p_factures_lignes_c.no_facture AND 
					(
						prestation_id IN (SELECT oid FROM activite.t_prestations where code IN ('PJ', 'GHS', 'AMP5')) OR
						rubrique_facturation_id IN (SELECT oid FROM activite[PX].t_rubriques_facturation where actes_inclus_public = '1')
					);

	

				DROP TABLE IF EXISTS w_actes_inclus_dans_sejour_t;
				CREATE TEMP TABLE w_actes_inclus_dans_sejour_t AS
				SELECT no_facture, 
					SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_actes_inclus_dans_sejour ELSE 0 END) AS montant_facture_c_actes_inclus_dans_sejour,
					SUM(CASE WHEN origine_facturation_id = 3 THEN montant_facture_actes_inclus_dans_sejour ELSE 0 END) AS montant_facture_h_actes_inclus_dans_sejour
				FROM activite[PX].p_factures_lignes_c 
				WHERE 
					'[ENV_TYPEETS]' IN ('2','3') AND
					montant_facture_actes_inclus_dans_sejour <> 0 
				GROUP BY 1;


				UPDATE activite[PX].p_factures SET 
					montant_facture_c_actes_inclus_dans_sejour = w_actes_inclus_dans_sejour_t.montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour = w_actes_inclus_dans_sejour_t.montant_facture_h_actes_inclus_dans_sejour
				FROM w_actes_inclus_dans_sejour_t
				WHERE 
					'[ENV_TYPEETS]' IN ('2','3') AND
					w_actes_inclus_dans_sejour_t.no_facture = p_factures.no_facture;

	
	
				-- Montants depuis PMSI
				
				--UPDATE pmsi.p_rss 
				--SET no_sejour_administratif = 
                 --   CASE WHEN p_rss.date_sortie = RSSSORT
				--	THEN KRSS.NODOSSIER ELSE no_sejour_administratif END
				--FROM prod_mederi.KRSS 
				--JOIN w_DOSSIER ON w_DOSSIER.NODOSSIER = KRSS.NODOSSIER
				--WHERE p_rss.no_rss = KRSS.NODOSSIER AND ghm_id <> 0;
	

				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_compte CASCADE;	
				DROP TABLE IF EXISTS w_factures_lignes_sup_c CASCADE;	
				DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup_tot CASCADE;	
				DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup CASCADE;	
				DROP TABLE IF EXISTS w_actes_inclus_dans_sejour CASCADE;		
				DROP TABLE IF EXISTS w_ghs_pj CASCADE;		
				DROP TABLE IF EXISTS w_actes_inclus_dans_sejour_t CASCADE;		
				DROP TABLE IF EXISTS w_factures_ventes_bg CASCADE;		
				DROP TABLE IF EXISTS w_factures_lignes_bg CASCADE;	
				
			]]></sqlcmd>
		</NODE>	
	
		<NODE label="Compte client Clinique">
			<sqlcmd><![CDATA[
			
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_8');

				INSERT INTO activite[PX].p_factures_soldes_c(
					no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22
				)
				SELECT
					no_facture,
					date_vente,
					rubrique_comptabilisation_id,
					prestation_id,
					SUM(montant_comptabilise),
					SUM(montant_comptabilise_0),
					SUM(montant_comptabilise_1),
					SUM(montant_comptabilise_2),
					SUM(montant_comptabilise_22),
					0,
					0,
					0,
					0,
					0
				FROM w_FAC_FACTURE_LIGNE_C
				WHERE date_vente IS NOT NULL  AND
					(montant_comptabilise <> 0 OR 
					montant_comptabilise_0 <> 0 OR 
					montant_comptabilise_1 <> 0 OR 
					montant_comptabilise_2 <> 0 OR 
					montant_comptabilise_22 <> 0 
					)
				GROUP BY 1,2,3,4;
	
	
	
				-- Comptes clients (REG)

				DROP TABLE IF EXISTS w_FAC_REGLEMENT_LIGNE_C;
				CREATE TEMP TABLE w_FAC_REGLEMENT_LIGNE_C AS
				SELECT 
					KACTES.NOFAC AS no_facture, 
					date(KRGLDET.DATE) AS date_reglement,

					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,
		 
					SUM(KRGLDET.MONTANT) AS montant_regle,
					SUM(CASE WHEN KREGL.DEBITEUR = 3 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_0,
					SUM(CASE WHEN KREGL.DEBITEUR = 1 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_1,
					SUM(CASE WHEN KREGL.DEBITEUR = 2 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_2,
					0 AS montant_regle_22
				FROM w_KRGLDET KRGLDET
                    JOIN w_KREGL KREGL ON KRGLDET.NOREGL = KREGL.NOREGL
                    JOIN prod_mederi.KACTES ON KACTES.ACCLEUNIK = KRGLDET.ACCLEUNIK 
                    LEFT JOIN prod_mederi.KRUBINT ON KACTES.NOACTE = KRUBINT.NOACTE 
					LEFT JOIN activite[PX].t_rubriques_facturation ON (KRUBINT.NOACTE = t_rubriques_facturation.code_original)
					LEFT JOIN activite.t_prestations ON NOACTESS = t_prestations.code
				WHERE 1=1
                    AND NOT ((KREGL.ORIGINE = 13  AND KREGL.DEBITEUR = 1) OR (KREGL.ORIGINE = 1  AND KREGL.DEBITEUR = 3))
                    AND KACTES.TYPERUB <> 4
                    AND KACTES.NOFAC IS NOT NULL
                GROUP BY 1,2,3,4;
				
				-- Règlements sans affectation
				INSERT INTO w_FAC_REGLEMENT_LIGNE_C
				SELECT 
					subview.no_facture AS no_facture, 
					date(KREGL.DATE) AS date_reglement,

					0::bigint AS rubrique_comptabilisation_id,
					0::bigint AS prestation_id,
		 
					SUM(KREGL.MONTANT) AS montant_regle,
					SUM(CASE WHEN KREGL.DEBITEUR = 3 THEN KREGL.MONTANT ELSE 0 END) AS montant_regle_0,
					SUM(CASE WHEN KREGL.DEBITEUR = 1 THEN KREGL.MONTANT ELSE 0 END) AS montant_regle_1,
					SUM(CASE WHEN KREGL.DEBITEUR = 2 THEN KREGL.MONTANT ELSE 0 END) AS montant_regle_2,
					0 AS montant_regle_22
				FROM w_KREGL KREGL
				JOIN 
					(
					SELECT no_sejour, (MAX(ARRAY[date_facture::text, no_facture]))[2] AS no_facture
					FROM activite[PX].p_factures
					GROUP BY 1
					) subview
					ON subview.no_sejour = NODOSSIER
				WHERE 1=1 AND
					KREGL.DEBITEUR = '3' AND
					NUMREGLD = '0' AND
					ignore = '0' AND
					forcehon = '0'
                GROUP BY 1,2,3,4
				;
                
                
                -- Médecins salariés
                
                INSERT INTO w_FAC_REGLEMENT_LIGNE_C
                SELECT 
                    KACTES.NOFAC AS no_facture, 
                    date(KRGLDET.DATE) AS date_reglement,

                    COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
                    COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,
         
                    SUM(KRGLDET.MONTANT) AS montant_regle,
                    SUM(CASE WHEN KREGL.DEBITEUR = 3 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_0,
                    SUM(CASE WHEN KREGL.DEBITEUR = 1 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_1,
                    SUM(CASE WHEN KREGL.DEBITEUR = 2 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_2,
                    0 AS montant_regle_22
                FROM w_KRGLDET KRGLDET
                    JOIN w_KREGL KREGL ON KRGLDET.NOREGL = KREGL.NOREGL
                    JOIN prod_mederi.KACTES ON KACTES.ACCLEUNIK = KRGLDET.ACCLEUNIK 
                    LEFT JOIN prod_mederi.KRUBINT ON KACTES.NOACTE = KRUBINT.NOACTE 
                    LEFT JOIN activite[PX].t_rubriques_facturation ON (KRUBINT.NOACTE = t_rubriques_facturation.code_original)
                    LEFT JOIN activite.t_prestations ON NOACTESS = t_prestations.code
                    JOIN W_KPRAT KPRAT ON KACTES.NOPRAT = KPRAT.NOPRAT AND CODETAB = 3
                    JOIN activite.t_divers ON t_divers.code = 'MEDSAL_COMPTACLI' AND valeur = 1
                WHERE 1=1
                    AND NOT ((KREGL.ORIGINE = 13  AND KREGL.DEBITEUR = 1) OR (KREGL.ORIGINE = 1  AND KREGL.DEBITEUR = 3))
                    AND KACTES.TYPERUB <> 4
                GROUP BY 1,2,3,4;
                
                -- Règlements 
            
                -- Acomptes 85%
                INSERT INTO w_FAC_REGLEMENT_LIGNE_C
                SELECT 
                    KACTES.NOFAC AS no_facture, 
                    date(KRGLDET.DATE) AS date_reglement,

                    COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
                    COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,
         
                    SUM(KRGLDET.MONTANT) AS montant_regle,
                    SUM(CASE WHEN KREGL.DEBITEUR = 3 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_0,
                    SUM(CASE WHEN KREGL.DEBITEUR = 1 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_1,
                    SUM(CASE WHEN KREGL.DEBITEUR = 2 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_2,
                    0 AS montant_regle_22
                    
                FROM w_KRGLDET KRGLDET
                    JOIN w_KREGL KREGL ON KRGLDET.NOREGL = KREGL.NOREGL
                    JOIN prod_mederi.KACTES ON KACTES.ACCLEUNIK = KRGLDET.ACCLEUNIK 
                    LEFT JOIN activite[PX].t_rubriques_facturation ON (t_rubriques_facturation.code_original = '*CTI_ACO85')
                    LEFT JOIN activite.t_prestations ON (t_prestations.code_original = '*CTI_ACO85')
                WHERE 1=1
                    AND KREGL.ORIGINE = 13
                    AND KREGL.DEBITEUR = 1
                    AND KACTES.TYPERUB <> 4
                    --AND JOUR_TYPEMVT <> 'FACAV'

                GROUP BY 1,2,3,4
                ;
                
                -- Acomptes 
                INSERT INTO w_FAC_REGLEMENT_LIGNE_C
                SELECT 
                    KACTES.NOFAC AS no_facture, 
                    date(KRGLDET.DATE) AS date_reglement,

                    COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
                    COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,
         
                    SUM(KRGLDET.MONTANT) AS montant_regle,
                    SUM(CASE WHEN KREGL.DEBITEUR = 3 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_0,
                    SUM(CASE WHEN KREGL.DEBITEUR = 1 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_1,
                    SUM(CASE WHEN KREGL.DEBITEUR = 2 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_2,
                    0 AS montant_regle_22

                FROM w_KRGLDET KRGLDET
                    JOIN w_KREGL KREGL ON KRGLDET.NOREGL = KREGL.NOREGL
                    JOIN prod_mederi.KACTES ON KACTES.ACCLEUNIK = KRGLDET.ACCLEUNIK 
                    LEFT JOIN activite[PX].t_rubriques_facturation ON (t_rubriques_facturation.code_original = '*CTI_ACO')
                    LEFT JOIN activite.t_prestations ON (t_prestations.code_original = '*CTI_ACO')
                WHERE 1=1
                    AND KREGL.ORIGINE = 1
                    AND KREGL.DEBITEUR = 3
                    AND KACTES.TYPERUB <> 4

                GROUP BY 1,2,3,4
                ;
                
                --correction par rapport aux règlement non affectés
                -- verrouillé pour l'instant par ELA
                 
                DROP TABLE IF EXISTS w_FAC_CORR;
                CREATE TEMP TABLE w_FAC_CORR AS
                SELECT NOREGL, DATE, MONTANT, SENS,DEBITEUR, KREGL.NODOSSIER, w_FAC_FACTURE.NOFAC, MNTPASS,MNTPAM,MNTPMUT,MNTHASS,MNTHAM,MNTHMUT,SLDPASS,SLDPAM,SLDPMUT,SLDHASS,SLDHAM,SLDHMUT,  
                    COALESCE(t_rubriques_facturation.oid::bigint,0) AS rubrique_comptabilisation_id,
                    COALESCE(t_prestations.oid::bigint,0) AS prestation_id
                FROM w_KREGL KREGL, prod_mederi.KDOSSIER, w_FAC_FACTURE
                    LEFT JOIN activite[PX].t_rubriques_facturation ON (t_rubriques_facturation.code_original = '*MED_REG_DOS')
                    LEFT JOIN activite.t_prestations ON (t_prestations.code_original = '*MED_REG_DOS')
                WHERE  NUMREGLD = 0 AND KREGL.DATECOMPTA IS NOT NULL            
                    AND KDOSSIER.NODOSSIER = KREGL.NODOSSIER
                    AND KDOSSIER.NODOSSIER = w_FAC_FACTURE.NODOSSIER 
                    AND w_FAC_FACTURE.NOFAC IS NOT NULL
                    AND FACAVOIR IS NULL AND
                    1 <> 1;
        
                CREATE INDEX  w_fac_corr_i1
                  ON  w_fac_corr
                  USING btree
                  (NOFAC);
                  
                ANALYSE w_FAC_CORR;
    
                -- insertion de règlements dossier sans détail sur les factures et leurs lignes
                        
                DROP TABLE IF EXISTS w_FAC_REG_SEJ;
                CREATE TEMP TABLE w_FAC_REG_SEJ as 
                SELECT 
                    NOREGL,
                    MAX(DEBITEUR) AS DEBITEUR,
                    MAX(NOFAC) AS NOFAC, 
                    MAX(DATE) AS date_reglement,
                   
                    MAX(rubrique_comptabilisation_id) AS rubrique_comptabilisation_id,
                    prestation_id AS prestation_id,
                  
                    CASE WHEN MAX(SENS) IS DISTINCT FROM '-'  THEN MAX(MONTANT) ELSE - MAX(MONTANT)  END AS montant_regle ,
                    CASE WHEN MAX(DEBITEUR) = 3 THEN CASE WHEN MAX(SENS) IS DISTINCT FROM '-' THEN MAX(MONTANT) ELSE - MAX(MONTANT) END ELSE 0 END AS montant_regle_0,
                    CASE WHEN MAX(DEBITEUR) = 1 THEN CASE WHEN MAX(SENS) IS DISTINCT FROM '-' THEN MAX(MONTANT) ELSE - MAX(MONTANT) END ELSE 0 END AS montant_regle_1,
                    CASE WHEN MAX(DEBITEUR) = 2 THEN CASE WHEN MAX(SENS) IS DISTINCT FROM '-' THEN MAX(MONTANT) ELSE - MAX(MONTANT) END ELSE 0 END AS montant_regle_2,
                    0 as montant_regle_22
                FROM 
                (SELECT 
                    NOREGL,
                    MONTANT,
                    w_FAC_CORR.NOFAC, 
                    date(w_FAC_CORR.DATE) AS DATE,
                    w_FAC_CORR.rubrique_comptabilisation_id,
                    w_FAC_CORR.prestation_id,
                    SENS,
                    DEBITEUR
--                  ,
--                  CASE
--                      WHEN MONTANT = MNTPASS THEN montant_facture_0
--                      WHEN MONTANT = MNTPAM THEN montant_facture_1
--                      WHEN MONTANT = MNTPMUT THEN montant_facture_2
--                      WHEN MONTANT = SLDPASS THEN  montant_facture_0
--                      WHEN MONTANT = SLDPAM THEN  montant_facture_1
--                      WHEN MONTANT = SLDPMUT THEN  montant_facture_2
--                      WHEN MONTANT = MNTHASS + MNTPASS THEN montant_facture_0
--                      WHEN MONTANT = MNTHAM + MNTPAM THEN montant_facture_1
--                      WHEN MONTANT = MNTHMUT + MNTPMUT THEN montant_facture_2 
--                      WHEN MONTANT = SLDHASS + SLDPASS THEN montant_facture_0
--                      WHEN MONTANT = SLDHAM + SLDPAM THEN montant_facture_1
--                      WHEN MONTANT = SLDHMUT + SLDPMUT THEN montant_facture_2
--                      WHEN MONTANT = MNTHASS THEN 0
--                      WHEN MONTANT = MNTHAM THEN 0
--                      WHEN MONTANT = MNTHMUT THEN 0
--                      WHEN MONTANT = SLDHASS THEN 0
--                      WHEN MONTANT = SLDHAM THEN 0
--                      WHEN MONTANT = SLDHMUT THEN 0
--                      ELSE 0 END as MONTANT_CALC
                FROM w_FAC_CORR
                --,w_FAC_FACTURE_LIGNE_C
                WHERE --w_FAC_CORR.NOFAC = w_FAC_FACTURE_LIGNE_C.no_facture
                    --AND 
                    (((MONTANT = MNTPASS  OR MONTANT = MNTPAM OR MONTANT = MNTPMUT
                        OR MONTANT = MNTHASS  OR MONTANT = MNTHAM OR MONTANT = MNTHMUT
                       OR MONTANT = MNTHASS + MNTPASS  OR MONTANT = MNTHAM+MNTPAM OR MONTANT = MNTHMUT+MNTPMUT))
                     --  AND w_FAC_CORR.NOFAC NOT IN (SELECT no_facture FROM w_FAC_REGLEMENT_LIGNE_C))
                    --   OR 
                    --   ((MONTANT = SLDPASS  OR MONTANT = SLDPAM OR MONTANT = SLDPMUT
                    --   OR MONTANT = SLDHASS  OR MONTANT = SLDHAM OR MONTANT = SLDHMUT
                  --     OR MONTANT = SLDHASS + SLDPASS  OR MONTANT = SLDHAM+SLDPAM OR MONTANT = SLDHMUT+SLDPMUT)
                      --)
                      )) as sub 
                     -- WHERE MONTANT_CALC = MONTANT
                GROUP BY NOREGL,prestation_id;
                
                INSERT INTO w_FAC_REGLEMENT_LIGNE_C
                SELECT 
                    NOFAC, 
                    date_reglement,
                   
                    rubrique_comptabilisation_id,
                    prestation_id,
                  
                    montant_regle ,
                    montant_regle_0,
                    montant_regle_1,
                    montant_regle_2,
                    0 as montant_regle_22
                FROM w_FAC_REG_SEJ
                WHERE montant_regle != 0;
                
                INSERT INTO w_FAC_REGLEMENT_LIGNE_C
                SELECT 
                    MAX(w_FAC_CORR.NOFAC) AS NOFAC, 
                    MAX(DATE) AS date_reglement,
                   
                    MAX(rubrique_comptabilisation_id) AS rubrique_comptabilisation_id,
                    MAX(prestation_id) AS prestation_id,
                  
                    CASE WHEN MAX(SENS) IS DISTINCT FROM '-'  THEN MAX(MONTANT) ELSE - MAX(MONTANT)  END AS montant_regle ,
                    CASE WHEN MAX(DEBITEUR) = 3 THEN CASE WHEN MAX(SENS) IS DISTINCT FROM '-'  THEN MAX(MONTANT) ELSE - MAX(MONTANT) END ELSE 0 END AS montant_regle_0,
                    CASE WHEN MAX(DEBITEUR) = 1 THEN CASE WHEN MAX(SENS) IS DISTINCT FROM '-'  THEN MAX(MONTANT) ELSE - MAX(MONTANT) END ELSE 0 END AS montant_regle_1,
                    CASE WHEN MAX(DEBITEUR) = 2 THEN CASE WHEN MAX(SENS) IS DISTINCT FROM '-'  THEN MAX(MONTANT) ELSE - MAX(MONTANT) END ELSE 0 END AS montant_regle_2,
                    0 as montant_regle_22
                FROM w_FAC_CORR
                WHERE NOREGL NOT IN (SELECT NOREGL FROM w_FAC_REG_SEJ)
                GROUP BY NOREGL;
                
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_1');
                
                UPDATE activite[PX].p_factures_soldes_c
                SET 
                    montant_regle = w_FAC_REGLEMENT_LIGNE_C.montant_regle,
                    montant_regle_0 = w_FAC_REGLEMENT_LIGNE_C.montant_regle_0,
                    montant_regle_1 = w_FAC_REGLEMENT_LIGNE_C.montant_regle_1,
                    montant_regle_2 = w_FAC_REGLEMENT_LIGNE_C.montant_regle_2,
                    montant_regle_22 = w_FAC_REGLEMENT_LIGNE_C.montant_regle_22
                FROM w_FAC_REGLEMENT_LIGNE_C
                WHERE p_factures_soldes_c.no_facture = w_FAC_REGLEMENT_LIGNE_C.no_facture AND 
                    p_factures_soldes_c.date_comptable = w_FAC_REGLEMENT_LIGNE_C.date_reglement AND 
                    p_factures_soldes_c.rubrique_comptabilisee_id = w_FAC_REGLEMENT_LIGNE_C.rubrique_comptabilisation_id AND 
                    p_factures_soldes_c.prestation_id = w_FAC_REGLEMENT_LIGNE_C.prestation_id;


                INSERT INTO activite[PX].p_factures_soldes_c(
                        no_facture, 
                        date_comptable, 
                        rubrique_comptabilisee_id, 
                        prestation_id, 
                        montant_comptabilise, 
                        montant_comptabilise_0, 
                        montant_comptabilise_1, 
                        montant_comptabilise_2, 
                        montant_comptabilise_22, 
                        montant_regle, 
                        montant_regle_0, 
                        montant_regle_1, 
                        montant_regle_2, 
                        montant_regle_22
                    )
                SELECT
                    w_FAC_REGLEMENT_LIGNE_C.no_facture,
                    w_FAC_REGLEMENT_LIGNE_C.date_reglement,
                    w_FAC_REGLEMENT_LIGNE_C.rubrique_comptabilisation_id,
                    w_FAC_REGLEMENT_LIGNE_C.prestation_id,
                    0,
                    0,
                    0,
                    0,
                    0,
                    w_FAC_REGLEMENT_LIGNE_C.montant_regle,
                    w_FAC_REGLEMENT_LIGNE_C.montant_regle_0,
                    w_FAC_REGLEMENT_LIGNE_C.montant_regle_1,
                    w_FAC_REGLEMENT_LIGNE_C.montant_regle_2,
                    w_FAC_REGLEMENT_LIGNE_C.montant_regle_22
                FROM w_FAC_REGLEMENT_LIGNE_C 
                    LEFT JOIN activite[PX].p_factures_soldes_c 
                    ON (p_factures_soldes_c.no_facture = w_FAC_REGLEMENT_LIGNE_C.no_facture
                        AND p_factures_soldes_c.date_comptable = w_FAC_REGLEMENT_LIGNE_C.date_reglement
                        AND p_factures_soldes_c.rubrique_comptabilisee_id = w_FAC_REGLEMENT_LIGNE_C.rubrique_comptabilisation_id
                        AND p_factures_soldes_c.prestation_id = w_FAC_REGLEMENT_LIGNE_C.prestation_id)
                WHERE date_reglement IS NOT NULL AND p_factures_soldes_c.no_facture IS NULL;
                
                
    
                -- Annulations par avoirs

                
                INSERT INTO activite[PX].p_factures_soldes_c(
                    no_facture, 
                    date_comptable, 
                    rubrique_comptabilisee_id, 
                    prestation_id, 
                    montant_comptabilise, 
                    montant_comptabilise_0, 
                    montant_comptabilise_1, 
                    montant_comptabilise_2, 
                    montant_comptabilise_22, 
                    montant_regle, 
                    montant_regle_0, 
                    montant_regle_1, 
                    montant_regle_2, 
                    montant_regle_22, 
                    od_avoir)
                SELECT 
                    p_factures_soldes_c.no_facture, 
                    date_od_avoir,
                    rubrique_comptabilisee_id, 
                    prestation_id, 
                    0,
                    0,
                    0,
                    0,
                    0,
                    p_factures_soldes_c.montant_comptabilise, 
                    p_factures_soldes_c.montant_comptabilise_0, 
                    p_factures_soldes_c.montant_comptabilise_1, 
                    p_factures_soldes_c.montant_comptabilise_2, 
                    p_factures_soldes_c.montant_comptabilise_22,
                    '1'
                FROM activite[PX].p_factures_soldes_c JOIN w_ods_avoir ON p_factures_soldes_c.no_facture = w_ods_avoir.no_facture
                WHERE p_factures_soldes_c.montant_comptabilise <> 0;
    

                INSERT INTO activite[PX].p_factures_soldes_c(
                    no_facture, 
                    date_comptable, 
                    rubrique_comptabilisee_id, 
                    prestation_id, 
                    montant_comptabilise, 
                    montant_comptabilise_0, 
                    montant_comptabilise_1, 
                    montant_comptabilise_2, 
                    montant_comptabilise_22, 
                    montant_regle, 
                    montant_regle_0, 
                    montant_regle_1, 
                    montant_regle_2, 
                    montant_regle_22, 
                    od_avoir)
                SELECT 
                    p_factures_soldes_c.no_facture, 
                    date_od_avoir,
                    rubrique_comptabilisee_id, 
                    prestation_id, 
                    0,
                    0,
                    0,
                    0,
                    0,
                    p_factures_soldes_c.montant_comptabilise, 
                    p_factures_soldes_c.montant_comptabilise_0, 
                    p_factures_soldes_c.montant_comptabilise_1, 
                    p_factures_soldes_c.montant_comptabilise_2, 
                    p_factures_soldes_c.montant_comptabilise_22,
                    '1'
                FROM activite[PX].p_factures_soldes_c JOIN w_ods_avoir ON p_factures_soldes_c.no_facture = w_ods_avoir.no_facture_od_avoir
                WHERE p_factures_soldes_c.montant_comptabilise <> 0;
                
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_2');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_3');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_4');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_8');
                

                -- Suppression des tables de travail non utilisées après
                DROP TABLE IF EXISTS w_FAC_FACTURE_LIGNE_C CASCADE; 
                DROP TABLE IF EXISTS w_FAC_REGLEMENT_LIGNE_C CASCADE;   
    
                -- maj soldes 
                UPDATE activite[PX].p_factures
                SET 
                    montant_regle_c = sub.montant_regle_c,
                    montant_regle_0_c = sub.montant_regle_0_c,
                    montant_regle_1_c = sub.montant_regle_1_c,
                    montant_regle_2_c = sub.montant_regle_2_c
                FROM (
                    SELECT 
                        no_facture,
                        SUM(reg_c.montant_regle) AS montant_regle_c,
                        SUM(reg_c.montant_regle_0) AS montant_regle_0_c,
                        SUM(reg_c.montant_regle_1) AS montant_regle_1_c,
                        SUM(reg_c.montant_regle_2) AS montant_regle_2_c
                    FROM activite[PX].p_factures_soldes_c reg_c
                    GROUP BY 1) as sub
                WHERE sub.no_facture = p_factures.no_facture;                       
                                        
            ]]></sqlcmd>
        </NODE>
    
        <NODE label="Lignes non facturées Honoraires">
            <sqlcmd><![CDATA[

                TRUNCATE activite[PX].p_factures_lignes_non_facturees_h;
                
                INSERT INTO activite[PX].p_factures_lignes_non_facturees_h(
                    no_facture, 
                    date_debut, 
                    date_fin, 
                    heure_debut, 
                    nb_rubrique, 
                    coefficient, 
                    medecin_facture_id, 
                    prestation_id, 
                    prix_unitaire, 
                    montant_depassement, 
                    lieu_id, 
                    acte_id, 
                    phase_ccam, 
                    activite_ccam, 
                    extension_ccam, 
                    modificateur_ccam_1, 
                    modificateur_ccam_2,
                    modificateur_ccam_3, 
                    modificateur_ccam_4)
                SELECT
                    p_factures.no_facture,
                    DATEACTE AS date_debut,
                    date_sortie AS date_fin,
                    replace(HDEBUT,':','')::int,
                    1 AS nb_rubrique,
                    QTE::int *KACTES.COEFF AS coefficient,
                    t_medecins_administratifs.oid AS medecin_facture_id,
                    t_prestations.oid AS prestation_id,
                    PRIXU::numeric AS prix_unitaire,
                    MDASS + MDCAI + MDMUT AS montant_depassement, 
                    p_sejours.lieu_sortie_id AS lieu_id,
                    COALESCE(t_actes.oid::bigint, 0) AS acte_id,
                    COALESCE(PHASE,'0') AS phase_ccam,
                    COALESCE(ACTIVITE,'0') AS activite_ccam,
                    '' AS extension_ccam, 
                    substr(MODIFICAT,1,1) AS modificateur_ccam_1, 
                    substr(MODIFICAT,2,1) AS modificateur_ccam_2,
                    substr(MODIFICAT,3,1) AS modificateur_ccam_3, 
                    substr(MODIFICAT,4,1) AS modificateur_ccam_4
                    
                FROM prod_mederi.KACTES 
                    LEFT JOIN w_KFACTURE KFACTURE ON KACTES.NOFAC = KFACTURE.NOFAC AND TYPEFAC IN (3,4)
                    JOIN activite[PX].p_sejours ON KACTES.NODOSSIER = p_sejours.code_original AND p_sejours.etat = ''
                    JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND type_facture = 'E'
                    JOIN activite[PX].t_medecins_administratifs ON NOPRAT = t_medecins_administratifs.code_original
                    JOIN activite.t_prestations ON NOACTE = t_prestations.code
                    JOIN base.t_actes ON (substring(NCCAM, 1, 7) = t_actes.code)
                WHERE TYPERUB = 4 AND KFACTURE.est_doublon = '0'

                ORDER BY p_sejours.no_sejour;
                                        
                                        
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Lignes factures Honoraires">
            <sqlcmd><![CDATA[

            
                DROP TABLE IF EXISTS W_KPRAT
                ;
                
                CREATE TEMP TABLE W_KPRAT AS
                SELECT * 
                FROM  prod_mederi.KPRAT
                WHERE CTID IN (
                            SELECT MAX(CTID)
                            from prod_mederi.KPRAT
                            GROUP BY NOPRAT
                        )
                ;
                
                INSERT INTO base.t_actes(
                    code, texte, texte_court, nomenclature, ccam_regroupement_id_1, ccam_regroupement_id_4, 
                    geste_marqueur_id)
                SELECT 
                    substring(NCCAM, 1, 7), 
                    substring(NCCAM, 1, 7), 
                    substring(NCCAM, 1, 7), 
                    MIN(CASE WHEN length(trim(NCCAM)) >= 7 THEN 'CCAM' ELSE 'NGAP' END),
                    MIN(CASE WHEN length(trim(NCCAM)) >= 7 THEN 0 ELSE t_ccam_regroupements.oid END),
                    MIN(CASE WHEN length(trim(NCCAM)) >= 7 THEN 0 ELSE t_ccam_regroupements.oid END),
                    0
                FROM w_FAC_FACTURE, prod_mederi.KACTES
                LEFT JOIN base.t_actes ON (trim(substring(NCCAM, 1, 7)) = trim(t_actes.code)), base.t_ccam_regroupements
                WHERE 
                    w_FAC_FACTURE.NOFAC = KACTES.NOFAC
                    AND TYPERUB = 4 AND t_actes.oid is  NULL
                    AND t_ccam_regroupements.code = 'NGAP'
                    AND NCCAM IS NOT NULL
                GROUP BY 1,2,3;



                DROP TABLE IF EXISTS w_FAC_FACTURE_LIGNE_H;
                
                CREATE TEMP TABLE w_FAC_FACTURE_LIGNE_H AS
                SELECT 
                    ACCLEUNIK,
                    KACTES.NOFAC AS no_facture, 
                    DATEACTE AS date_debut, 
                    COALESCE(DATEFIN,DATEACTE) AS date_fin, 
                    CASE WHEN FACPARTIEL != 9 AND DATEFAC IS NOT NULL THEN DATEFAC ELSE '20991231'::date END AS date_vente,
                    lieu_sortie_id,
                    CASE WHEN TYPEFAC NOT IN ('2','4') THEN QTE ELSE 0-QTE END AS nb_rubrique,
                    CASE WHEN TYPEFAC NOT IN ('2','4') THEN QTE ELSE 0-QTE END AS nb_prestations,
                    KACTES.COEFF as coefficient, 
                    1 AS coefficient_mco,
                    COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_facturation_id, 
                    COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
                    COALESCE(t_prestations.oid::bigint, 0) AS prestation_id, 
                    COALESCE(t_medecins_administratifs.oid::bigint, 0) AS medecin_facture_id,  
                    COALESCE(t_medecins_administratifs.oid::bigint, 0) AS medecin_comptabilise_id,  
                    PRIXU::numeric AS prix_unitaire,

                    COALESCE(t_actes.oid::bigint, 0) AS acte_id,
                    replace(HDEBUT,':','')::int AS heure_debut,
                    PHASE::int AS phase_ccam,
                    ACTIVITE::integer AS activite_ccam,
                    '' AS extension_ccam,
                    substr(MODIFICAT,1,1) AS modificateur_ccam_1, 
                    substr(MODIFICAT,2,1) AS modificateur_ccam_2,
                    substr(MODIFICAT,3,1) AS modificateur_ccam_3, 
                    substr(MODIFICAT,4,1) AS modificateur_ccam_4,
                
                    SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTASS + MNTMUT + MNTSS ELSE - (MNTASS + MNTMUT + MNTSS) END) AS montant_facture,
                    SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTASS ELSE - MNTASS END) AS montant_facture_0,
                    SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTSS ELSE - MNTSS END) AS montant_facture_1,
                    SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTMUT ELSE - MNTMUT END) AS montant_facture_2,
                    0  as montant_facture_22,
                    
                    SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MDCAI + MDMUT + MDASS ELSE - (MDCAI + MDMUT + MDASS) END) as montant_depassement,

                    0 AS montant_facture_actes_inclus_dans_sejour,
                    0 as montant_facture_0_actes_inclus_dans_sejour,
                    0 as montant_facture_1_actes_inclus_dans_sejour,
                    0 as montant_facture_2_actes_inclus_dans_sejour,
                    0 as montant_facture_22_actes_inclus_dans_sejour,
                    
                    AVG(1-TAUXSS-TAUXMUT) as taux_0,
                    AVG(TAUXSS) as taux_1,
                    AVG(TAUXMUT) as taux_2,
                    0 as taux_22,
    
                    SUM(CASE WHEN DATEFAC IS NOT NULL AND NOT (CODETAB = 3 AND valeur = 1) THEN CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTASS + MNTMUT + MNTSS ELSE - (MNTASS + MNTMUT + MNTSS) END ELSE 0 END) AS montant_comptabilise,
                    SUM(CASE WHEN DATEFAC IS NOT NULL AND NOT (CODETAB = 3 AND valeur = 1) THEN CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTASS ELSE - MNTASS END ELSE 0 END) AS montant_comptabilise_0,
                    SUM(CASE WHEN DATEFAC IS NOT NULL AND NOT (CODETAB = 3 AND valeur = 1) THEN CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTSS ELSE - MNTSS END ELSE 0 END) AS montant_comptabilise_1,
                    SUM(CASE WHEN DATEFAC IS NOT NULL AND NOT (CODETAB = 3 AND valeur = 1) THEN CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTMUT ELSE - MNTMUT END ELSE 0 END) AS montant_comptabilise_2,
                    0  as montant_comptabilise_22
                    
                FROM prod_mederi.KACTES
                    LEFT JOIN  w_FAC_FACTURE ON w_FAC_FACTURE.NOFAC = KACTES.NOFAC
                    LEFT JOIN activite[PX].t_rubriques_facturation ON (KACTES.NOACTE = t_rubriques_facturation.code_original)
                    LEFT JOIN prod_mederi.KRUBINT ON (KACTES.NOACTE = KRUBINT.NOACTE)
                    LEFT JOIN activite.t_prestations ON (NOACTESS = t_prestations.code)
                    LEFT JOIN activite[PX].t_medecins_administratifs ON (NOPRAT = t_medecins_administratifs.code_original)
                    LEFT JOIN base.t_actes ON (CASE WHEN NCCAM IS NULL THEN KACTES.NOACTE ELSE substring(NCCAM, 1, 7) END = t_actes.code)
                    LEFT JOIN W_KPRAT KPRAT ON KACTES.NOPRAT = KPRAT.NOPRAT
                    LEFT JOIN activite.t_divers ON t_divers.code = 'MEDSAL_COMPTACLI' AND valeur = 1
                WHERE 1=1
                    AND TYPEFAC NOT IN (3,4)
                    AND KACTES.TYPERUB = 4
                
                GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25;
        
                -- modificationd es factures avec règlements sans détail (trop percus )

         
     
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_1');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_2');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_3');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_4');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_5');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_6');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_7');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_8');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_9');

                INSERT INTO activite[PX].p_factures_lignes_h(
                    no_facture, 
                    date_debut, 
                    date_fin, 
                    nb_rubrique, 
                    nb_prestation, 
                    coefficient, 
                    coefficient_mco, 
                    medecin_facture_id, 
                    medecin_comptabilise_id, 
                    prestation_id, 
                    montant_facture, 
                    montant_facture_0, 
                    montant_facture_1, 
                    montant_facture_2, 
                    montant_facture_22, 
                    montant_depassement,
                    taux_0, 
                    taux_1, 
                    taux_2, 
                    taux_22, 
                    prix_unitaire, 
                    lieu_id, 
                    
                    montant_comptabilise, 
                    montant_comptabilise_0, 
                    montant_comptabilise_1, 
                    montant_comptabilise_2,
                    montant_comptabilise_22, 
                    
                    montant_encours, 
                    montant_encours_0, 
                    montant_encours_1, 
                    montant_encours_2, 
                    montant_encours_22,

                    montant_facture_actes_inclus_dans_sejour, 
                    montant_facture_0_actes_inclus_dans_sejour, 
                    montant_facture_1_actes_inclus_dans_sejour, 
                    montant_facture_2_actes_inclus_dans_sejour, 
                    montant_facture_22_actes_inclus_dans_sejour,

                    acte_id
                    )

                SELECT 
                    no_facture, 
                    date_debut, 
                    date_fin, 
                    nb_rubrique, 
                    nb_prestations, 
                    coefficient, 
                    coefficient_mco, 
                    medecin_facture_id, 
                    medecin_comptabilise_id, 
                    prestation_id, 
                    montant_facture, 
                    montant_facture_0, 
                    montant_facture_1, 
                    montant_facture_2, 
                    montant_facture_22, 
                    montant_depassement,
                    taux_0, 
                    taux_1, 
                    taux_2, 
                    taux_22, 
                    prix_unitaire, 
                    lieu_sortie_id, 
                    
                    montant_comptabilise, 
                    montant_comptabilise_0, 
                    montant_comptabilise_1, 
                    montant_comptabilise_2,
                    montant_comptabilise_22, 
                    
                    0, 
                    0, 
                    0, 
                    0, 
                    0,

                    montant_facture_actes_inclus_dans_sejour, 
                    montant_facture_0_actes_inclus_dans_sejour, 
                    montant_facture_1_actes_inclus_dans_sejour, 
                    montant_facture_2_actes_inclus_dans_sejour, 
                    montant_facture_22_actes_inclus_dans_sejour,

                    acte_id

                FROM w_FAC_FACTURE_LIGNE_H;

    
                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[PX].p_mouvements_sejour
                JOIN activite[PX].t_lieux ON lieu_id = t_lieux.oid
                JOIN activite[PX].t_services_facturation On service_facturation_id = t_services_facturation.oid
                GROUP BY 1,2;


                UPDATE activite[PX].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[PX].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_debut = 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);


                
                    
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_1');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_2');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_3');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_4');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_5');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_6');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_7');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_8');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_9');
                
                    
                -- Suppression des tables de travail non utilisées après
                        
                    
                                        
                                        
            ]]></sqlcmd>
        </NODE>
    
        <NODE label="Compte client Honoraires">
            <sqlcmd><![CDATA[
            
                DROP TABLE IF EXISTS W_KPRAT
                ;
                
                CREATE TEMP TABLE W_KPRAT AS
                SELECT * 
                FROM  prod_mederi.KPRAT
                WHERE CTID IN (
                            SELECT MAX(CTID)
                            from prod_mederi.KPRAT
                            GROUP BY NOPRAT
                        )
                ;
                
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_1');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_3');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_4');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_8');

                INSERT INTO activite[PX].p_factures_soldes_h(
                    no_facture, 
                    date_comptable, 
                    medecin_comptabilise_id, 
                    montant_comptabilise, 
                    montant_comptabilise_0, 
                    montant_comptabilise_1, 
                    montant_comptabilise_2, 
                    montant_comptabilise_22, 
                    montant_regle, 
                    montant_regle_0, 
                    montant_regle_1, 
                    montant_regle_2, 
                    montant_regle_22
                )
                SELECT
                    no_facture,
                    date_vente,
                    medecin_comptabilise_id,
                    SUM(montant_comptabilise),
                    SUM(montant_comptabilise_0),
                    SUM(montant_comptabilise_1),
                    SUM(montant_comptabilise_2),
                    SUM(montant_comptabilise_22),
                    0,
                    0,
                    0,
                    0,
                    0
                FROM w_FAC_FACTURE_LIGNE_H
                WHERE date_vente IS NOT NULL AND
                    (montant_comptabilise <> 0 OR 
                    montant_comptabilise_0 <> 0 OR 
                    montant_comptabilise_1 <> 0 OR 
                    montant_comptabilise_2 <> 0 OR 
                    montant_comptabilise_22 <> 0 
                    )
                    AND w_FAC_FACTURE_LIGNE_H.no_facture IS NOT NULL
                GROUP BY 1,2,3;
                
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_1');

                DROP TABLE IF EXISTS w_FAC_REGLEMENT_LIGNE_H;   
                CREATE TEMP TABLE w_FAC_REGLEMENT_LIGNE_H AS
                SELECT 
                    KACTES.NOFAC AS no_facture, 
                    KRGLDET.DATE AS date_reglement,

                    COALESCE(t_medecins_administratifs.oid::bigint, 0) AS medecin_comptabilise_id,  
         
                    SUM(KRGLDET.MONTANT) AS montant_regle,
                    SUM(CASE WHEN KREGL.DEBITEUR = 3 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_0,
                    SUM(CASE WHEN KREGL.DEBITEUR = 1 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_1,
                    SUM(CASE WHEN KREGL.DEBITEUR = 2 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_2,
                    0 AS montant_regle_22

                FROM w_KRGLDET KRGLDET
                    JOIN w_KREGL KREGL ON KRGLDET.NOREGL = KREGL.NOREGL
                    JOIN prod_mederi.KACTES ON KACTES.ACCLEUNIK = KRGLDET.ACCLEUNIK 
                    JOIN activite[PX].p_sejours ON KACTES.NODOSSIER = p_sejours.no_sejour
                    LEFT JOIN activite[PX].t_medecins_administratifs ON (KACTES.NOPRAT = t_medecins_administratifs.code_original)
                    LEFT JOIN activite.t_divers ON t_divers.code = 'MEDSAL_COMPTACLI'
                    JOIN W_KPRAT KPRAT ON KACTES.NOPRAT = KPRAT.NOPRAT AND (valeur != 1 OR CODETAB != 3)
                WHERE 1=1
                    AND NOT ((KREGL.ORIGINE = 13  AND KREGL.DEBITEUR = 1) OR (KREGL.ORIGINE = 1  AND KREGL.DEBITEUR = 3))
                    AND TYPERUB = 4
                GROUP BY 1,2,3;
				
				-- Règlements sans affectation
				INSERT INTO w_FAC_REGLEMENT_LIGNE_H
				SELECT 
					subview.no_facture AS no_facture, 
					date(KREGL.DATE) AS date_reglement,

					0::bigint AS  medecin_comptabilise_id,
		 
					SUM(KREGL.MONTANT) AS montant_regle,
					SUM(CASE WHEN KREGL.DEBITEUR = 3 THEN KREGL.MONTANT ELSE 0 END) AS montant_regle_0,
					SUM(CASE WHEN KREGL.DEBITEUR = 1 THEN KREGL.MONTANT ELSE 0 END) AS montant_regle_1,
					SUM(CASE WHEN KREGL.DEBITEUR = 2 THEN KREGL.MONTANT ELSE 0 END) AS montant_regle_2,
					0 AS montant_regle_22
				FROM w_KREGL KREGL
				JOIN 
					(
					SELECT no_sejour, (MAX(ARRAY[date_facture::text, no_facture]))[2] AS no_facture
					FROM activite[PX].p_factures
					GROUP BY 1
					) subview
					ON subview.no_sejour = NODOSSIER
				WHERE 1=1 AND
					KREGL.DEBITEUR = '3' AND
					NUMREGLD = '0' AND
					ignore = '0' AND
					forcehon = '1'
                GROUP BY 1,2,3
				;
                
                -- Acomptes
                INSERT INTO w_FAC_REGLEMENT_LIGNE_H
                SELECT 
                    KACTES.NOFAC AS no_facture, 
                    KRGLDET.DATE AS date_reglement,

                    0 AS medecin_comptabilise_id,  
         
                    SUM(KRGLDET.MONTANT) AS montant_regle,
                    SUM(CASE WHEN KREGL.DEBITEUR = 3 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_0,
                    SUM(CASE WHEN KREGL.DEBITEUR = 1 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_1,
                    SUM(CASE WHEN KREGL.DEBITEUR = 2 THEN KRGLDET.MONTANT ELSE 0 END) AS montant_regle_2,
                    0 AS montant_regle_22

                FROM w_KRGLDET KRGLDET
                    JOIN w_KREGL KREGL ON KRGLDET.NOREGL = KREGL.NOREGL
                    JOIN prod_mederi.KACTES ON KACTES.ACCLEUNIK = KRGLDET.ACCLEUNIK 
                    JOIN activite[PX].p_sejours ON KACTES.NODOSSIER = p_sejours.no_sejour
                    LEFT JOIN activite[PX].t_medecins_administratifs ON (KACTES.NOPRAT = t_medecins_administratifs.code_original)
                    LEFT JOIN activite.t_divers ON t_divers.code = 'MEDSAL_COMPTACLI'
                    JOIN W_KPRAT KPRAT ON KACTES.NOPRAT = KPRAT.NOPRAT AND (valeur != 1 OR CODETAB != 3)
                WHERE 1=1
                    AND ((KREGL.ORIGINE = 13  AND KREGL.DEBITEUR = 1) OR (KREGL.ORIGINE = 1  AND KREGL.DEBITEUR = 3))
                    AND TYPERUB = 4

                GROUP BY 1,2,3
                ;
                

                UPDATE w_FAC_REG_SEJ
                SET
                    montant_regle  = 0,
                    montant_regle_0 = 0,
                    montant_regle_1 = 0,
                    montant_regle_2 = 0
                    ;
                
                UPDATE w_FAC_REG_SEJ
                SET
                    montant_regle  = CASE WHEN SENS IS DISTINCT FROM '-'  THEN MONTANT ELSE - MONTANT END,
                    montant_regle_0 = CASE WHEN sub.DEBITEUR = 3 THEN CASE WHEN SENS IS DISTINCT FROM '-'  THEN MONTANT ELSE - MONTANT END ELSE 0 END,
                    montant_regle_1 = CASE WHEN sub.DEBITEUR = 1 THEN CASE WHEN SENS IS DISTINCT FROM '-'  THEN MONTANT ELSE - MONTANT END ELSE 0 END,
                    montant_regle_2 = CASE WHEN sub.DEBITEUR = 2 THEN CASE WHEN SENS IS DISTINCT FROM '-'  THEN MONTANT ELSE - MONTANT END ELSE 0 END
                FROM 
                (SELECT 
                    NOREGL,
                    w_FAC_CORR.NOFAC, 
                    date(w_FAC_CORR.DATE) AS DATE,
                    SENS,
                    DEBITEUR,
                    CASE
                        WHEN MONTANT = MNTHASS THEN montant_facture_0
                        WHEN MONTANT = MNTHAM THEN montant_facture_1
                        WHEN MONTANT = MNTHMUT THEN montant_facture_2
                        WHEN MONTANT = SLDHASS THEN  montant_facture_0
                        WHEN MONTANT = SLDHAM THEN  montant_facture_1
                        WHEN MONTANT = SLDHMUT THEN  montant_facture_2
                        WHEN MONTANT = MNTHASS + MNTPASS THEN montant_facture_0
                        WHEN MONTANT = MNTHAM + MNTPAM THEN montant_facture_1
                        WHEN MONTANT = MNTHMUT + MNTPMUT THEN montant_facture_2 
                        WHEN MONTANT = SLDHASS + SLDPASS THEN montant_facture_0
                        WHEN MONTANT = SLDHAM + SLDPAM THEN montant_facture_1
                        WHEN MONTANT = SLDHMUT + SLDPMUT THEN montant_facture_2
                        WHEN MONTANT = MNTPASS THEN 0
                        WHEN MONTANT = MNTPAM THEN 0
                        WHEN MONTANT = MNTPMUT THEN 0
                        WHEN MONTANT = SLDPASS THEN 0
                        WHEN MONTANT = SLDPAM THEN 0
                        WHEN MONTANT = SLDPMUT THEN 0
                        ELSE 0 END as MONTANT
                FROM w_FAC_CORR ,w_FAC_FACTURE_LIGNE_H
                WHERE w_FAC_CORR.NOFAC = w_FAC_FACTURE_LIGNE_H.no_facture
                AND (((MONTANT = MNTPASS  OR MONTANT = MNTPAM OR MONTANT = MNTPMUT
                        OR MONTANT = MNTHASS  OR MONTANT = MNTHAM OR MONTANT = MNTHMUT
                       OR MONTANT = MNTHASS + MNTPASS  OR MONTANT = MNTHAM+MNTPAM OR MONTANT = MNTHMUT+MNTPMUT)
                       AND w_FAC_CORR.NOFAC NOT IN (SELECT no_facture FROM w_FAC_REGLEMENT_LIGNE_H))
                       OR 
                       ((MONTANT = SLDPASS  OR MONTANT = SLDPAM OR MONTANT = SLDPMUT
                       OR MONTANT = SLDHASS  OR MONTANT = SLDHAM OR MONTANT = SLDHMUT
                       OR MONTANT = SLDHASS + SLDPASS  OR MONTANT = SLDHAM+SLDPAM OR MONTANT = SLDHMUT+SLDPMUT)
                      ))
                    ) as sub 
                WHERE sub.NOFAC = w_FAC_REG_SEJ.NOFAC 
                    AND sub.DEBITEUR = w_FAC_REG_SEJ.DEBITEUR
                    AND sub.DATE = w_FAC_REG_SEJ.date_reglement
                ;
                
                INSERT INTO w_FAC_REGLEMENT_LIGNE_H
                SELECT 
                    NOFAC, 
                    date_reglement,
                   
                    0 as medecin_comptabilise_id,
                  
                    montant_regle ,
                    montant_regle_0,
                    montant_regle_1,
                    montant_regle_2,
                    0 as montant_regle_22
                FROM w_FAC_REG_SEJ
                WHERE montant_regle != 0;
				
				DELETE FROM w_FAC_REGLEMENT_LIGNE_H
				WHERE w_FAC_REGLEMENT_LIGNE_H.no_facture NOT IN (SELECT p_factures.no_facture FROM activite[PX].p_factures)
				;
                
    
                -- Comptes clients (REG)

                UPDATE activite[PX].p_factures_soldes_h
                SET 
                montant_regle = w_FAC_REGLEMENT_LIGNE_H.montant_regle,
                montant_regle_0 = w_FAC_REGLEMENT_LIGNE_H.montant_regle_0,
                montant_regle_1 = w_FAC_REGLEMENT_LIGNE_H.montant_regle_1,
                montant_regle_2 = w_FAC_REGLEMENT_LIGNE_H.montant_regle_2,
                montant_regle_22 = w_FAC_REGLEMENT_LIGNE_H.montant_regle_22
                FROM w_FAC_REGLEMENT_LIGNE_H
                WHERE p_factures_soldes_h.no_facture = w_FAC_REGLEMENT_LIGNE_H.no_facture
                    AND p_factures_soldes_h.date_comptable = w_FAC_REGLEMENT_LIGNE_H.date_reglement
                    AND p_factures_soldes_h.medecin_comptabilise_id = w_FAC_REGLEMENT_LIGNE_H.medecin_comptabilise_id;  
    

                INSERT INTO activite[PX].p_factures_soldes_h(
                        no_facture, 
                        date_comptable, 
                        medecin_comptabilise_id, 
                        montant_comptabilise, 
                        montant_comptabilise_0, 
                        montant_comptabilise_1, 
                        montant_comptabilise_2, 
                        montant_comptabilise_22, 
                        montant_regle, 
                        montant_regle_0, 
                        montant_regle_1, 
                        montant_regle_2, 
                        montant_regle_22
                    )
                SELECT
                    w_FAC_REGLEMENT_LIGNE_H.no_facture,
                    w_FAC_REGLEMENT_LIGNE_H.date_reglement,
                    w_FAC_REGLEMENT_LIGNE_H.medecin_comptabilise_id,
                    0,
                    0,
                    0,
                    0,
                    0,
                    w_FAC_REGLEMENT_LIGNE_H.montant_regle,
                    w_FAC_REGLEMENT_LIGNE_H.montant_regle_0,
                    w_FAC_REGLEMENT_LIGNE_H.montant_regle_1,
                    w_FAC_REGLEMENT_LIGNE_H.montant_regle_2,
                    w_FAC_REGLEMENT_LIGNE_H.montant_regle_22
                FROM w_FAC_REGLEMENT_LIGNE_H 
                    LEFT JOIN activite[PX].p_factures_soldes_h 
                    ON (p_factures_soldes_h.no_facture = w_FAC_REGLEMENT_LIGNE_H.no_facture
                        AND p_factures_soldes_h.date_comptable = w_FAC_REGLEMENT_LIGNE_H.date_reglement
                        AND p_factures_soldes_h.medecin_comptabilise_id = w_FAC_REGLEMENT_LIGNE_H.medecin_comptabilise_id)
                WHERE TRUE
                AND date_reglement IS NOT NULL 
                AND p_factures_soldes_h.no_facture IS NULL
                AND w_FAC_REGLEMENT_LIGNE_H.no_facture IS NOT NULL;
                
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_3');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_4');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_8');
                
                -- Suppression des tables de travail non utilisées après
                DROP TABLE IF EXISTS w_FAC_REGLEMENT_LIGNE_H CASCADE;       
                DROP TABLE IF EXISTS w_FAC_FACTURE_LIGNE_H CASCADE; 
                                        
                -- maj soldes 
                UPDATE activite[PX].p_factures
                SET 
                    montant_regle_h = sub.montant_regle_h,
                    montant_regle_0_h = sub.montant_regle_0_h,
                    montant_regle_1_h = sub.montant_regle_1_h,
                    montant_regle_2_h = sub.montant_regle_2_h
                FROM (
                    SELECT 
                        no_facture,
                        SUM(reg_h.montant_regle) AS montant_regle_h,
                        SUM(reg_h.montant_regle_0) AS montant_regle_0_h,
                        SUM(reg_h.montant_regle_1) AS montant_regle_1_h,
                        SUM(reg_h.montant_regle_2) AS montant_regle_2_h
                    FROM activite[PX].p_factures_soldes_h reg_h
                    GROUP BY 1) as sub
                WHERE sub.no_facture = p_factures.no_facture;
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Post traitement entetes">
            <sqlcmd><![CDATA[
                -- médecins salariés
                UPDATE activite[PX].p_factures
                SET
                    montant_comptabilise_c = sub.montant_comptabilise_c,
                    montant_comptabilise_0_c = sub.montant_comptabilise_0_c,
                    montant_comptabilise_1_c = sub.montant_comptabilise_1_c,
                    montant_comptabilise_2_c = sub.montant_comptabilise_2_c,
                    montant_comptabilise_22_c = sub.montant_comptabilise_22_c
                FROM (
                SELECT 
                    no_facture,
                    SUM(COALESCE(montant_comptabilise,0)) AS montant_comptabilise_c,  
                    SUM(COALESCE(montant_comptabilise_0)) AS montant_comptabilise_0_c,  
                    SUM(COALESCE(montant_comptabilise_1,0)) AS montant_comptabilise_1_c,  
                    SUM(COALESCE(montant_comptabilise_2,0)) AS montant_comptabilise_2_c,  
                    SUM(COALESCE(montant_comptabilise_22,0)) AS montant_comptabilise_22_c
                FROM activite[PX].p_factures_lignes_c
                    GROUP BY 1
                ) as sub
                WHERE p_factures.no_facture = sub.no_facture;
                
                UPDATE activite[PX].p_factures
                SET
                    montant_comptabilise_h = sub.montant_comptabilise_h,
                    montant_comptabilise_0_h = sub.montant_comptabilise_0_h,
                    montant_comptabilise_1_h = sub.montant_comptabilise_1_h,
                    montant_comptabilise_2_h = sub.montant_comptabilise_2_h,
                    montant_comptabilise_22_h = sub.montant_comptabilise_22_h
                FROM (
                SELECT 
                    no_facture,
                    SUM(COALESCE(montant_comptabilise,0)) AS montant_comptabilise_h,  
                    SUM(COALESCE(montant_comptabilise_0)) AS montant_comptabilise_0_h,  
                    SUM(COALESCE(montant_comptabilise_1,0)) AS montant_comptabilise_1_h,  
                    SUM(COALESCE(montant_comptabilise_2,0)) AS montant_comptabilise_2_h,  
                    SUM(COALESCE(montant_comptabilise_22,0)) AS montant_comptabilise_22_h
                FROM activite[PX].p_factures_lignes_h
                    GROUP BY 1
                ) as sub
                WHERE p_factures.no_facture = sub.no_facture;
            
            
                -- Préfactures inutiles

                DELETE FROM activite[PX].p_factures 
                WHERE type_facture = 'P' AND
                    coalesce(montant_facture_c,0) = 0 AND
                    coalesce(montant_facture_h,0) = 0 AND 
                    coalesce(montant_comptabilise_c,0) = 0 AND 
                    coalesce(montant_comptabilise_h,0) = 0 AND 
                    coalesce(montant_regle_c,0) = 0 AND
                    coalesce(montant_regle_h,0) = 0 AND
                    no_facture NOT IN (SELECT no_facture FROM activite[PX].p_factures_soldes_c) AND
                    no_facture NOT IN (SELECT no_facture FROM activite[PX].p_factures_soldes_h)
;

                -- Facture reference
                
                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 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(CASE WHEN type_facture <> '1' AND type_facture <> 'X' AND type_facture <> 'P' AND 
                        (t_prestations.code IN ('GHS','PJ') OR (p_factures.no_facture LIKE '%BG' AND p_sejours.type_sejour IN ('1','2','5'))) THEN p_factures.no_facture ELSE null END) 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[PX].p_factures
                    JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                    JOIN activite[PX].t_lieux ON p_sejours.lieu_sortie_id = t_lieux.oid
                    JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
                    LEFT JOIN activite[PX].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','PJ')
                GROUP BY 1,2;
                
                CREATE INDEX w_sejours_facture_reference_i1
                      ON w_sejours_facture_reference
                      USING btree
                      (no_sejour);

                UPDATE activite[PX].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[PX].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[PX].p_factures
                SET type_facture = '0' 
                WHERE p_factures.type_facture = '2' AND
                    p_factures.no_facture = p_factures.no_facture_reference;
                
                UPDATE activite[PX].p_factures
                SET type_facture = '2' 
                WHERE p_factures.type_facture = '0' AND
                    p_factures.no_facture <> p_factures.no_facture_reference;
                    
                
                    
                    
                -- Suppression des tables de travail non utilisées après
                DROP TABLE IF EXISTS w_sejours_facture_reference CASCADE;   
                            
            ]]></sqlcmd>
        </NODE>

    </NODE>
    
    <NODE name="CHIFFRIER" label="CREATION DU CHIFFRIER">
        
        <NODE label="Récupération chiffrier">
            <sqlcmd><![CDATA[

                TRUNCATE activite[PX].p_chiffrier_comptable;

                INSERT INTO activite[PX].p_chiffrier_comptable(
                    date_comptable,
                    montant_ventes_c, 
                    montant_reglements_c, 
                    montant_solde_client_c, 
                    montant_ventes_h, 
                    montant_reglements_h, 
                    montant_solde_client_h
                )
               SELECT date_comptable,
                    SUM(montant_ventes_c) AS montant_ventes_c,
                    SUM(montant_reglements_c) AS montant_reglements_c,
                    SUM(montant_solde_client_c) AS montant_solde_client_c,
                    SUM(montant_ventes_h) AS montant_ventes_h,
                    SUM(montant_reglements_h) AS montant_reglements_h,
                    SUM(montant_solde_client_h) AS monatnt_solde_client_h
                FROM (
                    SELECT 
                        date_trunc('month',DATEFAC) AS date_comptable,
                        SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTPREST ELSE 0 -MNTPREST END) AS montant_ventes_c,
                        0 AS montant_reglements_c,
                        SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN SLDPASS + SLDPMUT + SLDPAM ELSE 0 - (SLDPASS + SLDPMUT + SLDPAM) END) AS montant_solde_client_c,
                        SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTHONO ELSE 0 -MNTHONO END) AS montant_ventes_h,
                        0 AS montant_reglements_h,
                        SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN SLDHASS + SLDHMUT + SLDHAM  ELSE 0 - (SLDHASS + SLDHMUT + SLDHAM ) END)  AS montant_solde_client_h
                    FROM w_KFACTURE KFACTURE
                    WHERE DATEFAC >=  '[ENV_ADM_ANNEEDEBUT]0101' AND 
                        NOFAC IS NOT NULL
                    GROUP BY 1
                    UNION ALL
                    SELECT 
                        date_trunc('month',DATE) AS date_comptable,
                        0 AS montant_vente_c,
                        SUM(CASE WHEN NOPRAT IS NULL THEN KRGLDET.MONTANT ELSE 0 END) AS montant_reglements_c,
                        0 AS montant_solde_c,
                        0 AS montant_vente_h,
                        SUM(CASE WHEN NOPRAT IS NOT NULL THEN KRGLDET.MONTANT ELSE 0 END) AS montant_reglements_h,
                        0 AS montant_solde_h
                    FROM w_KRGLDET KRGLDET 
                    WHERE DATE > '[ENV_ADM_ANNEEDEBUT]0101'
                    AND KRGLDET.NOFAC IS NOT NULL
                    GROUP BY 1
                    ORDER BY 1)  AS sub 
                GROUP BY 1;

                TRUNCATE activite[PX].p_factures_comptables;
                
                INSERT INTO activite[PX].p_factures_comptables (
                    no_facture,
                    date_comptable,
                    montant_ventes_c, 
                    montant_ventes_h,
                    montant_reglements_c,
                    montant_reglements_h
                )
                SELECT no_facture,
                    date_comptable,
                    SUM(montant_ventes_c) AS montant_ventes_c,
                    SUM(montant_ventes_h) AS montant_ventes_h,
                    SUM(montant_reglements_c) AS montant_reglements_c,
                    SUM(montant_reglements_h) AS montant_reglements_h
                FROM (
                    SELECT 
                        COALESCE(NOFAC,'000000000') AS no_facture,
                        DATEFAC AS date_comptable,
                        SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTPREST ELSE 0 -MNTPREST END) AS montant_ventes_c,
                        SUM(CASE WHEN TYPEFAC NOT IN ('2','4') THEN MNTHONO ELSE 0 -MNTHONO END) AS montant_ventes_h,
                        0::numeric AS montant_reglements_c,
                        0::numeric AS montant_reglements_h
                    FROM w_KFACTURE KFACTURE
                    WHERE DATEFAC >= '[ENV_ADM_ANNEEDEBUT]0101' AND
						NOFAC IS NOT NULL
                    GROUP BY 1,2
                    HAVING 
                        SUM(MNTPREST) <> 0 OR SUM(MNTHONO) <> 0
                    UNION
                    SELECT 
                            COALESCE(KRGLDET.NOFAC,'000000000') AS no_facture,
                            date_trunc('month',DATE) AS date_comptable,
                            0 AS montant_vente_c,
                            0 AS montant_vente_h,
                            SUM(CASE WHEN NOPRAT IS NULL THEN KRGLDET.MONTANT ELSE 0 END) AS montant_reglements_c,
                            SUM(CASE WHEN NOPRAT IS NOT NULL THEN KRGLDET.MONTANT ELSE 0 END) AS montant_reglements_h
                        FROM w_KRGLDET KRGLDET 
                        WHERE DATE >  '[ENV_ADM_ANNEEDEBUT]0101'
                        AND KRGLDET.NOFAC IS NOT NULL
                        GROUP BY 1,2
                      ) subview
                GROUP BY 1,2
                ORDER BY 1,2;
                
                
                                        
            ]]></sqlcmd>
        </NODE>
        
    </NODE>
    
    <NODE name="PARAM" label="RECUPERATION DES PARAMETRES">
        <NODE label="Préparation des tables">
            <sqlcmd><![CDATA[

                -- Préparation table des factures pour traiteement des factures P***
                DROP TABLE IF EXISTS w_KFACTURE;
                CREATE TEMP TABLE w_KFACTURE AS
                SELECT *,
					'0'::text AS est_doublon
                FROM prod_mederi.KFACTURE
                ;
				
				-- ELA Regroupment des factures en double
				UPDATE w_KFACTURE SET
					est_doublon = CASE WHEN NOENR_keep = NOENR THEN '0' ELSE  '1' END,
					MNTPREST = CASE WHEN NOENR_keep = NOENR THEN MNTPREST_sum ELSE MNTPREST END,
					MNTPAM = CASE WHEN NOENR_keep = NOENR THEN MNTPAM_sum ELSE MNTPAM END,
					MNTPMUT = CASE WHEN NOENR_keep = NOENR THEN MNTPMUT_sum ELSE MNTPMUT END,
					MNTPASS = CASE WHEN NOENR_keep = NOENR THEN MNTPASS_sum ELSE MNTPASS END,
					MNTHONO = CASE WHEN NOENR_keep = NOENR THEN MNTHONO_sum ELSE MNTHONO END,
					MNTHAM = CASE WHEN NOENR_keep = NOENR THEN MNTHAM_sum ELSE MNTHAM END,
					MNTHMUT = CASE WHEN NOENR_keep = NOENR THEN MNTHMUT_sum ELSE MNTHMUT END,
					MNTHASS = CASE WHEN NOENR_keep = NOENR THEN MNTHASS_sum ELSE MNTHASS END,
					HTFAC = CASE WHEN NOENR_keep = NOENR THEN HTFAC_sum ELSE HTFAC END,
					HTSS= CASE WHEN NOENR_keep = NOENR THEN HTSS_sum ELSE HTSS END,
					SLDPAM = CASE WHEN NOENR_keep = NOENR THEN SLDPAM_sum ELSE SLDPAM END,
					SLDPMUT = CASE WHEN NOENR_keep = NOENR THEN SLDPMUT_sum ELSE SLDPMUT END,
					SLDPASS = CASE WHEN NOENR_keep = NOENR THEN SLDPASS_sum ELSE SLDPASS END,
					SLDHAM = CASE WHEN NOENR_keep = NOENR THEN SLDHAM_sum ELSE SLDHAM END,
					SLDHMUT = CASE WHEN NOENR_keep = NOENR THEN SLDHMUT_sum ELSE SLDHMUT END,
					SLDHASS = CASE WHEN NOENR_keep = NOENR THEN SLDHASS_sum ELSE SLDHASS END
				FROM
				(
					SELECT NOFAC, MAX(NOENR) AS NOENR_keep,
						SUM(MNTPREST) AS MNTPREST_sum,
						SUM(MNTPAM) AS MNTPAM_sum,
						SUM(MNTPMUT) AS MNTPMUT_sum,
						SUM(MNTPASS) AS MNTPASS_sum,
						SUM(MNTHONO) AS MNTHONO_sum,
						SUM(MNTHAM) AS MNTHAM_sum,
						SUM(MNTHMUT) AS MNTHMUT_sum,
						SUM(MNTHASS) AS MNTHASS_sum,
						SUM(base.cti_to_number(HTFAC))::text AS HTFAC_sum,
						SUM(base.cti_to_number(HTSS))::text AS HTSS_sum,
						SUM(SLDPAM) AS SLDPAM_sum,
						SUM(SLDPMUT) AS SLDPMUT_sum,
						SUM(SLDPASS) AS SLDPASS_sum,
						SUM(SLDHAM) AS SLDHAM_sum,
						SUM(SLDHMUT) AS SLDHMUT_sum,
						SUM(SLDHASS) AS SLDHASS_sum
					FROM w_KFACTURE
					WHERE NOFAC IS NOT NULL
					GROUP BY 1
					HAVING count(*) > 1 AND
						count(distinct TYPEFAC) = 1
				) subview
				WHERE w_KFACTURE.NOFAC = subview.NOFAC
				;


				-- ELA Suppression des autres factures en double (en attendant mieux)
				UPDATE w_KFACTURE
				SET est_doublon = '1'
				WHERE NOFAC IN
				(
					SELECT NOFAC
					FROM w_KFACTURE
					WHERE NOFAC IS NOT NULL AND est_doublon = '0'
					GROUP BY 1
					HAVING count(*) > 1
				)
				;
				
                UPDATE w_KFACTURE
                SET MNTPREST = MNTPREST - MNTPASS, 
                    MNTPASS = MNTPREST - MNTPASS
                    WHERE NOFAC LIKE 'P%' AND
                        (MNTPREST IS DISTINCT FROM MNTPREST - MNTPASS OR
                    MNTPASS IS DISTINCT FROM MNTPREST - MNTPASS
                    )
                ;
                
                CREATE INDEX w_KFACTURE_ik_nofac
                  ON w_KFACTURE
                  USING btree
                  (nofac);
                  
                CREATE INDEX w_KFACTURE_ik_nodossier
                  ON w_KFACTURE
                  USING btree
                  (nodossier);
                  
                UPDATE w_KFACTURE
                SET DATEFACPAR = subview.DATEFIN
                FROM 
                    (SELECT NOFAC, MAX(COALESCE(DATEFIN,DATEACTE)) AS DATEFIN
                    FROM prod_mederi.KACTES
                    WHERE NOACTE = 'PJ'
                    GROUP BY 1
                    ) subview
                WHERE w_KFACTURE.NOFAC = subview.NOFAC AND
                    DATEFACPAR IS NOT NULL AND
                    TYPEFAC = '1' AND
                    (DATEFACPAR - subview.DATEFIN) > 1
                ;
                  
                -- Préparation table des reglements pour signer
                DROP TABLE IF EXISTS w_KREGL;
                CREATE TEMP TABLE w_KREGL AS
                SELECT *,
					'0'::text AS ignore,
					'0'::text AS forcehon
                FROM prod_mederi.KREGL
                ;
				
				UPDATE w_KREGL
                SET forcehon = '1'
                WHERE NUMREGLD = 0 AND
					libelle like 'Rglt %' AND
					libelle like '% Hon N%'
				;
				
				UPDATE w_KREGL
                SET ignore = '1'
                WHERE NUMREGLD = 0 AND
					ETATREGL <> '1' AND ORIGINE = 8
				;


                UPDATE w_KREGL SET
                SENS = CASE WHEN ORIGINE IN ('4', '6', '8','10','12','14','15') THEN '-' ELSE '' END,
                MONTANT = CASE WHEN ORIGINE IN ('4', '6', '8','10','12','14','15') THEN 0-MONTANT ELSE MONTANT END
                    ;
					
				ANALYSE w_KREGL
				;
                    
                CREATE INDEX w_KREGL_ik_nodossier
                  ON w_KREGL
                  USING btree
                  (nodossier);
                  
                CREATE INDEX w_KREGL_ik_noregl
                  ON w_KREGL
                  USING btree
                  (noregl);

                                
                DROP TABLE IF EXISTS w_KRGLDET;
                CREATE TEMP TABLE w_KRGLDET AS
                SELECT *
                FROM prod_mederi.KRGLDET
                ;

                UPDATE w_KRGLDET SET
                    MONTANT = CASE WHEN ORIGINE IN ('4', '6', '8','10','12','14','15') THEN 0-MONTANT ELSE MONTANT END
                WHERE ORIGINE IN ('4', '6', '8','10','12','14','15')
                ;
				
				ANALYSE w_KRGLDET
				;
                
                  
                CREATE INDEX w_KRGLDET_ik_nodossier
                  ON w_KRGLDET
                  USING btree
                  (nodossier);
                  
                CREATE INDEX w_KRGLDET_ik_noregl
                  ON w_KRGLDET
                  USING btree
                  (noregl);
                  
                CREATE INDEX w_KRGLDET_ik_nofac
                  ON w_KRGLDET
                  USING btree
                  (nofac);
                  
                  
                -- N° dossier vide sur entete reglement
                UPDATE w_KREGL
                SET NODOSSIER = subview.NODOSSIER
                FROM 
                (
                    SELECT w_KREGL.NOREGL, MAX(w_KFACTURE.NODOSSIER) AS NODOSSIER
                    FROM w_KREGL
                    JOIN w_KRGLDET ON w_KREGL.NOREGL = w_KRGLDET.NOREGL
                    JOIN w_KFACTURE ON w_KRGLDET.NOFAC = w_KFACTURE.NOFAC
                    WHERE w_KREGL.NODOSSIER IS NULL
                    GROUP BY 1
                ) subview
                WHERE w_KREGL.NOREGL = subview.NOREGL AND
                    w_KREGL.NODOSSIER IS NULL
                    ;
        
                                        
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Tiers payant">
            <sqlcmd><![CDATA[

                INSERT INTO activite[PX].t_types_tiers_payant(code, texte, texte_court)
                SELECT code, texte, texte FROM
                (
                SELECT '0' AS code, 'Patients' AS texte
                UNION ALL
                SELECT '1','Régime général'
                UNION ALL
                SELECT '2','Mutuelles'
                ) subview
                WHERE code NOT IN (SELECT code FROM activite[PX].t_types_tiers_payant);
                
                
                INSERT INTO base.t_grands_regimes(code, code_original, texte, texte_court)
                SELECT NOGREGIME, NOGREGIME, LIBELLE, LIBELLE 
                FROM prod_mederi.KGREGIME
                LEFT JOIN base.t_grands_regimes ON NOGREGIME = code
                WHERE t_grands_regimes.code IS NULL
                GROUP BY 1,2,3,4;
                
                

                INSERT INTO activite[PX].t_tiers_payant(oid, code, code_original, type_tiers_payant, texte, texte_court) 
                SELECT 0, '', '', '0', 'Non saisi', 'Non saisi'
                WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_tiers_payant);

                INSERT INTO activite[PX].t_tiers_payant(code, code_original, type_tiers_payant, texte, texte_court) 
                SELECT 'PATIENTS', '0', '0', 'Patients', 'Patients'
                WHERE '0' NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant);

                INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
                SELECT COORGDEST, COORGDEST, MAX(CASE WHEN ORGANISME = 1 THEN '1' WHEN COORGDEST like '%PATIENT%' THEN '0' ELSE '2' END), MAX(NOM), MAX(NOM) 
                FROM prod_mederi.KORGDEST 
                WHERE COORGDEST IN (
                            SELECT DISTINCT COORGDEST
                            FROM  prod_mederi.KDOSSIER
                            WHERE COORGDEST NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant)
                            UNION ALL
                            SELECT DISTINCT NOMUTUELLE
                            FROM  prod_mederi.KDOSSIER
                            WHERE NOMUTUELLE NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant))
                GROUP BY 1,2;
                    
                UPDATE activite[PX].t_tiers_payant
                SET grand_regime_id = t_grands_regimes.oid 
                FROM prod_mederi.KORGDEST
                    JOIN prod_mederi.KGREGIME ON KORGDEST.NOGREGIME = KGREGIME.NOGREGIME
                    JOIN base.t_grands_regimes ON KGREGIME.NOGREGIME = code
                WHERE t_tiers_payant.code_original = COORGDEST AND
                    grand_regime_id IS DISTINCT FROM t_grands_regimes.oid AND
                    KGREGIME.NOGREGIME <> '00';
                                        
                                        
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Médecins">
            <sqlcmd><![CDATA[
            
                INSERT INTO base.t_specialites_medecin(oid, code, code_original, texte, texte_court) 
                SELECT 0, '', '0', 'Non saisie', 'Non saisie'
                WHERE 0 NOT IN (SELECT oid FROM base.t_specialites_medecin);
                
                UPDATE base.t_specialites_medecin SET
                code_original = code where code_original is null and oid != 0;

                INSERT INTO base.t_specialites_medecin(code,code_original,texte,texte_court)
                SELECT 
                    NOSPEC,
                    NOSPEC,
                    LIBELLE,
                    LIBELLE
                FROM prod_mederi.KSPECIAL
                    LEFT JOIN base.t_specialites_medecin on t_specialites_medecin.code = NOSPEC
                WHERE t_specialites_medecin.code IS NULL 
                ORDER BY 1;
                

                INSERT INTO activite.t_specialites_medecin(oid, code, code_original, texte, texte_court) 
                SELECT 0, '', '0', 'Non saisie', 'Non saisie'
                WHERE 0 NOT IN (SELECT oid FROM activite.t_specialites_medecin);
                
                INSERT INTO base.t_medecins(oid, nom, prenom, numero_ordre, specialite_id ) 
                SELECT 0, 'Non renseigné', '', '', 0 WHERE 0 NOT IN (SELECT oid FROM base.t_medecins);

                INSERT INTO activite[PX].t_medecins_administratifs(oid, code_original, code, nom, prenom, specialite_id, medecin_id) 
                SELECT 0, '0', '****', 'Non renseigné', '', 0, 0 WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_medecins_administratifs);

                
                DROP TABLE IF EXISTS W_KPRAT
                ;
                
                CREATE TEMP TABLE W_KPRAT AS
                SELECT * 
                FROM  prod_mederi.KPRAT
                WHERE CTID IN (
                            SELECT MAX(CTID)
                            from prod_mederi.KPRAT
                            GROUP BY NOPRAT
                        )
                ;
                
				-- Médecins d'après la nomenclature classique
                DROP TABLE IF EXISTS w_medecins;
                CREATE TEMP TABLE w_medecins AS
                SELECT NOPRAT, 
                    NOPRAT AS MEDE_CODE,
                    base.cti_soundex_nom(NOMPRAT) AS NOMPRAT_SOUNDEX, 
                    base.cti_soundex_nom(COALESCE(PRENOMPRAT,'')) AS PRENOMPRAT_SOUNDEX, 
                    NOMPRAT, 
                    COALESCE(PRENOMPRAT,'') AS PRENOMPRAT, 
                    COALESCE(RPPS,'') AS RPPS,
                    COALESCE(NOSPEC,'') aS NOSPEC,
                    COALESCE(t_medecins_administratifs.medecin_id,0) as medecin_id
                FROM W_KPRAT 
                    LEFT JOIN activite[PX].t_medecins_administratifs ON NOPRAT = t_medecins_administratifs.code_original
                WHERE  (
                        NOPRAT IN (SELECT NOPRAT FROM prod_mederi.KDOSSIER GROUP BY 1)
                        OR NOPRAT IN (SELECT NOPRAT from prod_mederi.KACTES GROUP BY 1) 
                    );
					
				-- médecins utilisés dans les dossiers mais absents de la nomenclature
				INSERT INTO w_medecins (
					NOPRAT, 
					MEDE_CODE,
                    NOMPRAT_SOUNDEX, 
                    PRENOMPRAT_SOUNDEX, 
                    NOMPRAT, 
                    PRENOMPRAT, 
                    RPPS,
                    NOSPEC,
                    medecin_id
				)
				SELECT
				DISTINCT
					KSEJOUR.NOPRAT AS NOPRAT,
					KSEJOUR.NOPRAT AS MEDE_CODE,
					KSEJOUR.NOPRAT AS NOMPRAT_SOUNDEX, 
					KSEJOUR.NOPRAT AS PRENOMPRAT_SOUNDEX, 
					KSEJOUR.NOPRAT AS NOMPRAT,
					KSEJOUR.NOPRAT AS PRENOMPRAT,
					'' AS RPPS,
					'' AS NOSPEC,
					0 AS medecin_id
				FROM
					prod_mederi.KSEJOUR
					LEFT JOIN w_medecins ON w_medecins.MEDE_CODE = KSEJOUR.NOPRAT
				WHERE 1=1
					AND w_medecins.MEDE_CODE IS NULL
					AND KSEJOUR.NOPRAT IS DISTINCT FROM NULL;
                                        
                INSERT INTO base.t_medecins(nom, prenom, numero_ordre, specialite_id)
                SELECT w_medecins.NOMPRAT, w_medecins.PRENOMPRAT, w_medecins.RPPS, 0 FROM
                (SELECT SUBSTR(NOMPRAT_SOUNDEX, 1, 8) AS NOMPRAT_SOUNDEX, SUBSTR(PRENOMPRAT_SOUNDEX, 1, 8) AS PRENOMPRAT_SOUNDEX, RPPS, NOPRAT
                FROM w_medecins
                GROUP BY 1,2,3,4) subview, w_medecins
                WHERE w_medecins.NOPRAT = subview.NOPRAT
					AND w_medecins.NOPRAT != ALL (ARRAY(SELECT code FROM base.t_medecins)::text[])
                    AND subview.NOMPRAT_SOUNDEX || ',' || subview.PRENOMPRAT_SOUNDEX || ',' ||  subview.RPPS NOT IN 
                    (SELECT substr(base.cti_soundex_nom(nom),1,8)  || ',' || substr(base.cti_soundex_nom(prenom),1,8) || ',' || numero_ordre FROM base.t_medecins);


                INSERT INTO base.t_medecins(nom, prenom, specialite_id)
                SELECT w_medecins.NOMPRAT, w_medecins.PRENOMPRAT, 0 FROM
                (SELECT SUBSTR(NOMPRAT_SOUNDEX, 1, 8) AS NOMPRAT_SOUNDEX, SUBSTR(PRENOMPRAT_SOUNDEX, 1, 8) AS PRENOMPRAT_SOUNDEX, NOPRAT
                FROM w_medecins
                GROUP BY 1,2,3) subview, w_medecins
                WHERE w_medecins.NOPRAT = subview.NOPRAT
					AND w_medecins.NOPRAT != ALL (ARRAY(SELECT code FROM base.t_medecins)::text[])
                    AND subview.NOMPRAT_SOUNDEX || ',' || subview.PRENOMPRAT_SOUNDEX NOT IN 
                    (SELECT substr(base.cti_soundex_nom(nom),1,8)  || ',' || substr(base.cti_soundex_nom(prenom),1,8)  FROM base.t_medecins);


                UPDATE w_medecins SET medecin_id = subview.medecin_id
                FROM 
                (SELECT substr(base.cti_soundex_nom(nom),1,8) as nom , substr(base.cti_soundex_nom(prenom),1,8) as prenom, numero_ordre, MIN(oid) AS medecin_id FROM base.t_medecins GROUP BY 1,2,3) subview
                WHERE SUBSTR(NOMPRAT_SOUNDEX, 1, 8) = subview.nom
                AND SUBSTR(PRENOMPRAT_SOUNDEX, 1, 8) = subview.prenom
                AND RPPS = subview.numero_ordre
                AND w_medecins.medecin_id = 0;

                UPDATE w_medecins SET medecin_id = subview.medecin_id
                FROM 
                (SELECT base.cti_soundex_nom(nom) as nom , base.cti_soundex_nom(prenom) as prenom, MIN(oid) AS medecin_id FROM base.t_medecins GROUP BY 1,2) subview
                WHERE SUBSTR(NOMPRAT_SOUNDEX, 1, 8) = subview.nom
                AND SUBSTR(PRENOMPRAT_SOUNDEX, 1, 8) = subview.prenom
                AND w_medecins.medecin_id = 0;

                INSERT INTO activite[PX].t_medecins_administratifs(code_original, code, nom, prenom, specialite_id,  medecin_id)
                SELECT DISTINCT NOPRAT, NOPRAT, NOMPRAT, PRENOMPRAT, COALESCE(t_specialites_medecin.oid::bigint,0), medecin_id
                FROM w_medecins
                    LEFT JOIN base.t_specialites_medecin ON (NOSPEC = t_specialites_medecin.code_original)
                WHERE NOPRAT NOT IN (SELECT code_original FROM activite[PX].t_medecins_administratifs);

                UPDATE activite[PX].t_medecins_administratifs
                SET nom = NOMPRAT,
                    prenom = PRENOMPRAT,
                    specialite_id = COALESCE(t_specialites_medecin.oid,t_specialites_medecin_2.oid,0),
                    medecin_id = w_medecins.medecin_id
                FROM w_medecins 
                LEFT JOIN base.t_specialites_medecin ON (NOSPEC || '..' = t_specialites_medecin.code)
                LEFT JOIN base.t_specialites_medecin t_specialites_medecin_2 ON (NOSPEC = t_specialites_medecin_2.code)
                WHERE w_medecins.NOPRAT = t_medecins_administratifs.code_original
                    AND (
                    t_medecins_administratifs.nom <> NOMPRAT OR
                    t_medecins_administratifs.prenom <> PRENOMPRAT OR
                    t_medecins_administratifs.specialite_id <> COALESCE(t_specialites_medecin.oid,t_specialites_medecin_2.oid,0) OR
                    t_medecins_administratifs.medecin_id <> w_medecins.medecin_id
                );

                

                UPDATE activite[PX].t_medecins_administratifs
                SET specialite_id = subview.specialite_medecin_id
                FROM
                    (
                    SELECT t_medecins_administratifs.oid,t_specialites_medecin.oid AS specialite_medecin_id
                    FROM activite[PX].t_medecins_administratifs
                    JOIN base.t_specialites_medecin t_specialites_medecin_2 ON specialite_id = t_specialites_medecin_2.oid
                    JOIN base.t_specialites_medecin ON t_specialites_medecin_2.code || '..'  = t_specialites_medecin.code
                    ) subview
                WHERE t_medecins_administratifs.oid = subview.oid;

                UPDATE base.t_medecins SET specialite_id = subview.specialite_id FROM 
                (SELECT t_medecins.oid, MIN(t_medecins_administratifs.specialite_id) as specialite_id 
                FROM base.t_medecins, activite[PX].t_medecins_administratifs , base.t_specialites_medecin 
                WHERE t_medecins.oid = t_medecins_administratifs.medecin_id 
                AND t_medecins_administratifs.specialite_id = t_specialites_medecin.oid 
                GROUP BY t_medecins.oid) subview 
                WHERE t_medecins.oid = subview.oid AND t_medecins.oid <> 0 AND t_medecins.specialite_id = 0;                        


                -- no_adeli
				UPDATE activite[PX].t_medecins_administratifs
				SET no_adeli = CODEINSEE
				FROM prod_mederi.KPRAT
				WHERE t_medecins_administratifs.code_original = NOPRAT AND
					t_medecins_administratifs.NO_ADELI IS DISTINCT FROM CODEINSEE
				;                                        
                                        
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Hébergement">
            <sqlcmd><![CDATA[
                
                
                -- Modes de traitement
                
                INSERT INTO base.t_modes_traitement(code, texte, texte_court)
                SELECT MODETRAIT, MODETRAIT, MODETRAIT
                FROM prod_mederi.KSERVINT
                WHERE MODETRAIT NOT IN (SELECt code FROM base.t_modes_traitement)
                ORDER BY MODETRAIT;
                
                -- DMT
                
                INSERT INTO base.t_dmt(code, texte, texte_court)
                SELECT NOSERVSS, LIBSERVSS, LIBSERVSS
                FROM prod_mederi.KSERVSS
                    WHERE NOSERVSS NOT IN (SELECt code FROM base.t_dmt)
                ORDER BY NOSERVSS;
                
                -- Services
                
                INSERT INTO activite[PX].t_services_facturation(oid, code_original, code, texte, texte_court) 
                SELECT 0, 0, '****', 'Non renseigné', 'Non renseigné' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_services_facturation);

                INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, type_t2a)
                SELECT NOSERVINT, NOSERVINT, LIBELLE, LIBELLE, CASE WHEN GENPMSI = 1 THEN '1' ELSE '0' END
                FROM prod_mederi.KSERVINT
                WHERE 
                    NOSERVINT NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
                ORDER BY NOSERVINT;
                
                UPDATE activite[PX].t_services_facturation
                SET mode_traitement_id = subview.mode_traitement_id, dmt_id = subview.dmt_id
                FROM (
                    SELECT NOSERVINT, COALESCE(t_modes_traitement.oid,0) as mode_traitement_id, COALESCE(t_dmt.oid,0) as dmt_id
                    FROM prod_mederi.KSERVINT
                        LEFT JOIN base.t_modes_traitement ON MODETRAIT = t_modes_traitement.code
                        LEFT JOIN base.t_dmt ON NOSERVSS = t_dmt.code
                    WHERE 
                        (t_modes_traitement.oid IS NOT NULL OR t_dmt.oid IS NOT NULL)
                    ) subview
                WHERE code_original = NOSERVINT AND (t_services_facturation.mode_traitement_id = 0 OR t_services_facturation.dmt_id = 0);
                
                INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, est_absence) 
                SELECT '*ABS', '*ABS', 'Absence', 'Absence', '1' WHERE '*ABS' NOT IN (SELECT code_original FROM activite[PX].t_services_facturation);

                -- Unités fonctionnelles
                
                INSERT INTO activite[PX].t_unites_fonctionnelles(oid, code_original, code, texte, texte_court) 
                SELECT 0, 0, '', 'Non renseignée', 'Non renseignée' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_unites_fonctionnelles);
                
                INSERT INTO activite[PX].t_unites_fonctionnelles(code_original, code, texte, texte_court)
                SELECT NOSERVSS, NOSERVSS, LIBSERVSS, LIBSERVSS
                FROM prod_mederi.KSERVSS
                WHERE 
                    NOSERVSS NOT IN (SELECT code_original FROM activite[PX].t_unites_fonctionnelles)
                ORDER BY NOSERVSS;
                
                INSERT INTO activite[PX].t_unites_fonctionnelles(code_original, code, texte, texte_court) 
                SELECT '*ABS', '*ABS', 'Absence', 'Absence' WHERE '*ABS' NOT IN (SELECT code_original FROM activite[PX].t_unites_fonctionnelles);
                
                    
                -- Unités médicales

                INSERT INTO activite[PX].t_unites_medicales(oid, code_original, code, texte, texte_court) 
                SELECT 0, 0, '', 'Non renseignée', 'Non renseignée' WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_unites_medicales);

                INSERT INTO activite[PX].t_unites_medicales(code_original, code, texte, texte_court)
                SELECT CODEUM, CODEUM, MIN(LIBELLE), MIN(LIBELLE)
                FROM prod_mederi.KSERVINT
                JOIN prod_mederi.KSERVSS ON KSERVINT.NOSERVSS = KSERVSS.NOSERVSS
                WHERE 
                    CODEUM != '' AND
                    CODEUM NOT IN (SELECT code_original FROM activite[PX].t_unites_medicales)
                GROUP BY CODEUM
                ORDER BY CODEUM;
                
                INSERT INTO activite[PX].t_unites_medicales(code_original, code, texte, texte_court) 
                SELECT '*ABS', '*ABS', 'Absence', 'Absence' WHERE '*ABS' NOT IN (SELECT code_original FROM activite[PX].t_unites_medicales);


                -- Activités (um principale)

                INSERT INTO activite[PX].t_activites(oid, code_original, code, texte, texte_court) 
                SELECT 0, 0, '', 'Non renseignée', 'Non renseignée' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_activites);


                -- Etages et lits

                INSERT INTO activite[PX].t_etages(oid, code_original, code, texte, texte_court, nb_lits) 
                SELECT 0, 0, '', 'Non renseigné', 'Non renseigné', 0 WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_etages);

                INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court)
                SELECT SECTEUR, SECTEUR, SECTEUR, SECTEUR
                FROM prod_mederi.KCHAMBRE
                WHERE SECTEUR  NOT IN (SELECT code_original FROM activite[PX].t_etages WHERE code_original IS NOT NULL )
                GROUP BY SECTEUR
                ORDER BY SECTEUR;
                                    
                UPDATE activite[PX].t_lits SET 
                    code = replace(NOLIT,' ',''), 
                    texte = NOLIT, 
                    texte_court = NOLIT, 
                    etage_id = t_etages.oid
                FROM prod_mederi.KCHAMBRE, activite[PX].t_etages
                WHERE NOLIT = t_lits.code_original
                    AND SECTEUR = t_etages.code_original;

                -- mise à jour des chambres si elles ne sont pas dans la table kchambre mais que leur code est semblable (cas manque C par ex 201 A et 201 AC)
                -- no lit existe avec un caractère en moins
                        
                UPDATE prod_mederi.KSEJOUR 
                SET NOCHAMBRE = replace(NOCHAMBRE,' ','');
                
                UPDATE prod_mederi.KCHAMBRE 
                SET NOLIT = replace(NOLIT,' ','');
                
                -- cas nochambre = A et no lit = AC
                UPDATE prod_mederi.KSEJOUR
                SET NOCHAMBRE = ch.NOLIT
                FROM prod_mederi.KSEJOUR mv 
                    LEFT JOIN prod_mederi.KCHAMBRE ON mv.NOCHAMBRE = KCHAMBRE.NOLIT
                    LEFT JOIN prod_mederi.KCHAMBRE ch ON left(replace(ch.NOLIT,' ',''),-1)  = replace (mv.NOCHAMBRE,' ','')
                WHERE 
                    KSEJOUR.SECLEUNIK = mv.SECLEUNIK
                    AND length(KSEJOUR.NOCHAMBRE) > 2
                    AND KCHAMBRE.NOLIT IS NULL
                    AND ch.NOLIT IS NOT NULL;

                 -- cas nochambre = P, F ou rien et no lit = AC
                UPDATE prod_mederi.KSEJOUR
                SET NOCHAMBRE = ch.NOLIT
                FROM prod_mederi.KSEJOUR mv 
                    LEFT JOIN prod_mederi.KCHAMBRE ON mv.NOCHAMBRE = KCHAMBRE.NOLIT
                    LEFT JOIN prod_mederi.KCHAMBRE ch ON left(replace(ch.NOLIT,' ',''),-3)  = replace (mv.NOCHAMBRE,' ','')
                WHERE 
                    KSEJOUR.SECLEUNIK = mv.SECLEUNIK
                    AND length(KSEJOUR.NOCHAMBRE) > 2
                    AND KCHAMBRE.NOLIT IS NULL
                    AND ch.NOLIT IS NOT NULL;
 
                -- cas nochambre = XUSI
                UPDATE prod_mederi.KSEJOUR
                SET NOCHAMBRE = ch.NOLIT
                FROM prod_mederi.KSEJOUR mv 
                    LEFT JOIN prod_mederi.KCHAMBRE ON mv.NOCHAMBRE = KCHAMBRE.NOLIT
                    LEFT JOIN prod_mederi.KCHAMBRE ch ON replace(mv.NOCHAMBRE,'USI','') = ch.NOLIT
                WHERE 
                    KSEJOUR.SECLEUNIK = mv.SECLEUNIK
                    AND length(KSEJOUR.NOCHAMBRE) > 2
                    AND KCHAMBRE.NOLIT IS NULL
                    AND ch.NOLIT IS NOT NULL;
             
           
                INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
                SELECT NOLIT, NOLIT, NOLIT, NOLIT, t_etages.oid, CASE WHEN NOACTE = 'CP' THEN 'O' ELSE 'N' END AS CP
                FROM prod_mederi.KCHAMBRE, activite[PX].t_etages
                WHERE 
                    SECTEUR = t_etages.code_original
                    AND NOLIT NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL  )
                GROUP BY NOLIT, NOLIT, NOLIT, NOLIT, t_etages.oid, NOACTE   
                ;
                
                -- Lits non définis
                DROP TABLE IF EXISTS w_KSEJOUR_CHAMBRE;
                CREATE TEMP TABLE w_KSEJOUR_CHAMBRE AS
                        SELECT NOCHAMBRE AS NOLIT, ''::text AS SECTEUR
                        FROM prod_mederi.KSEJOUR
                        WHERE NOCHAMBRE NOT IN  (SELECT NOLIT FROM prod_mederi.KCHAMBRE WHERE NOLIT IS NOT NULL)
                GROUP BY 1
                ORDER BY 1;

                UPDATE w_KSEJOUR_CHAMBRE
                SET SECTEUR = subview.SECTEUR
                FROM
                (
                SELECT NOCHAMBRE, MAX(SECTEUR) AS SECTEUR
                FROM prod_mederi.KCHAMBRE
                WHERE NOCHAMBRE IS NOT NULL AND
                    NOCHAMBRE <> ''
                GROUP BY 1
                HAVING count(DISTINCT SECTEUR) = 1
                ) subview
                WHERE w_KSEJOUR_CHAMBRE.NOLIT LIKE subview.NOCHAMBRE || '%'
                ;
                
                INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
                SELECT NOLIT, NOLIT, NOLIT, NOLIT, t_etages.oid, 'N' AS CP
                FROM w_KSEJOUR_CHAMBRE, activite[PX].t_etages
                WHERE 
                    SECTEUR = t_etages.code_original
                    AND NOLIT NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL  )
                GROUP BY NOLIT, NOLIT, NOLIT, NOLIT, t_etages.oid   
                ;
    
                INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
                            SELECT code_original || '-0' , '', 'Non renseigné', 'Non renseigné', oid, 'O' 
                                    FROM activite[PX].t_etages
                                    WHERE oid > 0 AND
                                        code_original || '-0' NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL );
    
                UPDATE activite[PX].t_lits SET code = '*****' WHERE code = '';
            ]]></sqlcmd>
        </NODE>
                
        <NODE label="Facturation">
            <sqlcmd><![CDATA[
                
                -- Rubriques et prestations

                INSERT INTO activite[PX].t_rubriques_facturation(oid, code_original, code, texte, texte_court) 
                SELECT 0, 0, '', 'Non renseignée', 'Non renseignée' WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_rubriques_facturation);

                INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
                SELECT '*CTI_ACO85', 'ACO85', 'Acomptes 85%', 'Acomptes 85%'
                WHERE '*CTI_ACO85' NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation);
                
                INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
                SELECT '*CTI_ACO', 'ACOMPTE', 'Acomptes', 'Acomptes'
                WHERE '*CTI_ACO' NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation);
                
                INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
                SELECT '*MED_REG_DOS', 'MED_REG_DOS', 'Règlements dossier méderi', 'Règlement dossier médéri'
                WHERE '*MED_REG_DOS' NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation);
                
                -- Initialisation code prestation si pas saisi
                UPDATE prod_mederi.KRUBINT 
                SET NOACTESS = NOACTE 
                WHERE NOACTESS = '' OR NOACTESS IS NULL
                ;
                
                -- correction si code_original != code, changer code en #code

                INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
                SELECT NOACTE, NOACTE, MAX(LIBELLE), MAX(LIBELLE)
                FROM prod_mederi.KRUBINT 
                WHERE
                    NOACTE NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
                    AND NOACTE IN (SELECT NOACTE FROM prod_mederi.KACTES)
				GROUP BY 1,2
                ORDER BY NOACTE;
                
                -- correction remise du #code en code après import

                INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
                SELECT NOACTE, NOACTE, MAX(LIBELLE), MAX(LIBELLE)
                FROM prod_mederi.KACTES
                WHERE
                    NOACTE  NOT IN (SELECT code FROM activite[PX].t_rubriques_facturation)
				GROUP BY 1,2
                ORDER BY NOACTE;
                
                INSERT INTO activite.t_prestations(code, code_original, texte, texte_court)
                SELECT KRUBINT.NOACTESS, KRUBINT.NOACTESS,MAX(subview.LIBELLE),MAX(subview.LIBELLE)
                FROM prod_mederi.KRUBINT 
                    JOIN prod_mederi.KRUBINT as subview ON KRUBINT.NOACTESS = subview.NOACTE
                WHERE 
                    KRUBINT.NOACTESS NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL)
                GROUP BY 1,2
                ORDER BY 1,2;
                
                INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
                SELECT '*CTI_ACO85', 'ACO85', 'Acomptes 85%', 'Acomptes 85%'
                WHERE '*CTI_ACO85' NOT IN (SELECT code_original FROM activite.t_prestations WHERE code_original IS NOT NULL);
                
                INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
                SELECT '*CTI_ACO', 'ACOMPTE', 'Acomptes', 'Acomptes'
                WHERE '*CTI_ACO' NOT IN (SELECT code_original FROM activite.t_prestations WHERE code_original IS NOT NULL);
                
                INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
                SELECT '*MED_REG_DOS', 'MED_REG_DOS', 'Règlement dossier méderi', 'Règlement dossier méderi'
                WHERE '*MED_REG_DOS' NOT IN (SELECT code_original FROM activite.t_prestations WHERE code_original IS NOT NULL);         
                
                INSERT INTO activite.t_protocoles(oid, code_original, code, texte, texte_court) 
                SELECT 0, 0, '***', 'Non renseigné', 'Non renseigné' WHERE 0 NOT IN (SELECT oid FROM activite.t_protocoles);

                INSERT INTO base.t_actes(code, texte, texte_court, nomenclature)
                SELECT 
                    NOACTESS, 
                    max(LIBELLE), 
                    max(LIBELLE), 
                    'NGAP'
                FROM prod_mederi.KRUBINT
                WHERE
                    TYPERUB = 4
                    AND NOACTESS NOT IN (SELECT code FROM base.t_actes WHERE code IS NOT NULL)
                GROUP BY NOACTESS
                order by 1
                ;
                INSERT INTO base.t_actes(code, texte, texte_court, nomenclature)
                SELECT 
                    NOACTE, 
                    max(LIBELLE), 
                    max(LIBELLE), 
                    'NGAP'
                FROM prod_mederi.KRUBINT
                WHERE
                    TYPERUB = 4
                    AND NOACTE NOT IN (SELECT code FROM base.t_actes WHERE code IS NOT NULL)
                GROUP BY NOACTE
                order by 1
                ;
                
                INSERT INTO base.t_actes(code, texte, texte_court, nomenclature)
                SELECT substring(CODEACTE, 1, 7), substring(CODEACTE, 1, 7), substring(CODEACTE, 1, 7), 'CCAM'
                FROM prod_mederi.MCCAM
                WHERE substring(CODEACTE, 1, 7) <> '' AND substring(CODEACTE, 1, 7) NOT IN (SELECT code FROM base.t_actes WHERE code IS NOT NULL)
                GROUP BY 1,2,3;
        
                
                                        
                
                                        
            ]]></sqlcmd>
        </NODE>
        
    </NODE>
        
    <NODE name="POST" label="TRAITEMENTS COMPLEMENTAIRES">
    
        <NODE label="Compléments facture">
            <sqlcmd><![CDATA[
            
                
                
                DROP TABLE IF EXISTS w_factures;
                CREATE TEMP TABLE w_factures AS
                SELECT 
                    no_facture,
                    no_facture_reference,
                    CASE WHEN date_expedition_0 < date_facture AND date_facture <> '2099-12-31' THEN date_facture ELSE date_expedition_0 END AS date_expedition_0,

                    CASE WHEN montant_comptabilise_1_c = 0 THEN '00010101' WHEN montant_comptabilise_1_c = montant_regle_1_c THEN date_solde_1_c ELSE '20991231' END AS date_solde,
                    CASE WHEN montant_comptabilise_1_c = 0 THEN '00010101' WHEN montant_comptabilise_1_c = montant_regle_1_c THEN date_solde_1_c ELSE '20991231' END AS date_solde_c,
                    CASE WHEN montant_comptabilise_1_h = 0 THEN '00010101' WHEN montant_comptabilise_1_h = montant_regle_1_h THEN date_solde_1_h ELSE '20991231' END AS date_solde_h,
                    CASE WHEN montant_comptabilise_0_c = 0 THEN '00010101' WHEN montant_comptabilise_0_c = montant_regle_0_c THEN date_solde_0_c ELSE '20991231' END AS date_solde_0_c,
                    CASE WHEN montant_comptabilise_0_h = 0 THEN '00010101' WHEN montant_comptabilise_0_h = montant_regle_0_h THEN date_solde_0_h ELSE '20991231' END AS date_solde_0_h,
                    CASE WHEN montant_comptabilise_1_c = 0 THEN '00010101' WHEN montant_comptabilise_1_c = montant_regle_1_c THEN date_solde_1_c ELSE '20991231' END AS date_solde_1_c,
                    CASE WHEN montant_comptabilise_1_h = 0 THEN '00010101' WHEN montant_comptabilise_1_h = montant_regle_1_h THEN date_solde_1_h ELSE '20991231' END AS date_solde_1_h,
                    CASE WHEN montant_comptabilise_2_c = 0 THEN '00010101' WHEN montant_comptabilise_2_c = montant_regle_2_c THEN date_solde_2_c ELSE '20991231' END AS date_solde_2_c,
                    CASE WHEN montant_comptabilise_2_h = 0 THEN '00010101' WHEN montant_comptabilise_2_h = montant_regle_2_h THEN date_solde_2_h ELSE '20991231' END AS date_solde_2_h,
                    CASE WHEN montant_comptabilise_22_c = 0 THEN '00010101' WHEN montant_comptabilise_22_c = montant_regle_22_c THEN date_solde_22_c ELSE '20991231' END AS date_solde_22_c,
                    CASE WHEN montant_comptabilise_22_h = 0 THEN '00010101' WHEN montant_comptabilise_22_h = montant_regle_22_h THEN date_solde_22_h ELSE '20991231' END AS date_solde_22_h
                FROM activite[PX].p_factures;

                UPDATE w_factures SET
                    date_solde = GREATEST(date_solde_0_c, date_solde_0_h, date_solde_1_c, date_solde_1_h, date_solde_2_c, date_solde_2_h, date_solde_22_c, date_solde_22_h),
                    date_solde_c = GREATEST(date_solde_0_c, date_solde_1_c, date_solde_2_c, date_solde_22_c),
                    date_solde_h = GREATEST(date_solde_0_h, date_solde_1_h, date_solde_2_h, date_solde_22_h)
                WHERE 
                    date_solde IS DISTINCT FROM GREATEST(date_solde_0_c, date_solde_0_h, date_solde_1_c, date_solde_1_h, date_solde_2_c, date_solde_2_h, date_solde_22_c, date_solde_22_h) OR
                    date_solde_c IS DISTINCT FROM GREATEST(date_solde_0_c, date_solde_1_c, date_solde_2_c, date_solde_22_c) OR
                    date_solde_h IS DISTINCT FROM GREATEST(date_solde_0_h, date_solde_1_h, date_solde_2_h, date_solde_22_h) ;

                CREATE INDEX w_factures_i1
                    ON w_factures
                    USING btree
                    (no_facture);
                
                CREATE INDEX w_factures_i2
                    ON w_factures
                    USING btree
                    (no_facture_reference);



                DROP TABLE IF EXISTS w_factures_references_soldes;
                
                CREATE TEMP TABLE w_factures_references_soldes AS
                SELECT
                    no_facture_reference,
                    MAX(date_solde) AS date_solde_reference,
                    MAX(date_solde_c) AS date_solde_reference_c,
                    MAX(date_solde_h) AS date_solde_reference_h,
                    MAX(date_solde_0_c) AS date_solde_reference_0_c,
                    MAX(date_solde_0_h) AS date_solde_reference_0_h,
                    MAX(date_solde_1_c) AS date_solde_reference_1_c,
                    MAX(date_solde_1_h) AS date_solde_reference_1_h,
                    MAX(date_solde_2_c) AS date_solde_reference_2_c,
                    MAX(date_solde_2_h) AS date_solde_reference_2_h,
                    MAX(date_solde_22_c) AS date_solde_reference_22_c,
                    MAX(date_solde_22_h) AS date_solde_reference_22_h
                FROM w_factures
                GROUP BY no_facture_reference;


                CREATE INDEX w_factures_references_soldes_i1
                ON w_factures_references_soldes
                USING btree
                (no_facture_reference);

                


                UPDATE activite[PX].p_factures
                SET 
                    date_expedition_0 = w_factures.date_expedition_0,
                    date_solde = w_factures.date_solde,
                    date_solde_c = w_factures.date_solde_c,
                    date_solde_h = w_factures.date_solde_h,
                    date_solde_0_c = w_factures.date_solde_0_c,
                    date_solde_0_h = w_factures.date_solde_0_h,
                    date_solde_1_c = w_factures.date_solde_1_c,
                    date_solde_1_h = w_factures.date_solde_1_h,
                    date_solde_2_c = w_factures.date_solde_2_c,
                    date_solde_2_h = w_factures.date_solde_2_h,
                    date_solde_22_c = w_factures.date_solde_22_c,
                    date_solde_22_h = w_factures.date_solde_22_h,
                    date_solde_reference = w_factures_references_soldes.date_solde_reference,
                    date_solde_reference_c = w_factures_references_soldes.date_solde_reference_c,
                    date_solde_reference_h = w_factures_references_soldes.date_solde_reference_h,
                    date_solde_reference_0_c = w_factures_references_soldes.date_solde_reference_0_c,
                    date_solde_reference_0_h = w_factures_references_soldes.date_solde_reference_0_h,
                    date_solde_reference_1_c = w_factures_references_soldes.date_solde_reference_1_c,
                    date_solde_reference_1_h = w_factures_references_soldes.date_solde_reference_1_h,
                    date_solde_reference_2_c = w_factures_references_soldes.date_solde_reference_2_c,
                    date_solde_reference_2_h = w_factures_references_soldes.date_solde_reference_2_h,
                    date_solde_reference_22_c = w_factures_references_soldes.date_solde_reference_22_c,
                    date_solde_reference_22_h = w_factures_references_soldes.date_solde_reference_22_h
                FROM w_factures 
                    JOIN w_factures_references_soldes ON w_factures_references_soldes.no_facture_reference = w_factures.no_facture_reference
                WHERE p_factures.no_facture = w_factures.no_facture
                AND (
                    p_factures.date_expedition_0 IS DISTINCT FROM w_factures.date_expedition_0 OR 
                    p_factures.date_solde IS DISTINCT FROM w_factures.date_solde OR 
                    p_factures.date_solde_c IS DISTINCT FROM w_factures.date_solde_c OR 
                    p_factures.date_solde_h IS DISTINCT FROM w_factures.date_solde_h OR 
                    p_factures.date_solde_0_c IS DISTINCT FROM w_factures.date_solde_0_c OR 
                    p_factures.date_solde_0_h IS DISTINCT FROM w_factures.date_solde_0_h OR
                    p_factures.date_solde_1_c IS DISTINCT FROM w_factures.date_solde_1_c OR 
                    p_factures.date_solde_1_h IS DISTINCT FROM w_factures.date_solde_1_h OR
                    p_factures.date_solde_2_c IS DISTINCT FROM w_factures.date_solde_2_c OR 
                    p_factures.date_solde_2_h IS DISTINCT FROM w_factures.date_solde_2_h OR
                    p_factures.date_solde_22_c IS DISTINCT FROM w_factures.date_solde_22_c OR 
                    p_factures.date_solde_22_h IS DISTINCT FROM w_factures.date_solde_22_h OR
                    p_factures.date_solde_reference IS DISTINCT FROM w_factures_references_soldes.date_solde_reference OR 
                    p_factures.date_solde_reference_c IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_c OR 
                    p_factures.date_solde_reference_h IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_h OR 
                    p_factures.date_solde_reference_0_c IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_0_c OR 
                    p_factures.date_solde_reference_0_h IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_0_h OR
                    p_factures.date_solde_reference_1_c IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_1_c OR 
                    p_factures.date_solde_reference_1_h IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_1_h OR
                    p_factures.date_solde_reference_2_c IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_2_c OR 
                    p_factures.date_solde_reference_2_h IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_2_h OR
                    p_factures.date_solde_reference_22_c IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_22_c OR 
                    p_factures.date_solde_reference_22_h IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_22_h
                );
                
                -- Suppression des tables de travail non utilisées après
                DROP TABLE IF EXISTS w_factures CASCADE;
                DROP TABLE IF EXISTS w_factures_references_soldes CASCADE;          

                
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Compléments séjours">
            <sqlcmd><![CDATA[

                UPDATE activite[PX].p_sejours 
                SET date_groupage = date_facture 
                WHERE (date_groupage IS null OR date_groupage = '20991231') AND 
                    date_facture <> '2099-12-31';
                
                
                DROP TABLE IF EXISTS w_sejours_total;
                CREATE TEMP TABLE w_sejours_total AS
                SELECT   
                    p_sejours.no_sejour AS no_sejour, 
                    p_sejours.code_sorti,
                    p_sejours.date_sortie,
                    p_sejours.date_groupage,   
                    p_sejours.ghs_id,
    
                    MAX(COALESCE(p_factures.date_facture,'20991231')) AS date_facture,     
                    MAX(COALESCE(p_factures.date_expedition,'20991231')) AS date_expedition,  
                    MAX(COALESCE(p_factures.date_solde,'20991231')) AS date_solde,  
                    SUM(COALESCE(p_factures.montant_facture_c,0)) AS montant_facture_c,  
                    SUM(COALESCE(p_factures.montant_facture_h,0)) AS montant_facture_h,  
                    SUM(COALESCE(p_factures.montant_regle_c,0)) AS montant_regle_c,  
                    SUM(COALESCE(p_factures.montant_regle_h,0)) AS montant_regle_h,  
                    SUM(COALESCE(CASE WHEN p_factures.type_facture <> 'P' AND p_factures.type_facture <> 'E' AND p_factures.type_facture <> 'G' THEN 1 ELSE 0 END,0)) AS nb_factures,  
                    SUM(COALESCE(CASE WHEN p_factures.type_facture = '0' THEN 0 ELSE 1 END,0)) AS nb_factures_regularisation,  
                    SUM(COALESCE(p_factures.nb_rejets,0)) AS nb_rejets,  

                    SUM(COALESCE(p_factures.montant_facture_0_c,0)) AS montant_facture_0_c,  
                    SUM(COALESCE(p_factures.montant_facture_0_h,0)) AS montant_facture_0_h,  
                    SUM(COALESCE(p_factures.montant_regle_0_c,0)) AS montant_regle_0_c,  
                    SUM(COALESCE(p_factures.montant_regle_0_h,0)) AS montant_regle_0_h,  
                    MAX(COALESCE(CASE WHEN (p_factures.montant_facture_0_c <> 0 OR p_factures.montant_facture_0_h <> 0)  THEN p_factures.date_expedition_0 ELSE '0001-01-01' END,'20991231' )) AS date_expedition_0,   
                    MAX(COALESCE(CASE WHEN p_factures.date_solde_0_c < '2099-12-31' AND p_factures.date_solde_0_c > p_factures.date_solde_0_h THEN p_factures.date_solde_0_c ELSE p_factures.date_solde_0_h END,'20991231' )) AS date_solde_0,  
                    

                    SUM(COALESCE(p_factures.montant_facture_1_c,0)) AS montant_facture_1_c,  
                    SUM(COALESCE(p_factures.montant_facture_1_h,0)) AS montant_facture_1_h,  
                    SUM(COALESCE(p_factures.montant_regle_1_c,0)) AS montant_regle_1_c,  
                    SUM(COALESCE(p_factures.montant_regle_1_h,0)) AS montant_regle_1_h,  
                    MAX(COALESCE(CASE WHEN (p_factures.montant_facture_1_c <> 0 OR p_factures.montant_facture_1_h <> 0)  THEN p_factures.date_expedition_1 ELSE '0001-01-01' END,'20991231' )) AS date_expedition_1,  
                    MAX(COALESCE(CASE WHEN p_factures.date_solde_1_c < '2099-12-31' AND p_factures.date_solde_1_c > p_factures.date_solde_1_h THEN p_factures.date_solde_1_c ELSE p_factures.date_solde_1_h END,'20991231' )) AS date_solde_1,  

                    SUM(COALESCE(p_factures.montant_facture_2_c,0)) AS montant_facture_2_c,  
                    SUM(COALESCE(p_factures.montant_facture_2_h,0)) AS montant_facture_2_h,  
                    SUM(COALESCE(p_factures.montant_regle_2_c,0)) AS montant_regle_2_c,  
                    SUM(COALESCE(p_factures.montant_regle_2_h,0)) AS montant_regle_2_h,  
                    MAX(COALESCE(CASE WHEN (p_factures.montant_facture_2_c <> 0 OR p_factures.montant_facture_2_h <> 0)  THEN p_factures.date_expedition_2 ELSE '0001-01-01' END,'20991231' )) AS date_expedition_2,  
                    MAX(COALESCE(CASE WHEN p_factures.date_solde_2_c < '2099-12-31' AND p_factures.date_solde_2_c > p_factures.date_solde_2_h THEN p_factures.date_solde_2_c ELSE p_factures.date_solde_2_h END,'20991231' )) AS date_solde_2,  

                    SUM(COALESCE(p_factures.montant_facture_22_c,0)) AS montant_facture_22_c,  
                    SUM(COALESCE(p_factures.montant_facture_22_h,0)) AS montant_facture_22_h,  
                    SUM(COALESCE(p_factures.montant_regle_22_c,0)) AS montant_regle_22_c,  
                    SUM(COALESCE(p_factures.montant_regle_22_h,0)) AS montant_regle_22_h,  
                    MAX(COALESCE(CASE WHEN (p_factures.montant_facture_22_c <> 0 OR p_factures.montant_facture_22_h <> 0)  THEN p_factures.date_expedition_22 ELSE '0001-01-01' END,'20991231' )) AS date_expedition_22,  
                    MAX(COALESCE(CASE WHEN p_factures.date_solde_22_c < '2099-12-31' AND p_factures.date_solde_22_c > p_factures.date_solde_22_h THEN p_factures.date_solde_22_c ELSE p_factures.date_solde_22_h END,'20991231' )) AS date_solde_22 , 

                    
                    SUM(COALESCE(p_factures.montant_comptabilise_c,0)) AS montant_comptabilise_c,  
                    SUM(COALESCE(p_factures.montant_comptabilise_h,0)) AS montant_comptabilise_h,  
                    SUM(COALESCE(p_factures.montant_comptabilise_0_c,0)) AS montant_comptabilise_0_c,  
                    SUM(COALESCE(p_factures.montant_comptabilise_0_h,0)) AS montant_comptabilise_0_h,  
                    SUM(COALESCE(p_factures.montant_comptabilise_1_c,0)) AS montant_comptabilise_1_c,  
                    SUM(COALESCE(p_factures.montant_comptabilise_1_h,0)) AS montant_comptabilise_1_h,  
                    SUM(COALESCE(p_factures.montant_comptabilise_2_c,0)) AS montant_comptabilise_2_c,  
                    SUM(COALESCE(p_factures.montant_comptabilise_2_h,0)) AS montant_comptabilise_2_h,  
                    SUM(COALESCE(p_factures.montant_comptabilise_22_c,0)) AS montant_comptabilise_22_c,  
                    SUM(COALESCE(p_factures.montant_comptabilise_22_h,0)) AS montant_comptabilise_22_h,

                    SUM(COALESCE(p_factures.montant_comptabilise_budget_global_c,0)) AS montant_comptabilise_budget_global_c,  

                    SUM(COALESCE(p_factures.montant_facture_c_actes_inclus_dans_sejour,0)) AS montant_facture_c_actes_inclus_dans_sejour,  
                    SUM(COALESCE(p_factures.montant_facture_h_actes_inclus_dans_sejour,0)) AS montant_facture_h_actes_inclus_dans_sejour,

                    0::numeric AS delai_groupage, 
                    0::numeric AS delai_facture, 
                    0::numeric AS delai_expedition, 
                    0::numeric AS delai_solde, 
                    0::numeric AS delai_expedition_0, 
                    0::numeric AS delai_solde_0, 
                    0::numeric AS delai_expedition_1, 
                    0::numeric AS delai_solde_1, 
                    0::numeric AS delai_expedition_2, 
                    0::numeric AS delai_solde_2, 
                    0::numeric AS delai_expedition_22, 
                    0::numeric AS delai_solde_22
                
                FROM activite[PX].p_sejours LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND type_facture <> 'P'
                GROUP BY 1,2,3,4,5;
                
                
                UPDATE activite[PX].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';


                UPDATE w_sejours_total SET  
                    date_groupage = CASE WHEN date_groupage > '00010101' THEN date_groupage ELSE '20991231' END,
                    date_facture = CASE WHEN date_facture> '00010101' THEN date_facture ELSE '20991231' END,
                    date_expedition = CASE WHEN date_expedition > '00010101' THEN date_expedition ELSE '20991231' END,
                    date_solde = CASE WHEN date_solde > '00010101' THEN date_solde ELSE '20991231' END,
                    date_expedition_0 = CASE WHEN date_expedition_0 > '00010101' THEN date_expedition_0 ELSE '20991231' END,
                    date_solde_0 = CASE WHEN date_solde_0 > '00010101' THEN date_solde_0 ELSE '20991231' END,
                    date_expedition_1 = CASE WHEN date_expedition_1 > '00010101' THEN date_expedition_1 ELSE '20991231' END,
                    date_solde_1 = CASE WHEN date_solde_1 > '00010101' THEN date_solde_1 ELSE '20991231' END,
                    date_expedition_2 = CASE WHEN date_expedition_2 > '00010101' THEN date_expedition_2 ELSE '20991231' END,
                    date_solde_2 = CASE WHEN date_solde_2 > '00010101' THEN date_solde_2 ELSE '20991231' END,
                    date_expedition_22 = CASE WHEN date_expedition_22 > '00010101' THEN date_expedition_22 ELSE '20991231' END,
                    date_solde_22 = CASE WHEN date_solde_22 > '00010101' THEN date_solde_22 ELSE '20991231' END;

                    
                UPDATE w_sejours_total SET  
                    delai_groupage = CASE WHEN code_sorti = '1' AND date_groupage > date_sortie AND date_groupage < '2099-12-31' AND ghs_id <> 0
                                THEN date_groupage  - date_sortie ELSE 0 END, 
                    delai_facture = CASE WHEN code_sorti = '1' AND date_facture  > date_sortie AND date_facture < '2099-12-31' AND date_facture > date_sortie  
                                THEN date_facture  - date_sortie ELSE 0 END, 
                    delai_expedition = CASE WHEN code_sorti = '1' AND date_expedition  > date_sortie AND date_facture < '2099-12-31' AND date_expedition < '2099-12-31'  
                                THEN date_expedition  - date_sortie ELSE 0 END, 
                    delai_solde = CASE WHEN code_sorti = '1' AND date_solde > date_sortie AND date_facture < '2099-12-31' AND date_solde < '2099-12-31'  
                                THEN date_solde - date_sortie ELSE 0 END, 
                    delai_expedition_0 = CASE WHEN code_sorti = '1' AND date_expedition_0 > date_sortie AND date_facture < '2099-12-31' AND date_expedition_0 < '2099-12-31'  
                                THEN date_expedition_0  - date_sortie ELSE 0 END, 
                    delai_solde_0 = CASE WHEN code_sorti = '1'AND date_solde_0 > date_sortie AND date_facture < '2099-12-31' AND date_solde_0 < '2099-12-31'  
                                THEN date_solde_0 - date_sortie ELSE 0 END, 
                    delai_expedition_1 = CASE WHEN code_sorti = '1' AND date_expedition_1 > date_sortie AND date_facture < '2099-12-31' AND date_expedition_1 < '2099-12-31'  
                                THEN date_expedition_1  - date_sortie ELSE 0 END, 
                    delai_solde_1 = CASE WHEN code_sorti = '1' AND date_solde_1 > date_sortie AND date_facture < '2099-12-31' AND date_solde_1 < '2099-12-31'  
                                THEN date_solde_1 - date_sortie ELSE 0 END, 
                    delai_expedition_2 = CASE WHEN code_sorti = '1' AND date_expedition_2 > date_sortie AND date_facture < '2099-12-31' AND date_expedition_2 < '2099-12-31'  
                                THEN date_expedition_2  - date_sortie ELSE 0 END, 
                    delai_solde_2 = CASE WHEN code_sorti = '1' AND date_solde_2 > date_sortie AND date_facture < '2099-12-31' AND date_solde_2 < '2099-12-31'  
                                THEN date_solde_2 - date_sortie ELSE 0 END, 
                    delai_expedition_22 = CASE WHEN code_sorti = '1' AND date_expedition_22 > date_sortie AND date_facture < '2099-12-31' AND date_expedition_22 < '2099-12-31'  
                                THEN date_expedition_22  - date_sortie ELSE 0 END, 
                    delai_solde_22 = CASE WHEN code_sorti = '1' AND date_solde_22 > date_sortie AND date_facture < '2099-12-31' AND date_solde_22 < '2099-12-31'  
                                THEN date_solde_22 - date_sortie ELSE 0 END;

                ALTER TABLE w_sejours_total  ADD CONSTRAINT w_sejours_total_pkey PRIMARY KEY(no_sejour);



                UPDATE activite[PX].p_sejours SET

                    date_facture = w_sejours_total.date_facture,  
                    date_expedition = w_sejours_total.date_expedition,  
                    date_solde = w_sejours_total.date_solde,  
                    montant_facture_c = w_sejours_total.montant_facture_c,  
                    montant_facture_h = w_sejours_total.montant_facture_h,  
                    montant_regle_c = w_sejours_total.montant_regle_c,  
                    montant_regle_h = w_sejours_total.montant_regle_h,  
                    nb_factures = w_sejours_total.nb_factures,  
                    nb_factures_regularisation = w_sejours_total.nb_factures_regularisation,  
                    nb_factures_rejet = w_sejours_total.nb_rejets,  

                    montant_facture_0_c = w_sejours_total.montant_facture_0_c,  
                    montant_facture_0_h = w_sejours_total.montant_facture_0_h,  
                    montant_regle_0_c = w_sejours_total.montant_regle_0_c,  
                    montant_regle_0_h = w_sejours_total.montant_regle_0_h,  
                    date_expedition_0 = w_sejours_total.date_expedition_0,  
                    date_solde_0 = w_sejours_total.date_solde_0,  

                    montant_facture_1_c = w_sejours_total.montant_facture_1_c,  
                    montant_facture_1_h = w_sejours_total.montant_facture_1_h,  
                    montant_regle_1_c = w_sejours_total.montant_regle_1_c,  
                    montant_regle_1_h = w_sejours_total.montant_regle_1_h,  
                    date_expedition_1 = w_sejours_total.date_expedition_1,   
                    date_solde_1 = w_sejours_total.date_solde_1,  
         
                    montant_facture_2_c = w_sejours_total.montant_facture_2_c,  
                    montant_facture_2_h = w_sejours_total.montant_facture_2_h,  
                    montant_regle_2_c = w_sejours_total.montant_regle_2_c,  
                    montant_regle_2_h = w_sejours_total.montant_regle_2_h,  
                    date_expedition_2 = w_sejours_total.date_expedition_2, 
                    date_solde_2 = w_sejours_total.date_solde_2,  
         
                    montant_facture_22_c = w_sejours_total.montant_facture_22_c,  
                    montant_facture_22_h = w_sejours_total.montant_facture_22_h,  
                    montant_regle_22_c = w_sejours_total.montant_regle_22_c,  
                    montant_regle_22_h = w_sejours_total.montant_regle_22_h,  
                    date_expedition_22 = w_sejours_total.date_expedition_22, 
                    date_solde_22 = w_sejours_total.date_solde_22,
                    
                    montant_comptabilise_c = w_sejours_total.montant_comptabilise_c,  
                    montant_comptabilise_h = w_sejours_total.montant_comptabilise_h,  
                    montant_comptabilise_0_c = w_sejours_total.montant_comptabilise_0_c,  
                    montant_comptabilise_0_h = w_sejours_total.montant_comptabilise_0_h,  
                    montant_comptabilise_1_c = w_sejours_total.montant_comptabilise_1_c,  
                    montant_comptabilise_1_h = w_sejours_total.montant_comptabilise_1_h,  
                    montant_comptabilise_2_c = w_sejours_total.montant_comptabilise_2_c,  
                    montant_comptabilise_2_h = w_sejours_total.montant_comptabilise_2_h,  
                    montant_comptabilise_22_c = w_sejours_total.montant_comptabilise_22_c,  
                    montant_comptabilise_22_h = w_sejours_total.montant_comptabilise_22_h,

                    montant_comptabilise_budget_global_c = w_sejours_total.montant_comptabilise_budget_global_c,

                    montant_facture_c_actes_inclus_dans_sejour = w_sejours_total.montant_facture_c_actes_inclus_dans_sejour,
                    montant_facture_h_actes_inclus_dans_sejour = w_sejours_total.montant_facture_h_actes_inclus_dans_sejour,


                    delai_groupage = w_sejours_total.delai_groupage, 
                    delai_facture = w_sejours_total.delai_facture, 
                    delai_expedition = w_sejours_total.delai_expedition, 
                    delai_solde = w_sejours_total.delai_solde, 
                    delai_expedition_0 = w_sejours_total.delai_expedition_0, 
                    delai_solde_0 = w_sejours_total.delai_solde_0, 
                    delai_expedition_1 = w_sejours_total.delai_expedition_1, 
                    delai_solde_1 = w_sejours_total.delai_solde_1, 
                    delai_expedition_2 = w_sejours_total.delai_expedition_2, 
                    delai_solde_2 = w_sejours_total.delai_solde_2, 
                    delai_expedition_22 = w_sejours_total.delai_expedition_22, 
                    delai_solde_22 = w_sejours_total.delai_solde_22
                    
                FROM w_sejours_total
                WHERE w_sejours_total.no_sejour =  p_sejours.no_sejour

                AND (
                    p_sejours.date_facture IS DISTINCT FROM w_sejours_total.date_facture OR   
                    p_sejours.date_expedition IS DISTINCT FROM w_sejours_total.date_expedition OR   
                    p_sejours.date_solde IS DISTINCT FROM w_sejours_total.date_solde OR   
                    p_sejours.montant_facture_c IS DISTINCT FROM w_sejours_total.montant_facture_c OR   
                    p_sejours.montant_facture_h IS DISTINCT FROM w_sejours_total.montant_facture_h OR   
                    p_sejours.montant_regle_c IS DISTINCT FROM w_sejours_total.montant_regle_c OR   
                    p_sejours.montant_regle_h IS DISTINCT FROM w_sejours_total.montant_regle_h OR   
                    p_sejours.nb_factures IS DISTINCT FROM w_sejours_total.nb_factures OR   
                    p_sejours.nb_factures_regularisation IS DISTINCT FROM w_sejours_total.nb_factures_regularisation OR   
                    p_sejours.nb_factures_rejet IS DISTINCT FROM w_sejours_total.nb_rejets OR   

                    p_sejours.montant_facture_0_c IS DISTINCT FROM w_sejours_total.montant_facture_0_c OR   
                    p_sejours.montant_facture_0_h IS DISTINCT FROM w_sejours_total.montant_facture_0_h OR   
                    p_sejours.montant_regle_0_c IS DISTINCT FROM w_sejours_total.montant_regle_0_c OR   
                    p_sejours.montant_regle_0_h IS DISTINCT FROM w_sejours_total.montant_regle_0_h OR   
                    p_sejours.date_expedition_0 IS DISTINCT FROM w_sejours_total.date_expedition_0 OR   
                    p_sejours.date_solde_0 IS DISTINCT FROM w_sejours_total.date_solde_0 OR   

                    p_sejours.montant_facture_1_c IS DISTINCT FROM w_sejours_total.montant_facture_1_c OR   
                    p_sejours.montant_facture_1_h IS DISTINCT FROM w_sejours_total.montant_facture_1_h OR   
                    p_sejours.montant_regle_1_c IS DISTINCT FROM w_sejours_total.montant_regle_1_c OR   
                    p_sejours.montant_regle_1_h IS DISTINCT FROM w_sejours_total.montant_regle_1_h OR   
                    p_sejours.date_expedition_1 IS DISTINCT FROM w_sejours_total.date_expedition_1 OR    
                    p_sejours.date_solde_1 IS DISTINCT FROM w_sejours_total.date_solde_1 OR   
         
                    p_sejours.montant_facture_2_c IS DISTINCT FROM w_sejours_total.montant_facture_2_c OR   
                    p_sejours.montant_facture_2_h IS DISTINCT FROM w_sejours_total.montant_facture_2_h OR   
                    p_sejours.montant_regle_2_c IS DISTINCT FROM w_sejours_total.montant_regle_2_c OR   
                    p_sejours.montant_regle_2_h IS DISTINCT FROM w_sejours_total.montant_regle_2_h OR   
                    p_sejours.date_expedition_2 IS DISTINCT FROM w_sejours_total.date_expedition_2 OR  
                    p_sejours.date_solde_2 IS DISTINCT FROM w_sejours_total.date_solde_2 OR   
         
                    p_sejours.montant_facture_22_c IS DISTINCT FROM w_sejours_total.montant_facture_22_c OR   
                    p_sejours.montant_facture_22_h IS DISTINCT FROM w_sejours_total.montant_facture_22_h OR   
                    p_sejours.montant_regle_22_c IS DISTINCT FROM w_sejours_total.montant_regle_22_c OR   
                    p_sejours.montant_regle_22_h IS DISTINCT FROM w_sejours_total.montant_regle_22_h OR   
                    p_sejours.date_expedition_22 IS DISTINCT FROM w_sejours_total.date_expedition_22 OR  
                    p_sejours.date_solde_22 IS DISTINCT FROM w_sejours_total.date_solde_22 OR 
                    
                    p_sejours.montant_comptabilise_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_c OR   
                    p_sejours.montant_comptabilise_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_h OR   
                    p_sejours.montant_comptabilise_0_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_0_c OR   
                    p_sejours.montant_comptabilise_0_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_0_h OR   
                    p_sejours.montant_comptabilise_1_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_1_c OR   
                    p_sejours.montant_comptabilise_1_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_1_h OR   
                    p_sejours.montant_comptabilise_2_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_2_c OR   
                    p_sejours.montant_comptabilise_2_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_2_h OR   
                    p_sejours.montant_comptabilise_22_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_22_c OR   
                    p_sejours.montant_comptabilise_22_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_22_h OR   

                    p_sejours.montant_comptabilise_budget_global_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_budget_global_c OR   

                    p_sejours.montant_facture_c_actes_inclus_dans_sejour IS DISTINCT FROM w_sejours_total.montant_facture_c_actes_inclus_dans_sejour OR   
                    p_sejours.montant_facture_h_actes_inclus_dans_sejour IS DISTINCT FROM w_sejours_total.montant_facture_h_actes_inclus_dans_sejour OR

                    p_sejours.delai_groupage IS DISTINCT FROM w_sejours_total.delai_groupage OR   
                    p_sejours.delai_facture IS DISTINCT FROM w_sejours_total.delai_facture OR   
                    p_sejours.delai_expedition IS DISTINCT FROM w_sejours_total.delai_expedition OR   
                    p_sejours.delai_solde IS DISTINCT FROM w_sejours_total.delai_solde OR   
                    p_sejours.delai_expedition_0 IS DISTINCT FROM w_sejours_total.delai_expedition_0 OR   
                    p_sejours.delai_solde_0 IS DISTINCT FROM w_sejours_total.delai_solde_0 OR   
                    p_sejours.delai_expedition_1 IS DISTINCT FROM w_sejours_total.delai_expedition_1 OR   
                    p_sejours.delai_solde_1 IS DISTINCT FROM w_sejours_total.delai_solde_1 OR   
                    p_sejours.delai_expedition_2 IS DISTINCT FROM w_sejours_total.delai_expedition_2 OR   
                    p_sejours.delai_solde_2 IS DISTINCT FROM w_sejours_total.delai_solde_2 OR   
                    p_sejours.delai_expedition_22 IS DISTINCT FROM w_sejours_total.delai_expedition_22 OR   
                    p_sejours.delai_solde_22 IS DISTINCT FROM w_sejours_total.delai_solde_22

                );
                
                -- Ajout des coordonnées des patients par séjour
                INSERT INTO activite[PX].p_coordonnees_patient (
					sejour_id,
					adresse,
					code_postal_id,
					commune,
					telephone_fixe,
					telephone_portable,
					email						
					)
                SELECT
					p_sejours.oid,
                    COALESCE(ADRPAT1, '') || CASE WHEN COALESCE(ADRPAT2, '') != '' THEN ' - ' || ADRPAT2 ELSE '' END,
					COALESCE(t_codes_postaux.oid,0),
					VILLEPAT,
					CASE 
						WHEN SUBSTRING(TELDOM, 1,2) NOT IN ('06', '07') AND TELDOM <> '' THEN TELDOM
						WHEN SUBSTRING(TELBUR, 1,2) NOT IN ('06', '07') AND TELBUR <> '' THEN TELBUR
   					ELSE ''::text END AS numero_fixe,
					CASE 
						WHEN SUBSTRING(TELDOM, 1,2) IN ('06', '07') AND TELDOM <> '' THEN TELDOM
						WHEN SUBSTRING(TELBUR, 1,2) IN ('06', '07') AND TELBUR <> '' THEN TELBUR
   					ELSE ''::text END AS numero_portable,
					COALESCE(COURRIEL1, COURRIEL2, ''::text) 
				FROM activite[PX].p_sejours
					LEFT JOIN prod_mederi.KDOSSIER ON p_sejours.code_original = KDOSSIER.NODOSSIER
					LEFT JOIN base.t_codes_postaux ON CPPAT = t_codes_postaux.code
				;	

                -- Suppression des tables de travail non utilisées après
                DROP TABLE IF EXISTS w_sejours_total CASCADE;
                                                        
                                        
            ]]></sqlcmd>
        </NODE>
        
    
        <NODE label="Tables répliquées">
        
            <condition><![CDATA[
                "[PX]" == ""
            ]]></condition>
            
            <sqlcmd><![CDATA[

                
                                        
            ]]></sqlcmd>
        </NODE>
    </NODE>
    
    <NODE name="ENCOURS" label="ENCOURS ET VALORISATION DES NON FACTURES">
    
        
        
    <NODE label="Encours Mederi">
            <sqlcmd><![CDATA[
            
                -- comptes associés
                INSERT INTO activite[PX].t_compte(oid, code_original, code, texte, texte_court) 
                SELECT 0, 0, '', 'Non renseigné', 'Non renseigné' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_compte);

                INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
                SELECT 
                    NOCOMPTE,
                    NOCOMPTE,
                    array_to_string(array_agg(distinct KACTES.NOACTE),',') ||' service' || CASE WHEN array_length(array_agg(distinct KCPTRUB.NOSERVINT),1) != 1 THEn 's ' ELSE ' ' END || array_to_string(array_agg(distinct KCPTRUB.NOSERVINT),','),
                    array_to_string(array_agg(distinct KACTES.NOACTE),',') ||' service' || CASE WHEN array_length(array_agg(distinct KCPTRUB.NOSERVINT),1) != 1 THEn 's ' ELSE ' ' END || array_to_string(array_agg(distinct KCPTRUB.NOSERVINT),',')
                    FROM prod_mederi.KCPTRUB 
                        JOIN prod_mederi.KACTES ON KACTES.NOACTE = KCPTRUB.NOACTE
                WHERE NOCOMPTE NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code_original IS NOT NULL)
                GROUP BY 1,2
                ORDER BY 1,2;
                
                        
                INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
                SELECT 
                    NOCOMPTES,
                    NOCOMPTES,
                    array_to_string(array_agg(distinct KACTES.NOACTE),',') ||' (tous services)',
                    array_to_string(array_agg(distinct KACTES.NOACTE),',') ||' (tous services)'
                    FROM prod_mederi.KRUBINT 
                      JOIN prod_mederi.KACTES ON KACTES.NOACTE = KRUBINT.NOACTE
                WHERE NOCOMPTES != ''
                    AND NOCOMPTES NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code_original IS NOT NULL)
                GROUP BY 1,2
                ORDER BY 1,2;
                
                DROP TABLE IF EXISTS w_FAC_FACTURE_DAT_CRE;
                CREATE TEMP TABLE w_FAC_FACTURE_DAT_CRE AS
                SELECT date(date_trunc('month', DATECREAT) + interval '1 month' - interval '1 day') AS date_encours, MAX(DATECREAT) AS FACT_DAT_CRE
                FROM prod_mederi.KENCOURS
                WHERE 
                    DATECREAT >= '[ENV_ADM_ANNEEDEBUT]1201' 
                GROUP BY 1
                ORDER BY 1;
    
                CREATE INDEX w_FAC_FACTURE_DAT_CRE_i1 ON w_FAC_FACTURE_DAT_CRE USING btree (date_encours);
    
                -- encours sur medecins salaries(vide dans les encours mederi)
                DROP TABLE IF EXISTS w_factures_encours_salaries;
                CREATE TEMP TABLE w_factures_encours_salaries AS
                SELECT
                    NOFAC,
                    SUM(MONTANT + MNTCOMPL) AS montant_encours_salaries,
                    SUM(MNTASS + MDASS) AS montant_encours_salaries_0,
                    SUM(MNTSS + MDCAI) AS montant_encours_salaries_1,
                    SUM(MNTMUT + MDMUT) AS montant_encours_salaries_2,
                    0::numeric AS montant_encours_22
                FROM prod_mederi.KENCOURS
                JOIN W_KPRAT ON KENCOURS.NOPRAT = W_KPRAT.NOPRAT AND CODETAB = 3
                JOIN activite.t_divers ON t_divers.code = 'MEDSAL_COMPTACLI' AND valeur = 1
                WHERE TYPERUB = 4
                GROUP BY 1
                ORDER BY 1;

                CREATE INDEX w_factures_encours_salaries_i1 ON w_factures_encours_salaries USING btree (NOFAC);
    
    
                -- entetes factures encours         
                DROP TABLE IF EXISTS w_factures_references;
                CREATE TEMP TABLE w_factures_references AS
                SELECT
                    no_sejour,
                    date_fin,
                    MIN(date_debut) AS date_debut,
                    MAX(no_facture) AS no_facture
                FROM activite[PX].p_factures
                WHERE no_facture_reference = no_facture AND code_facture >= '1'
                GROUP BY 1,2;
            
                CREATE INDEX w_factures_references_i1 ON w_factures_references USING btree (no_sejour);
    
    
                DROP TABLE IF EXISTS w_factures_encours;
                CREATE TEMP TABLE w_factures_encours AS
                SELECT
                        0::bigint AS oid,
                        CASE WHEN KENCOURS.NOFAC != '' THEN KENCOURS.NOFAC ELSE KENCOURS.NODOSSIER END as NOFAC,
                        min(p_sejours.finess) as finess,
                        min(p_sejours.no_sejour) as no_sejour,
                        min(p_sejours.date_entree) as date_entree,
                        min(p_sejours.date_sortie) as date_sortie,
                        min(p_sejours.oid) AS sejour_id,
                        min(p_sejours.lieu_sortie_id) as lieu_sortie_id,
                        min(COALESCE(w_factures_references.no_facture,'ID' || KENCOURS.NOFAC)  || '.EP' || substr(to_char(date_part('year', w_FAC_FACTURE_DAT_CRE.date_encours),'FM0000'),3,2) || to_char(date_part('month', w_FAC_FACTURE_DAT_CRE.date_encours),'FM00')) AS no_facture,
                        min(w_factures_references.no_facture) AS no_facture_reference,
                        min(DATEACTE) AS date_debut,
                        max(COALESCE(DATEFIN,DATEACTE)) AS date_fin,
                        min(w_FAC_FACTURE_DAT_CRE.date_encours) as date_encours,
                        'P'::text AS code_origine,
                        min(CASE WHEN date_sortie > date_encours OR date(DATESORTIE) > date_encours THEN '0' ELSE '1' END) AS code_sorti,
                        min(p_sejours.tiers_payant_1_id) as tiers_payant_1_id,
                        min(p_sejours.tiers_payant_2_id) as tiers_payant_2_id,
                        min(p_sejours.tiers_payant_22_id) as tiers_payant_22_id,
                        min(p_sejours.tiers_payant_0_id) as tiers_payant_0_id,
                        min(p_sejours.ghs_id) as ghs_id,
                        min(p_sejours.ghs_bebe1_id) as ghs_bebe1_id,
                        min(p_sejours.ghs_bebe2_id) as ghs_bebe2_id,
                        min(p_sejours.ghs_bebe3_id) as ghs_bebe3_id,
                        min(p_sejours.code_cp_demandee) as code_cp_demandee,
                        SUM(MNTSS + MNTMUT + MNTASS) + SUM(COALESCE(montant_encours_salaries,0)) AS montant_encours_c,
                        SUM(MNTASS) + SUM(COALESCE(montant_encours_salaries_0,0))  AS montant_encours_0_c,
                        SUM(MNTSS) + SUM(COALESCE(montant_encours_salaries_1,0))  AS montant_encours_1_c,
                        SUM(MNTMUT) + SUM(COALESCE(montant_encours_salaries_2,0))  AS montant_encours_2_c,
                        0::numeric AS montant_encours_22_c,
                        0::numeric AS montant_encours_h,
                        0::numeric AS montant_encours_0_h,
                        0::numeric AS montant_encours_1_h,
                        0::numeric AS montant_encours_2_h,
                        0::numeric AS montant_encours_22_h
                FROM prod_mederi.KENCOURS
                    LEFT JOIN prod_mederi.KFACTURE ON KENCOURS.NOFAC = KFACTURE.NOFAC
                    JOIN w_FAC_FACTURE_DAT_CRE ON date(KENCOURS.DATECREAT) = w_FAC_FACTURE_DAT_CRE.FACT_DAT_CRE AND
                        date(date_trunc('month', DATEFAC) + interval '1 month' - interval '1 day') = date_encours
                    JOIN prod_mederi.KDOSSIER ON KENCOURS.NODOSSIER = KDOSSIER.NODOSSIER
                    JOIN activite[PX].p_sejours ON code_original = KENCOURS.NODOSSIER
                    LEFT JOIN w_factures_references ON p_sejours.no_sejour = w_factures_references.no_sejour AND
                        date_sortie BETWEEN w_factures_references.date_debut AND w_factures_references.date_fin
                    LEFT JOIN w_factures_encours_salaries ON w_factures_encours_salaries.NOFAC = KENCOURS.NOFAC
                GROUP BY 2;
                
                CREATE INDEX w_factures_encours_i1 ON w_factures_encours USING btree (NOFAC);
    
                
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_2');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_4');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_5');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_6');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_7');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_8');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_9');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_10');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_11');
                
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_2');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_3');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_4');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_5');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_6');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_7');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_8');
    
                DELETE FROM activite[PX].p_factures_encours WHERE code_origine = 'P';
                DELETE FROM activite[PX].p_factures_encours_lignes_c
                    WHERE no_facture NOT IN (SELECT no_facture FROM activite[PX].p_factures_encours);
                    
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_1');
                SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_1');
    
                INSERT INTO activite[PX].p_factures_encours(
                    sejour_id,
                    no_sejour,
                    no_facture,
                    no_facture_reference,
                    date_debut,
                    date_fin,
                    date_encours,
                    code_origine,
                    code_sorti,
                    tiers_payant_1_id,
                    tiers_payant_2_id,
                    tiers_payant_22_id,
                    tiers_payant_0_id,
                    ghs_id,
                    ghs_bebe1_id,
                    ghs_bebe2_id,
                    ghs_bebe3_id,
                    code_cp_demandee,
                    montant_encours_c,
                    montant_encours_0_c,
                    montant_encours_1_c,
                    montant_encours_2_c,
                    montant_encours_22_c,
                    montant_encours_h,
                    montant_encours_0_h,
                    montant_encours_1_h,
                    montant_encours_2_h,
                    montant_encours_22_h
                    )
                SELECT
                    sejour_id,
                    no_sejour,
                    no_facture,
                    no_facture_reference,
                    date_debut,
                    date_fin,
                    date_encours,
                    code_origine,
                    code_sorti,
                    tiers_payant_1_id,
                    tiers_payant_2_id,
                    tiers_payant_22_id,
                    tiers_payant_0_id,
                    ghs_id,
                    ghs_bebe1_id,
                    ghs_bebe2_id,
                    ghs_bebe3_id,
                    code_cp_demandee,
                    montant_encours_c,
                    montant_encours_0_c,
                    montant_encours_1_c,
                    montant_encours_2_c,
                    montant_encours_22_c,
                    montant_encours_h,
                    montant_encours_0_h,
                    montant_encours_1_h,
                    montant_encours_2_h,
                    montant_encours_22_h
                FROM w_factures_encours;
        
                UPDATE w_factures_encours SET oid = p_factures_encours.oid
                FROM activite[PX].p_factures_encours 
                WHERE w_factures_encours.no_facture = p_factures_encours.no_facture;
                
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_1');
        
                DROP SEQUENCE IF EXISTS w_factures_encours_lignes_c_sequence;
                CREATE TEMP SEQUENCE w_factures_encours_lignes_c_sequence;
        
                DROP TABLE IF EXISTS w_factures_encours_lignes_c;
                CREATE TEMP TABLE w_factures_encours_lignes_c AS
                SELECT
                    nextval('w_factures_encours_lignes_c_sequence'::regclass) AS oid,
                    no_sejour,
                    CASE WHEN KENCOURS.NOFAC != '' THEN KENCOURS.NOFAC ELSE KENCOURS.NODOSSIER END AS NOFAC,
                    w_factures_encours.oid AS facture_id,
                    w_factures_encours.no_facture,
                    w_factures_encours.date_entree,
                    w_factures_encours.date_sortie,
                    date(DATEACTE) AS date_debut,
                    COALESCE(date(DATEFIN),date(DATEACTE)) AS date_fin,
                    COEFF AS nb_rubrique,
                    1::numeric AS coefficient,
                    1 AS coefficient_mco,
                    COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_facturation_id, 
                    COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
                    MAX(COALESCE(t_compte.oid::bigint, 0)) AS compte_produit_id, 
                    COALESCE(t_prestations.oid::bigint, 0) AS prestation_id, 
                    

                    PRIXU AS prix_unitaire,
                    w_factures_encours.lieu_sortie_id AS lieu_id,
                    QTE AS nb_prestation,
        
                    AVG(1-TAUXSS-TAUXMUT) as taux_0,
                    AVG(TAUXSS) as taux_1,
                    AVG(TAUXMUT) as taux_2,
                    0::numeric as taux_22,
                    
                    SUM(MONTANT) AS montant_encours,
                    SUM(MNTASS) AS montant_encours_0,
                    SUM(MNTSS) AS montant_encours_1,
                    SUM(MNTMUT) AS montant_encours_2,
                    SUM(0) AS montant_encours_22
    
                FROM prod_mederi.KENCOURS
                    JOIN w_factures_encours ON CASE WHEN KENCOURS.NOFAC = '' THEN KENCOURS.NODOSSIER = w_factures_encours.NOFAC ELSE KENCOURS.NOFAC = w_factures_encours.NOFAC END
                    LEFT JOIN activite[PX].t_rubriques_facturation ON KENCOURS.NOACTE = t_rubriques_facturation.code_original
                    LEFT JOIN prod_mederi.KRUBINT ON KENCOURS.NOACTE = KRUBINT.NOACTE
                    LEFT JOIN (SELECT NOACTE, NOSERVINT, MAX(NOCOMPTE) AS NOCOMPTE FROM prod_mederi.KCPTRUB GROUP BY 1,2) sub ON KENCOURS.NOSERVINT = sub.NOSERVINT AND KENCOURS.NOACTE = sub.NOACTE
                    LEFT JOIN activite.t_prestations ON NOACTESS = t_prestations.code
                    LEFT JOIN activite[PX].t_compte ON (NOCOMPTE IS NOT NULL AND NOCOMPTE::bigint = t_compte.code_original) OR (NOCOMPTE IS NULL  AND NOCOMPTES::bigint = t_compte.code_original::bigint)
                WHERE KENCOURS.TYPERUB <> 4 --pas d'encours mederiu sur salariés
                GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19
                ORDER BY 1;
    
    
        
    
                DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c;
                CREATE TEMP TABLE w_factures_encours_lignes_sup_c AS
                SELECT
                    w_factures_encours_lignes_c.oid AS from_oid,
                    t_prestations.code AS prestation_code,
                    date(date_debut) AS date_debut_ghs,
                    date(date_fin - interval '1 day') AS date_fin_ghs,
                    (date(date_fin) - date(date_debut)) * CASE WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation_ghs,
                    CASE WHEN t_prestations.code = 'GHS' THEN date(w_factures_encours_lignes_c.date_entree + interval '1 day') ELSE date(w_factures_encours_lignes_c.date_debut + interval '1 day') END AS date_debut_det,
                    CASE WHEN t_prestations.code = 'GHS' THEN date(w_factures_encours_lignes_c.date_sortie - interval '1 day') ELSE date(w_factures_encours_lignes_c.date_debut + ((ABS(nb_prestation)-1) || ' day')::interval)  END AS date_fin_det,
                    ABS(CASE WHEN t_prestations.code = 'GHS' THEN date(w_factures_encours_lignes_c.date_sortie) - date(w_factures_encours_lignes_c.date_entree) ELSE nb_prestation END) AS nb_det,
                    w_factures_encours_lignes_c.*
                FROM w_factures_encours_lignes_c
                    JOIN activite[PX].p_sejours ON w_factures_encours_lignes_c.no_sejour = p_sejours.no_sejour
                    JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND 
                        (
                        code IN ('PJ', 'PJ1', 'PJ2', 'FJ', 'SSM', 'GHS', 'EXH', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO') OR
                        t_prestations.type_ventilation_jour = '1'
                        )
                WHERE (nb_prestation > 1 or nb_prestation < -1 OR (t_prestations.code = 'GHS' AND date(date_fin) - date(date_debut) > 1)) ;

    
                UPDATE w_factures_encours_lignes_sup_c SET 
                    date_fin_ghs = date(date_debut_exh - interval '1 day'),
                    date_fin_det = date(date_debut_exh - interval '1 day'),
                    nb_prestation_ghs = date(date_debut_exh - interval '1 day') - date_debut_ghs + 1,
                    nb_det = date(date_debut_exh - interval '1 day') - date_debut_ghs + 1
                FROM (
                    SELECT no_facture, date(MIN(date_debut)) AS date_debut_exh
                    FROM w_factures_encours_lignes_c
                        JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND code = 'EXH'
                    GROUP BY 1) subview
                WHERE w_factures_encours_lignes_sup_c.no_facture = subview.no_facture;

                CREATE INDEX w_factures_encours_lignes_sup_c_i1
                  ON w_factures_encours_lignes_sup_c
                  USING btree
                  (date_debut);
        
                DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c_gen;
                CREATE TEMP TABLE w_factures_encours_lignes_sup_c_gen AS
                SELECT
                    from_oid,
                    ''::text AS finess,
                    no_sejour,
                    no_facture,
                    facture_id,
                    date AS date_debut,
                    date AS date_fin,
                    lieu_id,
                    rubrique_facturation_id,
                    rubrique_comptabilisation_id,
                    compte_produit_id,
                    prestation_id,
                    CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_rubrique,
                    CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation,
                    coefficient,
                    coefficient_mco,
                    prix_unitaire,
                    oid,
                    taux_0,
                    taux_1,
                    taux_2,
                    taux_22,
                    round(montant_encours / ABS(nb_det),2) AS montant_encours,
                    round(montant_encours_0 / ABS(nb_det),2) AS montant_encours_0,
                    round(montant_encours_1 / ABS(nb_det),2) AS montant_encours_1,
                    round(montant_encours_2 / ABS(nb_det),2) AS montant_encours_2,
                    round(montant_encours_22 / ABS(nb_det),2) AS montant_encours_22
                FROM w_factures_encours_lignes_sup_c
                    JOIN base.p_calendrier ON p_calendrier.date BETWEEN date_debut_det AND date_fin_det ;
    
    
                DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c_gen_tot;
                CREATE TEMP TABLE w_factures_encours_lignes_sup_c_gen_tot AS
                SELECT from_oid,
                    SUM(nb_rubrique) AS nb_rubrique,
                    SUM(nb_prestation) AS nb_prestation,
                    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
                FROM w_factures_encours_lignes_sup_c_gen
                GROUP BY 1;


                UPDATE w_factures_encours_lignes_c
                SET
                    date_fin = w_factures_encours_lignes_c.date_debut,
                    nb_rubrique = w_factures_encours_lignes_c.nb_rubrique - w_factures_encours_lignes_sup_c_gen_tot.nb_rubrique,
                    nb_prestation = w_factures_encours_lignes_c.nb_prestation - w_factures_encours_lignes_sup_c_gen_tot.nb_prestation,
                    montant_encours = w_factures_encours_lignes_c.montant_encours - w_factures_encours_lignes_sup_c_gen_tot.montant_encours,
                    montant_encours_0 = w_factures_encours_lignes_c.montant_encours_0 - w_factures_encours_lignes_sup_c_gen_tot.montant_encours_0,
                    montant_encours_1 = w_factures_encours_lignes_c.montant_encours_1 - w_factures_encours_lignes_sup_c_gen_tot.montant_encours_1,
                    montant_encours_2 = w_factures_encours_lignes_c.montant_encours_2 - w_factures_encours_lignes_sup_c_gen_tot.montant_encours_2,
                    montant_encours_22 = w_factures_encours_lignes_c.montant_encours_22 - w_factures_encours_lignes_sup_c_gen_tot.montant_encours_22
                FROM w_factures_encours_lignes_sup_c_gen_tot
                WHERE w_factures_encours_lignes_c.oid = from_oid;
    
    
                INSERT INTO w_factures_encours_lignes_c(
                    oid,
                    no_sejour,
                    facture_id,
                    no_facture,
                    date_debut,
                    date_fin,
                    nb_rubrique,
                    coefficient,
                    coefficient_mco,
                    rubrique_facturation_id, 
                    rubrique_comptabilisation_id,
                    compte_produit_id,
                    prestation_id, 
                    taux_0,
                    taux_1,
                    taux_2,
                    taux_22,
                    prix_unitaire,
                    lieu_id,
                    nb_prestation,
                    montant_encours,
                    montant_encours_0,
                    montant_encours_1,
                    montant_encours_2,
                    montant_encours_22)
                SELECT
                    nextval('w_factures_encours_lignes_c_sequence'::regclass) AS oid,
                    no_sejour,
                    facture_id,
                    no_facture,
                    date_debut,
                    date_fin,
                    nb_rubrique,
                    coefficient,
                    coefficient_mco,
                    rubrique_facturation_id, 
                    rubrique_comptabilisation_id,
                    compte_produit_id,
                    prestation_id, 
                    taux_0,
                    taux_1,
                    taux_2,
                    taux_22,
                    prix_unitaire,
                    lieu_id,
                    nb_prestation,
                    montant_encours,
                    montant_encours_0,
                    montant_encours_1,
                    montant_encours_2,
                    montant_encours_22
                FROM w_factures_encours_lignes_sup_c_gen;
    
    
    
                UPDATE w_factures_encours_lignes_c 
                SET lieu_id = p_mouvements_sejour.lieu_id
                FROM activite[PX].p_mouvements_sejour
                WHERE w_factures_encours_lignes_c.no_sejour = p_mouvements_sejour.no_sejour AND
                    w_factures_encours_lignes_c.date_debut = p_mouvements_sejour.date AND 
                    (p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.nb_sorties_directes = 1) AND
                    w_factures_encours_lignes_c.lieu_id IS DISTINCT FROM p_mouvements_sejour.lieu_id;
    
                
    
                INSERT INTO activite[PX].p_factures_encours_lignes_c(
                    facture_id,
                    no_facture,
                    date_debut,
                    date_fin,
                    nb_rubrique,
                    coefficient,
                    coefficient_mco,
                    rubrique_facturation_id,
                    rubrique_comptabilisation_id,
                    compte_produit_id,
                    prestation_id,
                    taux_0,
                    taux_1,
                    taux_2,
                    taux_22,
                    prix_unitaire,
                    lieu_id,
                    nb_prestation,
                    montant_encours,
                    montant_encours_0,
                    montant_encours_1,
                    montant_encours_2,
                    montant_encours_22
                )
                SELECT
                    facture_id,
                    no_facture,
                    date_debut,
                    date_fin,
                    nb_rubrique,
                    coefficient,
                    coefficient_mco,
                    rubrique_facturation_id,
                    rubrique_comptabilisation_id,
                    compte_produit_id,
                    prestation_id,
                    taux_0,
                    taux_1,
                    taux_2,
                    taux_22,
                    prix_unitaire,
                    lieu_id,
                    nb_prestation,
                    montant_encours,
                    montant_encours_0,
                    montant_encours_1,
                    montant_encours_2,
                    montant_encours_22
                FROM w_factures_encours_lignes_c;
                
                
                SELECT base.cti_vacuum_table('activite[PX]','p_factures_encours');
                SELECT base.cti_vacuum_table('activite[PX]','p_factures_encours_lignes_c');
                
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_1');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_2');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_3');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_4');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_5');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_6');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_7');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_8');
                
                
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_2');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_4');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_5');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_6');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_7');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_8');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_9');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_10');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_11');
                
                -- Suppression des tables de travail non utilisées après
                DROP TABLE IF EXISTS w_compte CASCADE;
                DROP TABLE IF EXISTS w_factures_encours_salaries CASCADE;
                DROP TABLE IF EXISTS w_factures_references CASCADE;
                DROP TABLE IF EXISTS w_FAC_FACTURE_DAT_CRE CASCADE;
                DROP TABLE IF EXISTS w_factures_encours CASCADE;
                DROP TABLE IF EXISTS w_factures_encours_lignes_c CASCADE;
                DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c CASCADE;
                DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c_gen CASCADE;
                DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c_gen_tot CASCADE;
                
                DROP TABLE IF EXISTS w_DOSSIER;
            ]]></sqlcmd>
        </NODE>
     
    </NODE>
    

</ROOT>
