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

		<NODE label="Identification des séjours">
			<sqlcmd><![CDATA[
			
				-- Correction des heures
				
				UPDATE prod_sigems2.DOSSIER
				SET HEU_DOS =  to_char(to_number('00' || HEU_DOS,'0000'),'FM00')
				WHERE HEU_DOS <> to_char(to_number('00' || HEU_DOS,'0000'),'FM00');


				UPDATE prod_sigems2.DOSSIER
				SET MIN_DOS =  to_char(to_number('00' || MIN_DOS,'0000'),'FM00')
				WHERE MIN_DOS <> to_char(to_number('00' || MIN_DOS,'0000'),'FM00');
				
				
				UPDATE prod_sigems2.SEJOUR
				SET HEU_SEJ =  to_char(to_number('00' || HEU_SEJ,'0000'),'FM00')
				WHERE HEU_SEJ <> to_char(to_number('00' || HEU_SEJ,'0000'),'FM00');
				
				
				UPDATE prod_sigems2.DOSSIER
				SET HEU_DOS = MIN_DOS
				WHERE DEN_DOS = DSO_DOS AND MIN_DOS > HEU_DOS AND HEU_DOS = '00';
				
				
				-- Correction etat factures sur factures nulles non éditées -> comptabilisées
				UPDATE prod_sigems2.dos2 
				SET ETA_DOS2 = 5
				WHERE ETA_DOS2 = 2 AND DFA_DOS2 IS NOT NULL AND
					SJ1_DOS2 = 0 AND SJ2_DOS2 = 0 AND SJ3_DOS2 = 0 AND 
					HO1_DOS2 = 0 AND HO2_DOS2 = 0 AND HO3_DOS2 = 0;
					
				-- Correction anomalie : séjours en double chez SIGEMS
				SELECT base.cti_execute(
				'DELETE FROM prod_sigems2.DOSSIER
				USING 
					(
					SELECT ANN_DOS, COD_DOS, MAX(CTID) AS del_CTID 
					FROM prod_sigems2.DOSSIER
					GROUP BY 1,2
					HAVING count(*) > 1
					) subview
				WHERE DOSSIER.CTID = del_CTID',20);
				
				
				-- Correction anomalie : Factures en double chez SIGEMS
				DROP TABLE IF EXISTS w_DOS2_double;
				CREATE TEMP TABLE w_DOS2_double AS
				SELECT ANN_DOS2, 
					COD_DOS2, 
					IND_DOS2 
				FROM prod_sigems2.DOS2
				GROUP BY 1,2,3
				HAVING count(*) > 1 AND
					SUM(CASE WHEN ETA_DOS2 >= 2 THEN 1 ELSE 0 END) = 1;

				DELETE FROM prod_sigems2.DOS2
				USING w_DOS2_double
				WHERE DOS2.ANN_DOS2 = w_DOS2_double.ANN_DOS2 AND
					DOS2.COD_DOS2 = w_DOS2_double.COD_DOS2 AND
					DOS2.IND_DOS2 = w_DOS2_double.IND_DOS2 AND
					ETA_DOS2 <= 1;
				
				DELETE FROM prod_sigems2.DOS2
				USING 
					(
					SELECT ANN_DOS2, COD_DOS2, IND_DOS2, MAX(CTID) AS del_CTID 
					FROM prod_sigems2.dos2
					GROUP BY 1,2,3
					HAVING count(*) > 1
					) subview
				WHERE DOS2.CTID = del_CTID;
				
				DELETE FROM prod_sigems2.DOS2
				USING 
					(
					SELECT ANN_DOS2, COD_DOS2, IND_DOS2, MAX(CTID) AS del_CTID 
					FROM prod_sigems2.dos2
					GROUP BY 1,2,3
					HAVING count(*) > 1
					) subview
				WHERE DOS2.CTID = del_CTID;				

				-- Correction montants réglés sur factures annulées
				
				UPDATE prod_sigems2.DOS2
				SET 
					SR1_DOS2 = SJ1_DOS2,
					SR2_DOS2 = SJ2_DOS2,
					SR3_DOS2 = SJ3_DOS2,
					HR1_DOS2 = HO1_DOS2,
					HR2_DOS2 = HO2_DOS2,
					HR3_DOS2 = HO3_DOS2
				WHERE ETA_DOS2 IN ('4','5') AND
					COP_DOS2 = '1' AND
					(
						SR1_DOS2 IS DISTINCT FROM SJ1_DOS2 OR
						SR2_DOS2 IS DISTINCT FROM SJ2_DOS2 OR
						SR3_DOS2 IS DISTINCT FROM SJ3_DOS2 OR
						HR1_DOS2 IS DISTINCT FROM HO1_DOS2 OR
						HR2_DOS2 IS DISTINCT FROM HO2_DOS2 OR
						HR3_DOS2 IS DISTINCT FROM HO3_DOS2
					);

				-- Correction lignes affectée à indice 0 au lieu de 1
				UPDATE prod_sigems2.LIG_CLINI
				SET IND_LCL = 1
				FROM 
				(
					SELECT ANN_LCL, COD_LCL
					FROM prod_sigems2.LIG_CLINI
					JOIN prod_sigems2.DOS2 ON ANN_LCL = ANN_DOS2 AND COD_LCl = COD_DOS2 AND IND_DOS2 = 1 AND ETA_DOS2 >= 4
					WHERE IND_LCL IN (0,1) AND
						(ML1_LCL <> 0 OR ML2_LCL <> 0 OR ML3_LCL <> 0)
					GROUP BY 1,2
					HAVING MIN(IND_LCL) = 0 AND
						MAX(SJ1_DOS2) = SUM(ML1_LCL) AND
						MAX(SJ2_DOS2) = SUM(ML2_LCL) AND
						MAX(SJ3_DOS2) = SUM(ML3_LCL)
				) SUBVIEW
				WHERE LIG_CLINI.ANN_LCL = subview.ANN_LCL AND
					LIG_CLINI.COD_LCL = subview.COD_LCL AND
					LIG_CLINI.IND_LCL = 0;
				
				-- Lignes non facturées -> facture non calculée
				UPDATE prod_sigems2.LIG_CLINI
				SET IND_LCL = IND_DOS2
				FROM prod_sigems2.DOS2
				WHERE IND_LCL = 0 AND
					ANN_LCL = ANN_DOS2 AND COD_LCL = COD_DOS2 AND 
					ETA_DOS2 <= 2 AND DDE_LCL BETWEEN DEN_DOS2 AND DSO_DOS2 AND
					(ML1_LCL <> 0 OR
					ML2_LCL <> 0 OR
					ML3_LCL <> 0 OR
					PUN_LCL <> 0);
				
			
				-- Correction doublons
				UPDATE prod_sigems2.dossier_x 
				SET ANN_DOX = 'KO'
				FROM
				(
				select ann_dox, cod_dox, min(CTID) AS koctid from prod_sigems2.dossier_x
				group by 1,2
				having count(*) > 1
				) subview
				where CTID = koctid;
				
				UPDATE prod_sigems2.DOSSIER_MDT
				SET ANN_DOS = 'KO'
				FROM
				(
				SELECT ANN_DOS, COD_DOS, min(CTID) AS koctid 
				FROM prod_sigems2.DOSSIER_MDT
				GROUP BY 1,2
				HAVING count(*) > 1
				) subview
				WHERE CTID = koctid;
				
				-- Table de travail règlements clinique
				
				DROP TABLE IF EXISTS w_REG4;
				CREATE TEMP TABLE w_REG4 AS
				SELECT *
				FROM prod_sigems2.REG
				JOIN prod_sigems2.REG4 ON NUM_REG4 = SER_REG;

				CREATE INDEX w_REG4_i1
				  ON w_REG4
				  USING btree
				  (NUM_CLI);


				
				-- Table de travail règlements honoraires
				
				DROP TABLE IF EXISTS w_REG3;
				CREATE TEMP TABLE w_REG3 AS
				SELECT *
				FROM prod_sigems2.REG
				JOIN prod_sigems2.REG3 ON SER_REG3 = SER_REG;

				CREATE INDEX w_REG3_i1
				  ON w_REG3
				  USING btree
				  (LHO_REG3);
				
				-- Période (dernier mouvement pour détection now())
				DROP TABLE IF EXISTS w_PERIODE;
				CREATE TEMP TABLE w_PERIODE AS
				SELECT 
					0::bigint AS periode_id,
					CASE WHEN date_part('hour', DT_SIGEMS) < 9 THEN DATE(DT_SIGEMS - INTERVAL '1 day') ELSE date(DT_SIGEMS) END AS now_sigems,
					CASE WHEN date_part('hour', DT_SIGEMS) < 9 THEN DATE(DT_SIGEMS) ELSE date(DT_SIGEMS + INTERVAL '1 day') END AS now_sigems_1
				FROM (
					SELECT greatest(max(DT_CREATION), max(DT_VALIDATION), max(DT_CALCUL), max(DT_EDITION), max(DT_TELETRANS)) as DT_SIGEMS
					FROM prod_sigems2.HISTO_DOS
					WHERE  1=1
						AND (DT_CREATION is null OR DT_CREATION <= now())
						AND (DT_VALIDATION is null OR DT_VALIDATION <= now())
						AND (DT_CALCUL is null OR DT_CALCUL <= now())
						AND (DT_EDITION is null OR DT_EDITION <= now())
						AND (DT_TELETRANS is null OR DT_TELETRANS <= now())
					HAVING count(*) > 0
				) subview;


				INSERT INTO w_PERIODE
				SELECT 
					0::bigint AS periode_id,
					CASE WHEN date_part('hour', DT_CREATION) < 9 THEN DATE(DT_CREATION - INTERVAL '1 day') ELSE date(DT_CREATION) END AS now_sigems,
					CASE WHEN date_part('hour', DT_CREATION) < 9 THEN DATE(DT_CREATION) ELSE date(DT_CREATION + INTERVAL '1 day') END AS now_sigems_1
				FROM (
					SELECT now() AS DT_CREATION WHERE (SELECT COUNT(*) FROM w_PERIODE) = 0
				) subview;
				
				
				-- Selection
				
				DROP TABLE IF EXISTS w_DOSSIER_SELECT;

				CREATE TEMP TABLE w_DOSSIER_SELECT AS
				SELECT 
					ANN_DOS AS ANN_SELECT, 
					COD_DOS AS COD_SELECT,
					ANN_DOS || to_char(COD_DOS,'FM900000') AS no_sejour_SELECT,
					0::text AS type_t2a,
					0::text AS est_budget_global,
					0::text AS avec_facturation_intermediaire
				FROM prod_sigems2.DOSSIER
				WHERE DSO_DOS >= '[ENV_ADM_ANNEEDEBUT]0101' OR DSO_DOS IS NULL;

				CREATE INDEX w_DOSSIER_SELECT_i1
								  ON w_DOSSIER_SELECT
								  USING btree
								  (COD_SELECT);
								  
				DELETE FROM w_DOSSIER_SELECT
				USING prod_sigems2.SUPPRESSION_DOS 
				WHERE ANN_SELECT = ANNEE AND
					COD_SELECT = CODE;
					

				INSERT INTO w_DOSSIER_SELECT
				SELECT 
					ANN_DOS2, 
					COD_DOS2,
					ANN_DOS2 || to_char(COD_DOS2,'FM900000')
				FROM prod_sigems2.DOS2
				LEFT JOIN w_DOSSIER_SELECT ON ANN_DOS2 = ANN_SELECT AND COD_DOS2 = COD_SELECT
				WHERE ETA_DOS2 >= 3 AND	ANN_SELECT IS NULL
				GROUP BY 1,2,3
				HAVING (
					MAX(COALESCE(DFA_DOS2, '20991231')) >= '[ENV_ADM_ANNEEDEBUT]0101' OR
					SUM(SR1_DOS2) <> SUM(SJ1_DOS2) OR
					SUM(SR2_DOS2) <> SUM(SJ2_DOS2) OR
					SUM(SR3_DOS2) <> SUM(SJ3_DOS2) OR
					SUM(HR1_DOS2) <> SUM(HO1_DOS2) OR
					SUM(HR2_DOS2) <> SUM(HO2_DOS2) OR
					SUM(HR3_DOS2) <> SUM(HO3_DOS2)
					)
				ORDER BY 1,2;



				INSERT INTO w_DOSSIER_SELECT
				SELECT 
					ANN_LCL, 
					COD_LCL,
					ANN_LCL || to_char(COD_LCL,'FM900000') 
				FROM
				(
				SELECT ANN_LCL, COD_LCL FROM prod_sigems2.LIG_CLINI
									JOIN prod_sigems2.REG4 ON NUM_LCL = NUM_CLI
									JOIN prod_sigems2.REG ON NUM_REG4 = SER_REG
				WHERE DAT_REG >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1,2
				) subview
				LEFT JOIN w_DOSSIER_SELECT ON ANN_LCL = ANN_SELECT AND COD_LCL = COD_SELECT
				WHERE ANN_SELECT IS NULL;

				INSERT INTO w_DOSSIER_SELECT
				SELECT 
					ANN_LHO, 
					COD_LHO,
					ANN_LHO || to_char(COD_LHO,'FM900000')  
				FROM
				(
				SELECT ANN_LHO, COD_LHO FROM prod_sigems2.LIG_HONOR
									JOIN w_REG3 ON NUM_LHO = LHO_REG3
				WHERE DAT_REG >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1,2
				) subview
				LEFT JOIN w_DOSSIER_SELECT ON ANN_LHO = ANN_SELECT AND COD_LHO = COD_SELECT
				WHERE ANN_SELECT IS NULL;
				
				-- Suppression des prévus non rentrés ou prévus dans plus d'un mois
				DELETE FROM w_DOSSIER_SELECT 
				USING prod_sigems2.DOSSIER
				WHERE ANN_SELECT = 'PA' AND
					ANN_SELECT = ANN_DOS AND
					COD_SELECT = COD_DOS AND
					DEN_DOS <= date(NOW() - interval '1 days');

				DELETE FROM w_DOSSIER_SELECT 
				USING prod_sigems2.DOSSIER
				WHERE ANN_SELECT = 'PA' AND
					ANN_SELECT = ANN_DOS AND
					COD_SELECT = COD_DOS AND
					DEN_DOS > date(NOW() + interval '1 month');

				
				CREATE INDEX w_DOSSIER_SELECT_i2
					ON w_DOSSIER_SELECT
					USING btree
					(no_sejour_SELECT);
					
					


				
					
					
			]]></sqlcmd>
		</NODE>
					
		
	</NODE>

	<NODE name="SEJOUR" label="RECUPERATION DES SEJOURS">
	
		<NODE label="Patients">
			<sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_PATIENT;
				CREATE TEMP TABLE w_PATIENT AS
				SELECT 
					COD_PAT, 
					(CASE WHEN IPP IS NOT NULL THEN IPP ELSE COD_PAT END)::text AS no_patient,
					s_dos.ANN_DOS || to_char(s_dos.COD_DOS,'FM900000') AS SEJ_NUM,
					MAX(CASE WHEN NMA_PAT <> '' THEN NMA_PAT ELSE NOM_PAT END) AS NOM_PAT, 
					MAX(PRE_PAT) AS PRE_PAT, 
					MAX(NOM_PAT) AS NNA_PAT, 
					MAX(date(DNA_PAT)) AS DNA_PAT,
					MAX(SEX_PAT) AS SEX_PAT,
					MAX(AD1_PAT) AS AD1_PAT,
					MAX(AD2_PAT) AS AD2_PAT,
					MAX(CPO_PAT) AS CPO_PAT,
					MAX(VIL_PAT) AS VIL_PAT,
					MAX(TEL_PAT) AS TEL_PAT
				FROM prod_sigems2.PATIENT
					JOIN (SELECT CPH_DOS, ANN_DOS, COD_DOS FROM prod_sigems2.DOSSIER 
								JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_DOS = ANN_SELECT AND COD_DOS = COD_SELECT) s_dos ON CPH_DOS = COD_PAT
					LEFT JOIN (
								SELECT 
									ANN_DOS, COD_DOS, (MAX(Array[id_fic,ipp]))[2] AS IPP
								FROM 
									prod_sigems2.HPRIM_FIC_DETAIL GROUP BY 1,2) s_ipp ON s_ipp.COD_DOS = s_dos.COD_DOS AND s_ipp.ANN_DOS = s_dos.ANN_DOS
				GROUP BY 1,2,3;
				
				UPDATE w_PATIENT SET
					NOM_PAT = pool.NOM_PAT,
					PRE_PAT = pool.PRE_PAT,
					DNA_PAT = pool.DNA_PAT,
					NNA_PAT = pool.NNA_PAT
				FROM (
				SELECT 
					DISTINCT no_patient,
					last_value(NOM_PAT) OVER (PARTITION BY no_patient ORDER BY SEJ_NUM rows between unbounded preceding and unbounded following) AS NOM_PAT,
					last_value(PRE_PAT) OVER (PARTITION BY no_patient ORDER BY SEJ_NUM rows between unbounded preceding and unbounded following) AS PRE_PAT,
					last_value(DNA_PAT) OVER (PARTITION BY no_patient ORDER BY SEJ_NUM rows between unbounded preceding and unbounded following) AS DNA_PAT,
					last_value(NOM_PAT) OVER (PARTITION BY no_patient ORDER BY SEJ_NUM rows between unbounded preceding and unbounded following) AS NNA_PAT
				FROM w_patient) pool
				WHERE pool.no_patient = w_PATIENT.no_patient;
				
				CREATE INDEX w_PATIENT_i1
				  ON w_PATIENT 
				  USING btree
				  (COD_PAT);

				CREATE INDEX w_PATIENT_i2
				  ON w_PATIENT 
				  USING btree
				 (no_patient);
				  
				UPDATE activite[PX].p_patients
				SET nom = NOM_PAT, 
					nom_naissance = NNA_PAT, 
					prenom = PRE_PAT, 
					date_naissance = DNA_PAT
				FROM w_PATIENT 
				WHERE p_patients.no_patient = w_PATIENT.no_patient
					AND (
						p_patients.nom IS DISTINCT FROM NOM_PAT OR 
						p_patients.prenom IS DISTINCT FROM PRE_PAT OR
						nom_naissance IS DISTINCT FROM NNA_PAT OR
						p_patients.date_naissance IS DISTINCT FROM date(DNA_PAT)
					);

				INSERT INTO activite[PX].p_patients(finess, no_patient, nom, prenom, nom_naissance, date_naissance)
				SELECT '', w_PATIENT.no_patient, MAX(NOM_PAT), MAX(PRE_PAT), MAX(NNA_PAT), MAX(DNA_PAT)
				FROM w_PATIENT 
					LEFT JOIN activite[PX].p_patients ON (w_PATIENT.no_patient = p_patients.no_patient)
				WHERE p_patients.no_patient IS NULL
				GROUP BY 1,2
				;						
				
										
										
			]]></sqlcmd>
		</NODE>
				
		<NODE label="Séjours">
			<sqlcmd><![CDATA[
			
				-- GHS, GHM, date groupage
				
				DROP TABLE IF EXISTS w_GHS_VALORISE;
				CREATE TEMP TABLE w_GHS_VALORISE AS
				SELECT
					ANNEE AS ANN_GHSV,
					CODE AS COD_GHSV,
					ANNEE || to_char(CODE, 'FM900000') AS NUM_RSS,
					MAX(CASE WHEN ENFANT <= 0 THEN COALESCE(to_number('0' || GHS,'00000'),0) ELSE 0 END) AS GHS,
					MAX(CASE WHEN ENFANT > 0 THEN COALESCE(to_number('0' || GHS,'00000'),0) ELSE 0 END) AS GHS_BEBE1,
					''::text AS CLE_GHM
				FROM prod_sigems2.GHS_VALORISE
					 JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANNEE = ANN_SELECT AND CODE = COD_SELECT
				GROUP BY 1,2,3;
				
				
				UPDATE w_GHS_VALORISE
				SET GHS = 0, GHS_BEBE1 = 0 
				WHERE (GHS <> 0 OR GHS_BEBE1 <> 0) AND
					NUM_RSS IN (
					SELECT 
						NUM_RSS
					FROM prod_sigems2.UN_RUM
						JOIN prod_sigems2.PMSI_GHM ON UN_RUM.GHM = PMSI_GHM.CODE_GHM
					WHERE NUM_RSS IN (SELECT NUM_RSS FROM w_GHS_VALORISE WHERE GHS = 9999)
					GROUP BY 1
					HAVING MAX(CLE_GHM) LIKE '90%'
				);
				
				UPDATE w_GHS_VALORISE
				SET GHS = 0, GHS_BEBE1 = 0 
				WHERE (GHS <> 0 OR GHS_BEBE1 <> 0) AND
					NUM_RSS IN (
					SELECT 
						NUM_RSS
					FROM prod_sigems2.UN_RUM
						LEFT JOIN prod_sigems2.PMSI_GHM ON UN_RUM.GHM = PMSI_GHM.CODE_GHM
					WHERE NUM_RSS IN (SELECT NUM_RSS FROM w_GHS_VALORISE WHERE GHS = 9999) AND
						PMSI_GHM.CODE_GHM IS NULL
					GROUP BY 1
				);

				UPDATE w_GHS_VALORISE
				SET CLE_GHM = PMSI_GHM.CLE_GHM
				FROM prod_sigems2.UN_RUM
					JOIN prod_sigems2.PMSI_GHM ON UN_RUM.GHM = PMSI_GHM.CODE_GHM
				WHERE w_GHS_VALORISE.NUM_RSS = UN_RUM.NUM_RSS AND
					UN_RUM.NUM_RUM < 50 AND
					PMSI_GHM.CLE_GHM <> '' AND PMSI_GHM.CLE_GHM NOT LIKE '90%'
				;
				
				
				DROP TABLE IF EXISTS w_LIG_CLINI_forfaits;
				CREATE TEMP TABLE w_LIG_CLINI_forfaits AS
				SELECT
					ANN_LCL, 
					COD_LCL
				FROM prod_sigems2.LIG_CLINI
				WHERE PRO_LCL IN ('SE1', 'SE2', 'SE3', 'SE4','SE5', 'SE6', 'ATU', 'FPU', 'FFM')
				GROUP BY 1,2
				HAVING SUM(QTE_LCL) > 0;

				CREATE INDEX w_LIG_CLINI_forfaits_i1
				  ON w_LIG_CLINI_forfaits
				  USING btree
				  (COD_LCL);


				UPDATE w_GHS_VALORISE
				SET CLE_GHM = '', GHS = 0, GHS_BEBE1 = 0
				FROM w_LIG_CLINI_forfaits
				WHERE ANN_GHSV = ANN_LCL AND COD_GHSV = COD_LCL AND
					(CLE_GHM <> '' OR GHS <> 0 OR GHS_BEBE1 <> 0) ;

				DROP TABLE IF EXISTS w_LIG_CLINI_forfaits;	

				
				DROP TABLE IF EXISTS w_CONTROLE_DIM;
				CREATE TEMP TABLE w_CONTROLE_DIM AS
				SELECT
					ANNEE AS ANN_CTLD,
					CODE AS COD_CTLD,
					(MAX(Array[to_char(CONTROLE_DIM.NL,'FM0000'), CASE WHEN CONTROLE_DIM.ETAT >= 0 THEN CONTROLE_DIM.DATE_ACTION::text ELSE NULL END]))[2]::date AS DATE_GROUPAGE,
					(MAX(Array[to_char(CONTROLE_DIM.NL,'FM0000'), CASE WHEN CONTROLE_DIM.ETAT = 1 THEN CONTROLE_DIM.DATE_ACTION::text ELSE NULL END]))[2]::date AS DATE_VALIDATION
				FROM prod_sigems2.CONTROLE_DIM
				GROUP BY 1,2
				ORDER BY 1,2;

				UPDATE w_CONTROLE_DIM
				SET DATE_GROUPAGE = DATE_VALIDATION
				WHERE DATE_GROUPAGE IS NULL AND DATE_VALIDATION IS NOT NULL;


				UPDATE w_CONTROLE_DIM
				SET DATE_GROUPAGE = DATE_VALIDATION
				FROM activite.t_divers
				WHERE t_divers.code = 'SIGETAGRP' AND t_divers.valeur = '2' AND
					DATE_GROUPAGE IS DISTINCT FROM DATE_VALIDATION;


				UPDATE w_GHS_VALORISE
				SET GHS = 0, GHS_BEBE1 = 0
				FROM w_CONTROLE_DIM 
				WHERE ANN_GHSV = ANN_CTLD AND COD_GHSV = COD_CTLD AND DATE_GROUPAGE IS NULL AND
					(GHS <> 0 OR GHS_BEBE1 <> 0);

					
					
				-- Séjour

				DROP TABLE IF EXISTS w_DOSSIER_SEJOUR;
				CREATE TEMP TABLE w_DOSSIER_SEJOUR AS
				SELECT 
					ANN_DOS,
					COD_DOS,
					MAX(COALESCE(SER_SEJ,SER_DOS,'')) AS SER_DOS,
					MAX(COALESCE(NCH_SEJ,NCH_DOS,'')) AS NCH_DOS
				FROM prod_sigems2.DOSSIER
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_DOS = ANN_SELECT AND COD_DOS = COD_SELECT
					LEFT JOIN prod_sigems2.SEJOUR ON ANN_DOS = ANN_SEJ AND COD_DOS = COD_SEJ
				GROUP BY 1,2;
				
				CREATE INDEX w_DOSSIER_SEJOUR_i1
				  ON w_DOSSIER_SEJOUR
				  USING btree
				  (COD_DOS);



				-- RIS_DOS2 represente le risque d'un dossier. Cette donnee peut varier au fil des refacturations, il faut prendre la derniere utilisee
				DROP TABLE IF EXISTS w_DOS2;
				CREATE TEMP TABLE w_DOS2 AS
				SELECT
					ANN_DOS2,
					COD_DOS2,
					MAX(CP1_DOS2) AS CP1_DOS2,
					MAX(CA2_DOS2) AS CA2_DOS2,
                    (MAX(array[to_char(ind_dos2, 'FM999'), ris_dos2]))[2] as RIS_DOS2,
					COUNT(*)
				FROM prod_sigems2.DOS2
				JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_DOS2 = ANN_SELECT AND COD_DOS2 = COD_SELECT
				WHERE ETA_DOS2 >= 2
				GROUP BY 1,2;
				
				CREATE INDEX w_DOS2_i1
				  ON w_DOS2
				  USING btree
				  (COD_DOS2);
				 
				DROP TABLE IF EXISTS w_LIG_CLINI_externes;
				CREATE TEMP TABLE w_LIG_CLINI_externes AS 
				SELECT 
				ANN_LCL,
				COD_LCL,
				'07'::text AS MDT_LCL
				FROM prod_sigems2.LIG_CLINI
				JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LCL = ANN_SELECT AND COD_LCL = COD_SELECT
				WHERE pro_lcl IN ('SE1', 'SE2', 'SE3', 'SE4','SE5', 'SE6', 'ATU', 'FPU')
				GROUP BY 1,2
				HAVING SUM(QTE_LCL) > 0;

				CREATE INDEX w_LIG_CLINI_externes_i1
								  ON w_LIG_CLINI_externes
								  USING btree
								  (COD_LCL);  
								  
				DROP TABLE IF EXISTS w_LIG_CLINI_hospit;
				CREATE TEMP TABLE w_LIG_CLINI_hospit AS 
				SELECT 
				ANN_LCL,
				COD_LCL,
				MAX(CASE WHEN w_GHS_VALORISE.GHS IN (SELECT code FROM base.t_ghs WHERE texte like '%séance%') THEN '19'::text ELSE '03'::text END) AS MDT_LCL
				FROM prod_sigems2.LIG_CLINI
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LCL = ANN_SELECT AND COD_LCL = COD_SELECT
					LEFT JOIN w_GHS_VALORISE ON ANN_GHSV = ANN_LCL AND COD_GHSV = COD_LCL
				WHERE pro_lcl IN ('GHS')
				GROUP BY 1,2
				HAVING SUM(QTE_LCL) > 0;

				CREATE INDEX w_LIG_CLINI_hospit_i1
								  ON w_LIG_CLINI_hospit
								  USING btree
								  (COD_LCL);  
				  


				-- Concernant le risque du dossier, on privilegie le risque present sur les factures (RIS_DOS2) au risque saisi a l'ouverture du dossier (RIS_DOS)
				DROP TABLE IF EXISTS w_DOSSIER;
				CREATE TEMP TABLE w_DOSSIER AS
				SELECT 
					DOSSIER.ANN_DOS || to_char(DOSSIER.COD_DOS,'FM900000') AS SEJ_DOS,
					DOSSIER.ANN_DOS,
					DOSSIER.COD_DOS,
					COALESCE(MDT_REEL,MDT_DOS) AS MDT_DOS,
					COALESCE(w_LIG_CLINI_externes.MDT_LCL, w_LIG_CLINI_hospit.MDT_LCL, '') AS MDT_LCL,
					DMT_SER AS DMT_DOS,
					w_DOSSIER_SEJOUR.SER_DOS AS SER_DOS,
					w_DOSSIER_SEJOUR.SER_DOS || '_' || COALESCE(MDT_REEL,MDT_DOS) AS SER_DOS_MDT,
					COALESCE(SER_CHA,'') AS ETA_DOS,
					COALESCE(SER_CHA || '|' || w_DOSSIER_SEJOUR.NCH_DOS, '|') AS NCH_DOS,
					CCH_DOS,
					CPH_DOS,
					COALESCE(CHP_DOX,'') AS CHP_DOX,
					DEN_DOS,
					to_number('00' || MIN_DOS,'0000') AS MIN_DOS,
					to_timestamp(to_char(DEN_DOS,'YYYYMMDD') || MIN_DOS,'YYYYMMDDHH24')::timestamp without time zone AS w_DHEN_DOS,
					COALESCE(DSO_DOS,'20991231') AS DSO_DOS,
					to_number('00' || HEU_DOS,'0000') AS HEU_DOS,
					to_timestamp(to_char(COALESCE(DSO_DOS,'20991231'),'YYYYMMDD') || HEU_DOS,'YYYYMMDDHH24')::timestamp without time zone AS w_DHSO_DOS,
					COALESCE(CP1_DOS2,'') AS CP1_DOS2,
					COALESCE(CA2_DOS2,'') AS CA2_DOS2,
					CASE WHEN MSO_DOS <> '' THEN MSO_DOS ELSE '80' END AS MSO_DOS,
					COALESCE(DATE_GROUPAGE,'20991231'::date) AS DATE_GROUPAGE,
					COALESCE(GHS,0) AS GHS,
					COALESCE(CLE_GHM,'') AS CLE_GHM,
					COALESCE(GHS_BEBE1,0) AS GHS_BEBE1,
                    COALESCE(w_DOS2.RIS_DOS2, DOSSIER.RIS_DOS) AS RIS_DOS,
					w_DOSSIER_SEJOUR.SER_DOS || '|' || 
						COALESCE(MDT_REEL,MDT_DOS) || '|' || 
						w_DOSSIER_SEJOUR.NCH_DOS || '|' || 
						COALESCE(CCH_DOS,'|') || '|' || 
						COALESCE(CP1_DOS2,'') || '|' || 
						COALESCE(CA2_DOS2,'') || '|' || 
						COALESCE(GHS,0) || '|' || 
						COALESCE(CLE_GHM,'') || '|' || 
						COALESCE(GHS_BEBE1,0) AS key
				FROM prod_sigems2.DOSSIER
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_DOS = ANN_SELECT AND COD_DOS = COD_SELECT
					LEFT JOIN prod_sigems2.DOSSIER_X ON DOSSIER.ANN_DOS = DOSSIER_X.ANN_DOX AND DOSSIER.COD_DOS = DOSSIER_X.COD_DOX AND CHP_DOX <> ''
					LEFT JOIN prod_sigems2.DOSSIER_MDT ON DOSSIER.ANN_DOS = DOSSIER_MDT.ANN_DOS AND DOSSIER.COD_DOS = DOSSIER_MDT.COD_DOS
					LEFT JOIN w_LIG_CLINI_externes ON DOSSIER.ANN_DOS = w_LIG_CLINI_externes.ANN_LCL AND DOSSIER.COD_DOS = w_LIG_CLINI_externes.COD_LCL
					LEFT JOIN w_LIG_CLINI_hospit ON DOSSIER.ANN_DOS = w_LIG_CLINI_hospit.ANN_LCL AND DOSSIER.COD_DOS = w_LIG_CLINI_hospit.COD_LCL
					LEFT JOIN w_DOSSIER_SEJOUR ON DOSSIER.ANN_DOS = w_DOSSIER_SEJOUR.ANN_DOS AND DOSSIER.COD_DOS = w_DOSSIER_SEJOUR.COD_DOS
					LEFT JOIN w_GHS_VALORISE ON ANN_GHSV = DOSSIER.ANN_DOS AND COD_GHSV = DOSSIER.COD_DOS
					LEFT JOIN w_CONTROLE_DIM ON ANN_CTLD = DOSSIER.ANN_DOS AND COD_CTLD = DOSSIER.COD_DOS
					LEFT JOIN w_DOS2 ON ANN_DOS2 = DOSSIER.ANN_DOS AND COD_DOS2 = DOSSIER.COD_DOS
					LEFT JOIN prod_sigems2.SERVICE ON w_DOSSIER_SEJOUR.SER_DOS = COD_SER
					LEFT JOIN w_CHAMBRE ON w_DOSSIER_SEJOUR.NCH_DOS = COD_CHA AND w_DOSSIER_SEJOUR.NCH_DOS <> '' AND w_DOSSIER_SEJOUR.NCH_DOS <> '0'
				WHERE DEN_DOS IS NOT NULL;
				
				
				UPDATE w_DOSSIER
				SET ETA_DOS = substr(NCH_DOS,2), NCH_DOS = substr(NCH_DOS,2) || NCH_DOS
				WHERE ETA_DOS = '' AND NCH_DOS <> '|' AND NCH_DOS LIKE '|%';
				
				
				CREATE INDEX w_DOSSIER_i1
				  ON w_DOSSIER
				  USING btree
				  (SEJ_DOS);
				  
				CREATE INDEX w_DOSSIER_i2
				  ON w_DOSSIER
				  USING btree
				  (COD_DOS);
				  
				
				UPDATE w_DOSSIER
				SET DSO_DOS = base.cti_to_date(date_part('year',DEN_DOS),date_part('month',DSO_DOS),date_part('day',DSO_DOS)) 
				WHERE DSO_DOS > '20201001' and DSO_DOS <> '20991231'; 



				DROP TABLE IF EXISTS w_DOSSIER_key;
				CREATE TEMP TABLE w_DOSSIER_key AS
				SELECT
					key,
					SER_DOS,
					SER_DOS_MDT,
					ETA_DOS,
					NCH_DOS,
					CCH_DOS,
					CP1_DOS2,
					CA2_DOS2,
					GHS,
					CLE_GHM,
					GHS_BEBE1,
					0 AS mode_traitement_id,
					''::text AS mode_traitement_code,
					''::text AS dmt_code,
					'0'::text AS type_sejour_force,
					0::bigint AS lieu_id,
					0::bigint AS unite_fonctionnelle_id,
					0::bigint AS medecin_sejour_id,
					0::bigint AS ghs_id,
					0::bigint AS ghm_id,
					0::bigint AS ghs_bebe1_id,
					0::bigint AS ghs_bebe2_id,
					0::bigint AS ghs_bebe3_id,
					0::bigint AS tiers_payant_0_id,
					0::bigint AS tiers_payant_1_id,
					0::bigint AS tiers_payant_2_id,
					0::bigint AS tiers_payant_22_id
				FROM w_DOSSIER
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11;

				UPDATE w_DOSSIER_key SET
					mode_traitement_id = t_modes_traitement.oid,
					mode_traitement_code = t_modes_traitement.code,
					dmt_code = t_dmt.code,
					type_sejour_force = CASE WHEN t_services_facturation.type_sejour IN ('1', '2', '3', '4', '5') THEN t_services_facturation.type_sejour ELSE '0' END
				FROM activite[PX].t_services_facturation
					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 t_services_facturation.code_original = SER_DOS_MDT;
				
				UPDATE w_DOSSIER_key
					set medecin_sejour_id = t_medecins_administratifs.oid
				FROM activite[PX].t_medecins_administratifs
				WHERE CCH_DOS <> '' AND code_original = CCH_DOS;

				UPDATE w_DOSSIER_key
					set tiers_payant_0_id = t_tiers_payant.oid
				FROM activite[PX].t_tiers_payant
				WHERE code_original = 'PATIENT';

				UPDATE w_DOSSIER_key
					set tiers_payant_1_id = t_tiers_payant.oid
				FROM activite[PX].t_tiers_payant
				WHERE CP1_DOS2 <> '' AND code_original = CP1_DOS2;

				UPDATE w_DOSSIER_key
					set tiers_payant_2_id = t_tiers_payant.oid
				FROM activite[PX].t_tiers_payant
				WHERE CA2_DOS2 <> '' AND code_original = CA2_DOS2;

				UPDATE w_DOSSIER_key
					set ghs_id = t_ghs.oid
				FROM base.t_ghs
				WHERE GHS <> 0 AND t_ghs.code = GHS;
				
				UPDATE w_DOSSIER_key
					set ghm_id = t_ghm.oid
				FROM base.t_ghm
				WHERE CLE_GHM <> '' AND t_ghm.code = CLE_GHM AND t_ghm.code NOT LIKE '90%';

				UPDATE w_DOSSIER_key
					set ghs_bebe1_id = t_ghs.oid
				FROM base.t_ghs
				WHERE GHS_BEBE1 <> 0 AND t_ghs.code = GHS_BEBE1;

				INSERT INTO activite[PX].t_lieux(
							code_original_1, code_original_2, code_original_3, code_original_4, code_original_6)
				SELECT SER_DOS_MDT, '', ETA_DOS, NCH_DOS, SER_DOS
				FROM w_DOSSIER_key
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = SER_DOS_MDT AND
						code_original_2 = '' AND
						code_original_3 = ETA_DOS AND
						code_original_4 = NCH_DOS AND
						code_original_6 = SER_DOS
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4,5;

				UPDATE w_DOSSIER_key
					set lieu_id = t_lieux.oid
				FROM activite[PX].t_lieux
				WHERE code_original_1 = SER_DOS_MDT AND
						code_original_2 = '' AND
						code_original_3 = ETA_DOS AND
						code_original_4 = NCH_DOS AND
						code_original_6 = SER_DOS;

				UPDATE activite[PX].t_lieux SET
					service_facturation_id = COALESCE(t_services_facturation.oid,0),
					mode_traitement_id = COALESCE(t_services_facturation.mode_traitement_id,0) 
				FROM
					activite[PX].t_services_facturation 
				WHERE code_original_1 = t_services_facturation.code_original
					AND (t_lieux.service_facturation_id <> COALESCE(t_services_facturation.oid,0) OR
						t_lieux.mode_traitement_id <> COALESCE(t_services_facturation.mode_traitement_id,0)
					)
					;

				UPDATE activite[PX].t_lieux SET
					unite_fonctionnelle_id = COALESCE(t_unites_fonctionnelles.oid,0)
				FROM
					activite[PX].t_unites_fonctionnelles
				WHERE code_original_6 = t_unites_fonctionnelles.code_original
					AND unite_fonctionnelle_id <> COALESCE(t_unites_fonctionnelles.oid,0);
					
				UPDATE activite[PX].t_lieux SET
					unite_fonctionnelle_id = COALESCE(t_unites_fonctionnelles.oid,0)
				FROM
					activite[PX].t_unites_fonctionnelles
				WHERE code_original_6 = t_unites_fonctionnelles.code_original
					AND unite_fonctionnelle_id <> COALESCE(t_unites_fonctionnelles.oid,0);
				

				UPDATE activite[PX].t_lieux SET
					lit_id = COALESCE(t_lits.oid,0)
				FROM
					activite[PX].t_lits
				WHERE code_original_4 = t_lits.code_original AND
					t_lieux.lit_id <> COALESCE(t_lits.oid,0)
					;

				DROP TABLE IF EXISTS w_sejours;
				CREATE TEMP TABLE w_sejours AS
				SELECT 
					''::text AS finess,
					SEJ_DOS as no_sejour, 
					SEJ_DOS as code_original, 
					no_patient, 
					DEN_DOS as date_entree, 
					MIN_DOS * 10000 as heure_entree, 
					DSO_DOS as date_sortie, 
					HEU_DOS * 10000 as heure_sortie, 
					CASE WHEN SEX_PAT IN ('F') THEN '2' ELSE '1' END as code_sexe, 
					0 AS age, 
					CASE WHEN DSO_DOS IS NOT NULL AND DSO_DOS < '20991231' AND SEJ_DOS NOT LIKE 'P%' THEN 1 ELSE 0 END::numeric as code_sorti, 
					CASE WHEN SEJ_DOS LIKE 'P%' THEN 1::numeric ELSE 0::numeric END AS code_prevu,
					CASE 
						WHEN type_sejour_force <> '0' THEN type_sejour_force
						WHEN MDT_LCL IN ('03') AND DSO_DOS = DEN_DOS THEN '2' 
						WHEN MDT_LCL IN ('03') THEN '1' 
						WHEN MDT_LCL IN ('07') THEN '3' 
						WHEN mode_traitement_code IN ('07') OR dmt_code IN ('958') THEN '3' 
						WHEN mode_traitement_code IN ('19', '23') AND DSO_DOS = DEN_DOS THEN '2' 
						WHEN mode_traitement_code IN ('04') AND DSO_DOS = DEN_DOS THEN '2' 
						WHEN mode_traitement_code IN ('03') AND DSO_DOS = DEN_DOS THEN '2' 
						WHEN mode_traitement_code IN ('03') THEN '1' 
						ELSE '1' END as type_sejour,
					lieu_id AS lieu_sortie_id,
					unite_fonctionnelle_id,
					w_DOSSIER_key.medecin_sejour_id AS medecin_sejour_id,
					ghs_id,
					ghm_id,
					ghs_bebe1_id,
					0::numeric AS ghs_bebe2_id,
					0::numeric AS ghs_bebe3_id,
					DATE_GROUPAGE,
					CASE WHEN w_DOSSIER.CHP_DOX LIKE 'P%' THEN '1'::text ELSE '0'::text END AS code_cp_demandee,
					mode_traitement_id,
					CASE WHEN SUBSTR(ADM_DOS,1,1) <> '' THEN (CASE WHEN ANU_ADM <> '' THEN (CASE WHEN DAF_ADM IS NULL THEN ANU_ADM ELSE (CASE WHEN SUBSTR(ADM_DOS,1,1) IN ('6','7','8') THEN SUBSTR(ADM_DOS,1,1) ELSE '8' END) END) ELSE (CASE WHEN SUBSTR(ADM_DOS,1,1) IN ('6','7','8') THEN SUBSTR(ADM_DOS,1,1) ELSE '8' END) END)::text ELSE '0'::text END as mode_entree,
					CASE WHEN SUBSTR(ADM_DOS,2,1) <> '' THEN (CASE WHEN ANU_ADM <> '' AND DAF_ADM IS NULL THEN (CASE WHEN (SUBSTR(ADM_DOS,1,1) = 'S' OR SUBSTR(ADM_DOS,2,1) = 'R') THEN '1' ELSE SUBSTR(ADM_DOS,2,1) END) ELSE SUBSTR(ADM_DOS,2,1) END)::text ELSE '0'::text END as provenance,
					SUBSTR(MSO_DOS,1,1)::character(1) as mode_sortie,
					SUBSTR(MSO_DOS,2,1)::character(1) as destination,
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					0 AS est_budget_global,
					COALESCE(t_codes_postaux.oid, 0) as code_postal_id,
                    COALESCE(t_risque.oid, 0) as risque_id
				FROM w_DOSSIER
					LEFT JOIN prod_sigems2.DOSSIER_X ON w_DOSSIER.ANN_DOS = DOSSIER_X.ANN_DOX AND w_DOSSIER.COD_DOS = DOSSIER_X.COD_DOX
					LEFT JOIN prod_sigems2.ADMISSION ON COD_ADM = ADM_DOS
					JOIN w_DOSSIER_key ON w_DOSSIER.key = w_DOSSIER_key.key
					LEFT JOIN w_PATIENT ON CPH_DOS = COD_PAT AND SEJ_DOS = SEJ_NUM
					LEFT JOIN base.t_codes_postaux on t_codes_postaux.code = w_PATIENT.CPO_PAT
                    LEFT JOIN activite.t_risque ON t_risque.code = w_DOSSIER.RIS_DOS;
					
				-- Forcage type selon séjour
				UPDATE w_sejours
				SET type_sejour = t_sejour.type_sejour
				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');
					
				-- Calcul dates sortie prévisionnelles
				
				DROP TABLE IF EXISTS w_DOSSIER_DMS;
				CREATE TEMP TABLE w_DOSSIER_DMS AS
				SELECT PTH_DOS, round(AVG(date(DSO_DOS) - date(DEN_DOS)),0) AS dms
				FROM prod_sigems2.DOSSIER
				JOIN w_PERIODE ON periode_id = 0
				WHERE DEN_DOS IS NOT NULL AND DSO_DOS >= DEN_DOS AND DSO_DOS <= now_sigems
				GROUP BY 1;



				UPDATE w_sejours
				SET date_sortie = GREATEST(date_entree + (dms || ' days')::interval, now_sigems_1)
				FROM w_DOSSIER_select
				JOIN w_PERIODE ON periode_id = 0
				JOIN prod_sigems2.DOSSIER ON ANN_SELECT = ANN_DOS AND COD_SELECT = COD_DOS
				JOIN w_DOSSIER_DMS ON DOSSIER.PTH_DOS = w_DOSSIER_DMS.PTH_DOS
				WHERE no_sejour = no_sejour_SELECT AND 
					date_sortie = '20991231' AND code_sorti <> '1';


				DROP TABLE IF EXISTS w_sejours_DMS;
				CREATE TEMP TABLE w_sejours_DMS AS
				SELECT medecin_sejour_id, unite_fonctionnelle_id, round(AVG(date(date_sortie) - date(date_entree)),0) AS dms
				FROM w_sejours
				JOIN w_PERIODE ON periode_id = 0
				WHERE code_sorti = '1' AND date_sortie >= date_entree AND date_sortie <= now_sigems
				GROUP BY 1,2;


				UPDATE w_sejours
				SET date_sortie = GREATEST(date_entree + (dms || ' days')::interval, now_sigems_1)
				FROM w_sejours_DMS
				JOIN w_PERIODE ON periode_id = 0
				WHERE w_sejours.medecin_sejour_id =  w_sejours_DMS.medecin_sejour_id AND
					w_sejours.unite_fonctionnelle_id =  w_sejours_DMS.unite_fonctionnelle_id AND
					date_sortie = '20991231' AND code_sorti <> '1';


				DROP TABLE IF EXISTS w_sejours_DMS;
				CREATE TEMP TABLE w_sejours_DMS AS
				SELECT medecin_sejour_id, round(AVG(date(date_sortie) - date(date_entree)),0) AS dms
				FROM w_sejours
				JOIN w_PERIODE ON periode_id = 0
				WHERE code_sorti = '1' AND date_sortie >= date_entree AND date_sortie <= now_sigems
				GROUP BY 1;


				UPDATE w_sejours
				SET date_sortie = GREATEST(date_entree + (dms || ' days')::interval, now_sigems_1)
				FROM w_sejours_DMS
				JOIN w_PERIODE ON periode_id = 0
				WHERE w_sejours.medecin_sejour_id =  w_sejours_DMS.medecin_sejour_id AND
					date_sortie = '20991231' AND code_sorti <> '1';


				DROP TABLE IF EXISTS w_sejours_DMS;
				CREATE TEMP TABLE w_sejours_DMS AS
				SELECT round(AVG(date(date_sortie) - date(date_entree)),0) AS dms
				FROM w_sejours
				JOIN w_PERIODE ON periode_id = 0
				WHERE code_sorti = '1' AND date_sortie >= date_entree AND date_sortie <= now_sigems;


				UPDATE w_sejours
				SET date_sortie = GREATEST(date_entree + (dms || ' days')::interval, now_sigems_1)
				FROM w_sejours_DMS
				JOIN w_PERIODE ON periode_id = 0
				WHERE date_sortie = '20991231' AND code_sorti <> '1';
					
					
				UPDATE w_sejours SET heure_sortie = heure_entree + 40000
				WHERE code_sorti <> '1' AND date_sortie = date_entree AND heure_entree <= 190000;

				UPDATE w_sejours SET heure_sortie = 235959
				WHERE code_sorti <> '1' AND date_sortie = date_entree AND heure_entree > 190000;

				UPDATE w_sejours SET heure_sortie = 130000
				WHERE code_sorti <> '1' AND date_sortie > date_entree ;	
				
				
				UPDATE w_DOSSIER
				SET w_DHSO_DOS = to_timestamp(to_char(COALESCE(date_sortie,'20991231'),'YYYYMMDD') || to_char(heure_sortie,'FM000000'),'YYYYMMDDHH24')
				FROM w_sejours
				WHERE SEJ_DOS = no_sejour AND 
					(code_sorti <> '1' OR code_prevu = '1');
					
					
				-- Pointage séjours Budget Global
				UPDATE w_sejours
				SET est_budget_global = 1
				FROM activite[PX].t_lieux 
				JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid AND t_services_facturation.est_budget_global = '1'
				WHERE lieu_sortie_id = t_lieux.oid AND 
					w_sejours.est_budget_global IS DISTINCT FROM 1;
					
				
				-- FINESS
				UPDATE w_sejours
				SET finess = t_finess.code
				FROM activite[PX].t_lieux 
				JOIN activite[PX].t_services_facturation on  service_facturation_id = t_services_facturation.oid
				JOIN base.t_finess ON finess_id = t_finess.oid
				WHERE lieu_sortie_id = t_lieux.oid;
					
				UPDATE w_sejours
				SET finess = '000000000'
				WHERE finess = '';
					
				-- Validation des séjours

				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');

				UPDATE activite[PX].p_sejours SET
					finess = w_sejours.finess, 
					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, 
					lieu_sortie_id = w_sejours.lieu_sortie_id,
					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,
					date_groupage = w_sejours.date_groupage,
					ghs_id = w_sejours.ghs_id,
					ghm_id = w_sejours.ghm_id,
					ghs_bebe1_id = w_sejours.ghs_bebe1_id,
					ghs_bebe2_id = w_sejours.ghs_bebe2_id,
					ghs_bebe3_id = w_sejours.ghs_bebe3_id,
					code_postal_id = w_sejours.code_postal_id,
                    risque_id = w_sejours.risque_id
				FROM w_sejours
				WHERE w_sejours.no_sejour = p_sejours.no_sejour
				AND (
					w_sejours.finess IS DISTINCT FROM p_sejours.finess OR
					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.lieu_sortie_id IS DISTINCT FROM p_sejours.lieu_sortie_id 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.date_groupage IS DISTINCT FROM p_sejours.date_groupage OR
					w_sejours.ghs_id IS DISTINCT FROM p_sejours.ghs_id OR
					w_sejours.ghm_id IS DISTINCT FROM p_sejours.ghm_id OR
					w_sejours.ghs_bebe1_id IS DISTINCT FROM p_sejours.ghs_bebe1_id OR
					w_sejours.ghs_bebe2_id IS DISTINCT FROM p_sejours.ghs_bebe2_id OR
					w_sejours.ghs_bebe3_id IS DISTINCT FROM p_sejours.ghs_bebe3_id OR
					w_sejours.code_postal_id IS DISTINCT FROM p_sejours.code_postal_id OR
                    w_sejours.risque_id IS DISTINCT FROM p_sejours.risque_id
				);		


				INSERT INTO activite[PX].p_sejours (
					finess,
					no_sejour, 
					code_original, 
					no_patient, 
					date_entree, 
					heure_entree, 
					date_sortie, 
					heure_sortie, 
					code_sexe, 
					age, 
					code_sorti, 
					code_prevu, 
					type_sejour, 
					lieu_sortie_id,
					medecin_sejour_id,
					ghs_id,
					ghm_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_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,
					code_postal_id,
                    risque_id
				) 
				SELECT 
					w_sejours.finess, 
					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, 
					w_sejours.age, 
					w_sejours.code_sorti, 
					w_sejours.code_prevu, 
					w_sejours.type_sejour, 
					w_sejours.lieu_sortie_id,
					w_sejours.medecin_sejour_id,
					w_sejours.ghs_id,
					w_sejours.ghm_id,
					w_sejours.ghs_bebe1_id,
					w_sejours.ghs_bebe2_id,
					w_sejours.ghs_bebe3_id,
					w_sejours.date_groupage,
					w_sejours.code_cp_demandee,
					w_sejours.mode_traitement_id,
					w_sejours.mode_entree,
					w_sejours.provenance,
					w_sejours.mode_sortie,
					w_sejours.destination,
					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.code_postal_id,
                    w_sejours.risque_id

				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 WHERE no_sejour NOT IN (SELECT no_sejour_SELECT FROM w_DOSSIER_SELECT);
				
				DELETE FROM activite[PX].p_sejours USING
				(
				SELECT no_sejour, min(CTID) AS koctid 
				FROM activite[PX].p_sejours
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE CTID = koctid;
				
				-- 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');
									
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Mouvements">
			<sqlcmd><![CDATA[

				
				DROP TABLE IF EXISTS w_SEJOUR;
				CREATE TEMP TABLE w_SEJOUR AS
				SELECT 	
					SEJ_DOS,
					ANN_DOS,
					COD_DOS,
					w_DHEN_DOS,
					w_DHSO_DOS,
					CASE 
						WHEN DMT_SEJ IN ('401', '402', '403', '404', '405', '406', '407', '408', '409') THEN '1'::text
						WHEN DMT_DOS IN ('401', '402', '403', '404', '405', '406', '407', '408', '409') THEN '1'::text 
						WHEN DOSSIER_Y.URGENCE = 'U' THEN '1'::text 
						ELSE '0'::text END AS URG,
					COALESCE(SER_SEJ, SER_DOS) AS SER_SEJ,
					COALESCE(SER_SEJ || '_' || MDT_DOS, SER_DOS_MDT) AS SER_SEJ_MDT,
					COALESCE(SER_CHA, ETA_DOS) AS ETA_SEJ,
					COALESCE(SER_CHA || '|' || NCH_SEJ, NCH_DOS) AS NCH_SEJ,
					COALESCE(DAE_SEJ,DEN_DOS) AS DAE_SEJ,
					COALESCE(to_timestamp(to_char(DAE_SEJ,'YYYYMMDD') || MIN_DOS,'YYYYMMDDHH24'),w_DHSO_DOS)::timestamp without time zone AS w_DHAE_SEJ,
					COALESCE(DAS_SEJ,DSO_DOS) AS DAS_SEJ,
					COALESCE(to_number('00' || HEU_SEJ,'0000'), HEU_DOS) AS HEU_SEJ,
					COALESCE(to_timestamp(to_char(DAS_SEJ,'YYYYMMDD') || HEU_SEJ,'YYYYMMDDHH24'),w_DHSO_DOS)::timestamp without time zone AS w_DHAS_SEJ
				FROM w_DOSSIER 
					LEFT JOIN prod_sigems2.SEJOUR ON ANN_SEJ = ANN_DOS AND COD_SEJ = COD_DOS
					LEFT JOIN prod_sigems2.DOSSIER_Y ON ANNEE = ANN_DOS AND CODE = COD_DOS 
					LEFT JOIN w_CHAMBRE ON NCH_SEJ = COD_CHA AND NCH_SEJ <> '' AND NCH_SEJ <> '0'
				WHERE DAE_SEJ <= DAS_SEJ OR DAS_SEJ IS NULL OR SEJOUR.ANN_SEJ IS NULL
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
				ORDER BY SEJ_DOS
				; 


				UPDATE w_SEJOUR
				SET ETA_SEJ = substr(NCH_SEJ,2), NCH_SEJ = substr(NCH_SEJ,2) || NCH_SEJ
				WHERE ETA_SEJ = '' AND NCH_SEJ <> '|' AND NCH_SEJ LIKE '|%';


				INSERT INTO activite[PX].t_lieux(
							code_original_1, code_original_2, code_original_3, code_original_4, code_original_6)
				SELECT SER_SEJ_MDT, '', ETA_SEJ, NCH_SEJ, SER_SEJ
				FROM w_SEJOUR
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = SER_SEJ_MDT AND
						code_original_2 = '' AND
						code_original_3 = ETA_SEJ AND
						code_original_4 = NCH_SEJ AND
						code_original_6 = SER_SEJ 
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4,5;


				UPDATE activite[PX].t_lieux SET
					service_facturation_id = COALESCE(t_services_facturation.oid,0),
					mode_traitement_id = COALESCE(t_services_facturation.mode_traitement_id,0) 
				FROM
					activite[PX].t_services_facturation 
				WHERE code_original_1 = t_services_facturation.code_original
					AND (t_lieux.service_facturation_id <> COALESCE(t_services_facturation.oid,0) OR
						t_lieux.mode_traitement_id <> COALESCE(t_services_facturation.mode_traitement_id,0)
					)
					;

				UPDATE activite[PX].t_lieux SET
					unite_fonctionnelle_id = COALESCE(t_unites_fonctionnelles.oid,0)
				FROM
					activite[PX].t_unites_fonctionnelles
				WHERE code_original_6 = t_unites_fonctionnelles.code_original
					AND unite_fonctionnelle_id <> COALESCE(t_unites_fonctionnelles.oid,0);

				
				UPDATE activite[PX].t_lieux SET
					lit_id = COALESCE(t_lits.oid,0)
				FROM					activite[PX].t_lits
				WHERE code_original_4 = t_lits.code_original AND
					t_lieux.lit_id <> COALESCE(t_lits.oid,0)
					;
					
					
				-- L'étage 'NULL' est faux
				UPDATE activite[PX].t_lieux
				SET lit_id = 0
				WHERE code_original_3 = 'NULL';		

				-- Le lit 'NULL' est faux
				UPDATE activite[PX].t_lieux
				SET lit_id = t_lits_g.oid
				FROM activite[PX].t_lits 
				JOIN activite[PX].t_lits t_lits_g ON t_lits.etage_id = t_lits_g.etage_id AND t_lits_g.code_original LIKE '%|0'
				WHERE t_lieux.lit_id = t_lits.oid AND
					code_original_4 LIKE '%|NULL%' AND 
					code_original_3 <> '';
				

				DROP TABLE IF EXISTS w_SEJOUR_2;
				CREATE TEMP TABLE w_SEJOUR_2 AS
				SELECT 
					SEJ_DOS,
					ANN_DOS,
					COD_DOS,
					w_DHEN_DOS,
					w_DHSO_DOS,
					URG,
					SER_SEJ,
					SER_SEJ_MDT,
					ETA_SEJ,
					NCH_SEJ,
					'1'::text AS w_QENTREE,
					DAE_SEJ,
					w_DHAE_SEJ,
					'1'::text AS w_QSORTIE,
					DAS_SEJ,
					HEU_SEJ,
					w_DHAS_SEJ,
					''::text AS SER_SEJ_MDT_before,
					''::text AS ETA_SEJ_before,
					''::text AS SER_SEJ_MDT_next,
					''::text AS ETA_SEJ_next,
					COALESCE(t_lieux.oid,0) AS lieu_id
				FROM w_SEJOUR
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = SER_SEJ_MDT AND
						code_original_2 = '' AND
						code_original_3 = ETA_SEJ AND
						code_original_4 = NCH_SEJ AND
						code_original_6 = SER_SEJ
					)
				ORDER BY SEJ_DOS, w_DHAS_SEJ;




				DROP SEQUENCE IF EXISTS w_SEJOUR_seq;
				CREATE TEMP SEQUENCE w_SEJOUR_seq
					INCREMENT 1
					MINVALUE 1
					MAXVALUE 9223372036854775807
					START 1
					CACHE 1;


				DROP TABLE IF EXISTS w_SEJOUR;
				CREATE TEMP TABLE w_SEJOUR AS
				SELECT 
					nextval('w_SEJOUR_seq'::regclass) AS sequence, 
					SEJ_DOS,
					ANN_DOS,
					COD_DOS,
					w_DHEN_DOS,
					w_DHSO_DOS,
					URG,
					SER_SEJ,
					SER_SEJ_MDT,
					ETA_SEJ,
					NCH_SEJ,
					w_QENTREE,
					DAE_SEJ,
					w_DHAE_SEJ,
					w_QSORTIE,
					DAS_SEJ,
					HEU_SEJ,
					w_DHAS_SEJ,
					SER_SEJ_MDT_before,
					ETA_SEJ_before,
					SER_SEJ_MDT_next,
					ETA_SEJ_next,
					lieu_id
				FROM w_SEJOUR_2 
				ORDER BY SEJ_DOS, w_DHAS_SEJ;
				
				CREATE INDEX w_SEJOUR_i1
								  ON w_SEJOUR
								  USING btree
								  (SEJ_DOS);




				UPDATE w_SEJOUR
				SET 
					w_DHAE_SEJ = w_SEJOUR_before.w_DHAS_SEJ + interval '1 SECOND'
				FROM w_SEJOUR w_SEJOUR_before
				WHERE w_SEJOUR.SEJ_DOS = w_SEJOUR_before.SEJ_DOS
					AND w_SEJOUR.sequence = w_SEJOUR_before.sequence + 1;




				DROP TABLE IF EXISTS w_SEJOUR_SEJOUR;
				CREATE TEMP TABLE w_SEJOUR_SEJOUR AS
				SELECT 
					SEJ_DOS
				FROM w_SEJOUR
				GROUP BY 1
				HAVING count(*) > 1;

				DELETE FROM w_SEJOUR 
				USING w_SEJOUR_SEJOUR 
				WHERE w_SEJOUR_SEJOUR.SEJ_DOS = w_SEJOUR.SEJ_DOS AND w_DHAE_SEJ > w_DHSO_DOS;

				DELETE FROM w_SEJOUR 
				USING w_SEJOUR_SEJOUR 
				WHERE w_SEJOUR_SEJOUR.SEJ_DOS = w_SEJOUR.SEJ_DOS AND w_DHAS_SEJ < w_DHEN_DOS ;

				DROP TABLE IF EXISTS w_SEJOUR_SEJOUR;
				CREATE TEMP TABLE w_SEJOUR_SEJOUR AS
				SELECT 
					SEJ_DOS,
					MIN(sequence) AS sequence_1,
					MAX(sequence) AS sequence_9
				FROM w_SEJOUR
				GROUP BY 1;



				UPDATE w_SEJOUR
				SET w_DHAS_SEJ = w_DHSO_DOS
				FROM w_SEJOUR_SEJOUR 
				WHERE w_SEJOUR.SEJ_DOS = w_SEJOUR_SEJOUR.SEJ_DOS AND w_SEJOUR.sequence = w_SEJOUR_SEJOUR.sequence_9 AND
					w_DHAS_SEJ <> w_DHSO_DOS;


				UPDATE w_SEJOUR
				SET w_DHAE_SEJ = w_DHEN_DOS
				FROM w_SEJOUR_SEJOUR 
				WHERE w_SEJOUR.SEJ_DOS = w_SEJOUR_SEJOUR.SEJ_DOS AND w_SEJOUR.sequence = w_SEJOUR_SEJOUR.sequence_1 AND
					w_DHAE_SEJ <> w_DHEN_DOS;




				UPDATE w_SEJOUR
					SET 
						w_QSORTIE = '0',
						SER_SEJ_MDT_next = w_SEJOUR_next.SER_SEJ_MDT,
						ETA_SEJ_next = w_SEJOUR_next.ETA_SEJ
					FROM w_SEJOUR w_SEJOUR_next
					WHERE w_SEJOUR.SEJ_DOS = w_SEJOUR_next.SEJ_DOS
						AND w_SEJOUR.sequence = w_SEJOUR_next.sequence - 1;



				UPDATE w_SEJOUR
					SET 
						w_QENTREE = '0',
						w_DHAE_SEJ = w_SEJOUR_before.w_DHAS_SEJ + interval '1 SECOND',
						SER_SEJ_MDT_before = w_SEJOUR_before.SER_SEJ_MDT,
						ETA_SEJ_before = w_SEJOUR_before.ETA_SEJ
					FROM w_SEJOUR w_SEJOUR_before
					WHERE w_SEJOUR.SEJ_DOS = w_SEJOUR_before.SEJ_DOS
						AND w_SEJOUR.sequence = w_SEJOUR_before.sequence + 1;
						
						
				DELETE FROM w_SEJOUR WHERE w_DHAE_SEJ > w_DHAS_SEJ;
				
				



				DROP TABLE IF EXISTS w_mouvements_sejour;

				CREATE TEMP TABLE w_mouvements_sejour AS
				SELECT 
					w_SEJOUR.SEJ_DOS,
					w_SEJOUR.SEJ_DOS 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 =  date(w_DHAE_SEJ) THEN extract('hour' from w_DHAE_SEJ) * 10000 + extract('minute' from w_DHAE_SEJ) * 100 + extract('second' from w_DHAE_SEJ) ELSE 0 END AS heure_debut,
					CASE WHEN p_calendrier.date =  date(w_DHAS_SEJ) THEN extract('hour' from w_DHAS_SEJ) * 10000 + extract('minute' from w_DHAS_SEJ) * 100 + extract('second' from w_DHAS_SEJ) ELSE 240000 END AS heure_fin,
					CASE WHEN w_QENTREE = '1' AND p_calendrier.date =  date(w_DHAE_SEJ) AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_entrees_directes,
					CASE WHEN w_QSORTIE = '1' AND p_calendrier.date =  date(w_DHAS_SEJ) AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_sorties_directes,
					CASE WHEN w_QENTREE = '1' AND p_calendrier.date =  date(w_DHAE_SEJ) AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_entree,
					CASE WHEN w_QSORTIE = '1' AND p_calendrier.date =  date(w_DHAS_SEJ) 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 w_QENTREE = '1' AND p_calendrier.date =  date(w_DHAE_SEJ) AND p_sejours.type_sejour = '2' THEN 1 ELSE 0 END AS nb_ambulatoires,
					CASE WHEN w_QENTREE = '1' AND p_calendrier.date =  date(w_DHAE_SEJ) AND p_sejours.type_sejour = '3' THEN 1 ELSE 0 END AS nb_externes,
					CASE WHEN URG = '1' AND p_calendrier.date =  date(w_DHAE_SEJ) AND w_QENTREE = '1' THEN 1 ELSE 0 END AS nb_urgences,
					0 as nb_seances,

					CASE WHEN p_calendrier.date = date(w_DHAE_SEJ) AND p_sejours.type_sejour = '1' AND w_QENTREE <> '1' AND SER_SEJ_MDT <> SER_SEJ_MDT_before THEN 1 ELSE 0 END AS nb_entrees_mutation_service,
					CASE WHEN p_calendrier.date = date(w_DHAS_SEJ) AND p_sejours.type_sejour = '1' AND w_QSORTIE <> '1' AND SER_SEJ_MDT <> SER_SEJ_MDT_next THEN 1 ELSE 0 END AS nb_sorties_mutation_service,
					CASE WHEN p_calendrier.date = date(w_DHAE_SEJ) AND p_sejours.type_sejour = '1' AND w_QENTREE <> '1' AND ETA_SEJ <> ETA_SEJ_before THEN 1 ELSE 0 END AS nb_entrees_mutation_etage,
					CASE WHEN p_calendrier.date = date(w_DHAS_SEJ) AND p_sejours.type_sejour = '1' AND w_QSORTIE <> '1' AND ETA_SEJ <> ETA_SEJ_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' THEN 1 ELSE 0 END AS nb_jours_js_inclus,
					CASE WHEN p_sejours.type_sejour = '1' AND p_calendrier.date <> date(w_DHAS_SEJ) THEN 1 ELSE 0 END AS nb_jours_js_non_inclus,

					CASE WHEN p_sejours.type_sejour = '1' AND t_lits.chambre_particuliere = 'O' THEN '1' ELSE '0' END AS est_chambre_particuliere,
					CASE WHEN p_sejours.type_sejour = '1' AND t_lits.chambre_particuliere = 'O' THEN 1 ELSE 0 END AS nb_chambres_particulieres,

					0 AS nb_bebes,

					lieu_id,

					p_sejours.medecin_sejour_id as medecin_sejour_id,
					
					CASE WHEN p_sejours.code_prevu = '1' OR p_calendrier.date > date(now_sigems) THEN '1' ELSE '0' END AS est_mouvement_previsionnel
				FROM w_SEJOUR 
					JOIN w_PERIODE ON periode_id = 0
					JOIN activite[PX].p_sejours ON w_SEJOUR.SEJ_DOS = p_sejours.no_sejour AND p_sejours.etat = ''
					LEFT JOIN activite[PX].t_lits ON NCH_SEJ = t_lits.code_original
					JOIN base.p_calendrier ON (p_calendrier.date BETWEEN date(w_DHAE_SEJ) AND date(w_DHAS_SEJ) AND p_calendrier.date <= now() + interval '1 month' )
				ORDER BY sequence, p_calendrier.date;
				
				
				-- Bébés
				DROP TABLE IF EXISTS w_CCAM_RUM_bebes;
				
				CREATE TEMP TABLE w_CCAM_RUM_bebes AS
				SELECT jointure AS no_sejour,
					MAX(CASE WHEN t_actes.texte ILIKE '%multiple%' THEN 2 ELSE 1 END) AS nb_bebes
				FROM prod_sigems2.CCAM_RUM
					JOIN base.t_actes ON substring(CCAM_RUM.CODE, 1, 7) = t_actes.code AND 
						CCAM_RUM.CODE LIKE 'JQG%' AND 
						t_actes.texte ILIKE 'accouchement%' 
				WHERE ACTIVITE = '1'
				GROUP BY 1;
				
				UPDATE w_mouvements_sejour 
				SET nb_bebes = w_CCAM_RUM_bebes.nb_bebes
				FROM w_CCAM_RUM_bebes 
				WHERE w_CCAM_RUM_bebes.no_sejour = w_mouvements_sejour.no_sejour AND
					(nb_entrees_directes = 1 OR nb_externes = 1 OR nb_ambulatoires = 1);
					
				-- Séances
				DROP TABLE IF EXISTS w_LIG_HONOR_seances;
				
				CREATE TEMP TABLE w_LIG_HONOR_seances AS
				SELECT 
					SEJ_DOS,
					date(dde_lho) AS date,
					SUM(QTE_LHO) AS nb_seances
				FROM prod_sigems2.LIG_HONOR
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LHO = ANN_SELECT AND COD_LHO = COD_SELECT
					JOIN w_DOSSIER  ON ANN_LHO = ANN_DOS AND COD_LHO = COD_DOS
					JOIN prod_sigems2.PROD_HONOR ON CPH_LHO = COD_PRH
				WHERE ACT_PRH = 'K' AND 
					COF_LHO IN (15 , 30) AND 
					(CPH_LHO = 'CHI' OR DMT_LHO = '302')
				GROUP BY 1,2;
					
				CREATE INDEX w_LIG_HONOR_seances_i1
				  ON w_LIG_HONOR_seances
				  USING btree
				  (SEJ_DOS);
				  
				UPDATE w_mouvements_sejour
				SET nb_seances = w_LIG_HONOR_seances.nb_seances
				FROM w_LIG_HONOR_seances
				WHERE w_LIG_HONOR_seances.SEJ_DOS = w_mouvements_sejour.no_sejour AND 
					w_LIG_HONOR_seances.date = w_mouvements_sejour.date;
					
					
					
					
				DROP TABLE IF EXISTS w_LIG_CLINI_seances;
				
				CREATE TEMP TABLE w_LIG_CLINI_seances AS
				SELECT 
					SEJ_DOS,
					date(DDE_LCL) AS date,
					SUM(QTE_LCL) AS nb_seances
				FROM prod_sigems2.LIG_CLINI
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LCL = ANN_SELECT AND COD_LCL = COD_SELECT
					JOIN w_DOSSIER ON ANN_LCL = ANN_DOS AND COD_LCL = COD_DOS
				WHERE PRO_LCL IN ('D01', 'D02', 'D03', 'D04', 'D05', 'D06', 'D07', 'D08', 'D09', 'D10', 'D11', 'D12', 'D13', 'D14', 'D15', 'D16', 'D17', 'D18', 'D19')
				GROUP BY 1,2;
					
				CREATE INDEX w_LIG_CLINI_seances_i1
				  ON w_LIG_CLINI_seances
				  USING btree
				  (SEJ_DOS);
				  
				UPDATE w_mouvements_sejour
				SET nb_seances = w_LIG_CLINI_seances.nb_seances
				FROM w_LIG_CLINI_seances
				WHERE w_LIG_CLINI_seances.SEJ_DOS = w_mouvements_sejour.no_sejour AND 
					w_LIG_CLINI_seances.date = w_mouvements_sejour.date;
					
					
					
				
				-- 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 type_sejour <> '5' AND
					date_groupage < '20991231' 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;			

					
				
				-- Génération
				DELETE FROM w_mouvements_sejour 
				WHERE 
					nb_entrees_directes = 0 AND
					nb_sorties_directes = 0 AND
					est_jour_hospitalisation <> '1' AND
					nb_ambulatoires = 0 AND
					nb_externes = 0 AND
					nb_urgences = 0 AND
					nb_seances = 0 AND
					nb_entrees_mutation_service = 0 AND
					nb_sorties_mutation_service = 0 AND
					nb_entrees_mutation_etage = 0 AND
					nb_sorties_mutation_etage = 0 AND
					nb_entrees_mutation_activite = 0 AND
					nb_sorties_mutation_activite = 0 AND
					nb_entrees_mutation_unite_medicale = 0 AND
					nb_sorties_mutation_unite_medicale = 0 AND
					nb_jours_js_inclus = 0 AND
					nb_jours_js_non_inclus = 0 AND
					est_chambre_particuliere <> '1' AND
					nb_chambres_particulieres = 0 AND
					nb_bebes = 0;
					
					
				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');

				INSERT INTO activite[PX].p_mouvements_sejour(
							sejour_id, no_sejour, date, 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,est_mouvement_previsionnel, jour_semaine, is_weekend)
				SELECT sejour_id, no_sejour, date,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,est_mouvement_previsionnel, jour_semaine, is_weekend
				FROM w_mouvements_sejour 
				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');
				
				
				
				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 IS DISTINCT FROM p_mouvements_sejour.lieu_id);
						
				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 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
					)


										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lien PMSI">
		
			<condition><![CDATA[
				"[TYPE_TRAITEMENT]" == "E"
			]]></condition>
			
			<sqlcmd><![CDATA[
			
					SELECT activite.cti_reorganize_sejour_pmsi()

			]]></sqlcmd>
		</NODE>
		
	</NODE>

	<NODE name="FACTURE" label="RECUPERATION DES FACTURES">
	
	
		<NODE label="Correction mouvements">
			<sqlcmd><![CDATA[
						
				DROP TABLE IF EXISTS w_DOS2_caisse;
				CREATE TEMP TABLE w_DOS2_caisse AS
				SELECT ANN_DOS2 AS ANN_DOS2_S, COD_DOS2 AS COD_DOS2_S, 
					MAX(CP1_DOS2) AS CP1_DOS2_S, 
					MAX(CA1_DOS2) AS CA1_DOS2_S, 
					MAX(CA2_DOS2) AS CA2_DOS2_S
				FROM prod_sigems2.DOS2
				GROUP BY 1,2;
				
				CREATE INDEX w_DOS2_caisse_i1
				  ON w_DOS2_caisse
				  USING btree
				  (COD_DOS2_S);



				DROP TABLE IF EXISTS w_DOS2_fictif_cli;
				CREATE TEMP TABLE w_DOS2_fictif_cli AS
				SELECT ANN_LCL AS ANN_DOS2, COD_LCL AS COD_DOS2, IND_LCL AS IND_DOS2, MAX(DAT_REG) AS DAT_REG, 
					SUM(CASE WHEN CAI_REG = CP1_DOS2_S THEN MONT ELSE 0 END) AS SR1_DOS2,
					SUM(CASE WHEN CAI_REG = CA2_DOS2_S THEN MONT ELSE 0 END) AS SR2_DOS2,
					SUM(CASE WHEN CAI_REG IS DISTINCT FROM CP1_DOS2_S AND CAI_REG IS DISTINCT FROM CA2_DOS2_S THEN MONT ELSE 0 END) AS SR3_DOS2,
					0::numeric AS HR1_DOS2,
					0::numeric AS HR2_DOS2,
					0::numeric AS HR3_DOS2
				FROM prod_sigems2.LIG_CLINI
					JOIN prod_sigems2.REG4 ON NUM_LCL = NUM_CLI
					JOIN prod_sigems2.REG ON NUM_REG4 = SER_REG
					LEFT JOIN w_DOS2_caisse ON ANN_LCL = ANN_DOS2_S AND COD_LCL = COD_DOS2_S
					LEFT JOIN prod_sigems2.DOS2 ON ANN_LCL = ANN_DOS2 AND COD_LCL = COD_DOS2 AND IND_LCL = IND_DOS2
				WHERE ANN_DOS2 IS NULL
				GROUP BY 1,2,3
				HAVING SUM(MONT) <> 0;



				DROP TABLE IF EXISTS w_DOS2_fictif_hon;
				CREATE TEMP TABLE w_DOS2_fictif_hon AS
				SELECT ANN_LHO AS ANN_DOS2, COD_LHO AS COD_DOS2, IND_LHO AS IND_DOS2, MAX(DAT_REG) AS DAT_REG, 
					0::numeric AS SR1_DOS2,
					0::numeric AS SR2_DOS2,
					0::numeric AS SR3_DOS2,
					SUM(CASE WHEN CAI_REG = CP1_DOS2_S THEN MON_REG3 ELSE 0 END) AS HR1_DOS2,
					SUM(CASE WHEN CAI_REG = CA2_DOS2_S THEN MON_REG3 ELSE 0 END) AS HR2_DOS2,
					SUM(CASE WHEN CAI_REG IS DISTINCT FROM CP1_DOS2_S AND CAI_REG IS DISTINCT FROM CA2_DOS2_S THEN MON_REG3 ELSE 0 END) AS HR3_DOS2
				FROM prod_sigems2.LIG_HONOR
					JOIN w_REG3 ON NUM_LHO = LHO_REG3
					LEFT JOIN w_DOS2_caisse ON ANN_LHO = ANN_DOS2_S AND COD_LHO = COD_DOS2_S
					LEFT JOIN prod_sigems2.DOS2 ON ANN_LHO = ANN_DOS2 AND COD_LHO = COD_DOS2 AND IND_LHO = IND_DOS2
				WHERE ANN_DOS2 IS NULL
				GROUP BY 1,2,3
				HAVING SUM(MON_REG3) <> 0;


				INSERT INTO prod_sigems2.DOS2(
					ANN_DOS2,
					COD_DOS2,
					IND_DOS2,
					ETA_DOS2,
					DEN_DOS2,
					DSO_DOS2,
					HEU_DOS2,
					RIS_DOS2,
					JEX_DOS2,
					CFA_DOS2,
					COP_DOS2,
					DFA_DOS2,
					NDK_DOS2,
					DDK_DOS2,
					NB1_DOS2,
					DB1_DOS2,
					NB2_DOS2,
					DB2_DOS2,
					SJ1_DOS2,
					HO1_DOS2,
					SJ2_DOS2,
					HO2_DOS2,
					SJ3_DOS2,
					HO3_DOS2,
					SR1_DOS2,
					HR1_DOS2,
					SR2_DOS2,
					HR2_DOS2,
					SR3_DOS2,
					HR3_DOS2,
					CP1_DOS2,
					CA1_DOS2,
					CA2_DOS2,
					LOT_DOS2,
					REG_DOS2)
				SELECT
					ANN_DOS2,
					COD_DOS2,
					IND_DOS2,
					'9',
					DEN_DOS,
					DSO_DOS,
					HEU_DOS,
					'' AS RIS_DOS2,
					0 AS JEX_DOS2,
					'' AS CFA_DOS2,
					'' AS COP_DOS2,
					MIN(DAT_REG) AS DFA_DOS2,
					'' AS NDK_DOS2,
					NULL::date AS DDK_DOS2,
					0 AS NB1_DOS2,
					NULL::date AS DB1_DOS2,
					0 AS NB2_DOS2,
					NULL::date AS DB2_DOS2,
					0 AS SJ1_DOS2,
					0 AS HO1_DOS2,
					0 AS SJ2_DOS2,
					0 AS HO2_DOS2,
					0 AS SJ3_DOS2,
					0 AS HO3_DOS2,
					SUM(SR1_DOS2) AS SR1_DOS2,
					SUM(HR1_DOS2) AS HR1_DOS2,
					SUM(SR2_DOS2) AS SR2_DOS2,
					SUM(HR2_DOS2) AS HR2_DOS2,
					SUM(SR3_DOS2) AS SR3_DOS2,
					SUM(HR3_DOS2) AS HR3_DOS2,
					CP1_DOS2_S AS CP1_DOS2,
					CA1_DOS2_S AS CA1_DOS2,
					CA2_DOS2_S AS CA2_DOS2,
					'' AS LOT_DOS2,
					'' AS REG_DOS2
				FROM
					(SELECT * FROM w_DOS2_fictif_cli
					UNION
					SELECt * FROM w_DOS2_fictif_hon
					) subview
					JOIN prod_sigems2.DOSSIER ON ANN_DOS2 = ANN_DOS AND COD_DOS2 = COD_DOS
					JOIN w_DOS2_caisse ON ANN_DOS2 = ANN_DOS2_S AND COD_DOS2 = COD_DOS2_S
				GROUP BY ANN_DOS2,
					COD_DOS2,
					IND_DOS2,
					DEN_DOS,
					DSO_DOS,
					HEU_DOS,
					CP1_DOS2_S,
					CA1_DOS2_S,
					CA2_DOS2_S;
			
		]]></sqlcmd>
		</NODE>
	
		<NODE label="Entêtes">
			<sqlcmd><![CDATA[
			
			
				DROP TABLE IF EXISTS w_DOS2_eta2;
				CREATE TEMP TABLE w_DOS2_eta2 AS
				SELECT ANN_DOS2, COD_DOS2,
				MAX(IND_DOS2) AS IND_DOS2_ETA2
				FROM prod_sigems2.DOS2
				WHERE ETA_DOS2 = 2
				GROUP BY 1,2;

				CREATE INDEX w_DOS2_eta2_i1
				  ON w_DOS2_eta2
				  USING btree
				  (COD_DOS2);
			
							
			
				-- Type T2A/Budget global, facturation intermediaire par séjour
				UPDATE w_DOSSIER_SELECT SET
					est_budget_global = p_sejours.est_budget_global,
					type_t2a = t_services_facturation.type_t2a,
					avec_facturation_intermediaire = t_services_facturation.avec_facturation_intermediaire
				FROM activite[PX].p_sejours
				JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
				JOIN activite[PX].t_services_facturation on service_facturation_id = t_services_facturation.oid
				WHERE no_sejour = no_sejour_SELECT AND
					(
						w_DOSSIER_SELECT.est_budget_global IS DISTINCT FROM p_sejours.est_budget_global OR
						w_DOSSIER_SELECT.type_t2a IS DISTINCT FROM t_services_facturation.type_t2a OR
						w_DOSSIER_SELECT.avec_facturation_intermediaire IS DISTINCT FROM t_services_facturation.avec_facturation_intermediaire
					);
				
				-- Préparation lignes clinique (pour budget global SSR)
				
				DROP TABLE IF EXISTS w_ANALYG;
				CREATE TEMP TABLE w_ANALYG AS
				SELECT PRD_ANA, DMT_ANA, MDT_ANA, SER_ANA, MAX(CPT_ANA) AS CPT_ANA
				FROM prod_sigems2.ANALYG
				WHERE CPT_ANA <> ''
				GROUP BY 1,2,3,4
				ORDER BY 1,2,3,4;

				CREATE INDEX w_ANALYG_i1
				  ON w_ANALYG
				  USING btree
				  (PRD_ANA);

				DROP TABLE IF EXISTS w_LIG_CLINI;
				CREATE TEMP TABLE w_LIG_CLINI AS
				SELECT
					LIG_CLINI.*,
					CASE WHEN TX1_LCL <> 0 AND ML1_LCL = 0 AND type_t2a = '2' AND est_budget_global = '1' THEN TAR_LCL - ML2_LCL - ML3_LCL ELSE 0 END AS ML1_LCL_BG,
					ANN_LCL || to_char(COD_LCL,'FM900000') AS SEJ_DOS,
					ANN_LCL || to_char(COD_LCL,'FM900000') || '.' || to_char(CASE WHEN IND_LCL <> 0 THEN IND_LCL ELSE COALESCE(IND_DOS2_ETA2, IND_LCL) END,'FM9999900') AS no_facture,
					COALESCE(MDT_REEL,MDT_DOS) AS MDT_LCL,
					COALESCE(ACT_PRC,PRO_LCL) AS ACT_LCL,
					COALESCE(w_ANALYG_SER.CPT_ANA,w_ANALYG.CPT_ANA, AFA_PRC,'') AS CPT_ANA,
					PRO_LCL || '|' || 
					COALESCE(ACT_PRC,PRO_LCL) || 
					COALESCE(w_ANALYG_SER.CPT_ANA,w_ANALYG.CPT_ANA, AFA_PRC,'') AS key,
					CASE WHEN CASE WHEN IND_LCL <> 0 THEN IND_LCL ELSE COALESCE(IND_DOS2_ETA2, IND_LCL) END = 0 THEN '1' ELSE '0' END AS non_facturee
				FROM prod_sigems2.LIG_CLINI
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LCL = ANN_SELECT AND COD_LCL = COD_SELECT
					JOIN prod_sigems2.DOSSIER ON DOSSIER.ANN_DOS = ANN_LCL AND DOSSIER.COD_DOS = COD_LCL
					LEFT JOIN prod_sigems2.DOSSIER_MDT ON DOSSIER.ANN_DOS = DOSSIER_MDT.ANN_DOS AND DOSSIER.COD_DOS = DOSSIER_MDT.COD_DOS
					LEFT JOIN w_DOS2_ETA2 ON ANN_LCL = ANN_DOS2 AND COD_LCL = COD_DOS2
					LEFT JOIN prod_sigems2.PROD_CLINI ON PRO_LCL = COD_PRC
					LEFT JOIN w_ANALYG ON PRO_LCL = w_ANALYG.PRD_ANA AND w_ANALYG.DMT_ANA = '' AND w_ANALYG.MDT_ANA = '' AND w_ANALYG.SER_ANA = ''
					LEFT JOIN w_ANALYG w_ANALYG_SER ON PRO_LCL = w_ANALYG_SER.PRD_ANA AND w_ANALYG_SER.DMT_ANA = '' AND w_ANALYG_SER.MDT_ANA = '' AND w_ANALYG_SER.SER_ANA = SER_LCL
				WHERE 
					PRO_LCL <> 'ECAC' AND
					PRO_LCL <> 'GMOY';
					
				UPDATE w_LIG_CLINI
				SET MDT_LCL = '04'
				WHERE MDT_LCL = '23';
					
				CREATE INDEX w_LIG_CLINI_i1
				  ON w_LIG_CLINI
				  USING btree
				  (COD_LCL);
								
				CREATE INDEX w_LIG_CLINI_i2
				  ON w_LIG_CLINI
				  USING btree
				  (NUM_LCL);
				  
				CREATE INDEX w_LIG_CLINI_i3
				  ON w_LIG_CLINI
				  USING btree
				  (PRO_LCL);
				  
				CREATE INDEX w_LIG_CLINI_i4
				  ON w_LIG_CLINI
				  USING btree
				  (key);
				  
				CREATE INDEX w_LIG_CLINI_i5
				  ON w_LIG_CLINI
				  USING btree
				  (no_facture);
				  
				CREATE INDEX w_LIG_CLINI_i6
				  ON w_LIG_CLINI
				  USING btree
				  (SEJ_DOS);
				  


				  
				UPDATE w_LIG_CLINI
				SET CPT_ANA = w_ANALYG.CPT_ANA,
					key = PRO_LCL || '|' || 
						ACT_LCL ||  '|' || 
						w_ANALYG.CPT_ANA
				FROM w_ANALYG 
				WHERE PRO_LCL = PRD_ANA AND SER_ANA = '' AND DMT_ANA = DMT_LCL  AND MDT_ANA = '' AND
					w_LIG_CLINI.CPT_ANA IS DISTINCT FROM w_ANALYG.CPT_ANA;

				UPDATE w_LIG_CLINI
				SET CPT_ANA = w_ANALYG.CPT_ANA,
					key = PRO_LCL || '|' || 
						ACT_LCL ||  '|' || 
						w_ANALYG.CPT_ANA
				FROM w_ANALYG 
				WHERE PRO_LCL = PRD_ANA AND SER_ANA = '' AND DMT_ANA = '' AND MDT_ANA = MDT_LCL AND
					w_LIG_CLINI.CPT_ANA IS DISTINCT FROM w_ANALYG.CPT_ANA;


				UPDATE w_LIG_CLINI
				SET CPT_ANA = w_ANALYG.CPT_ANA,
					key = PRO_LCL || '|' || 
						ACT_LCL ||  '|' || 
						w_ANALYG.CPT_ANA
				FROM w_ANALYG 
				WHERE PRO_LCL = PRD_ANA AND SER_ANA = '' AND DMT_ANA = DMT_LCL AND MDT_ANA = MDT_LCL AND
					w_LIG_CLINI.CPT_ANA IS DISTINCT FROM w_ANALYG.CPT_ANA;
					
					
				UPDATE w_LIG_CLINI
				SET CPT_ANA = w_ANALYG.CPT_ANA,
					key = PRO_LCL || '|' || 
						ACT_LCL ||  '|' || 
						w_ANALYG.CPT_ANA
				FROM w_ANALYG 
				WHERE PRO_LCL = PRD_ANA AND SER_ANA = SER_LCL AND DMT_ANA = ''  AND MDT_ANA = '' AND
					w_LIG_CLINI.CPT_ANA IS DISTINCT FROM w_ANALYG.CPT_ANA;


				UPDATE w_LIG_CLINI
				SET CPT_ANA = w_ANALYG.CPT_ANA,
					key = PRO_LCL || '|' || 
						ACT_LCL ||  '|' || 
						w_ANALYG.CPT_ANA
				FROM w_ANALYG 
				WHERE PRO_LCL = PRD_ANA AND SER_ANA = SER_LCL AND DMT_ANA = DMT_LCL  AND MDT_ANA = '' AND
					w_LIG_CLINI.CPT_ANA IS DISTINCT FROM w_ANALYG.CPT_ANA;

				UPDATE w_LIG_CLINI
				SET CPT_ANA = w_ANALYG.CPT_ANA,
					key = PRO_LCL || '|' || 
						ACT_LCL ||  '|' || 
						w_ANALYG.CPT_ANA
				FROM w_ANALYG 
				WHERE PRO_LCL = PRD_ANA AND SER_ANA = SER_LCL AND DMT_ANA = '' AND MDT_ANA = MDT_LCL AND
					w_LIG_CLINI.CPT_ANA IS DISTINCT FROM w_ANALYG.CPT_ANA;

				UPDATE w_LIG_CLINI
				SET CPT_ANA = w_ANALYG.CPT_ANA,
					key = PRO_LCL || '|' || 
						ACT_LCL ||  '|' || 
						w_ANALYG.CPT_ANA
				FROM w_ANALYG 
				WHERE PRO_LCL = PRD_ANA AND SER_ANA = SER_LCL AND DMT_ANA = DMT_LCL AND MDT_ANA = MDT_LCL AND
					w_LIG_CLINI.CPT_ANA IS DISTINCT FROM w_ANALYG.CPT_ANA;

					
				  
				UPDATE w_LIG_CLINI
				SET 
					MR1_LCL = ML1_LCL,
					MR2_LCL = ML2_LCL,
					MR3_LCL = ML3_LCL
				FROM prod_sigems2.DOS2
				WHERE ANN_DOS2 = ANN_LCL AND
					COD_DOS2 = COD_LCL AND
					IND_DOS2 = IND_LCL AND
					ETA_DOS2 = '5' AND
					COP_DOS2 = '1' AND
					(
						MR1_LCL IS DISTINCT FROM ML1_LCL OR
						MR2_LCL IS DISTINCT FROM ML2_LCL OR
						MR3_LCL IS DISTINCT FROM ML3_LCL
					);

				DROP TABLE IF EXISTS w_factures_last;
				CREATE TEMP TABLE w_factures_last AS
				SELECT no_sejour, 
					MAX(no_facture) AS no_facture,
					MAX(CASE WHEN code_facture <> '1' THEN no_facture ELSE NULL END) AS no_facture_nf
				FROM activite[PX].p_factures 
				GROUP BY 1;

				UPDATE w_LIG_CLINI
				SET no_facture = CASE WHEN PRO_LCL <> 'ACPT' THEN COALESCE(w_factures_last.no_facture_nf,w_factures_last.no_facture) ELSE w_factures_last.no_facture END
				FROM w_factures_last
				WHERE w_LIG_CLINI.SEJ_DOS = w_factures_last.no_sejour AND
					w_LIG_CLINI.no_facture NOT IN (SELECT no_facture FROM activite[PX].p_factures);
				

				DROP TABLE IF EXISTS w_LIG_CLINI_keys;
				CREATE TEMP TABLE w_LIG_CLINI_keys AS
				SELECT key,
					PRO_LCL,
					ACT_LCL,
					CPT_ANA,
					0::bigint AS rubrique_facturation_id,
					0::bigint AS rubrique_comptabilisation_id,
					0::bigint AS prestation_id,
					0::bigint AS compte_produit_id
				FROM w_LIG_CLINI
				GROUP BY 1,2,3,4;

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT trim(PRO_LCL), trim(PRO_LCL), trim(PRO_LCL), trim(PRO_LCL)
				FROM w_LIG_CLINI_keys
				WHERE trim(PRO_LCL) <> '' AND
					trim(PRO_LCL) NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL)
				GROUP BY trim(PRO_LCL)
				ORDER BY trim(PRO_LCL);
				
				UPDATE activite.t_prestations SET
					code_original = ACT_LCL
				FROM w_LIG_CLINI_keys
				where t_prestations.code_original IS DISTINCT FROM ACT_LCL
					AND t_prestations.code = ACT_LCL;
					
				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT ACT_LCL, ACT_LCL, ACT_LCL, ACT_LCL
				FROM w_LIG_CLINI_keys
				WHERE ACT_LCL <> '' AND
					ACT_LCL NOT IN (SELECT code_original FROM activite.t_prestations WHERE code_original IS NOT NULL)
				GROUP BY ACT_LCL
				ORDER BY ACT_LCL;


				UPDATE w_LIG_CLINI_keys SET prestation_id = t_prestations.oid
				FROM activite.t_prestations
				WHERE ACT_LCL = t_prestations.code_original;

				UPDATE w_LIG_CLINI_keys SET 
					rubrique_facturation_id = t_rubriques_facturation.oid,
					rubrique_comptabilisation_id = t_rubriques_facturation.oid
				FROM activite[PX].t_rubriques_facturation
				WHERE PRO_LCL = t_rubriques_facturation.code_original;
				
				
				UPDATE w_LIG_CLINI_keys SET compte_produit_id = t_compte.oid
				FROM activite[PX].t_compte
				WHERE CPT_ANA = t_compte.code;
				
				CREATE INDEX w_LIG_CLINI_keys_i1
				  ON w_LIG_CLINI_keys
				  USING btree
				  (key);
				  
			
				-- préparation
				
				
				DROP TABLE IF EXISTS w_LIG_CLINI_mrx;
				CREATE TEMP TABLE w_LIG_CLINI_mrx AS
				SELECT
					ANN_LCL,
					COD_LCL,
					IND_LCL,
					NUM_LCL,
					DAT_REG,
					CASE WHEN CAI_REG = CP1_DOS2 THEN DAT_REG ELSE '00010101' END AS DR1_LCL,	
					CASE WHEN CAI_REG = CA2_DOS2 AND CAI_REG <> CP1_DOS2 THEN DAT_REG ELSE '00010101' END AS DR2_LCL,
					CASE WHEN CAI_REG <> CP1_DOS2 AND CAI_REG <> CA2_DOS2 THEN DAT_REG ELSE '00010101' END AS DR3_LCL,
					CASE WHEN CAI_REG = CP1_DOS2 THEN MONT + TVA ELSE 0 END AS MR1_LCL,	
					CASE WHEN CAI_REG = CA2_DOS2 AND CAI_REG <> CP1_DOS2 THEN MONT + TVA ELSE 0 END AS MR2_LCL,
					CASE WHEN CAI_REG <> CP1_DOS2 AND CAI_REG <> CA2_DOS2 THEN MONT + TVA ELSE 0 END AS MR3_LCL
				FROM prod_sigems2.LIG_CLINI
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LCL = ANN_SELECT AND COD_LCL = COD_SELECT
					JOIN prod_sigems2.DOS2 ON ANN_LCL = ANN_DOS2 AND COD_LCL = COD_DOS2 AND IND_LCL = IND_DOS2 AND ETA_DOS2 >= 1
					JOIN prod_sigems2.REG4 ON NUM_LCL = NUM_CLI
					JOIN prod_sigems2.REG ON NUM_REG4 = SER_REG;

				CREATE INDEX w_LIG_CLINI_mrx_i1
				  ON w_LIG_CLINI_mrx
				  USING btree
				  (NUM_LCL);
				  
				CREATE INDEX w_LIG_CLINI_mrx_i2
				  ON w_LIG_CLINI_mrx
				  USING btree
				  (COD_LCL);
				

				DROP TABLE IF EXISTS w_LIG_CLINI_tmrx;
				CREATE TEMP TABLE w_LIG_CLINI_tmrx AS
				SELECT ANN_LCL, 
					COD_LCL, 
					IND_LCL,
					MAX(DR1_LCL) AS DR1_LCL,
					MAX(DR2_LCL) AS DR2_LCL,
					MAX(DR3_LCL) AS DR3_LCL,
					SUM(MR1_LCL) AS MR1_LCL,
					SUM(MR2_LCL) AS MR2_LCL,
					SUM(MR3_LCL) AS MR3_LCL
				FROM w_LIG_CLINI_mrx
				GROUP BY 1,2,3;
				
				CREATE INDEX w_LIG_CLINI_tmrx_i1
				  ON w_LIG_CLINI_tmrx
				  USING btree
				  (COD_LCL);
				  
				 
				DROP TABLE IF EXISTS w_LIG_HONOR_mrx;
				CREATE TEMP TABLE w_LIG_HONOR_mrx AS
				SELECT
					ANN_LHO,
					COD_LHO,
					IND_LHO,
					NUM_LHO,
					DAT_REG,
					CASE WHEN CAI_REG = CP1_DOS2 THEN DAT_REG ELSE '00010101' END AS DR1_LHO,	
					CASE WHEN CAI_REG = CA2_DOS2 AND CAI_REG <> CP1_DOS2 THEN DAT_REG ELSE '00010101' END AS DR2_LHO,
					CASE WHEN CAI_REG <> CP1_DOS2 AND CAI_REG <> CA2_DOS2 THEN DAT_REG ELSE '00010101' END AS DR3_LHO,
					CASE WHEN CAI_REG = CP1_DOS2 THEN MON_REG3 ELSE 0 END AS MR1_LHO,	
					CASE WHEN CAI_REG = CA2_DOS2 AND CAI_REG <> CP1_DOS2 THEN MON_REG3 ELSE 0 END AS MR2_LHO,
					CASE WHEN CAI_REG <> CP1_DOS2 AND CAI_REG <> CA2_DOS2 THEN MON_REG3 ELSE 0 END AS MR3_LHO
				FROM prod_sigems2.LIG_HONOR
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LHO = ANN_SELECT AND COD_LHO = COD_SELECT
					JOIN prod_sigems2.DOS2 ON ANN_LHO = ANN_DOS2 AND COD_LHO = COD_DOS2 AND IND_LHO = IND_DOS2 AND ETA_DOS2 >= 1
					JOIN w_REG3 ON NUM_LHO = LHO_REG3;
					
				CREATE INDEX w_LIG_HONOR_mrx_i1
				  ON w_LIG_HONOR_mrx
				  USING btree
				  (NUM_LHO);
				  
				CREATE INDEX w_LIG_HONOR_mrx_i2
				  ON w_LIG_HONOR_mrx
				  USING btree
				  (COD_LHO);
				  
				
				  
				
				DROP TABLE IF EXISTS w_LIG_HONOR_tmrx;
				CREATE TEMP TABLE w_LIG_HONOR_tmrx AS
				SELECT ANN_LHO, 
					COD_LHO, 
					IND_LHO,
					MAX(DR1_LHO) AS DR1_LHO,
					MAX(DR2_LHO) AS DR2_LHO,
					MAX(DR3_LHO) AS DR3_LHO,
					SUM(MR1_LHO) AS MR1_LHO,
					SUM(MR2_LHO) AS MR2_LHO,
					SUM(MR3_LHO) AS MR3_LHO
				FROM w_LIG_HONOR_mrx
				GROUP BY 1,2,3;
				
				CREATE INDEX w_LIG_HONOR_tmrx_i1
				  ON w_LIG_HONOR_tmrx
				  USING btree
				  (COD_LHO);
				
				-- Factures 'normales'
				DROP TABLE IF EXISTS w_factures;
				CREATE TEMP TABLE w_factures AS
				SELECT 
					nextval('activite[PX].s_factures'::regclass) AS oid,
					p_sejours.oid AS sejour_id,
					SEJ_DOS AS no_sejour,
					ANN_DOS,
					COD_DOS,
					IND_DOS2,
					SEJ_DOS || '.' || to_char(IND_DOS2,'FM9999900') AS no_facture,
					CASE WHEN (SJ1_DOS2 < 0 OR HO1_DOS2 < 0 OR SJ2_DOS2 < 0 OR HO2_DOS2 < 0 OR SJ3_DOS2 < 0 OR HO3_DOS2 < 0) THEN SEJ_DOS || '.' || to_char(IND_DOS2,'FM9999900') ELSE SEJ_DOS || '.01' END AS no_facture_reference,
					CASE WHEN (SJ1_DOS2 < 0 OR HO1_DOS2 < 0 OR SJ2_DOS2 < 0 OR HO2_DOS2 < 0 OR SJ3_DOS2 < 0 OR HO3_DOS2 < 0) THEN 0 ELSE 0 END AS facture_reference_id,
					''::text AS no_facture_od_avoir,
					0::bigint AS facture_od_avoir_id,
					DEN_DOS2 AS date_debut,
					GREATEST(DSO_DOS2,DEN_DOS2) AS date_fin,
					p_sejours.ghs_id,
					p_sejours.ghs_bebe1_id,
					p_sejours.ghs_bebe2_id,
					p_sejours.ghs_bebe3_id,
					p_sejours.code_cp_demandee AS code_cp_demandee,
					CASE WHEN (SJ1_DOS2 < 0 OR HO1_DOS2 < 0 OR SJ2_DOS2 < 0 OR HO2_DOS2 < 0 OR SJ3_DOS2 < 0 OR HO3_DOS2 < 0) THEN '1' WHEN IND_DOS2 > 1 AND avec_facturation_intermediaire IS DISTINCT FROM '1' THEN '2' ELSE '0' END AS type_facture,
					CASE WHEN (SJ1_DOS2 < 0 OR HO1_DOS2 < 0 OR SJ2_DOS2 < 0 OR HO2_DOS2 < 0 OR SJ3_DOS2 < 0 OR HO3_DOS2 < 0) THEN 1::numeric ELSE 0::numeric END AS nb_rejets,
					
					CASE WHEN ETA_DOS2 >= 3 THEN 1::numeric ELSE 0::numeric END AS code_facture,
					CASE WHEN ETA_DOS2 >= 3 THEN COALESCE(DFA_DOS2, date(now())) ELSE '20991231' END AS date_facture,
					CASE WHEN ETA_DOS2 >= 3 AND DFA_DOS2 IS NOT NULL THEN 1::numeric ELSE 0::numeric END AS code_vente,
					CASE WHEN ETA_DOS2 >= 3 AND DFA_DOS2 IS NOT NULL THEN date_part('year', DFA_DOS2) * 100 + date_part('month', DFA_DOS2) ELSE 209912 END AS mois_vente,
					CASE WHEN ETA_DOS2 >= 3 AND DFA_DOS2 IS NOT NULL THEN DFA_DOS2 ELSE '20991231' END AS date_vente,
					''::text AS code_cloture,

					CASE WHEN p_sejours.ghs_id > 0 THEN 'GHS' ELSE '' END AS particularite_t2a,
					
					COALESCE(t_tiers_payant_0.oid,0) AS tiers_payant_0_id,
					COALESCE(t_tiers_payant_1.oid,0) AS tiers_payant_1_id,
					COALESCE(t_tiers_payant_2.oid,0) AS tiers_payant_2_id,
					0::bigint AS tiers_payant_22_id,

					CASE WHEN ETA_DOS2 >= 3 THEN SJ1_DOS2 + SJ2_DOS2 + SJ3_DOS2 ELSE 0 END AS montant_facture_c,
					CASE WHEN ETA_DOS2 >= 3 THEN HO1_DOS2 + HO2_DOS2 + HO3_DOS2 ELSE 0 END AS montant_facture_h,
					CASE WHEN ETA_DOS2 >= 3 THEN SJ3_DOS2 ELSE 0 END AS montant_facture_0_c,
					CASE WHEN ETA_DOS2 >= 3 THEN HO3_DOS2 ELSE 0 END AS montant_facture_0_h,
					CASE WHEN ETA_DOS2 >= 3 THEN SJ1_DOS2 ELSE 0 END AS montant_facture_1_c,
					CASE WHEN ETA_DOS2 >= 3 THEN HO1_DOS2 ELSE 0 END AS montant_facture_1_h,
					CASE WHEN ETA_DOS2 >= 3 THEN SJ2_DOS2 ELSE 0 END AS montant_facture_2_c,
					CASE WHEN ETA_DOS2 >= 3 THEN HO2_DOS2 ELSE 0 END AS montant_facture_2_h,
					0::numeric AS montant_facture_22_c,
					0::numeric AS montant_facture_22_h,
					CASE WHEN ETA_DOS2 >= 3 THEN SJ1_DOS2 + SJ2_DOS2 + SJ3_DOS2 ELSE 0 END AS montant_comptabilise_c,
					CASE WHEN ETA_DOS2 >= 3 THEN HO1_DOS2 + HO2_DOS2 + HO3_DOS2 ELSE 0 END AS montant_comptabilise_h,
					CASE WHEN ETA_DOS2 >= 3 THEN SJ3_DOS2 ELSE 0 END AS montant_comptabilise_0_c,
					CASE WHEN ETA_DOS2 >= 3 THEN HO3_DOS2 ELSE 0 END AS montant_comptabilise_0_h,
					CASE WHEN ETA_DOS2 >= 3 THEN SJ1_DOS2 ELSE 0 END AS montant_comptabilise_1_c,
					CASE WHEN ETA_DOS2 >= 3 THEN HO1_DOS2 ELSE 0 END AS montant_comptabilise_1_h,
					CASE WHEN ETA_DOS2 >= 3 THEN SJ2_DOS2 ELSE 0 END AS montant_comptabilise_2_c,
					CASE WHEN ETA_DOS2 >= 3 THEN HO2_DOS2 ELSE 0 END AS montant_comptabilise_2_h,
					0::numeric AS montant_comptabilise_22_c,
					0::numeric AS montant_comptabilise_22_h,
					COALESCE(MR1_LCL,0) + COALESCE(MR2_LCL,0) + COALESCE(MR3_LCL,0) AS montant_regle_c,
					COALESCE(MR1_LHO,0) + COALESCE(MR2_LHO,0) + COALESCE(MR3_LHO,0) AS montant_regle_h,
					COALESCE(MR3_LCL,0) AS montant_regle_0_c,
					COALESCE(MR3_LHO,0) AS montant_regle_0_h,
					COALESCE(MR1_LCL,0) AS montant_regle_1_c,
					COALESCE(MR1_LHO,0) AS montant_regle_1_h,
					COALESCE(MR2_LCL,0) AS montant_regle_2_c,
					COALESCE(MR2_LHO,0) AS montant_regle_2_h,
					0::numeric AS montant_regle_22_c,
					0::numeric AS montant_regle_22_h,
					'1'::text AS code_expedie_0,
					CASE WHEN COALESCE(DB1_DOS2,'00010101')::date > '00010101'::date THEN '1' ELSE '0' END AS code_expedie_1,
					CASE WHEN COALESCE(DB2_DOS2,'00010101')::date > '00010101'::date THEN '1' ELSE '0' END AS code_expedie_2,
					0::numeric AS code_expedie_22,
					CASE WHEN COALESCE(DB1_DOS2,'00010101')::date > '00010101' THEN COALESCE(DB1_DOS2,'00010101') ELSE COALESCE(DB2_DOS2,'00010101') END AS date_expedition,
					DFA_DOS2 AS date_expedition_0,
					COALESCE(DB1_DOS2,'00010101') AS date_expedition_1,
					COALESCE(DB2_DOS2,'00010101') AS date_expedition_2,
					'00010101'::date AS date_expedition_22,
					0 AS no_bordereau_0,
					NB1_DOS2 AS no_bordereau_1,
					NB2_DOS2 AS no_bordereau_2,
					0::numeric AS no_bordereau_22,

					LEAST(GREATEST(DR1_LCL, DR2_LCL, DR3_LCL, DR1_LHO, DR2_LHO, DR3_LHO), '20991231') AS date_solde,
					LEAST(GREATEST(DR1_LCL, DR2_LCL, DR3_LCL), '20991231') AS date_solde_c,
					LEAST(GREATEST(DR1_LHO, DR2_LHO, DR3_LHO), '20991231') AS date_solde_h,
					LEAST(DR3_LCL, '20991231') AS date_solde_0_c,
					LEAST(DR3_LHO, '20991231') AS date_solde_0_h,
					LEAST(DR1_LCL, '20991231') AS date_solde_1_c,
					LEAST(DR1_LHO, '20991231') AS date_solde_1_h,
					LEAST(DR2_LCL, '20991231') AS date_solde_2_c,
					LEAST(DR2_LHO, '20991231') AS date_solde_2_h,
					'20991231'::date AS date_solde_22_c,
					'20991231'::date AS date_solde_22_h,


					0::numeric AS montant_encours_c,
					0::numeric AS montant_encours_0_c,
					0::numeric AS montant_encours_1_c,
					0::numeric 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,

					'20991231'::date AS date_solde_reference,
					'20991231'::date AS date_solde_reference_c,
					'20991231'::date AS date_solde_reference_h,
					'20991231'::date AS date_solde_reference_0_c,
					'20991231'::date AS date_solde_reference_1_c,
					'20991231'::date AS date_solde_reference_2_c,
					'20991231'::date AS date_solde_reference_22_c,
					'20991231'::date AS date_solde_reference_0_h,
					'20991231'::date AS date_solde_reference_1_h,
					'20991231'::date AS date_solde_reference_2_h,
					'20991231'::date AS date_solde_reference_22_h,

					0::numeric AS delai_facture,
					0::numeric AS delai_solde,
					0::numeric AS delai_expedition,
					0::numeric AS delai_expedition_0,
					0::numeric AS delai_expedition_1,
					0::numeric AS delai_expedition_2,
					0::numeric AS delai_expedition_22,
					0::numeric AS delai_solde_0_c,
					0::numeric AS delai_solde_0_h,
					0::numeric AS delai_solde_1_c,
					0::numeric AS delai_solde_1_h,
					0::numeric AS delai_solde_2_c,
					0::numeric AS delai_solde_2_h,
					0::numeric AS delai_solde_22_c,
					0::numeric AS delai_solde_22_h,


					'20991231'::date AS date_encours,
					0::numeric AS montant_facture_c_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_h_actes_inclus_dans_sejour,
					0::numeric AS montant_comptabilise_budget_global_c

				FROM prod_sigems2.DOS2
					JOIN w_DOSSIER ON ANN_DOS2 = ANN_DOS AND COD_DOS2 = COD_DOS
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_DOS2 = ANN_SELECT AND COD_DOS2 = COD_SELECT
					JOIN activite[PX].p_sejours ON SEJ_DOS = p_sejours.code_original AND p_sejours.etat = ''
					LEFT JOIN w_LIG_CLINI_tmrx ON ANN_DOS2 = ANN_LCL AND COD_DOS2 = COD_LCL AND IND_DOS2 = IND_LCL
					LEFT JOIN w_LIG_HONOR_tmrx ON ANN_DOS2 = ANN_LHO AND COD_DOS2 = COD_LHO AND IND_DOS2 = IND_LHO
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_0 ON 'PATIENT' = t_tiers_payant_0.code_original
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_1 ON DOS2.CP1_DOS2 = t_tiers_payant_1.code_original
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON DOS2.CA2_DOS2 = t_tiers_payant_2.code_original
				WHERE ETA_DOS2 >= 1;
				
				
				-- Factures 'Budget global SSR'
				DROP TABLE IF EXISTS w_DOS2_BG;
				CREATE TEMP TABLE w_DOS2_BG AS
				SELECT
					ANN_LCL AS ANN_DOS2_BG, 
					COD_LCL AS COD_DOS2_BG, 
					IND_LCL AS IND_DOS2_BG, 
					SUM(ML1_LCL_BG) AS SJ1_DOS2_BG
				FROM w_LIG_CLINI
				WHERE ML1_LCL_BG <> 0
				GROUP BY 1,2,3;

				CREATE INDEX w_DOS2_BG_i1
				  ON w_DOS2_BG
				  USING btree
				  (COD_DOS2_BG);
				
				INSERT INTO w_factures
				SELECT 
					nextval('activite[PX].s_factures'::regclass) AS oid,
					p_sejours.oid AS sejour_id,
					SEJ_DOS AS no_sejour,
					ANN_DOS,
					COD_DOS,
					IND_DOS2,
					SEJ_DOS || '.' || to_char(IND_DOS2,'FM9999900') || '.BG' AS no_facture,
					SEJ_DOS || '.' || to_char(IND_DOS2,'FM9999900') || '.BG' AS no_facture_reference,
					0 AS facture_reference_id,
					''::text AS no_facture_od_avoir,
					0::bigint AS facture_od_avoir_id,
					DEN_DOS2 AS date_debut,
					GREATEST(DSO_DOS2,DEN_DOS2) AS date_fin,
					p_sejours.ghs_id,
					p_sejours.ghs_bebe1_id,
					p_sejours.ghs_bebe2_id,
					p_sejours.ghs_bebe3_id,
					p_sejours.code_cp_demandee AS code_cp_demandee,
					CASE WHEN (SJ1_DOS2 < 0 OR HO1_DOS2 < 0 OR SJ2_DOS2 < 0 OR HO2_DOS2 < 0 OR SJ3_DOS2 < 0 OR HO3_DOS2 < 0) THEN '1' WHEN IND_DOS2 > 1 AND avec_facturation_intermediaire IS DISTINCT FROM '1' THEN '2' ELSE '0' END AS type_facture,
					CASE WHEN (SJ1_DOS2_BG < 0 OR SJ1_DOS2 < 0 OR HO1_DOS2 < 0 OR SJ2_DOS2 < 0 OR HO2_DOS2 < 0 OR SJ3_DOS2 < 0 OR HO3_DOS2 < 0) THEN 1::numeric ELSE 0::numeric END AS nb_rejets,
					
					CASE WHEN ETA_DOS2 >= 3 THEN 1::numeric ELSE 0::numeric END AS code_facture,
					CASE WHEN ETA_DOS2 >= 3 THEN COALESCE(DFA_DOS2, date(now())) ELSE '20991231' END AS date_facture,
					CASE WHEN ETA_DOS2 >= 3 AND DFA_DOS2 IS NOT NULL THEN 1::numeric ELSE 0::numeric END AS code_vente,
					CASE WHEN ETA_DOS2 >= 3 AND DFA_DOS2 IS NOT NULL THEN date_part('year', DFA_DOS2) * 100 + date_part('month', DFA_DOS2) ELSE 209912 END AS mois_vente,
					CASE WHEN ETA_DOS2 >= 3 AND DFA_DOS2 IS NOT NULL THEN DFA_DOS2 ELSE '20991231' END AS date_vente,
					''::text AS code_cloture,

					CASE WHEN p_sejours.ghs_id > 0 THEN 'GHS' ELSE '' END AS particularite_t2a,
					
					COALESCE(t_tiers_payant_0.oid,0) AS tiers_payant_0_id,
					COALESCE(t_tiers_payant_1.oid,0) AS tiers_payant_1_id,
					COALESCE(t_tiers_payant_2.oid,0) AS tiers_payant_2_id,
					0::bigint AS tiers_payant_22_id,

					CASE WHEN ETA_DOS2 >= 3 THEN SJ1_DOS2_BG ELSE 0 END AS montant_facture_c,
					0::numeric AS montant_facture_h,
					0::numeric AS montant_facture_0_c,
					0::numeric AS montant_facture_0_h,
					CASE WHEN ETA_DOS2 >= 3 THEN SJ1_DOS2_BG ELSE 0 END AS montant_facture_1_c,
					0::numeric AS montant_facture_1_h,
					0::numeric AS montant_facture_2_c,
					0::numeric AS montant_facture_2_h,
					0::numeric AS montant_facture_22_c,
					0::numeric AS montant_facture_22_h,
					0::numeric AS montant_comptabilise_c,
					0::numeric AS montant_comptabilise_h,
					0::numeric AS montant_comptabilise_0_c,
					0::numeric AS montant_comptabilise_0_h,
					0::numeric AS montant_comptabilise_1_c,
					0::numeric AS montant_comptabilise_1_h,
					0::numeric AS montant_comptabilise_2_c,
					0::numeric AS montant_comptabilise_2_h,
					0::numeric AS montant_comptabilise_22_c,
					0::numeric AS montant_comptabilise_22_h,
					0::numeric AS montant_regle_c,
					0::numeric AS montant_regle_h,
					0::numeric AS montant_regle_0_c,
					0::numeric AS montant_regle_0_h,
					0::numeric AS montant_regle_1_c,
					COALESCE(MR1_LHO,0) AS montant_regle_1_h,
					0::numeric AS montant_regle_2_c,
					0::numeric AS montant_regle_2_h,
					0::numeric AS montant_regle_22_c,
					0::numeric AS montant_regle_22_h,
					'0'::text AS code_expedie_0,
					CASE WHEN COALESCE(DB1_DOS2,'00010101')::date > '00010101'::date THEN '1' ELSE '0' END AS code_expedie_1,
					'0' AS code_expedie_2,
					0::numeric AS code_expedie_22,
					CASE WHEN COALESCE(DB1_DOS2,'00010101')::date > '00010101' THEN COALESCE(DB1_DOS2,'00010101') ELSE '00010101'::date END AS date_expedition,
					'00010101'::date AS date_expedition_0,
					COALESCE(DB1_DOS2,'00010101') AS date_expedition_1,
					'00010101'::date AS date_expedition_2,
					'00010101'::date AS date_expedition_22,
					0::numeric AS no_bordereau_0,
					NB1_DOS2 AS no_bordereau_1,
					0::numeric AS no_bordereau_2,
					0::numeric AS no_bordereau_22,

					'20991231'::date AS date_solde,
					'20991231'::date AS date_solde_c,
					'20991231'::date AS date_solde_h,
					'20991231'::date AS date_solde_0_c,
					'20991231'::date AS date_solde_0_h,
					'20991231'::date AS date_solde_1_c,
					'20991231'::date AS date_solde_1_h,
					'20991231'::date AS date_solde_2_c,
					'20991231'::date AS date_solde_2_h,
					'20991231'::date AS date_solde_22_c,
					'20991231'::date AS date_solde_22_h,


					0::numeric AS montant_encours_c,
					0::numeric AS montant_encours_0_c,
					0::numeric AS montant_encours_1_c,
					0::numeric 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,

					'20991231'::date AS date_solde_reference,
					'20991231'::date AS date_solde_reference_c,
					'20991231'::date AS date_solde_reference_h,
					'20991231'::date AS date_solde_reference_0_c,
					'20991231'::date AS date_solde_reference_1_c,
					'20991231'::date AS date_solde_reference_2_c,
					'20991231'::date AS date_solde_reference_22_c,
					'20991231'::date AS date_solde_reference_0_h,
					'20991231'::date AS date_solde_reference_1_h,
					'20991231'::date AS date_solde_reference_2_h,
					'20991231'::date AS date_solde_reference_22_h,

					0::numeric AS delai_facture,
					0::numeric AS delai_solde,
					0::numeric AS delai_expedition,
					0::numeric AS delai_expedition_0,
					0::numeric AS delai_expedition_1,
					0::numeric AS delai_expedition_2,
					0::numeric AS delai_expedition_22,
					0::numeric AS delai_solde_0_c,
					0::numeric AS delai_solde_0_h,
					0::numeric AS delai_solde_1_c,
					0::numeric AS delai_solde_1_h,
					0::numeric AS delai_solde_2_c,
					0::numeric AS delai_solde_2_h,
					0::numeric AS delai_solde_22_c,
					0::numeric AS delai_solde_22_h,


					'20991231'::date AS date_encours,
					0::numeric AS montant_facture_c_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_h_actes_inclus_dans_sejour,
					SJ1_DOS2_BG AS montant_comptabilise_budget_global_c

				FROM prod_sigems2.DOS2
					JOIN w_DOSSIER ON ANN_DOS2 = ANN_DOS AND COD_DOS2 = COD_DOS
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_DOS2 = ANN_SELECT AND COD_DOS2 = COD_SELECT
					JOIN activite[PX].p_sejours ON SEJ_DOS = p_sejours.code_original AND p_sejours.etat = ''
					JOIN w_DOS2_BG ON ANN_DOS2 = ANN_DOS2_BG AND COD_DOS2 = COD_DOS2_BG AND IND_DOS2 = IND_DOS2_BG
					LEFT JOIN w_LIG_CLINI_tmrx ON ANN_DOS2 = ANN_LCL AND COD_DOS2 = COD_LCL AND IND_DOS2 = IND_LCL
					LEFT JOIN w_LIG_HONOR_tmrx ON ANN_DOS2 = ANN_LHO AND COD_DOS2 = COD_LHO AND IND_DOS2 = IND_LHO
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_0 ON 'PATIENT' = t_tiers_payant_0.code_original
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_1 ON DOS2.CP1_DOS2 = t_tiers_payant_1.code_original
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON DOS2.CA2_DOS2 = t_tiers_payant_2.code_original
				WHERE ETA_DOS2 >= 3;


				ALTER TABLE w_factures ADD CONSTRAINT w_factures_pkey PRIMARY KEY(no_facture);

				CREATE INDEX w_factures_i1
				  ON w_factures
				  USING btree
				  (no_sejour);

				CREATE INDEX w_factures_i2
				  ON w_factures
				  USING btree
				  (no_facture_reference);




				DROP TABLE IF EXISTS w_factures_od_avoir;
				CREATE TEMP TABLE w_factures_od_avoir AS
				SELECT
					oid AS facture_od_avoir_id,
					no_facture AS no_facture_od_avoir,
					''::text AS no_facture,
					0::bigint AS facture_id,
					no_sejour,
					IND_DOS2,
					montant_facture_c,
					montant_facture_0_c,
					montant_facture_1_c,
					montant_facture_2_c,
					montant_facture_22_c,
					montant_facture_h,
					montant_facture_0_h,
					montant_facture_1_h,
					montant_facture_2_h,
					montant_facture_22_h
				FROM w_factures
				WHERE type_facture = '1';



				ALTER TABLE w_factures_od_avoir ADD CONSTRAINT w_factures_od_avoir_od_pkey PRIMARY KEY(no_facture_od_avoir);

				CREATE INDEX w_factures_od_avoir_i1
				  ON w_factures_od_avoir
				  USING btree
				  (no_sejour);

				UPDATE w_factures_od_avoir SET no_facture = w_factures.no_facture, facture_id = w_factures.oid
				FROM w_factures   
				WHERE 
					w_factures_od_avoir.no_sejour = w_factures.no_sejour AND w_factures_od_avoir.IND_DOS2 = w_factures.IND_DOS2 + 1 AND
					w_factures_od_avoir.montant_facture_c = 0 - w_factures.montant_facture_c AND
					w_factures_od_avoir.montant_facture_0_c = 0 - w_factures.montant_facture_0_c AND
					w_factures_od_avoir.montant_facture_1_c = 0 - w_factures.montant_facture_1_c AND
					w_factures_od_avoir.montant_facture_2_c = 0 - w_factures.montant_facture_2_c AND
					w_factures_od_avoir.montant_facture_22_c = 0 - w_factures.montant_facture_22_c AND
					w_factures_od_avoir.montant_facture_h = 0 - w_factures.montant_facture_h AND
					w_factures_od_avoir.montant_facture_0_h = 0 - w_factures.montant_facture_0_h AND
					w_factures_od_avoir.montant_facture_1_h = 0 - w_factures.montant_facture_1_h AND
					w_factures_od_avoir.montant_facture_2_h = 0 - w_factures.montant_facture_2_h AND
					w_factures_od_avoir.montant_facture_22_h = 0 - w_factures.montant_facture_22_h;


				UPDATE w_factures SET 
					type_facture = 'X' ,
					no_facture_od_avoir = w_factures_od_avoir.no_facture_od_avoir,
					facture_od_avoir_id = w_factures_od_avoir.facture_od_avoir_id 
				FROM w_factures_od_avoir
				WHERE w_factures.no_facture = w_factures_od_avoir.no_facture AND w_factures_od_avoir.no_facture <> '' AND w_factures_od_avoir.no_facture_od_avoir <> '';

				UPDATE w_factures SET 
					no_facture_od_avoir = w_factures_od_avoir.no_facture,
					facture_od_avoir_id = w_factures_od_avoir.facture_id
				FROM w_factures_od_avoir
				WHERE w_factures.no_facture = w_factures_od_avoir.no_facture_od_avoir AND w_factures_od_avoir.no_facture <> '' AND w_factures_od_avoir.no_facture_od_avoir <> '';



				DROP TABLE IF EXISTS w_factures_references;
				CREATE TEMP TABLE w_factures_references AS
				SELECT no_sejour, COALESCE(MIN(CASE WHEN type_facture NOT IN ('X', '1') THEN no_facture ELSE NULL END), MIN(no_facture)) AS no_facture_reference
				FROM w_factures
				GROUP BY 1;


				UPDATE w_factures SET 
					no_facture_reference = w_factures_references.no_facture_reference,
					facture_reference_id = 0
				FROM w_factures_references
				WHERE w_factures.no_sejour = w_factures_references.no_sejour AND
					w_factures.no_facture_reference <> w_factures_references.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;

				ALTER TABLE w_factures_references_soldes ADD CONSTRAINT w_factures_references_soldes_pkey PRIMARY KEY(no_facture_reference);


				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 (
					oid,
					sejour_id,
					no_sejour,
					no_facture,
					no_facture_reference,
					facture_reference_id,
					no_facture_od_avoir,
					facture_od_avoir_id,
					date_debut,
					date_fin,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					code_cp_demandee,
					type_facture,
					nb_rejets,
					code_facture,
					date_facture,
					code_vente,
					mois_vente,
					date_vente,
					code_cloture,

					particularite_t2a,
					
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					montant_facture_c,
					montant_facture_h,
					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_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,
					montant_regle_c,
					montant_regle_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,
					code_expedie_0,
					code_expedie_1,
					code_expedie_2,
					code_expedie_22,
					date_expedition,
					date_expedition_0,
					date_expedition_1,
					date_expedition_2,
					date_expedition_22,
					no_bordereau_0,
					no_bordereau_1,
					no_bordereau_2,
					no_bordereau_22,

					date_solde,
					date_solde_c,
					date_solde_h,
					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,


					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,

					date_solde_reference,
					date_solde_reference_c,
					date_solde_reference_h,
					date_solde_reference_0_c,
					date_solde_reference_1_c,
					date_solde_reference_2_c,
					date_solde_reference_22_c,
					date_solde_reference_0_h,
					date_solde_reference_1_h,
					date_solde_reference_2_h,
					date_solde_reference_22_h,

					delai_facture,
					delai_solde,
					delai_expedition,
					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,


					date_encours,
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour,
					montant_comptabilise_budget_global_c

					)

				SELECT
					oid,
					sejour_id,
					no_sejour,
					no_facture,
					w_factures.no_facture_reference,
					facture_reference_id,
					no_facture_od_avoir,
					facture_od_avoir_id,
					date_debut,
					date_fin,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					code_cp_demandee,
					type_facture,
					nb_rejets,
					code_facture,
					date_facture,
					code_vente,
					mois_vente,
					date_vente,
					code_cloture,

					particularite_t2a,
					
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					montant_facture_c,
					montant_facture_h,
					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_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,
					montant_regle_c,
					montant_regle_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,
					code_expedie_0,
					code_expedie_1,
					code_expedie_2,
					code_expedie_22,
					CASE WHEN date_expedition <> '00010101' THEN date_expedition ELSE '20991231' END,
					CASE WHEN date_expedition_0 <> '00010101' THEN date_expedition_0 ELSE '20991231' END,
					CASE WHEN date_expedition_1 <> '00010101' THEN date_expedition_1 ELSE '20991231' END,
					CASE WHEN date_expedition_2 <> '00010101' THEN date_expedition_2 ELSE '20991231' END,
					CASE WHEN date_expedition_22 <> '00010101' THEN date_expedition_22 ELSE '20991231' END,
					no_bordereau_0,
					no_bordereau_1,
					no_bordereau_2,
					no_bordereau_22,

					CASE WHEN date_solde <> '00010101' THEN date_solde ELSE '20991231' END,
					CASE WHEN date_solde_c <> '00010101' THEN date_solde_c ELSE '20991231' END,
					CASE WHEN date_solde_h <> '00010101' THEN date_solde_h ELSE '20991231' END,
					CASE WHEN date_solde_0_c <> '00010101' THEN date_solde_0_c ELSE '20991231' END,
					CASE WHEN date_solde_0_h <> '00010101' THEN date_solde_0_h ELSE '20991231' END,
					CASE WHEN date_solde_1_c <> '00010101' THEN date_solde_1_c ELSE '20991231' END,
					CASE WHEN date_solde_1_h <> '00010101' THEN date_solde_1_h ELSE '20991231' END,
					CASE WHEN date_solde_2_c <> '00010101' THEN date_solde_2_c ELSE '20991231' END,
					CASE WHEN date_solde_2_h <> '00010101' THEN date_solde_2_h ELSE '20991231' END,
					CASE WHEN date_solde_22_c <> '00010101' THEN date_solde_22_c ELSE '20991231' END,
					CASE WHEN date_solde_22_h <> '00010101' THEN date_solde_22_h ELSE '20991231' END,


					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,

					CASE WHEN w_factures_references_soldes.date_solde_reference <> '00010101' THEN w_factures_references_soldes.date_solde_reference ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_c <> '00010101' THEN w_factures_references_soldes.date_solde_reference_c ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_h <> '00010101' THEN w_factures_references_soldes.date_solde_reference_h ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_0_c <> '00010101' THEN w_factures_references_soldes.date_solde_reference_0_c ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_1_c <> '00010101' THEN w_factures_references_soldes.date_solde_reference_1_c ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_2_c <> '00010101' THEN w_factures_references_soldes.date_solde_reference_2_c ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_22_c <> '00010101' THEN w_factures_references_soldes.date_solde_reference_22_c ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_0_h <> '00010101' THEN w_factures_references_soldes.date_solde_reference_0_h ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_1_h <> '00010101' THEN w_factures_references_soldes.date_solde_reference_1_h ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_2_h <> '00010101' THEN w_factures_references_soldes.date_solde_reference_2_h ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_22_h <> '00010101' THEN w_factures_references_soldes.date_solde_reference_22_h ELSE '20991231' END,

					delai_facture,
					delai_solde,
					delai_expedition,
					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,

					date_encours,
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour,
					montant_comptabilise_budget_global_c

				FROM w_factures 
					JOIN w_factures_references_soldes ON w_factures.no_facture_reference = w_factures_references_soldes.no_facture_reference
				WHERE oid NOT IN (SELECT oid FROM activite[PX].p_factures);

				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');
				
				
				-- Sur budget global, il faut deux tiers identiques
				INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
				SELECT t_tiers_payant.code_original || '(2)',
					t_tiers_payant.code,
					'2'::text,
					t_tiers_payant.texte || ' (AMC)',
					t_tiers_payant.texte_court || ' (AMC)'
				FROM activite[PX].p_sejours 
				JOIN activite[PX].t_tiers_payant ON p_sejours.tiers_payant_1_id = t_tiers_payant.oid
				LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON t_tiers_payant_2.code_original = (t_tiers_payant.code_original || '(2)')
				WHERE est_budget_global = '1' AND
					p_sejours.tiers_payant_1_id = p_sejours.tiers_payant_2_id AND
					p_sejours.tiers_payant_1_id <> 0 AND 
					t_tiers_payant_2.oid IS NULL
				GROUP BY 1,2,3,4,5;
				
				UPDATE activite[PX].p_sejours
				SET tiers_payant_2_id = subview.tiers_payant_2_id
				FROM
				(
				SELECT p_sejours.no_sejour,
					p_sejours.tiers_payant_1_id,
					t_tiers_payant_2.oid AS tiers_payant_2_id
				FROM activite[PX].p_sejours
				JOIN activite[PX].t_tiers_payant ON p_sejours.tiers_payant_1_id = t_tiers_payant.oid
				JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON t_tiers_payant_2.code_original = (t_tiers_payant.code_original || '(2)')
				WHERE est_budget_global = '1' AND
					p_sejours.tiers_payant_1_id = p_sejours.tiers_payant_2_id AND
					p_sejours.tiers_payant_1_id <> 0
				GROUP BY 1,2,3
				) subview
				WHERE p_sejours.no_sejour = subview.no_sejour;
					
				INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
				SELECT t_tiers_payant.code_original || '(2)',
					t_tiers_payant.code,
					'2'::text,
					t_tiers_payant.texte || ' (AMC)',
					t_tiers_payant.texte_court || ' (AMC)'
				FROM activite[PX].p_factures
				JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				JOIN activite[PX].t_tiers_payant ON p_factures.tiers_payant_1_id = t_tiers_payant.oid
				LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON t_tiers_payant_2.code_original = (t_tiers_payant.code_original || '(2)')
				WHERE est_budget_global = '1' AND
					p_factures.tiers_payant_1_id = p_factures.tiers_payant_2_id AND
					p_factures.tiers_payant_1_id <> 0 AND 
					t_tiers_payant_2.oid IS NULL
				GROUP BY 1,2,3,4,5;


				UPDATE activite[PX].p_factures
				SET tiers_payant_2_id = subview.tiers_payant_2_id
				FROM
				(
				SELECT p_factures.no_facture,
					p_factures.tiers_payant_1_id,
					t_tiers_payant_2.oid AS tiers_payant_2_id
				FROM activite[PX].p_factures
				JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				JOIN activite[PX].t_tiers_payant ON p_factures.tiers_payant_1_id = t_tiers_payant.oid
				JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON t_tiers_payant_2.code_original = (t_tiers_payant.code_original || '(2)')
				WHERE est_budget_global = '1' AND
					p_factures.tiers_payant_1_id = p_factures.tiers_payant_2_id AND
					p_factures.tiers_payant_1_id <> 0
				GROUP BY 1,2,3
				) subview
				WHERE p_factures.no_facture = subview.no_facture;
				
				
				
				-- 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.type_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,
					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,
					MAX(CASE WHEN p_factures.date_fin IS NULL THEN date_sortie ELSE p_factures.date_fin END) AS date_fin_facture_0,
					MAX(CASE WHEN p_factures.date_fin IS NOT NULL AND (date_sortie - date_entree < 30 OR p_sejours.type_sejour <> '1') AND t_services_facturation.avec_facturation_intermediaire IS DISTINCT FROM '1' 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 OR p_sejours.type_sejour <> '1') AND t_services_facturation.avec_facturation_intermediaire IS DISTINCT FROM '1' THEN date_sortie ELSE p_factures.date_fin END + interval '1 day', p_sejours.date_entree))) AS date_debut_encours,
					CASE WHEN code_sorti = '1' THEN date_sortie ELSE date(now()) END AS date_fin_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%'
					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' AND code_prevu <> 1
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12;
				
				-- Spécial séances avec facturation multiple
				UPDATE w_factures_trous
				SET date_fin_facture = date_fin_facture_0,
					date_debut_encours = date(date_fin_facture_0+interval '1 day')
				WHERE no_sejour IN
					(
					SELECT no_sejour
					FROM prod_sigems2.LIG_CLINI
						JOIN w_factures_trous ON ANN_LCL || to_char(COD_LCL,'FM900000') = no_sejour AND w_factures_trous.type_sejour = '5'
					WHERE PRO_LCL <> 'ACPT' AND PRO_LCL <> 'ECAC' AND PRO_LCL <> 'REGC' AND IND_LCL = 0 AND date(dde_lcl) > date_fin_facture_0
					)
				;
				
				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, 
					date_debut, 
					date_fin)
				SELECT finess, 
					no_sejour, 
					no_sejour || '.00' || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || p_calendrier.mois ELSE '' END, 
					no_sejour || '.00' || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || p_calendrier.mois 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 , 
					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;

					
				INSERT INTO activite[PX].p_factures(
					finess, 
					no_sejour, 
					no_facture, 
					no_facture_reference, 
					date_debut, 
					date_fin, 
					type_facture, 
					code_facture, 
					date_facture, 
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					tiers_payant_2_id, 
					tiers_payant_22_id,
					ghs_id)
				SELECT finess, 
					ANN_LCL || to_char(COD_LCL,'FM900000'), 
					ANN_LCL || to_char(COD_LCL,'FM900000') || '.00', 
					ANN_LCL || to_char(COD_LCL,'FM900000') || '.00', 
					date_entree, 
					date_sortie, 
					'0', 
					'0', 
					'20991231'::date,
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					tiers_payant_2_id, 
					tiers_payant_22_id,
					ghs_id
				FROM prod_sigems2.LIG_CLINI
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LCL = ANN_SELECT AND COD_LCL = COD_SELECT
					JOIN activite[PX].p_sejours ON ANN_LCL || to_char(COD_LCL,'FM900000') = no_sejour AND p_sejours.etat = ''
				WHERE PRO_LCL <> 'ACPT' AND PRO_LCL <> 'ECAC' AND
					ANN_LCL || to_char(COD_LCL,'FM900000') || '.' || to_char(IND_LCL,'FM9999900') NOT IN (SELECT no_facture FROM activite[PX].p_factures) AND
					ANN_LCL || to_char(COD_LCL,'FM900000') NOT IN (SELECT no_sejour FROM activite[PX].p_factures)
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14;
				
				INSERT INTO activite[PX].p_factures(
					finess, 
					sejour_id,
					no_sejour, 
					no_facture, 
					no_facture_reference, 
					date_debut, 
					date_fin, 
					type_facture, 
					code_facture, 
					date_facture, 
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					tiers_payant_2_id, 
					tiers_payant_22_id,
					ghs_id)
				SELECT finess, 
					p_sejours.oid,
					ANN_LHO || to_char(COD_LHO,'FM900000'), 
					ANN_LHO || to_char(COD_LHO,'FM900000') || '.00', 
					ANN_LHO || to_char(COD_LHO,'FM900000') || '.00', 
					date_entree, 
					date_sortie, 
					'0', 
					'0', 
					'20991231'::date,
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					tiers_payant_2_id, 
					tiers_payant_22_id,
					ghs_id
				FROM prod_sigems2.LIG_HONOR
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LHO = ANN_SELECT AND COD_LHO = COD_SELECT
					JOIN activite[PX].p_sejours ON ANN_LHO || to_char(COD_LHO,'FM900000') = no_sejour AND p_sejours.etat = ''
				WHERE CPH_LHO <> 'ACPT' AND CPH_LHO <> 'ECAH' AND
					ANN_LHO || to_char(COD_LHO,'FM900000') || '.' || to_char(IND_LHO,'FM9999900') NOT IN (SELECT no_facture FROM activite[PX].p_factures) AND
					ANN_LHO || to_char(COD_LHO,'FM900000') NOT IN (SELECT no_sejour FROM activite[PX].p_factures)
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15;
				
				
				
				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
					);

				

				UPDATE activite[PX].p_factures
				SET facture_od_avoir_id = p_factures_od_avoir.oid
				FROM activite[PX].p_factures p_factures_od_avoir
				WHERE p_factures.no_facture_od_avoir = p_factures_od_avoir.no_facture
					AND p_factures.facture_od_avoir_id <> p_factures_od_avoir.oid;
					
					
				-- premiere facture initiale (cas des annulations
				UPDATE activite[PX].p_factures 
				SET type_facture = '0' WHERE no_facture IN
				(
				SELECT no_facture_0 FROM
				(
				SELECT no_sejour, MAX(no_facture_reference) AS no_facture_0
				FROM activite[PX].p_factures
				GROUP BY 1
				HAVING SUM(CASE WHEN type_facture = '0' THEN 1 ELSE 0 END) = 0 AND MAX(no_facture_reference) IS NOT NULL
				) subview
				);
				
				
					
					
				-- Répartition montants comptabilisés tp2 sur tp1 quand tp1 = tp2
				UPDATE activite[PX].p_factures SET
					montant_comptabilise_1_c = montant_comptabilise_1_c + montant_comptabilise_2_c,
					montant_comptabilise_1_h = montant_comptabilise_1_h + montant_comptabilise_2_h,
					montant_regle_1_c = montant_regle_1_c + montant_regle_2_c,
					montant_regle_1_h = montant_regle_1_h + montant_regle_2_h
				WHERE tiers_payant_1_id = tiers_payant_2_id AND tiers_payant_1_id <> 0 AND
					(montant_comptabilise_2_c <> 0 OR montant_comptabilise_2_h <> 0 OR montant_regle_2_c <> 0 OR montant_regle_2_h <> 0);
				
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lignes non facturées Clinique">
			<sqlcmd><![CDATA[

				INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
					facture_id,
					no_facture, 
					date_debut, 
					date_fin, 
					nb_rubrique, 
					coefficient, 
					rubrique_facturation_id, 
					prestation_id, 
					prix_unitaire, 
					lieu_id)
				SELECT 
					p_factures.oid AS facture_id,
					p_factures.no_facture AS no_facture,
					CASE 
						WHEN substr(p_factures.no_facture,11,1) <> '_' THEN date(DDE_LCL)
						WHEN QTE_LCL = 1 THEN date(DDE_LCL)
						WHEN date(DDE_LCL) = date(COALESCE(DFI_LCL,DDE_LCL)) THEN date(DDE_LCL)
						ELSE GREATEST(p_factures.date_debut, date(DDE_LCL)) 
						END AS date_debut,
					CASE 
						WHEN substr(p_factures.no_facture,11,1) <> '_' THEN date(COALESCE(DFI_LCL,DDE_LCL))
						WHEN QTE_LCL = 1 THEN date(COALESCE(DFI_LCL,DDE_LCL))
						WHEN date(DDE_LCL) = date(COALESCE(DFI_LCL,DDE_LCL)) THEN date(COALESCE(DFI_LCL,DDE_LCL))
						ELSE LEAST(p_factures.date_fin, date(COALESCE(DFI_LCL,DDE_LCL)))
						END AS date_fin,
					CASE 
						WHEN substr(p_factures.no_facture,11,1) <> '_' THEN QTE_LCL
						WHEN QTE_LCL = 1 THEN QTE_LCL
						WHEN date(DDE_LCL) = date(COALESCE(DFI_LCL,DDE_LCL)) THEN QTE_LCL
						ELSE LEAST(p_factures.date_fin, date(COALESCE(DFI_LCL,DDE_LCL))) - GREATEST(p_factures.date_debut, date(DDE_LCL)) + 1
						END AS nb_rubrique,
					CASE WHEN COG_LCL <> 0 THEN COG_LCL ELSE 1 END AS coefficient,
					w_LIG_CLINI_keys.rubrique_facturation_id AS rubrique_facturation_id,
					w_LIG_CLINI_keys.prestation_id AS prestation_id,
					CASE 
                        WHEN TAR_LCL <> 0 AND QTE_LCL <> 0 THEN TAR_LCL/QTE_LCL 
                        WHEN PUN_LCL <> 0 THEN PUN_LCL
                        WHEN QTE_LCL <> 0 AND (ML1_LCL+ML2_LCL+ML3_LCL) <> 0 THEN (ML1_LCL+ML2_LCL+ML3_LCL)/QTE_LCL 
                        ELSE PUN_LCL 
                        END AS prix_unitaire,
					p_sejours.lieu_sortie_id AS lieu_id
				FROM w_LIG_CLINI
					JOIN activite[PX].p_factures ON w_LIG_CLINI.no_facture = substr(p_factures.no_facture,1,10) AND
						(
						DDE_LCL BETWEEN p_factures.date_debut AND p_factures.date_fin OR
						DFI_LCL BETWEEN p_factures.date_debut AND p_factures.date_fin
						)
					JOIN activite[PX].p_sejours ON w_LIG_CLINI.SEJ_DOS = p_sejours.code_original AND p_sejours.etat = ''
					JOIN w_LIG_CLINI_keys ON w_LIG_CLINI.key = w_LIG_CLINI_keys.key
				WHERE p_factures.code_facture <> '1' AND w_LIG_CLINI.PRO_LCL <> 'ACPT' 
				;
				
				
				DROP TABLE IF EXISTS w_LIG_CLINI_tmrx;
				CREATE TEMP TABLE w_LIG_CLINI_tmrx AS
				SELECT no_facture,
					SUM(MR1_LCL) AS MR1_LCL,
					SUM(MR2_LCL) AS MR2_LCL,
					SUM(MR3_LCL) AS MR3_LCL
				FROM w_LIG_CLINI
				WHERE PRO_LCL <> 'ECAC'
				GROUP BY 1;
				
				CREATE INDEX w_LIG_CLINI_tmrx_i1
				  ON w_LIG_CLINI_tmrx
				  USING btree
				  (no_facture);


				UPDATE activite[PX].p_factures SET 
					montant_regle_c = w_LIG_CLINI_tmrx.MR1_LCL + w_LIG_CLINI_tmrx.MR2_LCL + w_LIG_CLINI_tmrx.MR3_LCL,
					montant_regle_1_c = w_LIG_CLINI_tmrx.MR1_LCL,
					montant_regle_2_c = w_LIG_CLINI_tmrx.MR2_LCL,
					montant_regle_0_c = w_LIG_CLINI_tmrx.MR3_LCL
				FROM w_LIG_CLINI_tmrx
				WHERE p_factures.no_facture = w_LIG_CLINI_tmrx.no_facture AND
					(
						montant_regle_c <> w_LIG_CLINI_tmrx.MR1_LCL + w_LIG_CLINI_tmrx.MR2_LCL + w_LIG_CLINI_tmrx.MR3_LCL OR
						montant_regle_1_c <> w_LIG_CLINI_tmrx.MR1_LCL OR
						montant_regle_2_c <> w_LIG_CLINI_tmrx.MR2_LCL OR
						montant_regle_0_c <> w_LIG_CLINI_tmrx.MR3_LCL
					);
					
					
				
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lignes factures Clinique">
			<sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_REG4_un;
				CREATE TEMP TABLE w_REG4_un AS
				SELECT NUM_CLI
				FROM prod_sigems2.REG4
				GROUP BY 1;

				ALTER TABLE w_REG4_un ADD CONSTRAINT w_REG4_un_pkey PRIMARY KEY(NUM_CLI);
				
				DROP SEQUENCE IF EXISTS w_factures_lignes_c_seq;
				CREATE TEMP SEQUENCE w_factures_lignes_c_seq;
			
				DROP TABLE IF EXISTS w_factures_lignes_c;
				CREATE TEMP TABLE w_factures_lignes_c AS 
				SELECT
						nextval('w_factures_lignes_c_seq'::regclass) AS sequence, 
						p_factures.no_sejour,
						
						NUM_LCL,
						
						p_factures.oid AS facture_id,
						w_LIG_CLINI.no_facture AS no_facture,
						p_factures.date_vente,
						
						CASE WHEN COG_LCL <> 0 THEN COG_LCL ELSE 1 END AS coefficient,
						CASE WHEN COO_LCL > 0 THEN COO_LCL / 100 ELSE 1 END AS coefficient_mco,
						w_LIG_CLINI.PRO_LCL,
						w_LIG_CLINI_keys.rubrique_facturation_id AS rubrique_facturation_id,
						w_LIG_CLINI_keys.rubrique_comptabilisation_id AS rubrique_comptabilisation_id,
						w_LIG_CLINI_keys.prestation_id AS prestation_id,
						w_LIG_CLINI_keys.compte_produit_id AS compte_produit_id,
						p_sejours.lieu_sortie_id AS lieu_id,
						1::bigint AS origine_facturation_id,

						PUN_LCL AS prix_unitaire,
						TX3_LCL AS taux_0,
						CASE WHEN ML1_LCL_BG <> 0 THEN TX1_LCL ELSE 0 END AS taux_1,
						TX2_LCL AS taux_2,
						0::numeric AS taux_22,

						date(DDE_LCL) AS date_debut,
						date(COALESCE(DFI_LCL,DDE_LCL)) AS date_fin,
						QTE_LCL AS nb_rubrique,
						QTE_LCL AS nb_prestation,
						ML1_LCL + ML2_LCL + ML3_LCL AS montant_facture,
						ML3_LCL AS montant_facture_0,
						ML1_LCL AS montant_facture_1,
						ML2_LCL AS montant_facture_2,
						0::numeric AS montant_facture_22,
						ML1_LCL + ML2_LCL + ML3_LCL AS montant_comptabilise,
						ML3_LCL AS montant_comptabilise_0,
						ML1_LCL + CASE WHEN p_factures.tiers_payant_1_id = p_factures.tiers_payant_2_id AND p_factures.tiers_payant_1_id <> 0 THEN ML2_LCL ELSE 0 END AS montant_comptabilise_1,
						CASE WHEN p_factures.tiers_payant_1_id <> p_factures.tiers_payant_2_id THEN ML2_LCL ELSE 0 END AS montant_comptabilise_2,
						0::numeric AS montant_comptabilise_22,
						MR1_LCL + MR2_LCL + MR3_LCL AS montant_regle,
						MR3_LCL AS montant_regle_0,
						MR1_LCL + CASE WHEN p_factures.tiers_payant_1_id = p_factures.tiers_payant_2_id AND p_factures.tiers_payant_1_id <> 0 THEN MR2_LCL ELSE 0 END AS montant_regle_1,
						CASE WHEN p_factures.tiers_payant_1_id <> p_factures.tiers_payant_2_id THEN MR2_LCL ELSE 0 END AS montant_regle_2,
						0::numeric AS montant_regle_22,
						0::numeric AS montant_encours,
						0::numeric AS montant_encours_0,
						0::numeric AS montant_encours_1,
						0::numeric AS montant_encours_2,
						0::numeric AS montant_encours_22,
						0::numeric AS montant_facture_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_0_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_1_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_2_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_22_actes_inclus_dans_sejour,
						0::numeric AS montant_comptabilise_budget_global_1,
						0::numeric AS rubrique_facture_id
				FROM w_LIG_CLINI
					JOIN activite[PX].p_factures ON w_LIG_CLINI.no_facture = p_factures.no_facture
					JOIN activite[PX].p_sejours ON w_LIG_CLINI.SEJ_DOS = p_sejours.code_original AND p_sejours.etat = ''
					JOIN w_LIG_CLINI_keys ON w_LIG_CLINI.key = w_LIG_CLINI_keys.key
					LEFT JOIN w_REG4_un ON NUM_LCL = NUM_CLI
				WHERE (p_factures.code_facture = '1' AND w_LIG_CLINI.non_facturee <> '1') OR w_LIG_CLINI.PRO_LCL = 'ACPT' OR NUM_CLI IS NOT NULL;
				
				-- Lignes Budget global SSR
				INSERT INTO w_factures_lignes_c
				SELECT
						nextval('w_factures_lignes_c_seq'::regclass) AS sequence, 
						p_factures.no_sejour,
						
						NUM_LCL,
						
						p_factures.oid AS facture_id,
						w_LIG_CLINI.no_facture || '.BG' AS no_facture,
						p_factures.date_vente,
						
						CASE WHEN COG_LCL <> 0 THEN COG_LCL ELSE 1 END AS coefficient,
						CASE WHEN COO_LCL > 0 THEN COO_LCL / 100 ELSE 1 END AS coefficient_mco,
						w_LIG_CLINI.PRO_LCL,
						w_LIG_CLINI_keys.rubrique_facturation_id AS rubrique_facturation_id,
						w_LIG_CLINI_keys.rubrique_comptabilisation_id AS rubrique_comptabilisation_id,
						w_LIG_CLINI_keys.prestation_id AS prestation_id,
						w_LIG_CLINI_keys.compte_produit_id AS compte_produit_id,
						p_sejours.lieu_sortie_id AS lieu_id,
						1::bigint AS origine_facturation_id,

						PUN_LCL AS prix_unitaire,
						0::numeric AS taux_0,
						TX1_LCL AS taux_1,
						0::numeric AS taux_2,
						0::numeric AS taux_22,

						date(DDE_LCL) AS date_debut,
						date(COALESCE(DFI_LCL,DDE_LCL)) AS date_fin,
						QTE_LCL AS nb_rubrique,
						QTE_LCL AS nb_prestation,
						ML1_LCL_BG AS montant_facture,
						0::numeric AS montant_facture_0,
						ML1_LCL_BG AS montant_facture_1,
						0::numeric AS montant_facture_2,
						0::numeric AS montant_facture_22,
						0::numeric AS montant_comptabilise,
						0::numeric AS montant_comptabilise_0,
						0::numeric AS montant_comptabilise_1,
						0::numeric AS montant_comptabilise_2,
						0::numeric AS montant_comptabilise_22,
						0::numeric AS montant_regle,
						0::numeric AS montant_regle_0,
						0::numeric AS montant_regle_1,
						0::numeric AS montant_regle_2,
						0::numeric AS montant_regle_22,
						0::numeric AS montant_encours,
						0::numeric AS montant_encours_0,
						0::numeric AS montant_encours_1,
						0::numeric AS montant_encours_2,
						0::numeric AS montant_encours_22,
						0::numeric AS montant_facture_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_0_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_1_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_2_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_22_actes_inclus_dans_sejour,
						ML1_LCL_BG AS montant_comptabilise_budget_global_1,
						0::numeric AS rubrique_facture_id
				FROM w_LIG_CLINI
					JOIN activite[PX].p_factures ON w_LIG_CLINI.no_facture || '.BG' = p_factures.no_facture
					JOIN activite[PX].p_sejours ON w_LIG_CLINI.SEJ_DOS = p_sejours.code_original AND p_sejours.etat = ''
					JOIN w_LIG_CLINI_keys ON w_LIG_CLINI.key = w_LIG_CLINI_keys.key
				WHERE ML1_LCL_BG <> 0 AND 
					p_factures.code_facture = '1' AND w_LIG_CLINI.non_facturee <> '1';
				
				
				CREATE INDEX w_factures_lignes_c_i1
				  ON w_factures_lignes_c
				  USING btree
				  (NUM_LCL);
				  
				CREATE INDEX w_factures_lignes_c_i2
				  ON w_factures_lignes_c
				  USING btree
				  (sequence);
				  
				CREATE INDEX w_factures_lignes_c_i3
				  ON w_factures_lignes_c
				  USING btree
				  (no_sejour);
				
				  
				 
				  
				  
				-- Eclatement des supplements par jour
				DROP TABLE IF EXISTS w_factures_lignes_sup_c;

				CREATE TEMP TABLE w_factures_lignes_sup_c AS
				SELECT
					t_prestations.code AS prestation_code,
					date(p_sejours.date_entree) AS date_debut_ghs,
					date(p_sejours.date_sortie - interval '1 day') 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 t_prestations.code = 'GHS' THEN date(date_entree + interval '1 day') ELSE date(date_debut + interval '1 day') END AS date_debut_det,
					CASE WHEN t_prestations.code = 'GHS' THEN date(p_sejours.date_sortie - interval '1 day') ELSE date(date_debut + ABS(nb_prestation)-1)  END AS date_fin_det,
					ABS(CASE WHEN t_prestations.code = 'GHS' THEN date(date_sortie) - date(date_entree) ELSE nb_prestation END) AS nb_det,
					w_factures_lignes_c.*
				FROM w_factures_lignes_c
					JOIN activite[PX].p_sejours ON w_factures_lignes_c.no_sejour = p_sejours.no_sejour
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND 
						(
						code IN ('PJ', '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_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 w_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 AND
					w_factures_lignes_sup_c.prestation_code = 'GHS';

				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
					sequence,
					NUM_LCL,
					PRO_LCL,
					no_sejour,
					no_facture,
					date AS date_debut,
					date AS date_fin,
					date_vente,
					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,
					prestation_id,
					compte_produit_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,
					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,
					rubrique_comptabilisation_id,
					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 sequence,
					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 w_factures_lignes_c
				SET
					date_fin = w_factures_lignes_c.date_debut,
					nb_rubrique = w_factures_lignes_c.nb_rubrique - w_factures_lignes_sup_c_sup_tot.nb_rubrique,
					nb_prestation = w_factures_lignes_c.nb_prestation - w_factures_lignes_sup_c_sup_tot.nb_prestation,
					montant_facture = w_factures_lignes_c.montant_facture - w_factures_lignes_sup_c_sup_tot.montant_facture,
					montant_facture_0 = w_factures_lignes_c.montant_facture_0 - w_factures_lignes_sup_c_sup_tot.montant_facture_0,
					montant_facture_1 = w_factures_lignes_c.montant_facture_1 - w_factures_lignes_sup_c_sup_tot.montant_facture_1,
					montant_facture_2 = w_factures_lignes_c.montant_facture_2 - w_factures_lignes_sup_c_sup_tot.montant_facture_2,
					montant_facture_22 = w_factures_lignes_c.montant_facture_22 - w_factures_lignes_sup_c_sup_tot.montant_facture_22,
					montant_comptabilise = w_factures_lignes_c.montant_comptabilise - w_factures_lignes_sup_c_sup_tot.montant_comptabilise,
					montant_comptabilise_0 = w_factures_lignes_c.montant_comptabilise_0 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_0,
					montant_comptabilise_1 = w_factures_lignes_c.montant_comptabilise_1 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_1,
					montant_comptabilise_2 = w_factures_lignes_c.montant_comptabilise_2 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_2,
					montant_comptabilise_22 = w_factures_lignes_c.montant_comptabilise_22 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_22,
					montant_encours = w_factures_lignes_c.montant_encours - w_factures_lignes_sup_c_sup_tot.montant_encours,
					montant_encours_0 = w_factures_lignes_c.montant_encours_0 - w_factures_lignes_sup_c_sup_tot.montant_encours_0,
					montant_encours_1 = w_factures_lignes_c.montant_encours_1 - w_factures_lignes_sup_c_sup_tot.montant_encours_1,
					montant_encours_2 = w_factures_lignes_c.montant_encours_2 - w_factures_lignes_sup_c_sup_tot.montant_encours_2,
					montant_encours_22 = w_factures_lignes_c.montant_encours_22 - w_factures_lignes_sup_c_sup_tot.montant_encours_22,
					montant_facture_actes_inclus_dans_sejour = w_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 = w_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 = w_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 = w_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 = w_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 = w_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 w_factures_lignes_c.sequence = w_factures_lignes_sup_c_sup_tot.sequence;
				
				

				INSERT INTO w_factures_lignes_c(
					NUM_LCL,
					PRO_LCL,
					no_facture,
					no_sejour,
					date_debut,
					date_fin,
					date_vente,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					prestation_id,
					compte_produit_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,
					nb_prestation,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					rubrique_comptabilisation_id,
					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 
					0 - NUM_LCL,
					PRO_LCL,
					no_facture,
					no_sejour,
					date_debut,
					date_fin,
					date_vente,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					prestation_id,
					compte_produit_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,
					nb_prestation,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					rubrique_comptabilisation_id,
					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;
				
				
				-- Lieu exécution
				
				
				UPDATE w_factures_lignes_c
				SET lieu_id = p_mouvements_sejour.lieu_id
				FROM 
					activite[PX].p_mouvements_sejour
				WHERE
					w_factures_lignes_c.no_sejour = p_mouvements_sejour.no_sejour AND
					w_factures_lignes_c.date_fin = p_mouvements_sejour.date AND
					(230000 BETWEEN p_mouvements_sejour.heure_debut AND p_mouvements_sejour.heure_fin OR 
					nb_entrees_directes = 1 AND heure_fin = 240000 OR 
					nb_sorties_directes = 1 ) AND
					w_factures_lignes_c.lieu_id <> p_mouvements_sejour.lieu_id;
					
				-- Rubriques internes cti
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('w_factures_lignes_c');	
				  
				  
				-- Validation des lignes de facture  
				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 (
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					compte_produit_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,
					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,
					montant_comptabilise_budget_global_1,
					origine_facturation_id
				)
				SELECT
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					compte_produit_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,
					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,
					montant_comptabilise_budget_global_1,
					origine_facturation_id
				FROM w_factures_lignes_c
				WHERE PRO_LCL <> 'ACPT' AND montant_facture <> 0;
				
				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');
				
				
				
				
					
					
				DROP TABLE IF EXISTS w_sejours_facture_reference;

				CREATE TEMP TABLE w_sejours_facture_reference AS
				SELECT 
					no_sejour,
					COALESCE(
						MAX(CASE WHEN type_facture <> '1' AND type_facture <> 'X' AND t_prestations.code = 'GHS' THEN p_factures.no_facture ELSE null END),
						MAX(CASE WHEN type_facture <> '1' AND type_facture <> 'X' THEN p_factures.no_facture ELSE null END),
						MAX(p_factures.no_facture)
					) AS no_facture_reference
				FROM activite[PX].p_factures
					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 = 'GHS'
				GROUP BY no_sejour;


				CREATE INDEX w_sejours_facture_reference_i1
								  ON w_sejours_facture_reference
								  USING btree
								  (no_sejour);

				CREATE INDEX w_sejours_facture_reference_i2
								  ON w_sejours_facture_reference
								  USING btree
								  (no_facture_reference);


				UPDATE activite[PX].p_factures SET
					no_facture_reference = w_sejours_facture_reference.no_facture_reference,
					facture_reference_id = p_factures_references.oid
				FROM w_sejours_facture_reference
				JOIN activite[PX].p_factures p_factures_references ON p_factures_references.no_facture = w_sejours_facture_reference.no_facture_reference
				WHERE p_factures.no_sejour = w_sejours_facture_reference.no_sejour AND
					(p_factures.no_facture_reference IS DISTINCT FROM w_sejours_facture_reference.no_facture_reference OR
					p_factures.facture_reference_id IS DISTINCT FROM p_factures_references.oid
					)
				;
										
										
			]]></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(
					facture_id,
					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
					facture_id,
					no_facture,
					date_trunc('month',date_vente) + interval '1 month' - interval '1 day',
					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_factures_lignes_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,5;
				
				
				

				INSERT INTO activite[PX].p_factures_soldes_c(
					facture_id,
					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
					facture_id,
					no_facture, 
					date_trunc('month',DAT_REG) + interval '1 month' - interval '1 day',
					rubrique_comptabilisation_id, 
					prestation_id, 
					0::numeric AS montant_comptabilise, 
					0::numeric AS montant_comptabilise_0, 
					0::numeric AS montant_comptabilise_1, 
					0::numeric AS montant_comptabilise_2, 
					0::numeric AS montant_comptabilise_22, 
					SUM(MR1_LCL + MR2_LCL + MR3_LCL) AS montant_regle, 
					SUM(MR3_LCL) AS montant_regle_0, 
					SUM(MR1_LCL) AS montant_regle_1, 
					SUM(MR2_LCL) AS montant_regle_2,  
					0 AS montant_regle_22 
				FROM w_factures_lignes_c
					JOIN w_LIG_CLINI_mrx ON w_factures_lignes_c.NUM_LCL = w_LIG_CLINI_mrx.NUM_LCL
				WHERE no_facture NOT LIKE '%BG'
				GROUP BY 1,2,3,4,5;
				
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_1');
				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');
				
										
										
			]]></sqlcmd>
		</NODE>
	
		<NODE label="Lignes non facturées Honoraires">
			<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_LIG_HONOR;
				CREATE TEMP TABLE w_LIG_HONOR AS
				SELECT
					LIG_HONOR.*,
					COALESCE(CCAM_RUM.CODE,ACT_PRH,CPH_LHO) AS CCAM_ACTE,
					COALESCE(CCAM_RUM.PHASE,'') AS CCAM_PHASE,
					COALESCE(CCAM_RUM.ACTIVITE,'1') AS CCAM_ACTIVITE,
					COALESCE(CCAM_RUM.MODIF2,'') AS CCAM_MODIF1,
					COALESCE(CCAM_RUM.MODIF3,'') AS CCAM_MODIF2,
					COALESCE(CCAM_RUM.MODIF4,'') AS CCAM_MODIF3,
					COALESCE(CCAM_RUM.MODIF5,'') AS CCAM_MODIF4,
					COALESCE(CCAM_RUM.EXT_DOC,'') AS CCAM_EXT_DOC,
					COALESCE(ACT_PRH,CPH_LHO) AS ACT_LHO,
					ANN_LHO || to_char(COD_LHO,'FM900000') AS SEJ_DOS,
					ANN_LHO || to_char(COD_LHO,'FM900000') || '.' || to_char(CASE WHEN IND_LHO <> 0 THEN IND_LHO ELSE COALESCE(IND_DOS2_ETA2, IND_LHO) END,'FM9999900') AS no_facture,
					COALESCE(ACT_PRH,CPH_LHO) || '|' || 
					COALESCE(CCAM_RUM.CODE,ACT_PRH,CPH_LHO) || '|' || 
					CEX_LHO	AS key,
					CASE WHEN CASE WHEN IND_LHO <> 0 THEN IND_LHO ELSE COALESCE(IND_DOS2_ETA2, IND_LHO) END = 0 THEN '1' ELSE '0' END AS non_facturee
				FROM prod_sigems2.LIG_HONOR
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LHO = ANN_SELECT AND COD_LHO = COD_SELECT
					LEFT JOIN w_DOS2_ETA2 ON ANN_LHO = ANN_DOS2 AND COD_LHO = COD_DOS2
					LEFT JOIN prod_sigems2.CCAM_RUM ON LIG_HONOR.NUM_LHO = CCAM_RUM.NUM_LHO
					LEFT JOIN prod_sigems2.PROD_HONOR ON CPH_LHO = COD_PRH
				WHERE 
					CPH_LHO <> 'ECAH';

				
				CREATE INDEX w_LIG_HONOR_i1
				  ON w_LIG_HONOR
				  USING btree
				  (SEJ_DOS);
				  
				CREATE INDEX w_LIG_HONOR_i2
				  ON w_LIG_HONOR
				  USING btree
				  (no_facture);
				  
				CREATE INDEX w_LIG_HONOR_i3
				  ON w_LIG_HONOR
				  USING btree
				  (NUM_LHO);
					
				CREATE INDEX w_LIG_HONOR_i4
				  ON w_LIG_HONOR
				  USING btree
				  (key);	
				  
				UPDATE w_LIG_HONOR
				SET 
					MR1_LHO = ML1_LHO,
					MR2_LHO = ML2_LHO,
					MR3_LHO = ML3_LHO
				FROM prod_sigems2.DOS2
				WHERE ANN_DOS2 = ANN_LHO AND
					COD_DOS2 = COD_LHO AND
					IND_DOS2 = IND_LHO AND
					ETA_DOS2 = '5' AND
					COP_DOS2 = '1' AND
					(
						MR1_LHO IS DISTINCT FROM ML1_LHO OR
						MR2_LHO IS DISTINCT FROM ML2_LHO OR
						MR3_LHO IS DISTINCT FROM ML3_LHO
					);
					
				

					
				DROP TABLE IF EXISTS w_factures_last;
				CREATE TEMP TABLE w_factures_last AS
				SELECT no_sejour, 
					MAX(no_facture) AS no_facture,
					MAX(CASE WHEN code_facture <> '1' THEN no_facture ELSE NULL END) AS no_facture_nf
				FROM activite[PX].p_factures WHERE code_facture <> '1'
				GROUP BY 1;

				UPDATE w_LIG_HONOR
				SET no_facture = CASE WHEN ACT_LHO <> 'ACPT' THEN COALESCE(w_factures_last.no_facture_nf,w_factures_last.no_facture) ELSE w_factures_last.no_facture END
				FROM w_factures_last
				WHERE w_LIG_HONOR.SEJ_DOS = w_factures_last.no_sejour AND
					w_LIG_HONOR.no_facture NOT IN (SELECT no_facture FROM activite[PX].p_factures);


				DROP TABLE IF EXISTS w_LIG_HONOR_keys;
				CREATE TEMP TABLE w_LIG_HONOR_keys AS
				SELECT key,
					ACT_LHO,
					CCAM_ACTE,
					CEX_LHO,
					0::bigint AS prestation_id,
					0::bigint AS rubrique_facturation_id,
					0::bigint AS medecin_facture_id,
					0::bigint AS medecin_comptabilise_id,
					0::bigint AS acte_id
				FROM w_LIG_HONOR
				GROUP BY 1,2,3,4;
				
				UPDATE activite.t_prestations SET
					code_original = ACT_LHO
				FROM w_LIG_HONOR_keys
				where t_prestations.code_original IS DISTINCT FROM ACT_LHO
					AND t_prestations.code = ACT_LHO;
					
				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT ACT_LHO, ACT_LHO, ACT_LHO, ACT_LHO
				FROM w_LIG_HONOR_keys
				WHERE ACT_LHO <> '' AND
					ACT_LHO NOT IN (SELECT code_original FROM activite.t_prestations WHERE code_original IS NOT NULL)
				GROUP BY ACT_LHO
				ORDER BY ACT_LHO;

				INSERT INTO base.t_actes(code, texte, texte_court, nomenclature, ccam_regroupement_id_1, ccam_regroupement_id_4)
				SELECT substring(CCAM_ACTE, 1, 7), substring(CCAM_ACTE, 1, 7), substring(CCAM_ACTE, 1, 7), CASE WHEN length(CCAM_ACTE) >= 7 THEN 'CCAM' ELSE 'NGAP' END, 
					(SELECT oid FROM base.t_ccam_regroupements WHERE code = 'NGAP'), (SELECt oid FROM base.t_ccam_regroupements WHERE code = 'NGAP')
				FROM w_LIG_HONOR_keys
				WHERE substring(CCAM_ACTE, 1, 7) NOT IN (SELECT code FROM base.t_actes) AND length(CCAM_ACTE) < 7
				GROUP BY substring(CCAM_ACTE, 1, 7) ,CASE WHEN length(CCAM_ACTE) >= 7 THEN 'CCAM' ELSE 'NGAP' END
				ORDER BY substring(CCAM_ACTE, 1, 7) ;




				UPDATE w_LIG_HONOR_keys SET prestation_id = t_prestations.oid
				FROM activite.t_prestations
				WHERE ACT_LHO = t_prestations.code_original;
				
				UPDATE w_LIG_HONOR_keys SET rubrique_facturation_id = t_rubriques_facturation.oid
				FROM activite[PX].t_rubriques_facturation
				WHERE ACT_LHO = t_rubriques_facturation.code_original;

				UPDATE w_LIG_HONOR_keys SET 
					acte_id = t_actes.oid
				FROM base.t_actes
				WHERE substring(CCAM_ACTE, 1, 7) = t_actes.code;

				UPDATE w_LIG_HONOR_keys SET 
					medecin_facture_id = t_medecins_administratifs.oid,
					medecin_comptabilise_id = t_medecins_administratifs.oid
				FROM activite[PX].t_medecins_administratifs
				WHERE CEX_LHO = t_medecins_administratifs.code_original;
				
				
				CREATE INDEX w_LIG_HONOR_keys_i1
				  ON w_LIG_HONOR_keys
				  USING btree
				  (key);	
				
				DROP TABLE IF EXISTS w_LIG_HONOR_tmrx;
				CREATE TEMP TABLE w_LIG_HONOR_tmrx AS
				SELECT no_facture,
					SUM(MR1_LHO) AS MR1_LHO,
					SUM(MR2_LHO) AS MR2_LHO,
					SUM(MR3_LHO) AS MR3_LHO
				FROM w_LIG_HONOR
				WHERE ACT_LHO <> 'ECAC'
				GROUP BY 1;
				
				CREATE INDEX w_LIG_HONOR_tmrx_i1
				  ON w_LIG_HONOR_tmrx
				  USING btree
				  (no_facture);


				UPDATE activite[PX].p_factures SET 
					montant_regle_h = w_LIG_HONOR_tmrx.MR1_LHO + w_LIG_HONOR_tmrx.MR2_LHO + w_LIG_HONOR_tmrx.MR3_LHO,
					montant_regle_1_h = w_LIG_HONOR_tmrx.MR1_LHO,
					montant_regle_2_h = w_LIG_HONOR_tmrx.MR2_LHO,
					montant_regle_0_h = w_LIG_HONOR_tmrx.MR3_LHO
				FROM w_LIG_HONOR_tmrx
				WHERE p_factures.no_facture = w_LIG_HONOR_tmrx.no_facture AND
					(
						montant_regle_h <> w_LIG_HONOR_tmrx.MR1_LHO + w_LIG_HONOR_tmrx.MR2_LHO + w_LIG_HONOR_tmrx.MR3_LHO OR
						montant_regle_1_h <> w_LIG_HONOR_tmrx.MR1_LHO OR
						montant_regle_2_h <> w_LIG_HONOR_tmrx.MR2_LHO OR
						montant_regle_0_h <> w_LIG_HONOR_tmrx.MR3_LHO
					);
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lignes factures Honoraires">
			<sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_REG3_LHO;
				CREATE TEMP TABLE w_REG3_LHO AS
				SELECT LHO_REG3
				FROM prod_sigems2.REG3
				GROUP BY 1;
				
				ALTER TABLE w_REG3_LHO ADD CONSTRAINT w_REG3_LHO_pkey PRIMARY KEY(LHO_REG3);

				

				DROP TABLE IF EXISTS w_factures_lignes_h;
				CREATE TEMP TABLE w_factures_lignes_h AS 
				SELECT
						NUM_LHO,
						
						p_sejours.no_sejour,
						
						p_factures.oid AS facture_id,
						w_LIG_HONOR.no_facture AS no_facture,
						p_factures.date_vente,
						
						date(DDE_LHO) AS date_debut,
						to_number('00' || HEU_LHO, '0000') * 10000 AS heure_debut,
						date(DDE_LHO) AS date_fin,
						QTE_LHO AS nb_rubrique,
						QTE_LHO AS nb_prestation,
						round(CASE WHEN COF_LHO * DNB_LHO <> 0 THEN COF_LHO * DNB_LHO ELSE 1.00 END::numeric,2) AS coefficient,
						1::numeric AS coefficient_mco,
						w_LIG_HONOR_keys.medecin_facture_id AS medecin_facture_id,
						w_LIG_HONOR_keys.medecin_comptabilise_id AS medecin_comptabilise_id,
						w_LIG_HONOR.ACT_LHO,
						w_LIG_HONOR_keys.prestation_id AS prestation_id,
						w_LIG_HONOR_keys.rubrique_facturation_id AS rubrique_facturation_id,
						w_LIG_HONOR_keys.acte_id AS acte_id,	
						CCAM_ACTIVITE AS activite_ccam,
						CCAM_EXT_DOC AS extension_ccam,
						CCAM_PHASE AS phase_ccam,
						CCAM_MODIF1 AS modificateur_ccam_1,
						CCAM_MODIF2 AS modificateur_ccam_2,
						CCAM_MODIF3 AS modificateur_ccam_3,
						CCAM_MODIF4 AS modificateur_ccam_4,
						ML1_LHO + ML2_LHO + ML3_LHO AS montant_facture,
						ML3_LHO AS montant_facture_0,
						ML1_LHO AS montant_facture_1,
						ML2_LHO AS montant_facture_2,
						0::numeric AS montant_facture_22,
						CASE WHEN DEP_LHO IN ('A', 'B', 'C', 'D', 'E', 'F', 'M', 'N') THEN TAR_LHO - BAR_LHO ELSE 0 END AS montant_depassement,
						TX3_LHO AS taux_0,
						TX1_LHO AS taux_1,
						TX2_LHO AS taux_2,
						0::numeric AS taux_22,
						round(base.cti_division(BAR_LHO, QTE_LHO * COF_LHO),2) AS prix_unitaire,
						p_sejours.lieu_sortie_id AS lieu_id,
						ML1_LHO + ML2_LHO + ML3_LHO AS montant_comptabilise,
						ML3_LHO AS montant_comptabilise_0,
						ML1_LHO + CASE WHEN p_factures.tiers_payant_1_id = p_factures.tiers_payant_2_id AND p_factures.tiers_payant_1_id <> 0 THEN ML2_LHO ELSE 0 END AS montant_comptabilise_1,
						CASE WHEN p_factures.tiers_payant_1_id <> p_factures.tiers_payant_2_id THEN ML2_LHO ELSE 0 END AS montant_comptabilise_2,
						0::numeric AS montant_comptabilise_22,
						MR1_LHO + MR2_LHO + MR3_LHO AS montant_regle,
						MR3_LHO AS montant_regle_0,
						MR1_LHO + CASE WHEN p_factures.tiers_payant_1_id = p_factures.tiers_payant_2_id AND p_factures.tiers_payant_1_id <> 0 THEN MR2_LHO ELSE 0 END AS montant_regle_1,
						CASE WHEN p_factures.tiers_payant_1_id <> p_factures.tiers_payant_2_id THEN MR2_LHO ELSE 0 END AS montant_regle_2,
						0::numeric AS montant_regle_22,
						0::numeric AS montant_encours,
						0::numeric AS montant_encours_0,
						0::numeric AS montant_encours_1,
						0::numeric AS montant_encours_2,
						0::numeric AS montant_encours_22,
						0::numeric AS montant_facture_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_0_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_1_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_2_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_22_actes_inclus_dans_sejour
				FROM w_LIG_HONOR
					JOIN activite[PX].p_factures ON w_LIG_HONOR.no_facture = p_factures.no_facture
					JOIN activite[PX].p_sejours ON w_LIG_HONOR.SEJ_DOS = p_sejours.code_original
					JOIN w_LIG_HONOR_keys ON w_LIG_HONOR.key = w_LIG_HONOR_keys.key
					LEFT JOIN w_REG3_LHO ON w_LIG_HONOR.NUM_LHO = w_REG3_LHO.LHO_REG3
				WHERE (p_factures.code_facture = '1' AND w_LIG_HONOR.non_facturee <> '1') OR w_LIG_HONOR.ACT_LHO <> 'ECAH' OR w_REG3_LHO.LHO_REG3 IS NOT NULL;
				;
				
				
				CREATE INDEX w_factures_lignes_h_i1
				  ON w_factures_lignes_h
				  USING btree
				  (NUM_LHO);
				  
			    CREATE INDEX w_factures_lignes_h_i2
				  ON w_factures_lignes_h
				  USING btree
				  (no_sejour);
				  
				  
				-- Lieu exécution
				
				UPDATE w_factures_lignes_h
				SET lieu_id = p_mouvements_sejour.lieu_id
				FROM 
					activite[PX].p_mouvements_sejour
				WHERE
					w_factures_lignes_h.no_sejour = p_mouvements_sejour.no_sejour AND
					w_factures_lignes_h.date_fin = p_mouvements_sejour.date AND
					(230000 BETWEEN p_mouvements_sejour.heure_debut AND p_mouvements_sejour.heure_fin OR 
					nb_entrees_directes = 1 AND heure_fin = 240000 OR 
					nb_sorties_directes = 1 ) AND
					w_factures_lignes_h.lieu_id <> p_mouvements_sejour.lieu_id;



				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 (
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					medecin_facture_id,
					medecin_comptabilise_id,
					prestation_id,
					rubrique_facturation_id,
					acte_id,	
					activite_ccam,
					extension_ccam,
					phase_ccam,
					modificateur_ccam_1,
					modificateur_ccam_2,
					modificateur_ccam_3,
					modificateur_ccam_4,
					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
					)
				SELECT
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					medecin_facture_id,
					medecin_comptabilise_id,
					prestation_id,
					rubrique_facturation_id,
					acte_id,	
					activite_ccam,
					extension_ccam,
					phase_ccam,
					modificateur_ccam_1,
					modificateur_ccam_2,
					modificateur_ccam_3,
					modificateur_ccam_4,
					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
				FROM w_factures_lignes_h
				WHERE ACT_LHO <> 'ACPT' ;
				
				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');
				
				
				
										
										
			]]></sqlcmd>
		</NODE>
	
		<NODE label="Compte client Honoraires">
			<sqlcmd><![CDATA[
			
				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');
			
				-- Hors budget global
				INSERT INTO activite[PX].p_factures_soldes_h(
					facture_id,
					no_facture, 
					date_comptable, 
					medecin_comptabilise_id, 
					prestation_id,
					rubrique_comptabilisee_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
					facture_id,
					no_facture,
					date_trunc('month',date_vente) + interval '1 month' - interval '1 day',
					medecin_comptabilise_id,
					prestation_id,
					rubrique_facturation_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_factures_lignes_h
				JOIN activite[PX].p_sejours ON w_factures_lignes_h.no_sejour = p_sejours.no_sejour AND p_sejours.est_budget_global IS DISTINCT FROM '1'
				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,5,6;
				

				
				INSERT INTO activite[PX].p_factures_soldes_h(
					facture_id,
					no_facture, 
					date_comptable, 
					medecin_comptabilise_id, 
					prestation_id,
					rubrique_comptabilisee_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
					facture_id,
					no_facture, 
					date_trunc('month',DAT_REG) + interval '1 month' - interval '1 day',
					medecin_comptabilise_id, 
					prestation_id,
					rubrique_facturation_id,
					0::numeric AS montant_comptabilise, 
					0::numeric AS montant_comptabilise_0, 
					0::numeric AS montant_comptabilise_1, 
					0::numeric AS montant_comptabilise_2, 
					0::numeric AS montant_comptabilise_22, 
					SUM(MR1_LHO + MR2_LHO + MR3_LHO) AS montant_regle, 
					SUM(MR3_LHO) AS montant_regle_0, 
					SUM(MR1_LHO) AS montant_regle_1, 
					SUM(MR2_LHO) AS montant_regle_2,  
					0 AS montant_regle_22 
				FROM w_factures_lignes_h
					JOIN activite[PX].p_sejours ON w_factures_lignes_h.no_sejour = p_sejours.no_sejour AND p_sejours.est_budget_global IS DISTINCT FROM '1'
					JOIN w_LIG_HONOR_mrx ON w_factures_lignes_h.NUM_LHO = w_LIG_HONOR_mrx.NUM_LHO
				GROUP BY 1,2,3,4,5,6;
				
				-- Budget Global (sur ets)
				INSERT INTO activite[PX].p_factures_soldes_c(
					facture_id,
					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
					facture_id,
					no_facture,
					date_trunc('month',date_vente) + interval '1 month' - interval '1 day',
					rubrique_facturation_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_factures_lignes_h
				JOIN activite[PX].p_sejours ON w_factures_lignes_h.no_sejour = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
				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,5;
				

				
				INSERT INTO activite[PX].p_factures_soldes_c(
					facture_id,
					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
					facture_id,
					no_facture, 
					date_trunc('month',DAT_REG) + interval '1 month' - interval '1 day',
					rubrique_facturation_id, 
					prestation_id,
					0::numeric AS montant_comptabilise, 
					0::numeric AS montant_comptabilise_0, 
					0::numeric AS montant_comptabilise_1, 
					0::numeric AS montant_comptabilise_2, 
					0::numeric AS montant_comptabilise_22, 
					SUM(MR1_LHO + MR2_LHO + MR3_LHO) AS montant_regle, 
					SUM(MR3_LHO) AS montant_regle_0, 
					SUM(MR1_LHO) AS montant_regle_1, 
					SUM(MR2_LHO) AS montant_regle_2,  
					0 AS montant_regle_22 
				FROM w_factures_lignes_h
					JOIN activite[PX].p_sejours ON w_factures_lignes_h.no_sejour = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
					JOIN w_LIG_HONOR_mrx ON w_factures_lignes_h.NUM_LHO = w_LIG_HONOR_mrx.NUM_LHO
				GROUP BY 1,2,3,4,5;
				
				
				
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_1');
				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');
						
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Budget global MCO">
			<condition><![CDATA[
				"[ENV_TYPEETS]" != "1" && "[ENV_WITHPMSI]" == "1"
			]]></condition>
			<sqlcmd><![CDATA[

				-- Ajout des prestations PMSI aux prestations activité
				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT
					t_prestations_pmsi.code,
					t_prestations_pmsi.code,
					t_prestations_pmsi.texte,
					t_prestations_pmsi.texte
				FROM pmsi.p_rsf_detail
				JOIN pmsi.p_rss ON p_rss.oid = p_rsf_detail.rss_id AND p_rss.etat = '' AND p_rss.en_cours = '0'
				JOIN pmsi.t_prestations t_prestations_pmsi ON t_prestations_pmsi.oid = p_rsf_detail.prestation_id
				JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
				JOIN activite[PX].p_sejours on no_sejour_administratif = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
				LEFT JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code = t_prestations_pmsi.code
				WHERE est_ligne_rss = '1' AND p_rss.en_cours = '0' AND 
					operation_lamda IS DISTINCT FROM '1' AND
					operation_lamda IS DISTINCT FROM '2' AND
					t_rubriques_facturation.oid IS NULL
				GROUP BY 1,2,3,4;

				-- Ajout des prestations PMSI aux rubriques activité
				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT
					t_prestations_pmsi.code,
					t_prestations_pmsi.code,
					t_prestations_pmsi.texte,
					t_prestations_pmsi.texte
				FROM pmsi.p_rsf_detail
				JOIN pmsi.p_rss ON p_rss.oid = p_rsf_detail.rss_id AND p_rss.etat = '' AND p_rss.en_cours = '0'
				JOIN pmsi.t_prestations t_prestations_pmsi ON t_prestations_pmsi.oid = p_rsf_detail.prestation_id
				JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
				JOIN activite[PX].p_sejours on no_sejour_administratif = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
				LEFT JOIN activite.t_prestations t_prestations_activite ON t_prestations_activite.code = t_prestations_pmsi.code
				WHERE est_ligne_rss = '1' AND p_rss.en_cours = '0' AND 
					operation_lamda IS DISTINCT FROM '1' AND
					operation_lamda IS DISTINCT FROM '2' AND
					t_prestations_activite.oid IS NULL
				GROUP BY 1,2,3,4;

				-- Lignes PMSI à ajouter
				DROP TABLE IF EXISTS w_factures_lignes_pmsi;
				CREATE TEMP TABLE w_factures_lignes_pmsi AS
				SELECT
					p_sejours.no_sejour,
					p_sejours.oid AS sejour_id,
					p_sejours.no_sejour || '.BG' AS no_facture,
					0::bigint AS facture_id,
					CASE WHEN p_rsf_detail.type = 'C' THEN 'H' ELSE 'C' END AS clinique_honoraire,
					p_rsf_detail.date_debut,
					p_rsf_detail.date_fin,
					p_rsf_detail.nombre AS nb_rubrique,
					p_rsf_detail.nombre AS nb_prestation,
					p_rsf_detail.coefficient AS coefficient,
					p_rsf_detail.coefficient_mco,
					COALESCE(t_rubriques_facturation.oid,0::bigint) AS rubrique_facturation_id,
					COALESCE(t_rubriques_facturation.oid,0::bigint) AS rubrique_comptabilisation_id,
					COALESCE(t_prestations_activite.oid,0::bigint) AS prestation_id,
					p_rsf_detail.sejour_remboursable AS montant_facture,
					0::numeric AS montant_facture_0,
					p_rsf_detail.sejour_remboursable AS montant_facture_1,
					0::numeric AS montant_facture_2,
					0::numeric AS montant_facture_22,
					0::numeric AS taux_0,
					p_rsf_detail.taux_remboursement AS taux_1,
					0::numeric AS taux_2,
					0::numeric AS taux_22,
					p_rsf_detail.prix_unitaire,
					p_sejours.lieu_sortie_id AS lieu_id,
					0::numeric AS montant_comptabilise,
					0::numeric AS montant_comptabilise_0,
					0::numeric AS montant_comptabilise_1,
					0::numeric AS montant_comptabilise_2,
					0::numeric AS montant_comptabilise_22,
					0::numeric AS montant_encours,
					0::numeric AS montant_encours_0,
					0::numeric AS montant_encours_1,
					0::numeric AS montant_encours_2,
					0::numeric AS montant_encours_22,
					0::numeric AS montant_facture_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_0_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_1_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_2_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_22_actes_inclus_dans_sejour,
					CASE WHEN p_rsf_detail.type = 'C' THEN 2::bigint ELSE 1::bigint END AS origine_facturation_id,
					CASE WHEN p_rss.traitement_epmsi IN ('30','31','32','33') THEN p_rsf_detail.sejour_remboursable ELSE 0 END AS montant_comptabilise_budget_global_1,
					0::numeric AS protocole_id,
					0::numeric AS compte_produit_id,
					t_prestations_pmsi.code AS prestation_code,
					''::text AS uf_code,
					''::text AS dmt_code,
					''::text AS mt_code
				FROM pmsi.p_rsf_detail
				JOIN pmsi.p_rss ON p_rss.oid = p_rsf_detail.rss_id AND p_rss.etat = '' AND p_rss.en_cours = '0'
                JOIN pmsi.p_rsf_total ON p_rss.oid = p_rsf_total.rss_id AND p_rsf_total.valorise_fides IS DISTINCT FROM 1
				JOIN pmsi.t_prestations t_prestations_pmsi ON t_prestations_pmsi.oid = p_rsf_detail.prestation_id
				JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
				JOIN activite[PX].p_sejour_pmsi ON p_rss.oid = p_sejour_pmsi.rss_id
				JOIN activite[PX].p_sejours on p_sejour_pmsi.no_sejour = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
				LEFT JOIN activite.t_prestations t_prestations_activite ON t_prestations_activite.code = t_prestations_pmsi.code
				LEFT JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code = t_prestations_pmsi.code
				WHERE est_ligne_rss = '1' AND p_rss.en_cours = '0' AND
					operation_lamda IS DISTINCT FROM '1' AND
					operation_lamda IS DISTINCT FROM '2' AND
					p_rss.traitement_epmsi NOT IN ('12') ;

				-- compte
				UPDATE w_factures_lignes_pmsi
				SET uf_code = t_unites_fonctionnelles.code,
					dmt_code = CASE WHEN t_dmt.oid <> 0 THEN t_dmt.code ELSE '' END,
					mt_code = CASE WHEN t_modes_traitement.oid <> 0 THEN CASE WHEN t_modes_traitement.code <> '23' THEN t_modes_traitement.code ELSE '04' END ELSE '' END
				FROM activite[PX].t_lieux 
				JOIN activite[PX].t_unites_fonctionnelles ON unite_fonctionnelle_id = t_unites_fonctionnelles.oid
				JOIN activite[PX].t_services_facturation On service_facturation_id = t_services_facturation.oid
				JOIN base.t_dmt ON dmt_id = t_dmt.oid
				JOIN base.t_modes_traitement ON t_services_facturation.mode_traitement_id = t_modes_traitement.oid
				WHERE lieu_id = t_lieux.oid;


				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = t_compte.oid
				FROM prod_sigems2.ANALYG
				JOIN activite[PX].t_compte ON CPT_ANA = t_compte.code
				WHERE compte_produit_id = 0 AND
					PRD_ANA = prestation_code AND
					SER_ANA = uf_code AND
					DMT_ANA = dmt_code AND
					MDT_ANA = mt_code AND
					CPT_ANA <> '';

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = t_compte.oid
				FROM prod_sigems2.ANALYG
				JOIN activite[PX].t_compte ON CPT_ANA = t_compte.code
				WHERE compte_produit_id = 0 AND
					PRD_ANA = prestation_code AND
					SER_ANA = uf_code AND
					DMT_ANA = '' AND
					MDT_ANA = mt_code AND
					CPT_ANA <> '';

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = t_compte.oid
				FROM prod_sigems2.ANALYG
				JOIN activite[PX].t_compte ON CPT_ANA = t_compte.code
				WHERE compte_produit_id = 0 AND
					PRD_ANA = prestation_code AND
					SER_ANA = uf_code AND
					DMT_ANA = dmt_code AND
					MDT_ANA = '' AND
					CPT_ANA <> '';

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = t_compte.oid
				FROM prod_sigems2.ANALYG
				JOIN activite[PX].t_compte ON CPT_ANA = t_compte.code
				WHERE compte_produit_id = 0 AND
					PRD_ANA = prestation_code AND
					SER_ANA = uf_code AND
					DMT_ANA = '' AND
					MDT_ANA = '' AND
					CPT_ANA <> '';



				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = t_compte.oid
				FROM prod_sigems2.ANALYG
				JOIN activite[PX].t_compte ON CPT_ANA = t_compte.code
				WHERE compte_produit_id = 0 AND
					PRD_ANA = prestation_code AND
					SER_ANA = '' AND
					DMT_ANA = dmt_code AND
					MDT_ANA = mt_code AND
					CPT_ANA <> '';

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = t_compte.oid
				FROM prod_sigems2.ANALYG
				JOIN activite[PX].t_compte ON CPT_ANA = t_compte.code
				WHERE compte_produit_id = 0 AND
					PRD_ANA = prestation_code AND
					SER_ANA = '' AND
					DMT_ANA = '' AND
					MDT_ANA = mt_code AND
					CPT_ANA <> '';

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = t_compte.oid
				FROM prod_sigems2.ANALYG
				JOIN activite[PX].t_compte ON CPT_ANA = t_compte.code
				WHERE compte_produit_id = 0 AND
					PRD_ANA = prestation_code AND
					SER_ANA = '' AND
					DMT_ANA = dmt_code AND
					MDT_ANA = '' AND
					CPT_ANA <> '';

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = t_compte.oid
				FROM prod_sigems2.ANALYG
				JOIN activite[PX].t_compte ON CPT_ANA = t_compte.code
				WHERE compte_produit_id = 0 AND
					PRD_ANA = prestation_code AND
					SER_ANA = '' AND
					DMT_ANA = '' AND
					MDT_ANA = '' AND
					CPT_ANA <> '';

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = t_compte.oid
				FROM prod_sigems2.PROD_CLINI
				JOIN activite[PX].t_compte ON AFA_PRC = t_compte.code
				WHERE compte_produit_id = 0 AND
					COD_PRC = prestation_code;


				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = t_compte.oid
				FROM prod_sigems2.PROD_CLINI
				JOIN activite[PX].t_compte ON AFA_PRC = t_compte.code
				WHERE compte_produit_id = 0 AND
					LIB_PRC = prestation_code;
					
				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = t_compte.oid
				FROM prod_sigems2.ANALYG
				JOIN activite[PX].t_compte ON CPT_ANA = t_compte.code
				WHERE compte_produit_id = 0 AND
					PRD_ANA = trim(substr(prestation_code,1,4)) AND
					SER_ANA = '' AND
					DMT_ANA = '' AND
					MDT_ANA = '' AND
					CPT_ANA <> '';
					
				CREATE INDEX w_factures_lignes_pmsi_i1
						  ON w_factures_lignes_pmsi
						  USING btree
						  (no_sejour);
				

				-- Factures de base
				DROP TABLE IF EXISTS w_factures_pmsi_base;
				CREATE TEMP TABLE w_factures_pmsi_base AS 
				SELECT p_factures.no_sejour, 
					(MAX(Array[CASE WHEN p_factures.code_facture <> '0' THEN p_factures.date_facture ELSE '00010101' END::text,p_factures.no_facture]))[2] AS no_facture_base 
				FROM pmsi.p_rss
				JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
				JOIN activite[PX].p_sejour_pmsi ON p_rss.oid = p_sejour_pmsi.rss_id
				JOIN activite[PX].p_sejours on p_sejour_pmsi.no_sejour = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
				JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour
				WHERE p_rss.etat = '' AND 
					p_rss.en_cours = '0' 
				GROUP BY 1;
				
				CREATE INDEX w_factures_pmsi_base_i1
						  ON w_factures_pmsi_base
						  USING btree
						  (no_sejour);
						  
				CREATE INDEX w_factures_pmsi_base_i2
						  ON w_factures_pmsi_base
						  USING btree
						  (no_facture_base);

				-- Factures à créer
				DROP TABLE IF EXISTS w_factures_pmsi;
				CREATE TEMP TABLE w_factures_pmsi AS
				SELECT
					w_factures_lignes_pmsi.no_sejour,
					w_factures_lignes_pmsi.sejour_id,
					w_factures_lignes_pmsi.no_facture,
					p_sejours.date_entree AS date_debut,
					p_sejours.date_sortie AS date_fin,
					'0'::text AS type_facture,
					'1'::text AS code_facture,
					MAX(CASE 
						WHEN p_factures_base.date_facture IS NULL THEN p_sejours.date_sortie
						WHEN p_factures_base.date_facture <> '20991231' THEN p_factures_base.date_facture 
						WHEN p_sejours.date_groupage <> '20991231' THEN p_sejours.date_groupage
						ELSE p_sejours.date_sortie END)::date AS date_facture,
					MAX(COALESCE(p_factures_base.code_vente,'1')) AS code_vente,
					MAX(COALESCE(p_factures_base.mois_vente,209912)) AS mois_vente,
					MAX(COALESCE(p_factures_base.date_facture,p_sejours.date_sortie)) AS date_solde,
					'0'::text AS particularite_t2a,
					MAX(COALESCE(p_factures_base.date_vente,p_sejours.date_sortie)) AS date_vente,
					''::text AS code_cloture,
					MAX(p_sejours.code_cp_demandee) AS code_cp_demandee,
					'20991231'::date AS date_encours,
					MAX(p_sejours.ghs_id) AS ghs_id,
					MAX(p_sejours.ghs_bebe1_id) AS ghs_bebe1_id,
					MAX(p_sejours.ghs_bebe2_id) AS ghs_bebe2_id,
					MAX(p_sejours.ghs_bebe3_id) AS ghs_bebe3_id,
					MAX(p_sejours.ghm_id) AS ghm_id,
					SUM(montant_facture) AS montant_facture_c,
					0::numeric AS montant_facture_h,
					0::numeric AS montant_regle_c,
					0::numeric AS montant_regle_h,
					0::numeric AS delai_facture,
					0::numeric AS delai_solde,
					'20991231'::date AS date_expedition,
					0::numeric AS delai_expedition,
					MAX(p_sejours.tiers_payant_1_id) AS tiers_payant_1_id,
					MAX(p_sejours.tiers_payant_2_id) AS tiers_payant_2_id,
					MAX(p_sejours.tiers_payant_22_id) AS tiers_payant_22_id,
					MAX(p_sejours.tiers_payant_0_id) AS tiers_payant_0_id,
					'20991231'::date AS date_solde_0_c,
					'20991231'::date AS date_solde_0_h,
					'20991231'::date AS date_solde_1_c,
					'20991231'::date AS date_solde_1_h,
					'20991231'::date AS date_solde_2_c,
					'20991231'::date AS date_solde_2_h,
					'20991231'::date AS date_solde_22_c,
					'20991231'::date AS date_solde_22_h,
					'20991231'::date AS date_expedition_0,
					'20991231'::date AS date_expedition_1,
					'20991231'::date AS date_expedition_2,
					'20991231'::date AS date_expedition_22,
					'0'::text AS code_expedie_0,
					'0'::text AS code_expedie_1,
					'0'::text AS code_expedie_2,
					'0'::text AS code_expedie_22,
					''::text AS no_bordereau_0,
					''::text AS no_bordereau_1,
					''::text AS no_bordereau_2,
					''::text AS no_bordereau_22,
					0::numeric AS montant_facture_0_c,
					0::numeric AS montant_facture_0_h,
					SUM(montant_facture) AS montant_facture_1_c,
					0::numeric AS montant_facture_1_h,
					0::numeric AS montant_facture_2_c,
					0::numeric AS montant_facture_2_h,
					0::numeric AS montant_facture_22_c,
					0::numeric AS montant_facture_22_h,
					0::numeric AS montant_regle_0_c,
					0::numeric AS montant_regle_0_h,
					0::numeric AS montant_regle_1_c,
					0::numeric AS montant_regle_1_h,
					0::numeric AS montant_regle_2_c,
					0::numeric AS montant_regle_2_h,
					0::numeric AS montant_regle_22_c,
					0::numeric AS montant_regle_22_h,
					0::numeric AS delai_expedition_0,
					0::numeric AS delai_expedition_1,
					0::numeric AS delai_expedition_2,
					0::numeric AS delai_expedition_22,
					0::numeric AS delai_solde_0_c,
					0::numeric AS delai_solde_0_h,
					0::numeric AS delai_solde_1_c,
					0::numeric AS delai_solde_1_h,
					0::numeric AS delai_solde_2_c,
					0::numeric AS delai_solde_2_h,
					0::numeric AS delai_solde_22_c,
					0::numeric AS delai_solde_22_h,
					0::numeric AS montant_encours_c,
					0::numeric AS montant_encours_0_c,
					0::numeric AS montant_encours_1_c,
					0::numeric 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,
					0::numeric AS nb_rejets,
					0::numeric AS montant_comptabilise_c,
					0::numeric AS montant_comptabilise_h,
					0::numeric AS montant_comptabilise_0_c,
					0::numeric AS montant_comptabilise_0_h,
					0::numeric AS montant_comptabilise_1_c,
					0::numeric AS montant_comptabilise_1_h,
					0::numeric AS montant_comptabilise_2_c,
					0::numeric AS montant_comptabilise_2_h,
					0::numeric AS montant_comptabilise_22_c,
					0::numeric AS montant_comptabilise_22_h,
					w_factures_lignes_pmsi.no_facture AS no_facture_reference,
					0::bigint AS facture_reference_id,
					'20991231'::date AS date_solde_reference,
					'20991231'::date AS date_solde_reference_c,
					'20991231'::date AS date_solde_reference_h,
					'20991231'::date AS date_solde_reference_0_c,
					'20991231'::date AS date_solde_reference_1_c,
					'20991231'::date AS date_solde_reference_2_c,
					'20991231'::date AS date_solde_reference_22_c,
					'20991231'::date AS date_solde_reference_0_h,
					'20991231'::date AS date_solde_reference_1_h,
					'20991231'::date AS date_solde_reference_2_h,
					'20991231'::date AS date_solde_reference_22_h,
					'20991231'::date AS date_solde_c,
					'20991231'::date AS date_solde_h,
					0::numeric AS montant_facture_c_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_h_actes_inclus_dans_sejour,
					SUM(montant_comptabilise_budget_global_1) AS montant_comptabilise_budget_global_c,
					'' AS no_facture_od_avoir,
					0::bigint AS facture_od_avoir_id
				FROM w_factures_lignes_pmsi
				JOIN activite[PX].p_sejours ON w_factures_lignes_pmsi.no_sejour = p_sejours.no_sejour
				JOIN w_factures_pmsi_base ON w_factures_lignes_pmsi.no_sejour = w_factures_pmsi_base.no_sejour
				LEFT JOIN activite[PX].p_factures p_factures_base ON w_factures_pmsi_base.no_facture_base = p_factures_base.no_facture 
				GROUP BY 1,2,3,4,5;
				
				INSERT INTO w_factures_pmsi
				SELECT
					p_sejours.no_sejour,
					p_sejours.oid AS sejour_id,
					p_sejours.no_sejour || '.BG',
					p_sejours.date_entree AS date_debut,
					p_sejours.date_sortie AS date_fin,
					'0'::text AS type_facture,
					'1'::text AS code_facture,
					MAX(CASE 
						WHEN p_sejours.date_groupage <> '20991231' THEN p_sejours.date_groupage
						ELSE p_sejours.date_sortie END)::date AS date_facture,
					'1' AS code_vente,
					209912 AS mois_vente,
					'20991231' AS date_solde,
					'0'::text AS particularite_t2a,
					'20991231' AS date_vente,
					''::text AS code_cloture,
					MAX(p_sejours.code_cp_demandee) AS code_cp_demandee,
					'20991231'::date AS date_encours,
					MAX(p_sejours.ghs_id) AS ghs_id,
					MAX(p_sejours.ghs_bebe1_id) AS ghs_bebe1_id,
					MAX(p_sejours.ghs_bebe2_id) AS ghs_bebe2_id,
					MAX(p_sejours.ghs_bebe3_id) AS ghs_bebe3_id,
					MAX(p_sejours.ghm_id) AS ghm_id,
					0 AS montant_facture_c,
					0::numeric AS montant_facture_h,
					0::numeric AS montant_regle_c,
					0::numeric AS montant_regle_h,
					0::numeric AS delai_facture,
					0::numeric AS delai_solde,
					'20991231'::date AS date_expedition,
					0::numeric AS delai_expedition,
					MAX(p_sejours.tiers_payant_1_id) AS tiers_payant_1_id,
					MAX(p_sejours.tiers_payant_2_id) AS tiers_payant_2_id,
					MAX(p_sejours.tiers_payant_22_id) AS tiers_payant_22_id,
					MAX(p_sejours.tiers_payant_0_id) AS tiers_payant_0_id,
					'20991231'::date AS date_solde_0_c,
					'20991231'::date AS date_solde_0_h,
					'20991231'::date AS date_solde_1_c,
					'20991231'::date AS date_solde_1_h,
					'20991231'::date AS date_solde_2_c,
					'20991231'::date AS date_solde_2_h,
					'20991231'::date AS date_solde_22_c,
					'20991231'::date AS date_solde_22_h,
					'20991231'::date AS date_expedition_0,
					'20991231'::date AS date_expedition_1,
					'20991231'::date AS date_expedition_2,
					'20991231'::date AS date_expedition_22,
					'0'::text AS code_expedie_0,
					'0'::text AS code_expedie_1,
					'0'::text AS code_expedie_2,
					'0'::text AS code_expedie_22,
					''::text AS no_bordereau_0,
					''::text AS no_bordereau_1,
					''::text AS no_bordereau_2,
					''::text AS no_bordereau_22,
					0::numeric AS montant_facture_0_c,
					0::numeric AS montant_facture_0_h,
					0::numeric AS montant_facture_1_c,
					0::numeric AS montant_facture_1_h,
					0::numeric AS montant_facture_2_c,
					0::numeric AS montant_facture_2_h,
					0::numeric AS montant_facture_22_c,
					0::numeric AS montant_facture_22_h,
					0::numeric AS montant_regle_0_c,
					0::numeric AS montant_regle_0_h,
					0::numeric AS montant_regle_1_c,
					0::numeric AS montant_regle_1_h,
					0::numeric AS montant_regle_2_c,
					0::numeric AS montant_regle_2_h,
					0::numeric AS montant_regle_22_c,
					0::numeric AS montant_regle_22_h,
					0::numeric AS delai_expedition_0,
					0::numeric AS delai_expedition_1,
					0::numeric AS delai_expedition_2,
					0::numeric AS delai_expedition_22,
					0::numeric AS delai_solde_0_c,
					0::numeric AS delai_solde_0_h,
					0::numeric AS delai_solde_1_c,
					0::numeric AS delai_solde_1_h,
					0::numeric AS delai_solde_2_c,
					0::numeric AS delai_solde_2_h,
					0::numeric AS delai_solde_22_c,
					0::numeric AS delai_solde_22_h,
					0::numeric AS montant_encours_c,
					0::numeric AS montant_encours_0_c,
					0::numeric AS montant_encours_1_c,
					0::numeric 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,
					0::numeric AS nb_rejets,
					0::numeric AS montant_comptabilise_c,
					0::numeric AS montant_comptabilise_h,
					0::numeric AS montant_comptabilise_0_c,
					0::numeric AS montant_comptabilise_0_h,
					0::numeric AS montant_comptabilise_1_c,
					0::numeric AS montant_comptabilise_1_h,
					0::numeric AS montant_comptabilise_2_c,
					0::numeric AS montant_comptabilise_2_h,
					0::numeric AS montant_comptabilise_22_c,
					0::numeric AS montant_comptabilise_22_h,
					p_sejours.no_sejour || '.BG' AS no_facture_reference,
					0::bigint AS facture_reference_id,
					'20991231'::date AS date_solde_reference,
					'20991231'::date AS date_solde_reference_c,
					'20991231'::date AS date_solde_reference_h,
					'20991231'::date AS date_solde_reference_0_c,
					'20991231'::date AS date_solde_reference_1_c,
					'20991231'::date AS date_solde_reference_2_c,
					'20991231'::date AS date_solde_reference_22_c,
					'20991231'::date AS date_solde_reference_0_h,
					'20991231'::date AS date_solde_reference_1_h,
					'20991231'::date AS date_solde_reference_2_h,
					'20991231'::date AS date_solde_reference_22_h,
					'20991231'::date AS date_solde_c,
					'20991231'::date AS date_solde_h,
					0::numeric AS montant_facture_c_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_h_actes_inclus_dans_sejour,
					0::numeric AS montant_comptabilise_budget_global_c,
					'' AS no_facture_od_avoir,
					0::bigint AS facture_od_avoir_id
				FROM pmsi.p_rss
				JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
				JOIN activite[PX].p_sejours on no_sejour_administratif = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
				LEFT JOIN w_factures_pmsi ON p_sejours.no_sejour = w_factures_pmsi.no_sejour 
				WHERE p_rss.en_cours = '0' AND 
					w_factures_pmsi.no_facture IS NULL AND
					p_sejours.date_sortie >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					p_sejours.no_sejour NOT IN 
						(
							SELECT p_factures.no_sejour 
							FROM activite[PX].p_factures
							WHERE montant_facture_1_c <> 0
						)
				GROUP BY 1,2,3,4,5;


				UPDATE w_factures_pmsi
				SET date_vente = date_facture, mois_vente = date_part('year',date_facture)*100 +  date_part('month',date_facture)
				WHERE date_vente = '20991231';

				UPDATE w_factures_pmsi
				SET date_solde = date_facture
				WHERE date_vente IS DISTINCT FROM date_facture;
				
				
				-- Ajout des factures
				INSERT INTO activite[PX].p_factures
					(no_sejour, no_facture, date_debut, date_fin, type_facture, 
					   code_facture, date_facture, code_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_1_id, tiers_payant_2_id, tiers_payant_22_id, tiers_payant_0_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, date_vente, code_cloture, 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, 
					   code_cp_demandee, date_encours, ghs_bebe1_id, ghs_bebe2_id, ghs_bebe3_id, 
					   nb_rejets, 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, no_facture_reference, date_solde_reference, 
					   date_solde_reference_c, date_solde_reference_h, date_solde_reference_0_c, 
					   date_solde_reference_1_c, date_solde_reference_2_c, date_solde_reference_22_c, 
					   date_solde_reference_0_h, date_solde_reference_1_h, date_solde_reference_2_h, 
					   date_solde_reference_22_h, date_solde_c, date_solde_h, montant_facture_c_actes_inclus_dans_sejour, 
					   montant_facture_h_actes_inclus_dans_sejour, montant_comptabilise_budget_global_c, 
					   no_facture_od_avoir, sejour_id, facture_reference_id, facture_od_avoir_id, 
					   ghm_id)
				  SELECt no_sejour, no_facture, date_debut, date_fin, type_facture, 
					   code_facture, date_facture, code_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_1_id, tiers_payant_2_id, tiers_payant_22_id, tiers_payant_0_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, date_vente, code_cloture, 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, 
					   code_cp_demandee, date_encours, ghs_bebe1_id, ghs_bebe2_id, ghs_bebe3_id, 
					   nb_rejets, 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, no_facture_reference, date_solde_reference, 
					   date_solde_reference_c, date_solde_reference_h, date_solde_reference_0_c, 
					   date_solde_reference_1_c, date_solde_reference_2_c, date_solde_reference_22_c, 
					   date_solde_reference_0_h, date_solde_reference_1_h, date_solde_reference_2_h, 
					   date_solde_reference_22_h, date_solde_c, date_solde_h, montant_facture_c_actes_inclus_dans_sejour, 
					   montant_facture_h_actes_inclus_dans_sejour, montant_comptabilise_budget_global_c, 
					   no_facture_od_avoir, sejour_id, facture_reference_id, facture_od_avoir_id, 
					   ghm_id
				   FROM w_factures_pmsi;



					-- Ajout des lignes
				   INSERT INTO activite[PX].p_factures_lignes_c(
						no_facture, date_debut, date_fin, nb_rubrique, coefficient, coefficient_mco, 
						rubrique_facturation_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, rubrique_comptabilisation_id, 
						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, protocole_id, compte_produit_id)
					SELECT 
						p_factures.no_facture, w_factures_lignes_pmsi.date_debut, w_factures_lignes_pmsi.date_fin, nb_rubrique, coefficient, coefficient_mco, 
							rubrique_facturation_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, rubrique_comptabilisation_id, 
							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, 
							p_factures.oid AS facture_id, protocole_id, compte_produit_id
					FROM w_factures_lignes_pmsi
					JOIN activite[PX].p_factures ON w_factures_lignes_pmsi.no_facture = p_factures.no_facture ;
					
					

					
					-- En cours PMSI public
					INSERT INTO activite[PX].p_factures(
						sejour_id,
						no_sejour, 
						no_facture, 
						no_facture_reference, 
						date_debut, 
						date_fin, 
						type_facture, 
						code_facture, 
						date_facture, 
						tiers_payant_0_id, 
						tiers_payant_1_id, 
						tiers_payant_2_id, 
						tiers_payant_22_id,
						ghs_id)
					SELECT 
						p_sejours.oid,
						p_sejours.no_sejour, 
						p_sejours.no_sejour || '.BG', 
						p_sejours.no_sejour || '.BG', 
						p_sejours.date_entree, 
						p_sejours.date_sortie, 
						'0', 
						'0', 
						'20991231'::date,
						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.ghs_id
					FROM pmsi.p_rss
					JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
					JOIN activite[PX].p_sejours on no_sejour_administratif = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
					LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND p_factures.no_facture LIKE '%BG'
					WHERE p_rss.en_cours = '1' AND p_factures.no_facture IS NULL
					GROUP BY 1,2,3,4,5,6,10,11,12;
					
					-- Sejours BG PMSi qui ne sont pas dans les RSS
					INSERT INTO activite[PX].p_factures(
						sejour_id,
						no_sejour, 
						no_facture, 
						no_facture_reference, 
						date_debut, 
						date_fin, 
						type_facture, 
						code_facture, 
						date_facture, 
						tiers_payant_0_id, 
						tiers_payant_1_id, 
						tiers_payant_2_id, 
						tiers_payant_22_id,
						ghs_id)
					SELECT p_sejours.oid,
						p_sejours.no_sejour, 
						p_sejours.no_sejour || '.BG', 
						p_sejours.no_sejour || '.BG', 
						p_sejours.date_entree, 
						p_sejours.date_sortie, 
						'0', 
						'0', 
						'20991231'::date,
						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.ghs_id
					FROM activite[PX].p_sejours
					JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
					JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
					WHERE p_sejours.est_budget_global = '1' AND
						type_t2a = '1' AND
						date_entree between now() - interval '1 year' AND  now() AND
						code_sorti = '1' AND
						no_sejour NOT IN (SELECt no_sejour FROm activite[PX].p_factures where no_facture like '%BG') AND
						no_sejour NOT IN (
							SELECT p_factures.no_sejour
							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
							WHERE p_sejours.est_budget_global = '1' AND
								code_facture = '1' AND
								t_prestations.code = 'PJ' AND
								(taux_2 = 100 OR taux_0 = 100) 
							GROUP BY 1
							HAVING SUM(montant_facture_0+montant_facture_2) > 0
						);
					
					
					
					-- Factures non assurés ajoutées à tord (on trouve un 100% dans patient ou tp1
					DROP TABLE IF EXISTS w_sejours_bg_24;
					CREATE TEMP TABLE w_sejours_bg_24 AS
					SELECT p_factures.no_sejour, SUM(montant_facture_0+montant_facture_1+montant_facture_2) AS montant_facture_100
					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
					JOIN activite[PX].p_sejour_pmsi ON p_sejour_pmsi.sejour_id = p_sejours.oid
					JOIN pmsi.p_rss ON p_sejour_pmsi.rss_id = p_rss.oid
					WHERE p_sejours.est_budget_global = '1' AND
						code_facture = '1' AND
						t_prestations.code = 'PJ' AND
						(taux_1 = 100 OR 
						taux_2 = 100 OR 
						taux_0 = 100 OR
						taux_0+taux_1+taux_2=0 AND montant_facture_1 = montant_facture
						) AND
						p_rss.traitement_epmsi NOT IN ('30','31','32','33')
					GROUP BY 1
					HAVING SUM(montant_facture_0+montant_facture_1+montant_facture_2) > 0
					ORDER BY 1;

					DELETE FROM activite[PX].p_factures_lignes_c
					USING activite[PX].p_factures
					WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
						p_factures.no_sejour IN (SELECT no_sejour FROM w_sejours_bg_24) AND
						p_factures_lignes_c.no_facture LIKE '%BG' AND
						origine_facturation_id = 1;

					UPDATE activite[PX].p_factures SET
						montant_facture_c = 0,
						montant_facture_1_c = 0,
						montant_comptabilise_1_c =0,
						montant_comptabilise_budget_global_c = 0
					WHERE no_sejour IN (SELECT no_sejour FROM w_sejours_bg_24) AND
						no_facture LIKE '%BG' AND
						montant_comptabilise_budget_global_c = 0;

					
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Budget global Actes">
			<condition><![CDATA[
				"[ENV_TYPEETS]" != "1"
			]]></condition>
			<sqlcmd><![CDATA[
	
							
					-- Valorisation actes	
					DROP TABLE IF EXISTS w_sejours_hospit_bg;
					CREATE TEMP TABLE w_sejours_hospit_bg AS	
					SELECT p_factures.no_sejour AS no_sejour_bg,
						MIN(CASE
							WHEN t_prestations.code IN ('GHS', 'PJ') THEN origine_facturation_id
							WHEN origine_facturation_id = 2 THEN origine_facturation_id
							WHEN type_sejour = '3' THEN 2
							ELSE 9 END) AS origine_facturation_id
					FROM activite[PX].p_sejours
					JOIN activite[PX].p_factures ON p_factures.no_sejour = p_sejours.no_sejour AND p_factures.code_facture = '1'
					LEFT JOIN activite[PX].p_factures_lignes_c ON p_factures_lignes_c.no_facture = p_factures.no_facture
					LEFT JOIN activite.t_prestations ON prestation_id = t_prestations.oid
					WHERE est_budget_global = '1' 
					GROUP BY 1;

					
					-- actes inclus	dans séjour	
					UPDATE activite[PX].p_factures_lignes_h
					SET 
						montant_facture_actes_inclus_dans_sejour = prix_unitaire * nb_prestation * coefficient,
						montant_facture_1_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient) * taux_1 / 100.00,
						montant_facture_2_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient) * taux_2 / 100.00,
						montant_facture_0_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient) * taux_0 / 100.00
					FROM activite[PX].p_factures 
					JOIN w_sejours_hospit_bg ON p_factures.no_sejour = w_sejours_hospit_bg.no_sejour_bg AND origine_facturation_id = 1
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND prix_unitaire <> 0 AND
						montant_facture_actes_inclus_dans_sejour = 0 AND
						(montant_facture_1 + montant_facture_2 + montant_facture_0) = 0 AND
						(taux_0 <> 0 OR taux_1 <> 0 OR taux_2 <> 0 OR taux_22 <> 0);
						
					UPDATE activite[PX].p_factures_lignes_h
					SET 
						montant_facture_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient),
						montant_facture_1_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient)
					FROM activite[PX].p_factures 
					JOIN w_sejours_hospit_bg ON p_factures.no_sejour = w_sejours_hospit_bg.no_sejour_bg AND origine_facturation_id = 1
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND prix_unitaire <> 0 AND
						montant_facture_actes_inclus_dans_sejour = 0 AND
						(montant_facture_1 + montant_facture_2 + montant_facture_0) = 0 AND
						taux_1 = 0 AND taux_2 = 0 AND taux_0 = 0;


					UPDATE activite[PX].p_factures_lignes_h
					SET 
						montant_facture_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient) * taux_1 / 100.00,
						montant_facture_1_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient) * taux_1 / 100.00
					FROM activite[PX].p_factures 
					JOIN w_sejours_hospit_bg ON p_factures.no_sejour = w_sejours_hospit_bg.no_sejour_bg AND origine_facturation_id = 1
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND prix_unitaire <> 0 AND
						montant_facture_actes_inclus_dans_sejour = 0 AND
						(montant_facture_2 + montant_facture_0) <> 0 AND montant_facture_1 = 0;
						
					
					--arrondis
					UPDATE activite[PX].p_factures_lignes_h
					SET montant_facture_1_actes_inclus_dans_sejour = 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)
					WHERE montant_facture_1_actes_inclus_dans_sejour <> 0 AND 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);
										
								
					
					-- actes externes
					UPDATE activite[PX].p_factures_lignes_h
					SET 
						montant_facture = prix_unitaire * nb_prestation * coefficient,
						montant_facture_1 = (prix_unitaire * nb_prestation * coefficient) * taux_1 / 100.00,
						montant_facture_2 = (prix_unitaire * nb_prestation * coefficient) * taux_2 / 100.00,
						montant_facture_0 = (prix_unitaire * nb_prestation * coefficient) * taux_0 / 100.00
					FROM activite[PX].p_factures 
					JOIN w_sejours_hospit_bg ON p_factures.no_sejour = w_sejours_hospit_bg.no_sejour_bg AND origine_facturation_id = 2
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND prix_unitaire <> 0 AND
						(montant_facture_1 + montant_facture_2 + montant_facture_0) = 0;

					UPDATE activite[PX].p_factures_lignes_h
					SET 
						montant_facture = prix_unitaire * nb_prestation * coefficient,
						montant_facture_1 = (prix_unitaire * nb_prestation * coefficient) * taux_1 / 100.00
					FROM activite[PX].p_factures 
					JOIN w_sejours_hospit_bg ON p_factures.no_sejour = w_sejours_hospit_bg.no_sejour_bg AND origine_facturation_id = 2
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND prix_unitaire <> 0  AND
						taux_1 <> 0 AND (montant_facture_2 + montant_facture_0) <> 0 AND montant_facture_1 = 0;


					-- Arrondis
					UPDATE activite[PX].p_factures_lignes_h
					SET montant_facture_1 = montant_facture - (montant_facture_0+montant_facture_1+montant_facture_2+montant_facture_22)
					FROM activite[PX].p_factures 
					JOIN w_sejours_hospit_bg ON p_factures.no_sejour = w_sejours_hospit_bg.no_sejour_bg AND origine_facturation_id = 2
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND 
						montant_facture_1 <> 0 AND 
						montant_facture <> (montant_facture_0+montant_facture_1+montant_facture_2+montant_facture_22);
						
						
					-- Ajout des honoraires budget global dans la partie CLINIQUE
					INSERT INTO activite[PX].p_factures_lignes_c(
						no_facture,
						date_debut,
						date_fin,
						nb_rubrique,
						coefficient,
						coefficient_mco,
						rubrique_facturation_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,
						nb_prestation,
						montant_comptabilise,
						montant_comptabilise_0,
						montant_comptabilise_1,
						montant_comptabilise_2,
						montant_comptabilise_22,
						rubrique_comptabilisation_id,
						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,
						protocole_id,
						compte_produit_id)
					SELECT 
						p_factures.no_facture,
						p_factures_lignes_h.date_debut,
						p_factures_lignes_h.date_fin,
						nb_rubrique,
						coefficient,
						coefficient_mco,
						COALESCE(t_rubriques_facturation.oid,0) AS rubrique_facturation_id,
						prestation_id,
						CASE WHEN montant_comptabilise_0 <> 0 THEN montant_facture_0 ELSE 0 END +
						CASE WHEN montant_comptabilise_1 <> 0 THEN montant_facture_1 ELSE 0 END +
						CASE WHEN montant_comptabilise_2 <> 0 THEN montant_facture_2 ELSE 0 END +
						CASE WHEN montant_comptabilise_22 <> 0 THEN montant_facture_22 ELSE 0 END AS montant_facture,
						CASE WHEN montant_comptabilise_0 <> 0 THEN montant_facture_0 ELSE 0 END AS montant_facture_0,
						CASE WHEN montant_comptabilise_1 <> 0 THEN montant_facture_1 ELSE 0 END AS montant_facture_1,
						CASE WHEN montant_comptabilise_2 <> 0 THEN montant_facture_2 ELSE 0 END AS montant_facture_2,
						CASE WHEN montant_comptabilise_22 <> 0 THEN montant_facture_22 ELSE 0 END AS montant_facture_22,
						taux_0,
						taux_1,
						taux_2,
						taux_22,
						prix_unitaire,
						lieu_id,
						CASE WHEN montant_comptabilise_1 <> 0 THEN nb_prestation ELSE 0 END,
						montant_comptabilise,
						montant_comptabilise_0,
						montant_comptabilise_1,
						montant_comptabilise_2,
						montant_comptabilise_22,
						COALESCE(t_rubriques_facturation.oid,0) AS rubrique_comptabilisation_id,
						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,
						2::bigint AS origine_facturation_id,
						0::numeric AS montant_comptabilise_budget_global_1,
						p_factures.oid AS facture_id,
						protocole_id,
						0::bigint AS compte_produit_id
					FROM activite[PX].p_factures_lignes_h
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid
					LEFT JOIN activite[PX].t_rubriques_facturation ON t_prestations.code = t_rubriques_facturation.code
					JOIN activite[PX].p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture 
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour AND est_budget_global = '1'
					WHERE p_factures.code_facture = '1' AND
						(montant_comptabilise <> 0 OR montant_comptabilise_0 <> 0 OR montant_comptabilise_1 <> 0 OR montant_comptabilise_2 <> 0) ;

				
					UPDATE activite[PX].p_factures_lignes_h
					SET montant_comptabilise = 0, montant_comptabilise_0 = 0, montant_comptabilise_1 = 0, montant_comptabilise_2 = 0
					FROM activite[PX].p_factures
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour AND est_budget_global = '1'
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND 
						(montant_comptabilise <> 0 OR montant_comptabilise_0 <> 0 OR montant_comptabilise_1 <> 0 OR montant_comptabilise_2 <> 0) ;
						
						
					-- Ajout des actes inclus dans séjour dans la partie clinique
					DROP TABLE IF EXISTS w_actes_inclus;
					CREATE TEMP TABLE w_actes_inclus AS
					SELECT 
						p_factures.no_sejour,
						p_factures.no_facture AS no_facture,
						p_factures_lignes_h.date_debut,
						p_factures_lignes_h.date_fin,
						nb_rubrique,
						coefficient,
						coefficient_mco,
						COALESCE(t_rubriques_facturation.oid,0) AS rubrique_facturation_id,
						prestation_id,
						0::numeric AS montant_facture,
						0::numeric AS montant_facture_0,
						0::numeric AS montant_facture_1,
						0::numeric AS montant_facture_2,
						0::numeric AS montant_facture_22,
						taux_0,
						taux_1,
						taux_2,
						taux_22,
						prix_unitaire,
						lieu_id,
						nb_prestation,
						0::numeric AS montant_comptabilise,
						0::numeric AS montant_comptabilise_0,
						0::numeric AS montant_comptabilise_1,
						0::numeric AS montant_comptabilise_2,
						0::numeric AS montant_comptabilise_22,
						COALESCE(t_rubriques_facturation.oid,0) AS rubrique_comptabilisation_id,
						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,
						3::bigint AS origine_facturation_id,
						0::numeric AS montant_comptabilise_budget_global_1,
						p_factures.oid AS facture_id,
						protocole_id,
						0::bigint AS compte_produit_id
					FROM activite[PX].p_factures_lignes_h
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid
					LEFT JOIN activite[PX].t_rubriques_facturation ON t_prestations.code = t_rubriques_facturation.code
					JOIN activite[PX].p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture 
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour AND est_budget_global = '1'
					WHERE 
						(montant_facture_actes_inclus_dans_sejour <> 0 OR 
						montant_facture_0_actes_inclus_dans_sejour <> 0 OR 
						montant_facture_1_actes_inclus_dans_sejour <> 0 OR 
						montant_facture_2_actes_inclus_dans_sejour <> 0) ;


					UPDATE w_actes_inclus
					SET no_facture = p_factures.no_facture, facture_id = p_factures.oid
					FROM activite[PX].p_factures 
					WHERE w_actes_inclus.no_sejour = p_factures.no_sejour AND
						p_factures.no_facture LIKE '%BG' ;


					INSERT INTO activite[PX].p_factures_lignes_c	
					(
						no_facture,
						date_debut,
						date_fin,
						nb_rubrique,
						coefficient,
						coefficient_mco,
						rubrique_facturation_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,
						nb_prestation,
						montant_comptabilise,
						montant_comptabilise_0,
						montant_comptabilise_1,
						montant_comptabilise_2,
						montant_comptabilise_22,
						rubrique_comptabilisation_id,
						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,
						protocole_id,
						compte_produit_id
					)	
					SELECT 
						no_facture,
						date_debut,
						date_fin,
						nb_rubrique,
						coefficient,
						coefficient_mco,
						rubrique_facturation_id,
						prestation_id,
						0::numeric AS montant_facture,
						0::numeric AS montant_facture_0,
						0::numeric AS montant_facture_1,
						0::numeric AS montant_facture_2,
						0::numeric AS montant_facture_22,
						taux_0,
						taux_1,
						taux_2,
						taux_22,
						prix_unitaire,
						lieu_id,
						nb_prestation,
						montant_comptabilise,
						montant_comptabilise_0,
						montant_comptabilise_1,
						montant_comptabilise_2,
						montant_comptabilise_22,
						rubrique_comptabilisation_id,
						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,
						protocole_id,
						compte_produit_id
					FROM w_actes_inclus;
					
					-- Correction n° facture
					UPDATE activite[PX].p_factures_lignes_c
						SET no_facture = p_factures.no_facture, facture_id = p_factures.oid
						FROM activite[PX].p_factures 
						WHERE p_factures_lignes_c.montant_facture_actes_inclus_dans_sejour <> 0 AND
							substr(p_factures_lignes_c.no_facture,1,7) = p_factures.no_sejour AND
							p_factures.no_facture LIKE '%BG' AND
							p_factures_lignes_c.no_facture NOT LIKE '%BG' AND
							p_factures_lignes_c.montant_facture = 0 AND
							p_factures_lignes_c.montant_comptabilise = 0;

					UPDATE activite[PX].p_factures_lignes_h
						SET no_facture = p_factures.no_facture, facture_id = p_factures.oid
						FROM activite[PX].p_factures 
						WHERE p_factures_lignes_h.montant_facture_actes_inclus_dans_sejour <> 0 AND
							substr(p_factures_lignes_h.no_facture,1,7) = p_factures.no_sejour AND
							p_factures.no_facture LIKE '%BG' AND
							p_factures_lignes_h.no_facture NOT LIKE '%BG' AND
							p_factures_lignes_h.montant_facture = 0 AND
							p_factures_lignes_h.montant_comptabilise = 0;
						
						
					-- Cumuls factures
					DROP TABLE IF EXISTS w_factures_corrigees;
					CREATE TEMP TABLE w_factures_corrigees AS 
					SELECT
						p_factures_lignes_c.no_facture,
						
						COALESCE(SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture ELSE 0 END),0) AS ligne_facture_c,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_0 ELSE 0 END),0) AS ligne_facture_0_c,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_1 ELSE 0 END),0) AS ligne_facture_1_c,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_2 ELSE 0 END),0) AS ligne_facture_2_c,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_22 ELSE 0 END),0) AS ligne_facture_22_c,
						COALESCE(SUM(montant_comptabilise),0) AS ligne_comptabilise_c,
						COALESCE(SUM(montant_comptabilise_0),0) AS ligne_comptabilise_0_c,
						COALESCE(SUM(montant_comptabilise_1),0) AS ligne_comptabilise_1_c,
						COALESCE(SUM(montant_comptabilise_2),0) AS ligne_comptabilise_2_c,
						COALESCE(SUM(montant_comptabilise_22),0) AS ligne_comptabilise_22_c,
						
						COALESCE(SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture ELSE 0 END),0) AS ligne_facture_h,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_0 ELSE 0 END),0) AS ligne_facture_0_h,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_1 ELSE 0 END),0) AS ligne_facture_1_h,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_2 ELSE 0 END),0) AS ligne_facture_2_h,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_22 ELSE 0 END),0) AS ligne_facture_22_h,
						0::numeric AS ligne_comptabilise_h,
						0::numeric AS ligne_comptabilise_0_h,
						0::numeric AS ligne_comptabilise_1_h,
						0::numeric AS ligne_comptabilise_2_h,
						0::numeric AS ligne_comptabilise_22_h
					FROM activite[PX].p_factures
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour AND est_budget_global = '1'
					LEFT JOIN activite[PX].p_factures_lignes_c ON p_factures_lignes_c.no_facture = p_factures.no_facture 
					GROUP BY 1
					HAVING SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_c) OR
						SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_0 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_0_c) OR
						SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_1 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_1_c) OR
						SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_2 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_2_c) OR
						SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_22 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_22_c) OR
						SUM(montant_comptabilise) IS DISTINCT FROM MAX(p_factures.montant_comptabilise_c) OR
						SUM(montant_comptabilise_0) IS DISTINCT FROM MAX(p_factures.montant_comptabilise_0_c) OR
						SUM(montant_comptabilise_1) IS DISTINCT FROM MAX(p_factures.montant_comptabilise_1_c) OR
						SUM(montant_comptabilise_2) IS DISTINCT FROM MAX(p_factures.montant_comptabilise_2_c) OR
						SUM(montant_comptabilise_22) IS DISTINCT FROM MAX(p_factures.montant_comptabilise_22_c) OR

						SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_h) OR
						SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_0 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_0_h) OR
						SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_1 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_1_h) OR
						SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_2 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_2_h) OR 
						SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_22 ELSE 0 END) IS DISTINCT FROM  MAX(p_factures.montant_facture_22_h) OR
						0::numeric IS DISTINCT FROM MAX(p_factures.montant_comptabilise_h) OR
						0::numeric IS DISTINCT FROM MAX(p_factures.montant_comptabilise_0_h) OR
						0::numeric IS DISTINCT FROM MAX(p_factures.montant_comptabilise_1_h) OR
						0::numeric IS DISTINCT FROM MAX(p_factures.montant_comptabilise_2_h) OR
						0::numeric IS DISTINCT FROM MAX(p_factures.montant_comptabilise_22_h) ;

					UPDATE activite[PX].p_factures
					SET 
						montant_facture_c = w_factures_corrigees.ligne_facture_c,
						montant_facture_0_c = w_factures_corrigees.ligne_facture_0_c,
						montant_facture_1_c = w_factures_corrigees.ligne_facture_1_c,
						montant_facture_2_c = w_factures_corrigees.ligne_facture_2_c,
						montant_facture_22_c = w_factures_corrigees.ligne_facture_22_c,
						montant_comptabilise_c = w_factures_corrigees.ligne_comptabilise_c,
						montant_comptabilise_0_c = w_factures_corrigees.ligne_comptabilise_0_c,
						montant_comptabilise_1_c = w_factures_corrigees.ligne_comptabilise_1_c,
						montant_comptabilise_2_c = w_factures_corrigees.ligne_comptabilise_2_c,
						montant_comptabilise_22_c = w_factures_corrigees.ligne_comptabilise_22_c,
						montant_facture_h = w_factures_corrigees.ligne_facture_h,
						montant_facture_0_h = w_factures_corrigees.ligne_facture_0_h,
						montant_facture_1_h = w_factures_corrigees.ligne_facture_1_h,
						montant_facture_2_h = w_factures_corrigees.ligne_facture_2_h,
						montant_facture_22_h = w_factures_corrigees.ligne_facture_22_h,
						montant_comptabilise_h = w_factures_corrigees.ligne_comptabilise_h,
						montant_comptabilise_0_h = w_factures_corrigees.ligne_comptabilise_0_h,
						montant_comptabilise_1_h = w_factures_corrigees.ligne_comptabilise_1_h,
						montant_comptabilise_2_h = w_factures_corrigees.ligne_comptabilise_2_h,
						montant_comptabilise_22_h = w_factures_corrigees.ligne_comptabilise_22_h
					FROM w_factures_corrigees
					WHERE w_factures_corrigees.no_facture = p_factures.no_facture;
					
					
					-- Report des actes non facturés honoraires budget global pour encours
					INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
						facture_id,
						no_facture, 
						date_debut, 
						date_fin, 
						nb_rubrique, 
						coefficient, 
						rubrique_facturation_id, 
						prestation_id, 
						prix_unitaire, 
						lieu_id)
					SELECT 
						p_factures.oid AS facture_id,
						p_factures.no_facture AS no_facture,
						p_factures_lignes_h.date_debut,
						p_factures_lignes_h.date_fin,
						p_factures_lignes_h.nb_rubrique,
						p_factures_lignes_h.coefficient,
						p_factures_lignes_h.rubrique_facturation_id,
						p_factures_lignes_h.prestation_id,
						p_factures_lignes_h.prix_unitaire,
						p_factures_lignes_h.lieu_id
					FROM activite[PX].p_factures_lignes_h
					JOIN activite[PX].p_factures on p_factures_lignes_h.no_facture = p_factures.no_facture
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
					WHERE p_factures.code_facture = '0' AND 
						p_sejours.est_budget_global = '1' AND
						p_sejours.type_sejour = '3' AND
						p_factures.no_sejour NOT IN (SELECT no_sejour FROM activite[PX].p_factures WHERE code_facture = '1') AND
						p_factures_lignes_h.no_facture NOT IN (SELECT no_facture FROM activite[PX].p_factures_lignes_non_facturees_c)
						;
						
					
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Factures de référence">
			<sqlcmd><![CDATA[
				-- Facture de référence
				
				DROP TABLE IF EXISTS w_factures_reference;
				CREATE TEMP TABLE w_factures_reference AS
				SELECT
					p_factures.no_sejour,
					CASE WHEN avec_facturation_intermediaire = '1' THEN date_debut ELSE '00010101' END AS date_debut_reference,
					MAX(CASE WHEN avec_facturation_intermediaire = '1' THEN date_fin ELSE '20991231' END) AS date_fin_reference,
					(MAX(Array[
						CASE WHEN type_facture NOT IN ('1','X') THEN '9' ELSE '0' END || 
						CASE WHEN no_facture LIKE '%BG' THEN '9' ELSE '0' END || 
						CASE WHEN p_factures.montant_facture_1_c + p_factures.montant_facture_1_h <> 0 OR p_factures.montant_facture_c + p_factures.montant_facture_h = 0 THEN '9' ELSE '0' END || 
						p_factures.date_facture::text,no_facture
					]))[2] AS no_facture_reference
				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 lieu_sortie_id = t_lieux.oid
				JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
				GROUP BY 1,2
				ORDER BY 1,2;

				CREATE INDEX w_factures_reference_i1
						  ON w_factures_reference
						  USING btree
						  (no_sejour);

				CREATE INDEX w_factures_reference_i2
						  ON w_factures_reference
						  USING btree
						  (no_facture_reference);


				UPDATE activite[PX].p_factures SET
					no_facture_reference = w_factures_reference.no_facture_reference,
					facture_reference_id = p_factures_reference.oid
				FROM w_factures_reference
				JOIN activite[PX].p_factures p_factures_reference ON p_factures_reference.no_facture = w_factures_reference.no_facture_reference
				WHERE w_factures_reference.no_sejour = p_factures.no_sejour AND
					p_factures.date_debut BETWEEN date_debut_reference AND date_fin_reference AND
					(
						p_factures.no_facture_reference IS DISTINCT FROM w_factures_reference.no_facture_reference OR
						p_factures.facture_reference_id IS DISTINCT FROM p_factures_reference.oid
					);

				UPDATE activite[PX].p_factures SET
					facture_reference_id = p_factures_references.oid
				FROM activite[PX].p_factures p_factures_references
				WHERE p_factures.no_facture_reference = p_factures_references.no_facture AND
					p_factures.facture_reference_id IS DISTINCT FROM p_factures_references.oid
				;
			]]></sqlcmd>
		</NODE>

		
	</NODE>
	
	<NODE name="CHIFFRIER" label="CREATION DU CHIFFRIER">
		
		<NODE label="Récupération chiffrier SIGEMS">
			<sqlcmd><![CDATA[
				
				DROP TABLE IF EXISTS w_ECRIT_une;
				CREATE TEMP TABLE w_ECRIT_une AS
				SELECT 
					CASE WHEN count(*) > 0 THEN '1' ELSE '0' END AS une_ecriture
				FROM prod_sigems2.ECRIT;
				
				DROP TABLE IF EXISTS w_JNAL;
				CREATE TEMP TABLE w_JNAL AS
				SELECT *
				FROM prod_sigems2.JNAL
				WHERE JNAL.TYP IN ('A') OR JNAL.CODEJ = 'VENT';

				CREATE INDEX w_JNAL_i1
					  ON w_JNAL
					  USING btree
					  (CODEJ);
				
				DROP TABLE IF EXISTS w_ECRIT_comptes_clients;
				CREATE TEMP TABLE w_ECRIT_comptes_clients AS
				SELECT 
					NUM AS ECR_CPTE
				FROM prod_sigems2.COMPTE
				WHERE 
					TYP = 'C' AND
					NUM NOT IN (SELECT COD_PRA FROM prod_sigems2.praticien) AND 
					NUM NOT IN (SELECT CO2_PRA FROM prod_sigems2.praticien)
				GROUP BY 1;

				CREATE INDEX w_ECRIT_comptes_clients_i1
					  ON w_ECRIT_comptes_clients
					  USING btree
					  (ECR_CPTE);

				
				DROP TABLE IF EXISTS w_factures_comptables;
				
				CREATE TEMP TABLE w_factures_comptables AS
				SELECT 
					0 AS facture_id,
					CASE WHEN SERI IS NOT NULL THEN ANNEE || to_char(DOS_ECRIT.CODE,'FM900000') || '.' || to_char(INDICE,'FM9999900') ELSE NULL END AS no_facture,
					date_trunc('month', ECR_DATE) + interval '1 month' - interval '1 day' AS date_comptable,
					SUM(CASE WHEN ECR_JNAL = 'VENT' THEN ECR_DEBIT - ECR_CREDIT ELSE 0 END) AS montant_ventes_c, 
					SUM(CASE WHEN t_divers.valeur IS DISTINCT FROM '1' AND ECR_JNAL <> 'VENT' THEN ECR_CREDIT - ECR_DEBIT  ELSE 0 END) AS montant_reglements_c, 
					0::numeric AS montant_ventes_h, 
					0::numeric AS montant_reglements_h
				FROM prod_sigems2.ECRIT
					JOIN w_JNAL ON ECR_JNAL = w_JNAL.CODEJ 
					JOIN w_ECRIT_comptes_clients ON ECRIT.ECR_CPTE = w_ECRIT_comptes_clients.ECR_CPTE
					LEFT JOIN prod_sigems2.DOS_ECRIT ON SERI = ECR_NUM
					LEFT JOIN activite.t_divers ON t_divers.code = 'CHIFERRREG'
				WHERE 
					ECR_PLAN <> 'G' AND
					ECR_PLAN <> 'H' AND
					ECR_ANNUL <> 'S' AND
					ECR_DATE >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					ECRIT.ECR_CPTE <> 'NOEMIE' AND 
					ECRIT.ECR_CPTE <> 'ANCIEN' AND 
					ECRIT.ECR_CPTE <> 'ACOMPT' AND
					ECRIT.ECR_CPTE NOT LIKE 'ECART%' AND
					ECRIT.ECR_CPTE NOT LIKE 'ACPT%' AND
					ECRIT.ECR_CPTE <> '411FTN'    
				GROUP BY 1,2,3;
				-- parametrer liste CPTE a exclure
				
				INSERT INTO w_factures_comptables
				SELECT 
					0::bigint AS facture_id,
					ANN_DOS2 || to_char(COD_DOS2,'FM900000') || '.' || to_char(IND_DOS2,'FM9999900') AS no_facture,
					date_trunc('month',DFA_DOS2) + interval '1 month' - interval '1 day' AS date_comptable,
					SUM(SJ1_DOS2 + SJ2_DOS2 + SJ3_DOS2) AS montant_ventes_c, 
					0::numeric AS montant_reglements_c, 
					0::numeric AS montant_ventes_h, 
					0::numeric AS montant_reglements_h
				FROM prod_sigems2.DOS2
				JOIN w_ecrit_une ON une_ecriture = '0'
				LEFT JOIN activite[PX].p_sejours ON ANN_DOS2 || to_char(COD_DOS2,'FM900000') = p_sejours.no_sejour
				WHERE DFA_DOS2 IS NOT NULL AND ETA_DOS2 >= 3 AND DFA_DOS2 >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1,2,3;

				INSERT INTO w_factures_comptables
				SELECT 
					0::bigint AS facture_id,
					ANN_DOS2 || to_char(COD_DOS2,'FM900000') || '.' || to_char(IND_DOS2,'FM9999900') AS no_facture,
					date_trunc('month',DFA_DOS2) + interval '1 month' - interval '1 day' AS date_comptable,
					SUM(CASE WHEN est_budget_global = '1' THEN HO1_DOS2 + HO2_DOS2 + HO3_DOS2 ELSE 0 END) AS montant_ventes_c, 
					0::numeric AS montant_reglements_c, 
					SUM(CASE WHEN est_budget_global IS DISTINCT FROM '1' THEN HO1_DOS2 + HO2_DOS2 + HO3_DOS2 ELSE 0 END) AS montant_ventes_h, 
					0::numeric AS montant_reglements_h
				FROM prod_sigems2.DOS2
				LEFT JOIN activite[PX].p_sejours ON ANN_DOS2 || to_char(COD_DOS2,'FM900000') = p_sejours.no_sejour
				WHERE DFA_DOS2 IS NOT NULL AND ETA_DOS2 >= 3 AND DFA_DOS2 >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1,2,3;

				INSERT INTO w_factures_comptables
				SELECT
					0::bigint AS facture_id,
					ANN_LCL || to_char(COD_LCL ,'FM900000') || '.' || to_char(IND_LCL ,'FM9999900') AS no_facture,
					date_trunc('month', DAT_REG) + interval '1 month' - interval '1 day' AS date_comptable,
					0::numeric AS montant_ventes_c, 
					SUM(MONT) AS montant_reglements_c, 
					0::numeric AS montant_ventes_h, 
					0::numeric AS montant_reglements_h
				FROM w_REG4
					JOIN prod_sigems2.LIG_CLINI ON NUM_LCL = NUM_CLI
					JOIN prod_sigems2.DOS2 ON ANN_LCL = ANN_DOS2 AND COD_LCL = COD_DOS2 AND IND_LCL = IND_DOS2 AND ETA_DOS2 >= 2
					JOIN activite.t_divers ON t_divers.code = 'CHIFERRREG' AND t_divers.code = 'CHIFERRREG' AND t_divers.valeur = '1'
					LEFT JOIN activite[PX].p_sejours ON ANN_DOS2 || to_char(COD_DOS2,'FM900000') = p_sejours.no_sejour
				WHERE DAT_REG >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1,2,3;



				INSERT INTO w_factures_comptables
				SELECT
					0::bigint AS facture_id,
					ANN_LHO || to_char(COD_LHO ,'FM900000') || '.' || to_char(IND_LHO ,'FM9999900') AS no_facture,
					date_trunc('month', DAT_REG) + interval '1 month' - interval '1 day' AS date_comptable,
					0::numeric AS montant_ventes_c, 
					SUM(CASE WHEN est_budget_global = '1' THEN MON_REG3 ELSE 0 END) AS montant_reglements_c, 
					0::numeric AS montant_ventes_h, 
					SUM(CASE WHEN est_budget_global IS DISTINCT FROM '1' THEN MON_REG3 ELSE 0 END) AS montant_reglements_h
				FROM w_REG3
					JOIN prod_sigems2.LIG_HONOR ON NUM_LHO = LHO_REG3
					JOIN prod_sigems2.DOS2 ON ANN_LHO = ANN_DOS2 AND COD_LHO = COD_DOS2 AND IND_LHO = IND_DOS2 AND ETA_DOS2 >= 2
					LEFT JOIN activite[PX].p_sejours ON ANN_DOS2 || to_char(COD_DOS2,'FM900000') = p_sejours.no_sejour
				WHERE DAT_REG >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1,2,3;

				
				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), 
					SUM(montant_reglements_c), 
					0 AS montant_solde_client_c,
					SUM(montant_ventes_h), 
					SUM(montant_reglements_h),
					0 AS montant_solde_client_h
				FROM w_factures_comptables
				WHERE date_comptable >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1;
				
				TRUNCATE activite[PX].p_factures_comptables;

				INSERT INTO activite[PX].p_factures_comptables(
					facture_id,
					no_facture,
					date_comptable, 
					montant_ventes_c, 
					montant_reglements_c, 
					montant_ventes_h, 
					montant_reglements_h)

				SELECT 
					facture_id,
					no_facture,
					date_comptable, 
					SUM(montant_ventes_c), 
					SUM(montant_reglements_c), 
					SUM(montant_ventes_h), 
					SUM(montant_reglements_h)
				FROM w_factures_comptables
				WHERE no_facture IS NOT NULL AND
					date_comptable >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1,2,3;

				
										
			]]></sqlcmd>
		</NODE>
		
	</NODE>
	
	<NODE name="PARAM" label="RECUPERATION DES PARAMETRES">
	
		<NODE label="Type d'environnement">
			<sqlcmd><![CDATA[
				CTISELECT_PROPERTY_READ 'ENV_WITHPMSI', MAX(CASE WHEN schemaname = 'pmsi' AND tablename = 'p_rss' THEN 1 ELSE 0 END) 
				FROM pg_tables 
				WHERE schemaname = 'pmsi' AND tablename = 'p_rss'
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Adaptations base SIGEMS (Multi Sites)">
			<condition><![CDATA[
				"[ENV_TYPEETS]" != "1"
			]]></condition>
			<sqlcmd><![CDATA[
				
				DROP TABLE IF EXISTS w_services_type_exception;
				CREATE TEMP TABLE w_services_type_exception AS
				SELECT SER_DOS AS SER, (MIN(Array[to_char(nb,'FM000000000'),CH1]))[2] AS CH1_exeption
				FROM
					(
					SELECT
						SER_DOS, CH1, count(*) AS nb
					FROM prod_sigems2.DOSSIER
					JOIN prod_sigems2.DOSSIER_Y ON DOSSIER.COD_DOS = DOSSIER_Y.CODE AND
						DOSSIER.ANN_DOS = DOSSIER_Y.ANNEE
					WHERE ANN_DOS <> 'PA' AND CH1 <> ''
					GROUP BY 1,2
					ORDER BY 1,2
					) subview
				GROUP BY 1
				HAVING count(*) > 1;

				CREATE INDEX w_services_type_exception_i1
					ON w_services_type_exception
					USING btree
					(SER);
				
				INSERT INTO w_services_type_exception 
				SELECT SER_SEJ AS SER, (MIN(Array[to_char(nb,'FM000000000'),CH1]))[2] AS CH1_exeption
				FROM
					(
					SELECT
						SER_SEJ, CH1, count(*) AS nb
					FROM prod_sigems2.SEJOUR
					JOIN prod_sigems2.DOSSIER_Y ON SEJOUR.COD_SEJ = DOSSIER_Y.CODE AND
						SEJOUR.ANN_SEJ  = DOSSIER_Y.ANNEE
					LEFT JOIN w_services_type_exception ON SER_SEJ = SER
					WHERE ANN_SEJ <> 'PA' AND CH1 <> '' AND w_services_type_exception.SER IS NULL
					GROUP BY 1,2
					ORDER BY 1,2
					) subview
				GROUP BY 1
				HAVING count(*) > 1;

				DROP TABLE IF EXISTS w_DOSSIER_CH1;
				CREATE TEMP TABLE w_DOSSIER_CH1 AS 
				SELECT
					ANN_DOS AS ANN_CH1, COD_DOS AS COD_CH1, SER_DOS AS SER_CH1, trim(SER_DOS) || (CASE WHEN CH1 = 'PSPH' THEN 'E' ELSE 'O' END) AS SER_CH1_NEW
				FROM prod_sigems2.DOSSIER
				JOIN prod_sigems2.DOSSIER_Y ON DOSSIER.COD_DOS = DOSSIER_Y.CODE AND
					DOSSIER.ANN_DOS = DOSSIER_Y.ANNEE
				JOIN w_services_type_exception ON SER_DOS = SER
				WHERE ANN_DOS <> 'PA' AND CH1 = CH1_exeption
				GROUP BY 1,2,3,4
				ORDER BY 1,2,3;

				CREATE INDEX w_DOSSIER_CH1_i1
					ON w_DOSSIER_CH1
					USING btree
					(COD_CH1);	

				INSERT INTO w_DOSSIER_CH1 
				SELECT
					ANN_SEJ AS ANN_CH1, COD_SEJ AS COD_CH1, SER_SEJ AS SER_CH1, trim(SER_SEJ) || (CASE WHEN CH1 = 'PSPH' THEN 'E' ELSE 'O' END) AS SER_CH1_NEW
				FROM prod_sigems2.SEJOUR
				JOIN prod_sigems2.DOSSIER_Y ON SEJOUR.COD_SEJ = DOSSIER_Y.CODE AND
					SEJOUR.ANN_SEJ = DOSSIER_Y.ANNEE
				JOIN w_services_type_exception ON SER_SEJ = SER
				LEFT JOIN w_DOSSIER_CH1 ON SEJOUR.COD_SEJ = w_DOSSIER_CH1.COD_CH1 AND
					SEJOUR.ANN_SEJ = w_DOSSIER_CH1.ANN_CH1 AND
					SEJOUR.SER_SEJ = w_DOSSIER_CH1.SER_CH1
				WHERE ANN_SEJ <> 'PA' AND CH1 = CH1_exeption AND
					w_DOSSIER_CH1.SER_CH1 IS NULL
				GROUP BY 1,2,3,4
				ORDER BY 1,2,3;

				ALTER TABLE prod_sigems2.DOSSIER ALTER COLUMN SER_DOS TYPE text;

				UPDATE prod_sigems2.DOSSIER
				SET SER_DOS = SER_CH1_NEW
				FROM w_DOSSIER_CH1
				WHERE ANN_CH1 = ANN_DOS AND
					COD_CH1 = COD_DOS AND
					SER_CH1 = SER_DOS;

				ALTER TABLE prod_sigems2.SEJOUR ALTER COLUMN SER_SEJ TYPE text;

				UPDATE prod_sigems2.SEJOUR
				SET SER_SEJ = SER_CH1_NEW
				FROM w_DOSSIER_CH1
				WHERE ANN_CH1 = ANN_SEJ AND
					COD_CH1 = COD_SEJ AND
					SER_CH1 = SER_SEJ;

				ALTER TABLE prod_sigems2.LIG_CLINI ALTER COLUMN SER_LCL TYPE text;

				UPDATE prod_sigems2.LIG_CLINI
				SET SER_LCL = SER_CH1_NEW
				FROM w_DOSSIER_CH1
				WHERE ANN_CH1 = ANN_LCL AND
					COD_CH1 = COD_LCL AND
					SER_CH1 = SER_LCL;

				ALTER TABLE prod_sigems2.LIG_HONOR ALTER COLUMN SER_LHO TYPE text;

				UPDATE prod_sigems2.LIG_HONOR
				SET SER_LHO = SER_CH1_NEW
				FROM w_DOSSIER_CH1
				WHERE ANN_CH1 = ANN_LHO AND
					COD_CH1 = COD_LHO AND
					SER_CH1 = SER_LHO;

				ALTER TABLE prod_sigems2.SERVICE 
					ALTER COLUMN COD_SER TYPE text,
					ALTER COLUMN NOM_SER TYPE text;

				INSERT INTO prod_sigems2.SERVICE (COD_SER, NOM_SER, DMT_SER)
				SELECT trim(COD_SER) || (CASE WHEN CH1_exeption = 'PSPH' THEN 'E' ELSE 'O' END),
					replace(replace(replace(NOM_SER,'ESPIC',''),'OQN',''),'  ',' ') || (CASE WHEN CH1_exeption = 'PSPH' THEN ' ESPIC' ELSE ' OQN' END),
					DMT_SER
				FROM prod_sigems2.SERVICE
				JOIN w_services_type_exception ON COD_SER = SER
				WHERE (trim(COD_SER) || (CASE WHEN CH1_exeption = 'PSPH' THEN 'E' ELSE 'O' END)) NOT IN 
					(SELECT COD_SER FROM prod_sigems2.SERVICE);

				ALTER TABLE prod_sigems2.ANALYG ALTER COLUMN SER_ANA TYPE text;
				
				INSERT INTO prod_sigems2.ANALYG(PRD_ANA, SER_ANA, DMT_ANA, MDT_ANA, RIS_ANA, ISO_ANA, TAU_ANA, CPT_ANA)
				SELECT ANALYG.PRD_ANA, COD_SER, ANALYG.DMT_ANA, ANALYG.MDT_ANA, ANALYG.RIS_ANA, ANALYG.ISO_ANA, ANALYG.TAU_ANA, ANALYG.CPT_ANA
				FROM prod_sigems2.ANALYG
				JOIN prod_sigems2.SERVICE ON SER_ANA = substr(COD_SER,1,4) AND
					substr(COD_SER,5,1) IN ('E', 'O')
				LEFT JOIN prod_sigems2.ANALYG ANALYG_deja ON
					ANALYG.PRD_ANA = ANALYG_deja.PRD_ANA AND
					COD_SER = ANALYG_deja.SER_ANA AND
					ANALYG.DMT_ANA = ANALYG_deja.DMT_ANA AND
					ANALYG.MDT_ANA = ANALYG_deja.MDT_ANA AND
					ANALYG.RIS_ANA = ANALYG_deja.RIS_ANA AND
					ANALYG.ISO_ANA = ANALYG_deja.ISO_ANA AND
					ANALYG.TAU_ANA = ANALYG_deja.TAU_ANA AND
					ANALYG.CPT_ANA = ANALYG_deja.CPT_ANA
				WHERE ANALYG_deja.PRD_ANA 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 activite[PX].t_tiers_payant(oid, code, code_original, type_tiers_payant, texte, texte_court) 
				SELECT 0, '', '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 'PATIENT', 'PATIENT', '0', 'PATIENTS', 'PATIENTS'
				WHERE 'PATIENT' NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant WHERE code_original IS NOT NULL);

				INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
				SELECT COD_TPA, COD_TPA, 
					MAX(CASE WHEN length(COD_TPA) = 8 AND substr(COD_TPA,1,2) BETWEEN '01' AND '99' THEN '1' ELSE '2' END), 
					MAX(NOM_TPA), MAX(NOM_TPA)
				FROM prod_sigems2.TIERS_PAYANT
				WHERE COD_TPA NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant WHERE code_original IS NOT NULL)
				GROUP BY 1,2;
								
				
				UPDATE activite[PX].t_tiers_payant
				SET grand_regime_id = t_grands_regimes.oid
				FROM base.t_grands_regimes
				WHERE t_grands_regimes.code = substr(t_tiers_payant.code,1,2) AND
					t_tiers_payant.code between '01' AND '999' AND
					(grand_regime_id = 0 OR grand_regime_id IS NULL);
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Médecins">
			<sqlcmd><![CDATA[

				INSERT INTO base.t_specialites_medecin(code_original, code, texte, texte_court)
				SELECT 
					CSP_PRA, 
					CSP_PRA, 
					COALESCE(LIB_SPE, CSP_PRA), 
					COALESCE(LIB_SPE, CSP_PRA) 
				FROM 
					prod_sigems2.PRATICIEN
					LEFT JOIN prod_sigems2.SPECIALITE ON CSP_PRA = COD_SPE
					LEFT JOIN base.t_specialites_medecin spe on spe.code_original::text = CSP_PRA::text
				WHERE 1=1
					AND spe.code_original IS NULL
					AND CSP_PRA IS NOT NULL 
					AND CSP_PRA::text <> ''::text
				GROUP BY 1,2,3,4
				ORDER BY 1;

				INSERT INTO activite[PX].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[PX].t_specialites_medecin);
				
				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);


				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_medecins;
				CREATE TEMP TABLE w_medecins AS
				SELECT 
					COD_PRA AS COD_PRA,
					base.cti_soundex_nom(NOM_PRA) AS NOM_PRA_SOUNDEX, 
					base.cti_soundex_nom(PRE_PRA) AS PRE_PRA_SOUNDEX, 
					NOM_PRA, 
					PRE_PRA AS PRE_PRA, 
					SUBSTR(COALESCE(NID_PRA,''),1,9) AS NID_PRA, 
					CSP_PRA AS CSP_PRA, 
					COALESCE(t_medecins_administratifs.medecin_id,0) as medecin_id
				FROM prod_sigems2.PRATICIEN
					LEFT JOIN activite[PX].t_medecins_administratifs ON COD_PRA = t_medecins_administratifs.code_original;




				INSERT INTO base.t_medecins(nom, prenom, numero_ordre, specialite_id)
				SELECT w_medecins.NOM_PRA, w_medecins.PRE_PRA, w_medecins.NID_PRA, 0 FROM
				(SELECT SUBSTR(NOM_PRA_SOUNDEX, 1, 8) AS NOM_PRA_SOUNDEX, SUBSTR(PRE_PRA_SOUNDEX, 1, 8) AS PRE_PRA_SOUNDEX, NID_PRA, MIN(COD_PRA) AS COD_PRA
				FROM w_medecins
				GROUP BY 1,2,3) subview, w_medecins
				WHERE w_medecins.COD_PRA = subview.COD_PRA
					AND subview.NOM_PRA_SOUNDEX || ',' || subview.PRE_PRA_SOUNDEX || ',' ||  subview.NID_PRA 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, numero_ordre, specialite_id)
				SELECT w_medecins.NOM_PRA, w_medecins.PRE_PRA, w_medecins.NID_PRA, 0 FROM
				(SELECT NOM_PRA_SOUNDEX, PRE_PRA_SOUNDEX, MIN(COD_PRA) AS COD_PRA
				FROM w_medecins
				GROUP BY 1,2) subview, w_medecins
				WHERE w_medecins.COD_PRA = subview.COD_PRA
					AND subview.NOM_PRA_SOUNDEX || ',' || subview.PRE_PRA_SOUNDEX NOT IN 
					(SELECT base.cti_soundex_nom(nom)  || ',' || base.cti_soundex_nom(prenom) 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(NOM_PRA_SOUNDEX, 1, 8) = subview.nom
				AND SUBSTR(PRE_PRA_SOUNDEX, 1, 8) = subview.prenom
				AND NID_PRA = 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(NOM_PRA_SOUNDEX, 1, 8) = subview.nom
				AND SUBSTR(PRE_PRA_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 COD_PRA, COD_PRA, NOM_PRA, PRE_PRA, COALESCE(t_specialites_medecin.oid,0), medecin_id
				FROM w_medecins
					LEFT JOIN base.t_specialites_medecin ON CSP_PRA = t_specialites_medecin.code_original
				WHERE COD_PRA NOT IN (SELECT code_original FROM activite[PX].t_medecins_administratifs);

				UPDATE activite[PX].t_medecins_administratifs
				SET nom = NOM_PRA,
					prenom = PRE_PRA,
					specialite_id = COALESCE(t_specialites_medecin.oid,0),
					medecin_id = w_medecins.medecin_id
				FROM w_medecins LEFT JOIN base.t_specialites_medecin ON CSP_PRA = t_specialites_medecin.code_original
				WHERE w_medecins.COD_PRA = t_medecins_administratifs.code_original
					AND (
					t_medecins_administratifs.nom <> NOM_PRA OR
					t_medecins_administratifs.prenom <> PRE_PRA OR
					t_medecins_administratifs.specialite_id <> COALESCE(t_specialites_medecin.oid,0) OR
					t_medecins_administratifs.medecin_id <> w_medecins.medecin_id
				);

				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;

										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Hébergement">
			<sqlcmd><![CDATA[
				
				-- 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);

				DROP TABLE IF EXISTS w_SERVICE;
				CREATE TEMP TABLE w_SERVICE AS
				SELECT
					COD_SER || '_' || COALESCE(MDT_REEL,MDT_DOS) AS COD_SER,
					NOM_SER || ' (' || COALESCE(MDT_REEL,MDT_DOS) || ')' AS NOM_SER,
					COALESCE(MDT_REEL,MDT_DOS) AS MDT_SER,
					DMT_SER
				FROM prod_sigems2.DOSSIER
					JOIN prod_sigems2.SERVICE ON SER_DOS = COD_SER
					LEFT JOIN prod_sigems2.DOSSIER_MDT ON DOSSIER.ANN_DOS = DOSSIER_MDT.ANN_DOS AND DOSSIER.COD_DOS = DOSSIER_MDT.COD_DOS
				GROUP BY 1,2,3,4;
				
				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits, type_t2a)
				SELECT COD_SER, COD_SER, NOM_SER, NOM_SER, 0 AS nb_lits, '0' AS type_t2a
				FROM w_SERVICE
				WHERE COD_SER NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
				ORDER BY COD_SER;
				
				UPDATE activite[PX].t_services_facturation SET
					texte = NOM_SER,
					texte_court = CASE WHEN texte_court = texte THEN NOM_SER ELSE texte_court END
				FROM w_SERVICE
				WHERE COD_SER = code_original AND
					(
						texte IS DISTINCT FROM NOM_SER OR
						texte_court IS DISTINCT FROM CASE WHEN texte_court = texte THEN NOM_SER ELSE texte_court END
					);
				
				UPDATE activite[PX].t_services_facturation
				SET mode_traitement_id = COALESCE(t_modes_traitement.oid,0)
				FROM w_SERVICE
					LEFT JOIN base.t_modes_traitement ON MDT_SER = t_modes_traitement.code
				WHERE t_services_facturation.code_original = COD_SER AND 
					COALESCE(mode_traitement_id,0) = 0 AND
					COALESCE(mode_traitement_id,0) <> COALESCE(t_modes_traitement.oid,0);
				
				DROP TABLE IF EXISTS w_SERVICE;
				CREATE TEMP TABLE w_SERVICE AS
				SELECT
					SER_SEJ || '_' || COALESCE(MDT_REEL,MDT_DOS) AS COD_SER,
					NOM_SER || ' (' || COALESCE(MDT_REEL,MDT_DOS) || ')' AS NOM_SER,
					COALESCE(MDT_REEL,MDT_DOS) AS MDT_SER,
					DMT_SER
				FROM prod_sigems2.DOSSIER
					JOIN prod_sigems2.SEJOUR ON ANN_SEJ = ANN_DOS AND COD_SEJ = COD_DOS
					JOIN prod_sigems2.SERVICE ON SER_SEJ = COD_SER
					LEFT JOIN prod_sigems2.DOSSIER_MDT ON DOSSIER.ANN_DOS = DOSSIER_MDT.ANN_DOS AND DOSSIER.COD_DOS = DOSSIER_MDT.COD_DOS
				GROUP BY 1,2,3,4;

				
				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits, type_t2a)
				SELECT COD_SER, COD_SER, NOM_SER, NOM_SER, 0 AS nb_lits, '0' AS type_t2a
				FROM w_SERVICE
				WHERE COD_SER NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
				ORDER BY COD_SER;
				
				UPDATE activite[PX].t_services_facturation SET
					texte = NOM_SER,
					texte_court = CASE WHEN texte_court = texte THEN NOM_SER ELSE texte_court END
				FROM w_SERVICE
				WHERE COD_SER = code_original AND
					(
						texte IS DISTINCT FROM NOM_SER OR
						texte_court IS DISTINCT FROM CASE WHEN texte_court = texte THEN NOM_SER ELSE texte_court END
					);

				
				UPDATE activite[PX].t_services_facturation
				SET mode_traitement_id = COALESCE(t_modes_traitement.oid,0)
				FROM w_SERVICE
					LEFT JOIN base.t_modes_traitement ON MDT_SER = t_modes_traitement.code
				WHERE t_services_facturation.code_original = COD_SER AND 
					COALESCE(mode_traitement_id,0) = 0 AND
					COALESCE(mode_traitement_id,0) <> COALESCE(t_modes_traitement.oid,0);

				UPDATE activite[PX].t_services_facturation
				SET dmt_id = COALESCE(t_dmt.oid,0)
				FROM w_SERVICE
					LEFT JOIN base.t_dmt ON DMT_SER = t_dmt.code
				WHERE t_services_facturation.code_original = COD_SER AND 
					COALESCE(dmt_id,0) = 0 AND
					COALESCE(dmt_id,0) <> COALESCE(t_dmt.oid,0);

				-- 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 COD_SER, COD_SER, NOM_SER, NOM_SER
				FROM prod_sigems2.SERVICE
				WHERE COD_SER NOT IN (SELECT code_original FROM activite[PX].t_unites_fonctionnelles)
				ORDER BY COD_SER;
				
				UPDATE activite[PX].t_unites_fonctionnelles SET
					texte = NOM_SER,
					texte_court = CASE WHEN texte_court = texte THEN NOM_SER ELSE texte_court END
				FROM prod_sigems2.SERVICE
				WHERE COD_SER = code_original AND
					(
						texte IS DISTINCT FROM NOM_SER OR
						texte_court IS DISTINCT FROM CASE WHEN texte_court = texte THEN NOM_SER ELSE texte_court END
					);
					
				-- 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 CODE, CODE, LIB, LIB
								FROM prod_sigems2.UNITE_MEDICALE
								WHERE CODE NOT IN (SELECT code_original FROM activite[PX].t_unites_medicales)
								ORDER BY CODE;


				-- Activités

				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
				
				DROP TABLE IF EXISTS w_CHAMBRE;
				CREATE TEMP TABLE W_CHAMBRE AS
				SELECT COD_CHA, NOM_CHA, TYP_CHA, NBL_CHA, SER_CHA, CHAMBRE
				FROM prod_sigems2.CHAMBRE
				WHERE COD_CHA <> '' AND
					COD_CHA <> '0';
				
				CREATE INDEX w_CHAMBRE_i1
				  ON w_CHAMBRE
				  USING btree
				  (COD_CHA);
				  
				UPDATE w_CHAMBRE
				SET SER_CHA = COD_CHA 
				WHERE SER_CHA = '';
				
				
				
				INSERT INTO w_CHAMBRE
				SELECT NCH_DOS, NCH_DOS, '', 0, MAX(SECT_ENTREE), NCH_DOS
				FROM prod_sigems2.DOSSIER
				JOIN prod_sigems2.DOSSIER_SUPPL ON DOSSIER_SUPPL.COD_DOS = DOSSIER.COD_DOS AND
								DOSSIER_SUPPL.ANN_DOS = DOSSIER.ANN_DOS
				WHERE SECT_ENTREE <> '' AND
					NCH_DOS NOT IN (SELECT COD_CHA FROM w_CHAMBRE) AND
					NCH_DOS <> '' AND
					NCH_DOS <> '0'
				GROUP BY 1
				ORDER BY 1;
				
				INSERT INTO w_CHAMBRE
				SELECT NCH_SEJ, NCH_SEJ, '', 0, MAX(SECT_ENTREE), NCH_SEJ
				FROM prod_sigems2.SEJOUR
				JOIN prod_sigems2.DOSSIER_SUPPL ON DOSSIER_SUPPL.COD_DOS = SEJOUR.COD_SEJ AND
								DOSSIER_SUPPL.ANN_DOS = SEJOUR.ANN_SEJ
				WHERE SECT_ENTREE <> '' AND
					NCH_SEJ NOT IN (SELECT COD_CHA FROM w_CHAMBRE) AND
					NCH_SEJ <> '' AND
					NCH_SEJ <> '0'
				GROUP BY 1
				ORDER BY 1;
				  
				  
				INSERT INTO w_CHAMBRE
				SELECT NCH_DOS, NCH_DOS, MAX(TYP_CHA), MAX(NBL_CHA), MAX(SER_CHA), MAX(COD_CHA)
				FROM prod_sigems2.DOSSIER
				JOIN w_CHAMBRE ON SUBSTR(NCH_DOS,1,3) = COD_CHA
				WHERE LENGTH(NCH_DOS) > 3 AND LENGTH(COD_CHA) = 3 AND
					NCH_DOS NOT IN (SELECT COD_CHA FROM w_CHAMBRE) AND
					NCH_DOS <> '' AND
					NCH_DOS <> '0'
				GROUP BY 1
				ORDER BY 1;

				
				INSERT INTO w_CHAMBRE
				SELECT NCH_SEJ, NCH_SEJ, MAX(TYP_CHA), MAX(NBL_CHA), MAX(SER_CHA), MAX(COD_CHA)
				FROM prod_sigems2.SEJOUR
				JOIN w_CHAMBRE ON SUBSTR(NCH_SEJ,1,3) = COD_CHA
				WHERE LENGTH(NCH_SEJ) > 3 AND LENGTH(COD_CHA) = 3 AND
					NCH_SEJ NOT IN (SELECT COD_CHA FROM w_CHAMBRE) AND
					NCH_SEJ <> '' AND
					NCH_SEJ <> '0'
				GROUP BY 1
				ORDER BY 1;


				INSERT INTO w_CHAMBRE
				SELECT NCH_DOS, NCH_DOS, MAX(TYP_CHA), MAX(NBL_CHA), MAX(SER_CHA), MAX(COD_CHA)
				FROM prod_sigems2.DOSSIER
				JOIN w_CHAMBRE ON SUBSTR(NCH_DOS,1,3) = SUBSTR(COD_CHA,1,3)
				WHERE NCH_DOS NOT IN (SELECT COD_CHA FROM w_CHAMBRE) AND
					NCH_DOS <> '' AND
					NCH_DOS <> '0'
				GROUP BY 1
				ORDER BY 1;


				INSERT INTO w_CHAMBRE
				SELECT NCH_DOS, NCH_DOS, MAX(TYP_CHA), MAX(NBL_CHA), MAX(SER_CHA), MAX(COD_CHA)
				FROM prod_sigems2.DOSSIER
				JOIN w_CHAMBRE ON SUBSTR(NCH_DOS,1,2) = SUBSTR(COD_CHA,1,2)
				WHERE NCH_DOS NOT IN (SELECT COD_CHA FROM w_CHAMBRE) AND
					NCH_DOS <> '' AND
					NCH_DOS <> '0'
				GROUP BY 1
				ORDER BY 1;


				INSERT INTO w_CHAMBRE
				SELECT NCH_DOS, NCH_DOS, MAX(TYP_CHA), MAX(NBL_CHA), MAX(SER_CHA), MAX(COD_CHA)
				FROM prod_sigems2.DOSSIER
				JOIN w_CHAMBRE ON SUBSTR(NCH_DOS,1,1) = SUBSTR(COD_CHA,1,1)
				WHERE NCH_DOS NOT IN (SELECT COD_CHA FROM w_CHAMBRE) AND
					NCH_DOS <> '' AND
					NCH_DOS <> '0'
				GROUP BY 1
				ORDER BY 1;



				INSERT INTO w_CHAMBRE
				SELECT NCH_SEJ, NCH_SEJ, MAX(TYP_CHA), MAX(NBL_CHA), MAX(SER_CHA), MAX(COD_CHA)
				FROM prod_sigems2.SEJOUR
				JOIN w_CHAMBRE ON SUBSTR(NCH_SEJ,1,3) = SUBSTR(COD_CHA,1,3)
				WHERE NCH_SEJ NOT IN (SELECT COD_CHA FROM w_CHAMBRE) AND
					NCH_SEJ <> '' AND
					NCH_SEJ <> '0'
				GROUP BY 1
				ORDER BY 1;


				INSERT INTO w_CHAMBRE
				SELECT NCH_SEJ, NCH_SEJ, MAX(TYP_CHA), MAX(NBL_CHA), MAX(SER_CHA), MAX(COD_CHA)
				FROM prod_sigems2.SEJOUR
				JOIN w_CHAMBRE ON SUBSTR(NCH_SEJ,1,2) = SUBSTR(COD_CHA,1,2)
				WHERE NCH_SEJ NOT IN (SELECT COD_CHA FROM w_CHAMBRE) AND
					NCH_SEJ <> '' AND
					NCH_SEJ <> '0'
				GROUP BY 1
				ORDER BY 1;


				INSERT INTO w_CHAMBRE
				SELECT NCH_SEJ, NCH_SEJ, MAX(TYP_CHA), MAX(NBL_CHA), MAX(SER_CHA), MAX(COD_CHA)
				FROM prod_sigems2.SEJOUR
				JOIN w_CHAMBRE ON SUBSTR(NCH_SEJ,1,1) = SUBSTR(COD_CHA,1,1)
				WHERE NCH_SEJ NOT IN (SELECT COD_CHA FROM w_CHAMBRE) AND
					NCH_SEJ <> '' AND
					NCH_SEJ <> '0'
				GROUP BY 1
				ORDER BY 1;

				
				

				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, nb_lits)
				SELECT SER_CHA, SER_CHA, SER_CHA, SER_CHA, 0 AS nb_lits
				FROM w_CHAMBRE
				WHERE SER_CHA <> '' AND SER_CHA NOT IN (SELECT code_original FROM activite[PX].t_etages WHERE code_original IS NOT NULL)
				GROUP BY SER_CHA
				ORDER BY SER_CHA;
				
				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court, nb_lits)
				SELECT COD_CHA, COD_CHA, MAX(NOM_CHA), MAX(NOM_CHA), 0 AS nb_lits
				FROM w_CHAMBRE
				WHERE COD_CHA <> '' AND SER_CHA = '' AND COD_CHA NOT IN (SELECT code_original FROM activite[PX].t_etages WHERE code_original IS NOT NULL)
				GROUP BY COD_CHA
				ORDER BY COD_CHA;


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

				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
				SELECT SER_CHA || '|' || COD_CHA, COD_CHA, NOM_CHA, NOM_CHA, 
					t_etages.oid, CASE WHEN TYP_CHA LIKE 'P%' THEN 'O' ELSE 'N' END
				FROM w_CHAMBRE
					JOIN activite[PX].t_etages ON SER_CHA = t_etages.code_original
				WHERE COD_CHA <> '' AND SER_CHA || '|' || COD_CHA NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL)
				ORDER BY 1;
				
				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
				SELECT COD_CHA || '|' || COD_CHA, COD_CHA, NOM_CHA, NOM_CHA, 
					t_etages.oid, CASE WHEN TYP_CHA LIKE 'P%' THEN 'O' ELSE 'N' END
				FROM w_CHAMBRE
					JOIN activite[PX].t_etages ON COD_CHA = t_etages.code_original
				WHERE COD_CHA <> '' AND SER_CHA = '' AND COD_CHA || '|' || COD_CHA NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL)
				ORDER BY 1;
				
				
				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 );


									
			]]></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 trim(COD_PRC), trim(COD_PRC), MAX(LIB_PRC), MAX(LIB_PRC)
				FROM prod_sigems2.PROD_CLINI
				WHERE trim(COD_PRC) NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
				GROUP BY 1,2
				ORDER BY trim(COD_PRC);
				
				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT trim(COD_PRH), trim(COD_PRH), MAX(LIB_PRH), MAX(LIB_PRH)
				FROM prod_sigems2.PROD_HONOR
				WHERE trim(COD_PRH) NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
				GROUP BY 1,2
				ORDER BY 1;



				INSERT INTO activite.t_prestations(oid, code_original, code, texte, texte_court, clinique_honoraire) 
				SELECT 0, 0, '', 'Non renseignée', 'Non renseignée', '' WHERE 0 NOT IN (SELECT oid FROM activite.t_prestations);
				
				UPDATE activite.t_prestations  
					SET code_original = code
				WHERE oid > 0   
				    AND code_original NOT LIKE '*CTI%'  
				    AND code_original IS DISTINCT FROM code  
				;

				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT ACT_PRC, ACT_PRC, MAX(ACT_PRC), MAX(ACT_PRC)
				FROM prod_sigems2.PROD_CLINI
				WHERE ACT_PRC NOT IN (SELECT code_original FROM activite.t_prestations)
				GROUP BY 1,2
				ORDER BY ACT_PRC;

				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT CASE WHEN ACT_PRH <> '' THEN ACT_PRH ELSE COD_PRH END , 
					CASE WHEN ACT_PRH <> '' THEN ACT_PRH ELSE COD_PRH END, 
					MAX(CASE WHEN ACT_PRH <> '' THEN ACT_PRH ELSE COD_PRH END), 
					MAX(CASE WHEN ACT_PRH <> '' THEN ACT_PRH ELSE COD_PRH END)
				FROM prod_sigems2.PROD_HONOR
				WHERE CASE WHEN ACT_PRH <> '' THEN ACT_PRH ELSE COD_PRH END NOT IN (SELECT code_original FROM activite.t_prestations)
				GROUP BY 1,2
				ORDER BY 1;
				
				
				
				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 AFA_PRC, AFA_PRC, MAX(INT1), MAX(INT1)
				FROM prod_sigems2.PROD_CLINI
				JOIN prod_sigems2.COMPTE ON AFA_PRC = NUM				
				WHERE AFA_PRC <> '' AND AFA_PRC NOT IN (SELECT code FROM activite[PX].t_compte)
				GROUP BY 1
				ORDER BY 1;
				
				INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
				SELECT CPT_ANA, CPT_ANA, MAX(INT1), MAX(INT1)
				FROM prod_sigems2.ANALYG
				JOIN prod_sigems2.COMPTE ON CPT_ANA = num AND ANALYG.TYP_ANA = COMPTE.TYP 
				WHERE CPT_ANA NOT IN (SELECT code FROM activite[PX].t_compte)
				GROUP BY 1
				ORDER BY 1;
                
                -- Codes risques
                INSERT INTO activite[PX].t_risque(code, texte)
                SELECT
                    COD_RIS, LIB_RIS
                FROM
                    prod_sigems.RISQUE
                    LEFT JOIN activite[PX].t_risque ON t_risque.code = COD_RIS
                WHERE
                    t_risque.code IS NULL;
										
			]]></sqlcmd>
		</NODE>
		
	</NODE>
		
	<NODE name="POST" label="TRAITEMENTS COMPLEMENTAIRES">
	
		
		<NODE label="Réorientation prestations">
			<sqlcmd><![CDATA[
	
				-- Les FSD privés doivent être remonté en part établissement
				INSERT INTO activite[PX].p_factures_lignes_c
					(
					no_facture,
					facture_id,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					prestation_id,
					protocole_id,
					compte_produit_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,
					nb_prestation,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					rubrique_comptabilisation_id,
					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
					)
				SELECT
					p_factures_lignes_h.no_facture,
					p_factures_lignes_h.facture_id,
					p_factures_lignes_h.date_debut,
					p_factures_lignes_h.date_fin,
					p_factures_lignes_h.nb_rubrique,
					p_factures_lignes_h.coefficient,
					p_factures_lignes_h.coefficient_mco,
					p_factures_lignes_h.rubrique_facturation_id,
					p_factures_lignes_h.prestation_id,
					p_factures_lignes_h.protocole_id,
					0::bigint AS compte_produit_id,
					p_factures_lignes_h.montant_facture,
					p_factures_lignes_h.montant_facture_0,
					p_factures_lignes_h.montant_facture_1,
					p_factures_lignes_h.montant_facture_2,
					p_factures_lignes_h.montant_facture_22,
					p_factures_lignes_h.taux_0,
					p_factures_lignes_h.taux_1,
					p_factures_lignes_h.taux_2,
					p_factures_lignes_h.taux_22,
					p_factures_lignes_h.prix_unitaire,
					p_factures_lignes_h.lieu_id,
					p_factures_lignes_h.nb_prestation,
					p_factures_lignes_h.montant_comptabilise,
					p_factures_lignes_h.montant_comptabilise_0,
					p_factures_lignes_h.montant_comptabilise_1,
					p_factures_lignes_h.montant_comptabilise_2,
					p_factures_lignes_h.montant_comptabilise_22,
					p_factures_lignes_h.rubrique_comptabilisation_id,
					p_factures_lignes_h.montant_encours,
					p_factures_lignes_h.montant_encours_0,
					p_factures_lignes_h.montant_encours_1,
					p_factures_lignes_h.montant_encours_2,
					p_factures_lignes_h.montant_encours_22,
					p_factures_lignes_h.montant_facture_actes_inclus_dans_sejour,
					p_factures_lignes_h.montant_facture_0_actes_inclus_dans_sejour,
					p_factures_lignes_h.montant_facture_1_actes_inclus_dans_sejour,
					p_factures_lignes_h.montant_facture_2_actes_inclus_dans_sejour,
					p_factures_lignes_h.montant_facture_22_actes_inclus_dans_sejour,
					1::bigint AS origine_facturation_id,
					0::numeric AS montant_comptabilise_budget_global_1
				FROM activite[PX].p_factures_lignes_h
				JOIN activite[PX].p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture
				JOIN activite[PX].p_sejours On p_factures.no_sejour = p_sejours.no_sejour
				JOIN activite[PX].t_rubriques_facturation ON rubrique_facturation_id = t_rubriques_facturation.oid
				WHERE est_budget_global IS DISTINCT FROM '1' AND
					est_force_etablissement = '1';

				DROP TABLE IF EXISTS w_factures_h_ets;
				CREATE TEMP TABLE w_factures_h_ets AS
				SELECT
					p_factures_lignes_h.no_facture,
					SUM(p_factures_lignes_h.montant_facture) AS montant_facture,
					SUM(p_factures_lignes_h.montant_facture_0) AS montant_facture_0,
					SUM(p_factures_lignes_h.montant_facture_1) AS montant_facture_1,
					SUM(p_factures_lignes_h.montant_facture_2) AS montant_facture_2,
					SUM(p_factures_lignes_h.montant_facture_22) AS montant_facture_22,
					SUM(p_factures_lignes_h.montant_comptabilise) AS montant_comptabilise,
					SUM(p_factures_lignes_h.montant_comptabilise_0) AS montant_comptabilise_0,
					SUM(p_factures_lignes_h.montant_comptabilise_1) AS montant_comptabilise_1,
					SUM(p_factures_lignes_h.montant_comptabilise_2) AS montant_comptabilise_2,
					SUM(p_factures_lignes_h.montant_comptabilise_22) AS montant_comptabilise_22
				FROM activite[PX].p_factures_lignes_h
				JOIN activite[PX].p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture
				JOIN activite[PX].p_sejours On p_factures.no_sejour = p_sejours.no_sejour
				JOIN activite[PX].t_rubriques_facturation ON rubrique_facturation_id = t_rubriques_facturation.oid
				WHERE est_budget_global IS DISTINCT FROM '1' AND
					est_force_etablissement = '1'
				GROUP BY 1;

				CREATE INDEX w_factures_h_ets_i1 ON w_factures_h_ets USING btree (no_facture);

				UPDATE activite[PX].p_factures SET 
					montant_facture_c = montant_facture_c + montant_facture,
					montant_facture_0_c = montant_facture_0_c + montant_facture_0,
					montant_facture_1_c = montant_facture_1_c + montant_facture_1,
					montant_facture_2_c = montant_facture_2_c + montant_facture_2,
					montant_facture_22_c = montant_facture_22_c + montant_facture_22,
					montant_comptabilise_c = montant_comptabilise_c + montant_comptabilise,
					montant_comptabilise_0_c = montant_comptabilise_0_c + montant_comptabilise_0,
					montant_comptabilise_1_c = montant_comptabilise_1_c + montant_comptabilise_1,
					montant_comptabilise_2_c = montant_comptabilise_2_c + montant_comptabilise_2,
					montant_comptabilise_22_c = montant_comptabilise_22_c + montant_comptabilise_22,
					montant_facture_h = montant_facture_h - montant_facture,
					montant_facture_0_h = montant_facture_0_h - montant_facture_0,
					montant_facture_1_h = montant_facture_1_h - montant_facture_1,
					montant_facture_2_h = montant_facture_2_h - montant_facture_2,
					montant_facture_22_h = montant_facture_22_h - montant_facture_22,
					montant_comptabilise_h = montant_comptabilise_h - montant_comptabilise,
					montant_comptabilise_0_h = montant_comptabilise_0_h - montant_comptabilise_0,
					montant_comptabilise_1_h = montant_comptabilise_1_h - montant_comptabilise_1,
					montant_comptabilise_2_h = montant_comptabilise_2_h - montant_comptabilise_2,
					montant_comptabilise_22_h = montant_comptabilise_22_h - montant_comptabilise_22
				FROM w_factures_h_ets
				WHERE w_factures_h_ets.no_facture = p_factures.no_facture;

				DELETE FROM activite[PX].p_factures_lignes_h
				USING activite[PX].t_rubriques_facturation
				WHERE rubrique_facturation_id = t_rubriques_facturation.oid AND
					est_force_etablissement = '1';


				-- Les FSD public doivent être transformés en part établissement
				DROP TABLE IF EXISTS w_factures_h_ets;
				CREATE TEMP TABLE w_factures_h_ets AS
				SELECT
					p_factures_lignes_c.no_facture,
					SUM(p_factures_lignes_c.montant_facture) AS montant_facture,
					SUM(p_factures_lignes_c.montant_facture_0) AS montant_facture_0,
					SUM(p_factures_lignes_c.montant_facture_1) AS montant_facture_1,
					SUM(p_factures_lignes_c.montant_facture_2) AS montant_facture_2,
					SUM(p_factures_lignes_c.montant_facture_22) AS montant_facture_22
				FROM activite[PX].p_factures_lignes_c
				JOIN activite[PX].t_rubriques_facturation ON rubrique_facturation_id = t_rubriques_facturation.oid
				WHERE est_force_etablissement = '1' AND origine_facturation_id = 2
				GROUP BY 1;

				CREATE INDEX w_factures_h_ets_i1 ON w_factures_h_ets USING btree (no_facture);

				UPDATE activite[PX].p_factures SET 
					montant_facture_c = montant_facture_c + montant_facture,
					montant_facture_0_c = montant_facture_0_c + montant_facture_0,
					montant_facture_1_c = montant_facture_1_c + montant_facture_1,
					montant_facture_2_c = montant_facture_2_c + montant_facture_2,
					montant_facture_22_c = montant_facture_22_c + montant_facture_22,
					montant_facture_h = montant_facture_h - montant_facture,
					montant_facture_0_h = montant_facture_0_h - montant_facture_0,
					montant_facture_1_h = montant_facture_1_h - montant_facture_1,
					montant_facture_2_h = montant_facture_2_h - montant_facture_2,
					montant_facture_22_h = montant_facture_22_h - montant_facture_22
				FROM w_factures_h_ets
				WHERE w_factures_h_ets.no_facture = p_factures.no_facture;

				UPDATE activite[PX].p_factures_lignes_c
				SET origine_facturation_id = 1
				FROM activite[PX].t_rubriques_facturation
				WHERE rubrique_facturation_id = t_rubriques_facturation.oid AND
					est_force_etablissement = '1' AND
					origine_facturation_id = 2;

				
				-- Les FSD comptabilisés doivent être transformés en part établissement

				DROP TABLE IF EXISTS w_factures_soldes_h_ets;
				CREATE TEMP TABLE w_factures_soldes_h_ets AS
				SELECT
					p_factures_soldes_h.no_facture,
					p_factures_soldes_h.date_comptable,
					SUM(p_factures_soldes_h.montant_comptabilise) AS montant_comptabilise,
					SUM(p_factures_soldes_h.montant_comptabilise_0) AS montant_comptabilise_0,
					SUM(p_factures_soldes_h.montant_comptabilise_1) AS montant_comptabilise_1,
					SUM(p_factures_soldes_h.montant_comptabilise_2) AS montant_comptabilise_2,
					SUM(p_factures_soldes_h.montant_comptabilise_22) AS montant_comptabilise_22,
					SUM(p_factures_soldes_h.montant_regle) AS montant_regle,
					SUM(p_factures_soldes_h.montant_regle_0) AS montant_regle_0,
					SUM(p_factures_soldes_h.montant_regle_1) AS montant_regle_1,
					SUM(p_factures_soldes_h.montant_regle_2) AS montant_regle_2,
					SUM(p_factures_soldes_h.montant_regle_22) AS montant_regle_22
				FROM activite[PX].p_factures_soldes_h
				JOIN activite[PX].t_rubriques_facturation ON rubrique_comptabilisee_id = t_rubriques_facturation.oid
				WHERE est_force_etablissement = '1'
				GROUP BY 1,2;

				DROP TABLE IF EXISTS w_factures_h_ets;
				CREATE TEMP TABLE w_factures_h_ets AS
				SELECT
					no_facture,
					SUM(montant_regle) AS montant_regle,
					SUM(montant_regle_0) AS montant_regle_0,
					SUM(montant_regle_1) AS montant_regle_1,
					SUM(montant_regle_2) AS montant_regle_2,
					SUM(montant_regle_22) AS montant_regle_22
				FROM w_factures_soldes_h_ets
				GROUP BY 1;

				CREATE INDEX w_factures_h_ets_i1 ON w_factures_h_ets USING btree (no_facture);

				UPDATE activite[PX].p_factures SET 
					montant_regle_c = montant_regle_c + montant_regle,
					montant_regle_0_c = montant_regle_0_c + montant_regle_0,
					montant_regle_1_c = montant_regle_1_c + montant_regle_1,
					montant_regle_2_c = montant_regle_2_c + montant_regle_2,
					montant_regle_22_c = montant_regle_22_c + montant_regle_22,
					montant_regle_h = montant_regle_h - montant_regle,
					montant_regle_0_h = montant_regle_0_h - montant_regle_0,
					montant_regle_1_h = montant_regle_1_h - montant_regle_1,
					montant_regle_2_h = montant_regle_2_h - montant_regle_2,
					montant_regle_22_h = montant_regle_22_h - montant_regle_22
				FROM w_factures_h_ets
				WHERE w_factures_h_ets.no_facture = p_factures.no_facture;

				INSERT INTO activite[PX].p_factures_soldes_c
					(
					no_facture,
					facture_id,
					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_h.no_facture,
					p_factures_soldes_h.facture_id,
					p_factures_soldes_h.date_comptable,
					p_factures_soldes_h.rubrique_comptabilisee_id,
					p_factures_soldes_h.prestation_id,
					p_factures_soldes_h.montant_comptabilise,
					p_factures_soldes_h.montant_comptabilise_0,
					p_factures_soldes_h.montant_comptabilise_1,
					p_factures_soldes_h.montant_comptabilise_2,
					p_factures_soldes_h.montant_comptabilise_22,
					p_factures_soldes_h.montant_regle,
					p_factures_soldes_h.montant_regle_0,
					p_factures_soldes_h.montant_regle_1,
					p_factures_soldes_h.montant_regle_2,
					p_factures_soldes_h.montant_regle_22,
					p_factures_soldes_h.od_avoir
				FROM activite[PX].p_factures_soldes_h
				JOIN activite[PX].t_rubriques_facturation ON rubrique_comptabilisee_id = t_rubriques_facturation.oid
				WHERE est_force_etablissement = '1';

				DELETE FROM activite[PX].p_factures_soldes_h
				USING activite[PX].t_rubriques_facturation
				WHERE rubrique_comptabilisee_id = t_rubriques_facturation.oid AND
					est_force_etablissement = '1';


				-- Le chiffrier est 'modifié' selon que qui a été modifié
				UPDATE activite[PX].p_factures_comptables SET
					montant_ventes_c = montant_ventes_c + montant_comptabilise,
					montant_reglements_c = montant_reglements_c  + montant_regle,
					montant_ventes_h = montant_ventes_h - montant_comptabilise,
					montant_reglements_h = montant_reglements_h  - montant_regle
				FROM w_factures_soldes_h_ets
				WHERE p_factures_comptables.no_facture = w_factures_soldes_h_ets.no_facture AND
					p_factures_comptables.date_comptable = w_factures_soldes_h_ets.date_comptable;

				INSERT INTO activite[PX].p_factures_comptables
					(
					no_facture, 
					facture_id,
					date_comptable, 
					provider_id, 
					montant_ventes_c, 
					montant_reglements_c, 
					montant_ventes_h, 
					montant_reglements_h
					)
				SELECT 
					w_factures_soldes_h_ets.no_facture, 
					0::bigint AS facture_id,
					w_factures_soldes_h_ets.date_comptable, 
					0::bigint AS provider_id, 
					w_factures_soldes_h_ets.montant_comptabilise AS montant_ventes_c, 
					w_factures_soldes_h_ets.montant_regle AS montant_reglements_c, 
					0 - w_factures_soldes_h_ets.montant_comptabilise AS montant_ventes_h, 
					0 - w_factures_soldes_h_ets.montant_regle AS montant_reglements_h
				FROM w_factures_soldes_h_ets
				LEFT JOIN activite[PX].p_factures_comptables ON  
					p_factures_comptables.no_facture = w_factures_soldes_h_ets.no_facture AND
					p_factures_comptables.date_comptable = w_factures_soldes_h_ets.date_comptable
				WHERE p_factures_comptables.no_facture IS NULL;

				DROP TABLE IF EXISTS w_chiffrier_h_ets;
				CREATE TEMP TABLE w_chiffrier_h_ets AS
				SELECT
					date_comptable,
					0::bigint AS provider_id,
					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_regle) AS montant_regle,
					SUM(montant_regle_0) AS montant_regle_0,
					SUM(montant_regle_1) AS montant_regle_1,
					SUM(montant_regle_2) AS montant_regle_2,
					SUM(montant_regle_22) AS montant_regle_22
				FROM w_factures_soldes_h_ets
				GROUP BY 1;

				CREATE INDEX w_chiffrier_h_ets_i1 ON w_chiffrier_h_ets USING btree (date_comptable);

				UPDATE activite[PX].p_chiffrier_comptable SET
					montant_ventes_c = montant_ventes_c + montant_comptabilise,
					montant_reglements_c = montant_reglements_c  + montant_regle,
					montant_ventes_h = montant_ventes_h - montant_comptabilise,
					montant_reglements_h = montant_reglements_h  - montant_regle
				FROM w_chiffrier_h_ets
				WHERE p_chiffrier_comptable.date_comptable = w_chiffrier_h_ets.date_comptable;

				INSERT INTO activite[PX].p_chiffrier_comptable
					(
					date_comptable, 
					provider_id, 
					montant_ventes_c, 
					montant_reglements_c, 
					montant_ventes_h, 
					montant_reglements_h
					)
				SELECT 
					w_chiffrier_h_ets.date_comptable, 
					0::bigint AS provider_id, 
					w_chiffrier_h_ets.montant_comptabilise AS montant_ventes_c, 
					w_chiffrier_h_ets.montant_regle AS montant_reglements_c, 
					0 - w_chiffrier_h_ets.montant_comptabilise AS montant_ventes_h, 
					0 - w_chiffrier_h_ets.montant_regle AS montant_reglements_h
				FROM w_chiffrier_h_ets
				LEFT JOIN activite[PX].p_chiffrier_comptable ON p_chiffrier_comptable.date_comptable = w_chiffrier_h_ets.date_comptable
				WHERE p_chiffrier_comptable.date_comptable IS NULL AND
					w_chiffrier_h_ets.date_comptable >= '[ENV_ADM_ANNEEDEBUT]0101';
	
	
			]]></sqlcmd>
		</NODE>
		
		<NODE name="Compléments patients">
			<sqlcmd><![CDATA[
				-- ajout des coordonnées 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,
					AD1_PAT || CASE WHEN AD2_PAT != '' THEN ' - ' || AD2_PAT ELSE '' END,
					COALESCE(t_codes_postaux.oid,0),
					VIL_PAT,
					TEL_PAT,
					PORTABLE,
					MAIL
				FROM w_PATIENT
					LEFT JOIN prod_sigems.PAT_COMPL ON w_PATIENT.COD_PAT = PAT_COMPL.COD_PAT
					LEFT JOIN base.t_codes_postaux ON CPO_PAT = t_codes_postaux.code
					JOIN activite[PX].p_sejours ON no_sejour = SEJ_NUM
				;
			]]></sqlcmd>
		</NODE>
	
		<NODE label="Compléments facture">
			<sqlcmd><![CDATA[
							
				
			
				UPDATE activite[PX].p_factures SET date_expedition_0 = date_facture WHERE date_expedition_0 < date_facture AND date_facture <> '2099-12-31';

				
			]]></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 w_sejours_total
				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

				);
														
										
			]]></sqlcmd>
		</NODE>
		
	
		<NODE label="Tables répliquées">
			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>
			
			<sqlcmd><![CDATA[

				
										
			]]></sqlcmd>
		</NODE>
	</NODE>
	
	
</ROOT>
