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

		<NODE label="Corrections diverses">
			<sqlcmd><![CDATA[
			
				-- Correction des heures
				
				UPDATE prod_sigems.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_sigems.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_sigems.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_sigems.SEJOUR
				SET MIN_SEJ =  to_char(to_number('00' || MIN_SEJ,'0000'),'FM00')
				WHERE MIN_SEJ <> to_char(to_number('00' || MIN_SEJ,'0000'),'FM00');
				
				
				UPDATE prod_sigems.DOSSIER
				SET HEU_DOS = MIN_DOS
				WHERE DEN_DOS = DSO_DOS AND MIN_DOS > HEU_DOS AND HEU_DOS = '00';
                
                -- Correction médecin séjour pour récupérer médecin à la sortie
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'SIGEMS_MEDSEJ',
					'Transformation code médecin selon historique médecins',
					'1',
					'1=Récupérer médecin à la sortie, 0=Récupérer uniquement médecin séjour'
				WHERE 'SIGEMS_MEDSEJ' NOT IN (SELECT code FROM activite.t_divers);
                ;

                SELECT *
                FROM base.cti_execute('
                    UPDATE prod_sigems.DOSSIER
					SET CCH_DOS = CCH_DOS_sortie
					FROM 
					(
						SELECT annee, code, (MAX(Array[COALESCE(FIN,''20991231'')::text,SEJOUR_CLINIQUE.PRATICIEN]))[2] AS CCH_DOS_sortie
						FROM prod_sigems.SEJOUR_CLINIQUE
						JOIN prod_sigems.PRATICIEN ON SEJOUR_CLINIQUE.PRATICIEN = COD_PRA
						WHERE praticien <> '''' 
						GROUP BY 1,2
						HAVING count(DISTINCT PRATICIEN) > 1
					) subview
					WHERE ANN_DOS = ANNEE AND COD_DOS = CODE AND
						CCH_DOS <> CCH_DOS_sortie
						',1)
						WHERE 'SIGEMS_MEDSEJ' IN (SELECT code FROM activite.t_divers WHERE code = 'SIGEMS_MEDSEJ' AND valeur = '1')
				;
				
				-- Transformation UF (refonte FICOM GHM Grenoble)
				UPDATE prod_SIGEMS.DOSSIER
					SET SER_DOS = TO_UF
				FROM prod_sigems.DOSSIER_MDT,
					activite.t_sigems_transformation_uf
				WHERE DOSSIER.ANN_DOS = DOSSIER_MDT.ANN_DOS AND
					DOSSIER.COD_DOS = DOSSIER_MDT.COD_DOS AND
					SER_DOS = FROM_UF AND
					MDT_REEL = FROM_MODE AND
					CCH_DOS = FROM_MEDECIN AND
					SER_DOS <> TO_UF
				;

				UPDATE prod_SIGEMS.SEJOUR
					SET SER_SEJ = TO_UF
				FROM prod_SIGEMS.DOSSIER,
					prod_sigems.DOSSIER_MDT,
					activite.t_sigems_transformation_uf
				WHERE DOSSIER.ANN_DOS = SEJOUR.ANN_SEJ AND
					DOSSIER.COD_DOS = SEJOUR.COD_SEJ AND
					DOSSIER.ANN_DOS = DOSSIER_MDT.ANN_DOS AND
					DOSSIER.COD_DOS = DOSSIER_MDT.COD_DOS AND
					SER_SEJ = FROM_UF AND
					MDT_REEL = FROM_MODE AND
					CCH_DOS = FROM_MEDECIN AND
					SER_SEJ <> TO_UF
				;
				
				
				-- Correction etat factures sur factures nulles non éditées -> comptabilisées
				UPDATE prod_sigems.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 TP1 (99999999 = patient)
				UPDATE prod_sigems.DOS2 
				SET CP1_DOS2 = ''
				WHERE CP1_DOS2 = '99999999' AND
					SJ1_DOS2 = 0 AND
					HO1_DOS2 = 0
				;
				-- Correction TP2 (99999999 = patient)
				UPDATE prod_sigems.DOS2 
				SET CA2_DOS2 = ''
				WHERE CA2_DOS2 = '99999999' AND
					SJ2_DOS2 = 0 AND
					HO2_DOS2 = 0
				;
					
				-- Correction anomalie : séjours en double chez SIGEMS
				SELECT base.cti_execute(
				'DELETE FROM prod_sigems.DOSSIER
				USING 
					(
					SELECT ANN_DOS, COD_DOS, MAX(CTID) AS del_CTID 
					FROM prod_sigems.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_sigems.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_sigems.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_sigems.DOS2
				USING 
					(
					SELECT ANN_DOS2, COD_DOS2, IND_DOS2, MAX(CTID) AS del_CTID 
					FROM prod_sigems.dos2
					GROUP BY 1,2,3
					HAVING count(*) > 1
					) subview
				WHERE DOS2.CTID = del_CTID;
				
				DELETE FROM prod_sigems.DOS2
				USING 
					(
					SELECT ANN_DOS2, COD_DOS2, IND_DOS2, MAX(CTID) AS del_CTID 
					FROM prod_sigems.dos2
					GROUP BY 1,2,3
					HAVING count(*) > 1
					) subview
				WHERE DOS2.CTID = del_CTID;				

				
				-- Correction lignes affectée à indice 0 au lieu de 1
				UPDATE prod_sigems.LIG_CLINI
				SET IND_LCL = 1
				FROM 
				(
					SELECT ANN_LCL, COD_LCL
					FROM prod_sigems.LIG_CLINI
					JOIN prod_sigems.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_sigems.LIG_CLINI
				SET IND_LCL = IND_DOS2
				FROM prod_sigems.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);
                    
				UPDATE prod_sigems.LIG_HONOR
				SET IND_LHO = 1
				FROM 
				(	SELECT ANN_LHO, COD_LHO
					FROM prod_sigems.LIG_HONOR
					JOIN prod_sigems.DOS2 ON ANN_LHO = ANN_DOS2 AND COD_LHO = COD_DOS2 AND IND_DOS2 = 1 AND ETA_DOS2 >= 4
					WHERE IND_LHO IN (0,1) AND
						(ML1_LHO <> 0 OR ML2_LHO <> 0 OR ML3_LHO <> 0)
					GROUP BY 1,2
					HAVING MIN(IND_LHO) = 0 AND
						MAX(HO1_DOS2) >= SUM(ML1_LHO) AND
						MAX(HO2_DOS2) >= SUM(ML2_LHO) AND
						MAX(HO3_DOS2) >= SUM(ML3_LHO)
					) SUBVIEW
				WHERE LIG_HONOR.ANN_LHO = subview.ANN_LHO AND
					LIG_HONOR.COD_LHO = subview.COD_LHO AND
					LIG_HONOR.IND_LHO = 0;

                -- Lignes restées avec indice à 0 sur dossier en état 3 
                UPDATE prod_sigems.LIG_CLINI
                SET IND_LCL = subview.IND_DOS2
                FROM
                (
                SELECT 
                    ANN_DOS2,
                    COD_DOS2,
                    MAX(IND_DOS2) AS IND_DOS2,
                    SUM(LIG_CLINI_0.ML1_LCL),
                    SUM(LIG_CLINI_0.ML2_LCL),
                    SUM(LIG_CLINI_0.ML3_LCL)
                FROM prod_sigems.DOS2
                LEFT JOIN prod_sigems.LIG_CLINI ON
                    LIG_CLINI.ANN_LCL = ANN_DOS2 AND
                    LIG_CLINI.COD_LCL = COD_DOS2 AND
                    LIG_CLINI.IND_LCL = IND_DOS2 AND
                    LIG_CLINI.PRO_LCL <> 'REGC'
                JOIN prod_sigems.LIG_CLINI LIG_CLINI_0 ON
                    LIG_CLINI_0.ANN_LCL = ANN_DOS2 AND
                    LIG_CLINI_0.COD_LCL = COD_DOS2 AND
                    LIG_CLINI_0.IND_LCL = 0
                WHERE ETA_DOS2 IN (3,4) AND
                    (
                        SJ1_DOS2 <> 0 OR
                        SJ2_DOS2 <> 0 OR
                        SJ3_DOS2 <> 0
                    ) AND
                    LIG_CLINI.ANN_LCL IS NULL
                GROUP BY 1,2
                HAVING 
                    MAX(SJ1_DOS2) = SUM(LIG_CLINI_0.ML1_LCL) AND
                    MAX(SJ2_DOS2) = SUM(LIG_CLINI_0.ML2_LCL) AND
                    MAX(SJ3_DOS2) = SUM(LIG_CLINI_0.ML3_LCL) AND
                    count(DISTINCT IND_DOS2) = 1
                ) subview
                WHERE LIG_CLINI.ANN_LCL = subview.ANN_DOS2 AND
                    LIG_CLINI.COD_LCL = subview.COD_DOS2 AND
                    LIG_CLINI.IND_LCL = 0
                ;

            
                UPDATE prod_sigems.LIG_HONOR
                SET IND_LHO = subview.IND_DOS2
                FROM
                (
                SELECT 
                    ANN_DOS2,
                    COD_DOS2,
                    MAX(IND_DOS2) AS IND_DOS2,
                    SUM(LIG_HONOR_0.ML1_LHO),
                    SUM(LIG_HONOR_0.ML2_LHO),
                    SUM(LIG_HONOR_0.ML3_LHO)
                FROM prod_sigems.DOS2
                LEFT JOIN prod_sigems.LIG_HONOR ON
                    LIG_HONOR.ANN_LHO = ANN_DOS2 AND
                    LIG_HONOR.COD_LHO = COD_DOS2 AND
                    LIG_HONOR.IND_LHO = IND_DOS2 AND
                    LIG_HONOR.CPH_LHO <> 'REGH'
                 JOIN prod_sigems.LIG_HONOR LIG_HONOR_0 ON
                    LIG_HONOR_0.ANN_LHO = ANN_DOS2 AND
                    LIG_HONOR_0.COD_LHO = COD_DOS2 AND
                    LIG_HONOR_0.IND_LHO = 0
                WHERE ETA_DOS2 IN (3,4) AND
                    (
                        HO1_DOS2 <> 0 OR
                        HO2_DOS2 <> 0 OR
                        HO3_DOS2 <> 0
                    ) AND
                    LIG_HONOR.ANN_LHO IS NULL
                GROUP BY 1,2
                HAVING 
                    MAX(HO1_DOS2) = SUM(LIG_HONOR_0.ML1_LHO) AND
                    MAX(HO2_DOS2) = SUM(LIG_HONOR_0.ML2_LHO) AND
                    MAX(HO3_DOS2) = SUM(LIG_HONOR_0.ML3_LHO) AND
                    count(DISTINCT IND_DOS2) = 1
                ) subview
                WHERE LIG_HONOR.ANN_LHO = subview.ANN_DOS2 AND
                    LIG_HONOR.COD_LHO = subview.COD_DOS2 AND
                    LIG_HONOR.IND_LHO = 0
				;
				
				-- Lignes de factures clinique avec règlements sans facture correspondante
				DROP TABLE IF EXISTS w_LIG_CLINI_corr;
				CREATE TEMP TABLE w_LIG_CLINI_corr AS 
				SELECT ANN_LCL, COD_LCL, IND_LCL, 
					CASE 
					WHEN IND_LCL > 1 AND right(IND_LCL::text,1) IN ('2','4','6','8','0') THEN IND_LCL - 1
					WHEN IND_LCL > 2 THEN IND_LCL - 2
					ELSE -1::numeric END AS TO_IND_LCL
				FROM prod_sigems.LIG_CLINI
				JOIN prod_sigems.REG4 ON NUM_CLI = NUM_LCL
				LEFT JOIN prod_sigems.dos2 ON 
					ANN_LCL = ANN_DOS2 AND
					COD_LCL = COD_DOS2 AND
					IND_LCL = IND_DOS2  
				WHERE IND_LCL <> 0 AND
					PRO_LCL = 'REGC' AND
					ANN_DOS2 IS NULL
				GROUP BY 1,2,3,4
				;
				
				ANALYSE w_LIG_CLINI_corr
				;

				UPDATE w_LIG_CLINI_corr
				SET TO_IND_LCL = -2
				FROM
				(
					SELECT ANN_LCL, COD_LCL, IND_LCL
					FROM w_LIG_CLINI_corr
					LEFT JOIN prod_sigems.DOS2 ON
						ANN_LCL = ANN_DOS2 AND
						COD_LCL = COD_DOS2 AND
						TO_IND_LCL = IND_DOS2
					WHERE TO_IND_LCL > 0 AND
						ANN_DOS2 IS NULL
				) subview
				WHERE 
					subview.ANN_LCL = w_LIG_CLINI_corr.ANN_LCL AND
					subview.COD_LCL = w_LIG_CLINI_corr.COD_LCL AND
					subview.IND_LCL = w_LIG_CLINI_corr.IND_LCL
				;

				UPDATE w_LIG_CLINI_corr
				SET TO_IND_LCL = subview.TO_IND_LCL
				FROM
				(
					SELECT ANN_LCL, COD_LCL, IND_LCL, MAX(IND_DOS2) AS TO_IND_LCL
					FROM w_LIG_CLINI_corr
					JOIN prod_sigems.DOS2 ON
						ANN_LCL = ANN_DOS2 AND
						COD_LCL = COD_DOS2 AND
						IND_LCL > IND_DOS2
					WHERE TO_IND_LCL < 0 
				GROUP BY 1,2,3
				) subview
				WHERE 
					subview.ANN_LCL = w_LIG_CLINI_corr.ANN_LCL AND
					subview.COD_LCL = w_LIG_CLINI_corr.COD_LCL AND
					subview.IND_LCL = w_LIG_CLINI_corr.IND_LCL
				;

				UPDATE prod_sigems.LIG_CLINI
				SET IND_LCL = w_LIG_CLINI_corr.TO_IND_LCL
				FROM w_LIG_CLINI_corr
				WHERE LIG_CLINI.ANN_LCL = w_LIG_CLINI_corr.ANN_LCL AND
					LIG_CLINI.COD_LCL = w_LIG_CLINI_corr.COD_LCL AND
					LIG_CLINI.IND_LCL = w_LIG_CLINI_corr.IND_LCL AND
					w_LIG_CLINI_corr.TO_IND_LCL > 0
				;
				
				-- Lignes de factures honoraire avec règlements sans facture correspondante
				DROP TABLE IF EXISTS w_LIG_HONOR_corr;
				CREATE TEMP TABLE w_LIG_HONOR_corr AS 
				SELECT ANN_LHO, COD_LHO, IND_LHO, 
					CASE 
					WHEN IND_LHO > 1 AND right(IND_LHO::text,1) IN ('2','4','6','8','0') THEN IND_LHO - 1
					WHEN IND_LHO > 2 THEN IND_LHO - 2
					ELSE -1::numeric END AS TO_IND_LHO
				FROM prod_sigems.LIG_HONOR
				JOIN prod_sigems.REG3 ON LHO_REG3 = NUM_LHO
				LEFT JOIN prod_sigems.dos2 ON 
					ANN_LHO = ANN_DOS2 AND
					COD_LHO = COD_DOS2 AND
					IND_LHO = IND_DOS2  
				WHERE IND_LHO <> 0 AND
					CPH_LHO = 'REGH' AND
					ANN_DOS2 IS NULL
				GROUP BY 1,2,3,4
				;
				
				UPDATE w_LIG_HONOR_corr
				SET TO_IND_LHO = -2
				FROM
				(
					SELECT ANN_LHO, COD_LHO, IND_LHO
					FROM w_LIG_HONOR_corr
					LEFT JOIN prod_sigems.DOS2 ON
						ANN_LHO = ANN_DOS2 AND
						COD_LHO = COD_DOS2 AND
						TO_IND_LHO = IND_DOS2
					WHERE TO_IND_LHO > 0 AND
						ANN_DOS2 IS NULL
				) subview
				WHERE 
					subview.ANN_LHO = w_LIG_HONOR_corr.ANN_LHO AND
					subview.COD_LHO = w_LIG_HONOR_corr.COD_LHO AND
					subview.IND_LHO = w_LIG_HONOR_corr.IND_LHO
				;

				UPDATE w_LIG_HONOR_corr
				SET TO_IND_LHO = subview.TO_IND_LHO
				FROM
				(
					SELECT ANN_LHO, COD_LHO, IND_LHO, MAX(IND_DOS2) AS TO_IND_LHO
					FROM w_LIG_HONOR_corr
					JOIN prod_sigems.DOS2 ON
						ANN_LHO = ANN_DOS2 AND
						COD_LHO = COD_DOS2 AND
						IND_LHO > IND_DOS2
					WHERE TO_IND_LHO < 0 
				GROUP BY 1,2,3
				) subview
				WHERE 
					subview.ANN_LHO = w_LIG_HONOR_corr.ANN_LHO AND
					subview.COD_LHO = w_LIG_HONOR_corr.COD_LHO AND
					subview.IND_LHO = w_LIG_HONOR_corr.IND_LHO
				;

				UPDATE prod_sigems.LIG_HONOR
				SET IND_LHO = w_LIG_HONOR_corr.TO_IND_LHO
				FROM w_LIG_HONOR_corr
				WHERE LIG_HONOR.ANN_LHO = w_LIG_HONOR_corr.ANN_LHO AND
					LIG_HONOR.COD_LHO = w_LIG_HONOR_corr.COD_LHO AND
					LIG_HONOR.IND_LHO = w_LIG_HONOR_corr.IND_LHO AND
					w_LIG_HONOR_corr.TO_IND_LHO > 0
				;


				UPDATE prod_sigems.LIG_CLINI
					SET SER_LCL = '*CDL'
				FROM
				(
				SELECT ANN_LCL, COD_LCL
				FROM prod_sigems.LIG_CLINI
				JOIN 
					(SELECT ANN_DOS2 AS ANN_DOS2_fac,
						COD_DOS2 AS COD_DOS2_fac
					FROM prod_sigems.DOS2
					WHERE ETA_DOS2 >= 4
					GROUP BY 1,2
					) subview ON
						ANN_LCL = ANN_DOS2_fac AND
						COD_LCL = COD_DOS2_fac
				LEFT JOIN prod_sigems.DOS2 ON 
					ANN_DOS2 = ANN_LCL AND
					COD_DOS2 = COD_LCL AND
					IND_DOS2 = IND_LCL
					WHERE IND_LCL = 0 AND 
						COD_DOS2 IS NULL
						GROUP BY 1,2
				) subview
				WHERE LIG_CLINI.ANN_LCL = subview.ANN_LCL AND
					LIG_CLINI.COD_LCL = subview.COD_LCL AND
					LIG_CLINI.IND_LCL = 0
				;
				
				UPDATE prod_sigems.LIG_HONOR
					SET SER_LHO = '*CDL'
				FROM
				(
				SELECT ANN_LHO, COD_LHO
				FROM prod_sigems.LIG_HONOR
				JOIN 
					(SELECT ANN_DOS2 AS ANN_DOS2_fac,
						COD_DOS2 AS COD_DOS2_fac
					FROM prod_sigems.DOS2
					WHERE ETA_DOS2 >= 4
					GROUP BY 1,2
					) subview ON
						ANN_LHO = ANN_DOS2_fac AND
						COD_LHO = COD_DOS2_fac
				LEFT JOIN prod_sigems.DOS2 ON 
					ANN_DOS2 = ANN_LHO AND
					COD_DOS2 = COD_LHO AND
					IND_DOS2 = IND_LHO
					WHERE IND_LHO = 0 AND 
						COD_DOS2 IS NULL
						GROUP BY 1,2
				) subview
				WHERE LIG_HONOR.ANN_LHO = subview.ANN_LHO AND
					LIG_HONOR.COD_LHO = subview.COD_LHO AND
					LIG_HONOR.IND_LHO = 0
				;
			
				-- Correction doublons
				UPDATE prod_sigems.dossier_x 
				SET ANN_DOX = 'KO'
				FROM
				(
				select ann_dox, cod_dox, min(CTID) AS koctid from prod_sigems.dossier_x
				group by 1,2
				having count(*) > 1
				) subview
				where CTID = koctid;
                
                UPDATE prod_sigems.DOSSIER_Y
				SET ANNEE = 'KO'
				FROM
				(
				SELECT ANNEE, CODE, min(CTID) AS okctid 
				FROM prod_sigems.DOSSIER_Y
				GROUP BY 1,2
				HAVING count(*) > 1
				) subview
				WHERE DOSSIER_Y.ANNEE = subview.ANNEE AND
				DOSSIER_Y.CODE = subview.CODE AND
				CTID <> okctid;
				
				UPDATE prod_sigems.DOSSIER_MDT
				SET ANN_DOS = 'KO'
				FROM
				(
				SELECT ANN_DOS, COD_DOS, min(CTID) AS koctid 
				FROM prod_sigems.DOSSIER_MDT
				GROUP BY 1,2
				HAVING count(*) > 1
				) subview
				WHERE CTID = koctid;
                
                -- Correction provenance (5) pour les urgences
                UPDATE prod_sigems.DOSSIER_X
                SET ADM_DOS = CASE WHEN substr(ADM_DOS,1,1) <> '' THEN substr(ADM_DOS,1,1) ELSE '8' END || '5'
                FROM prod_sigems.DOSSIER_Y 
                WHERE DOSSIER_X.ANN_DOX = DOSSIER_Y.ANNEE AND
                    DOSSIER_X.COD_DOX = DOSSIER_Y.CODE AND
                    DOSSIER_X.ANN_DOX <> 'KO' AND
                    DOSSIER_Y.URGENCE = 'U' AND
                    substr(ADM_DOS,2,1) <> '5'
                    ;
					
				-- Correction de liens avoir farfelus
				UPDATE prod_sigems.DOS2_LIEN_AVOIR
				SET ANN = 'K'||substr(DOS2_LIEN_AVOIR.ANN,2)
				FROM
				(
				SELECT ANN, COD, IND, MAX(CASE WHEN COP_DOS2 = '4' THEN IND_DOS2 ELSE 0 END) AS IND_AVOIR_OK
				FROM prod_sigems.DOS2_LIEN_AVOIR
				LEFT JOIN prod_sigems.DOS2 ON 
					ANN = ANN_DOS2 AND
					COD = COD_DOS2 AND
					IND_AVOIR = IND_DOS2
				GROUP BY 1,2,3
				having count(*) > 1
				) subview
				WHERE DOS2_LIEN_AVOIR.ANN = subview.ANN AND
					DOS2_LIEN_AVOIR.COD = subview.COD AND
					DOS2_LIEN_AVOIR.IND = subview.IND AND
					IND_AVOIR <> IND_AVOIR_OK AND
					IND_AVOIR_OK <> 0
				;
				
				-- Correction des montants réglés (incohérences base entre factures, lignes et ecritures)
				UPDATE prod_sigems.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
				FROM prod_sigems.DOS2_LIEN_AVOIR
				WHERE ANN_DOS2 = ANN AND COD_DOS2 = COD AND IND_DOS2 = IND_AVOIR AND
					(
					SR1_DOS2 <> SJ1_DOS2 OR
					SR2_DOS2 <> SJ2_DOS2 OR
					SR3_DOS2 <> SJ3_DOS2 OR
					HR1_DOS2 <> HO1_DOS2 OR
					HR2_DOS2 <> HO2_DOS2 OR
					HR3_DOS2 <> HO3_DOS2
					)
				;


				UPDATE prod_sigems.DOS2 DOS2F SET
					HR1_DOS2 = 0-DOS2A.HR1_DOS2,
					HR2_DOS2 = 0-DOS2A.HR2_DOS2,
					HR3_DOS2 = 0-DOS2A.HR3_DOS2
				FROM prod_sigems.DOS2_LIEN_AVOIR
					JOIN prod_sigems.DOS2 DOS2A ON DOS2A.ANN_DOS2 = ANN AND DOS2A.COD_DOS2 = COD AND DOS2A.IND_DOS2 = IND_AVOIR
				WHERE DOS2F.ANN_DOS2 = ANN AND DOS2F.COD_DOS2 = COD AND DOS2F.IND_DOS2 = IND AND
					NOT (DOS2F.HR1_DOS2 = 0-DOS2A.HR1_DOS2 AND DOS2F.HR2_DOS2 = 0-DOS2A.HR2_DOS2 AND DOS2F.HR3_DOS2 = 0-DOS2A.HR3_DOS2) AND
					(DOS2A.HR1_DOS2 <> 0 OR DOS2A.HR2_DOS2 <> 0 OR DOS2A.HR3_DOS2 <> 0)
					
				;



				UPDATE prod_sigems.DOS2 DOS2F SET
					SR1_DOS2 = 0-DOS2A.SR1_DOS2,
					SR2_DOS2 = 0-DOS2A.SR2_DOS2,
					SR3_DOS2 = 0-DOS2A.SR3_DOS2
				FROM prod_sigems.DOS2_LIEN_AVOIR
					JOIN prod_sigems.DOS2 DOS2A ON DOS2A.ANN_DOS2 = ANN AND DOS2A.COD_DOS2 = COD AND DOS2A.IND_DOS2 = IND_AVOIR
				WHERE DOS2F.ANN_DOS2 = ANN AND DOS2F.COD_DOS2 = COD AND DOS2F.IND_DOS2 = IND AND
					NOT (DOS2F.SR1_DOS2 = 0-DOS2A.SR1_DOS2 AND DOS2F.SR2_DOS2 = 0-DOS2A.SR2_DOS2 AND DOS2F.SR3_DOS2 = 0-DOS2A.SR3_DOS2) AND
					(DOS2A.SR1_DOS2 <> 0 OR DOS2A.SR2_DOS2 <> 0 OR DOS2A.SR3_DOS2 <> 0)
				;


				UPDATE prod_sigems.LIG_CLINI SET
					MR1_LCL = ML1_LCL
				FROM prod_sigems.DOS2
				WHERE ANN_DOS2 = ANN_LCL AND
					COD_DOS2 = COD_LCL AND
					IND_DOS2 = IND_LCL AND
					SR1_DOS2 = SJ1_DOS2 AND
					SR1_DOS2 <> 0 AND
					MR1_LCL <> ML1_LCL
				;

				UPDATE prod_sigems.LIG_CLINI SET
					MR2_LCL = ML2_LCL
				FROM prod_sigems.DOS2
				WHERE ANN_DOS2 = ANN_LCL AND
					COD_DOS2 = COD_LCL AND
					IND_DOS2 = IND_LCL AND
					SR2_DOS2 = SJ2_DOS2 AND
					SR2_DOS2 <> 0 AND
					MR2_LCL <> ML2_LCL
				;

				UPDATE prod_sigems.LIG_CLINI SET
					MR3_LCL = ML3_LCL
				FROM prod_sigems.DOS2
				WHERE ANN_DOS2 = ANN_LCL AND
					COD_DOS2 = COD_LCL AND
					IND_DOS2 = IND_LCL AND
					SR3_DOS2 = SJ3_DOS2 AND
					SR3_DOS2 <> 0 AND
					MR3_LCL <> ML3_LCL
				;




				UPDATE prod_sigems.LIG_HONOR SET
					MR1_LHO = ML1_LHO
				FROM prod_sigems.DOS2
				WHERE ANN_DOS2 = ANN_LHO AND
					COD_DOS2 = COD_LHO AND
					IND_DOS2 = IND_LHO AND
					HR1_DOS2 = HO1_DOS2 AND
					HR1_DOS2 <> 0 AND
					MR1_LHO <> ML1_LHO
				;

				UPDATE prod_sigems.LIG_HONOR SET
					MR2_LHO = ML2_LHO
				FROM prod_sigems.DOS2
				WHERE ANN_DOS2 = ANN_LHO AND
					COD_DOS2 = COD_LHO AND
					IND_DOS2 = IND_LHO AND
					HR2_DOS2 = HO2_DOS2 AND
					HR2_DOS2 <> 0 AND
					MR2_LHO <> ML2_LHO
				;

				UPDATE prod_sigems.LIG_HONOR SET
					MR3_LHO = ML3_LHO
				FROM prod_sigems.DOS2
				WHERE ANN_DOS2 = ANN_LHO AND
					COD_DOS2 = COD_LHO AND
					IND_DOS2 = IND_LHO AND
					HR3_DOS2 = HO3_DOS2 AND
					HR3_DOS2 <> 0 AND
					MR3_LHO <> ML3_LHO
				;

				UPDATE prod_sigems.DOS2
				SET SR1_DOS2 = MR1_DOS2
				FROM
				(
				SELECT ANN_LCL, COD_LCL, IND_LCL,
					SUM(MR1_LCL) AS MR1_DOS2
				FROM prod_sigems.DOS2
				JOIN prod_sigems.LIG_CLINI ON
					ANN_DOS2 = ANN_LCL AND
					COD_DOS2 = COD_LCL AND
					IND_DOS2 = IND_LCL AND
					PRO_LCL <> 'ECAC'
				GROUP BY 1,2,3
				HAVING MAX(SR1_DOS2) <> SUM(MR1_LCL)
				) subview
				WHERE ANN_DOS2 = ANN_LCL AND
					COD_DOS2 = COD_LCL AND
					IND_DOS2 = IND_LCL
				;

				UPDATE prod_sigems.DOS2
				SET SR2_DOS2 = MR2_DOS2
				FROM
				(
				SELECT ANN_LCL, COD_LCL, IND_LCL,
					SUM(MR2_LCL) AS MR2_DOS2
				FROM prod_sigems.DOS2
				JOIN prod_sigems.LIG_CLINI ON
					ANN_DOS2 = ANN_LCL AND
					COD_DOS2 = COD_LCL AND
					IND_DOS2 = IND_LCL AND
					PRO_LCL <> 'ECAC'
				GROUP BY 1,2,3
				HAVING MAX(SR2_DOS2) <> SUM(MR2_LCL)
				) subview
				WHERE ANN_DOS2 = ANN_LCL AND
					COD_DOS2 = COD_LCL AND
					IND_DOS2 = IND_LCL
				;

				UPDATE prod_sigems.DOS2
				SET SR3_DOS2 = MR3_DOS2
				FROM
				(
				SELECT ANN_LCL, COD_LCL, IND_LCL,
					SUM(MR3_LCL) AS MR3_DOS2
				FROM prod_sigems.DOS2
				JOIN prod_sigems.LIG_CLINI ON
					ANN_DOS2 = ANN_LCL AND
					COD_DOS2 = COD_LCL AND
					IND_DOS2 = IND_LCL AND
					PRO_LCL <> 'ECAC'
				GROUP BY 1,2,3
				HAVING MAX(SR3_DOS2) <> SUM(MR3_LCL)
				) subview
				WHERE ANN_DOS2 = ANN_LCL AND
					COD_DOS2 = COD_LCL AND
					IND_DOS2 = IND_LCL
				;


				UPDATE prod_sigems.DOS2
				SET HR1_DOS2 = MR1_DOS2
				FROM
				(
				SELECT ANN_LHO, COD_LHO, IND_LHO,
					SUM(MR1_LHO) AS MR1_DOS2
				FROM prod_sigems.DOS2
				JOIN prod_sigems.LIG_HONOR ON
					ANN_DOS2 = ANN_LHO AND
					COD_DOS2 = COD_LHO AND
					IND_DOS2 = IND_LHO AND
					CPH_LHO <> 'ECAH'
				GROUP BY 1,2,3
				HAVING MAX(HR1_DOS2) <> SUM(MR1_LHO)
				) subview
				WHERE ANN_DOS2 = ANN_LHO AND
					COD_DOS2 = COD_LHO AND
					IND_DOS2 = IND_LHO
				;

				UPDATE prod_sigems.DOS2
				SET HR2_DOS2 = MR2_DOS2
				FROM
				(
				SELECT ANN_LHO, COD_LHO, IND_LHO,
					SUM(MR2_LHO) AS MR2_DOS2
				FROM prod_sigems.DOS2
				JOIN prod_sigems.LIG_HONOR ON
					ANN_DOS2 = ANN_LHO AND
					COD_DOS2 = COD_LHO AND
					IND_DOS2 = IND_LHO AND
					CPH_LHO <> 'ECAH'
				GROUP BY 1,2,3
				HAVING MAX(HR2_DOS2) <> SUM(MR2_LHO)
				) subview
				WHERE ANN_DOS2 = ANN_LHO AND
					COD_DOS2 = COD_LHO AND
					IND_DOS2 = IND_LHO
				;

				UPDATE prod_sigems.DOS2
				SET HR3_DOS2 = MR3_DOS2
				FROM
				(
				SELECT ANN_LHO, COD_LHO, IND_LHO,
					SUM(MR3_LHO) AS MR3_DOS2
				FROM prod_sigems.DOS2
				JOIN prod_sigems.LIG_HONOR ON
					ANN_DOS2 = ANN_LHO AND
					COD_DOS2 = COD_LHO AND
					IND_DOS2 = IND_LHO AND
					CPH_LHO <> 'ECAH'
				GROUP BY 1,2,3
				HAVING MAX(HR3_DOS2) <> SUM(MR3_LHO)
				) subview
				WHERE ANN_DOS2 = ANN_LHO AND
					COD_DOS2 = COD_LHO AND
					IND_DOS2 = IND_LHO
				;
				
				
				-- Références à des factures inexistantes
				DROP TABLE IF EXISTS w_DOS_ECRIT_err;
				CREATE TEMP TABLE w_DOS_ECRIT_ERR AS
				SELECT DOS_ECRIT.*, NULL::numeric AS IND_DOS2
				FROM prod_sigems.DOS_ECRIT
				LEFT JOIN prod_sigems.DOS2 ON
					ANNEE = DOS2.ANN_DOS2 AND
					CODE = DOS2.COD_DOS2 AND
					INDICE = DOS2.IND_DOS2
				WHERE DOS2.ANN_DOS2 IS NULL
				;

				UPDATE prod_sigems.DOS_ECRIT
				SET INDICE = subview.IND_DOS2
				FROM
				(
				SELECT ANNEE, CODE, INDICE, MAX(DOS2.IND_DOS2) AS IND_DOS2
				FROM prod_sigems.DOS2
				JOIN w_DOS_ECRIT_err ON 
					ANNEE = DOS2.ANN_DOS2 AND
					CODE = DOS2.COD_DOS2
				GROUP BY 1,2,3
				) subview
				WHERE DOS_ECRIT.ANNEE = subview.ANNEE AND
					DOS_ECRIT.CODE = subview.CODE AND
					DOS_ECRIT.INDICE = subview.INDICE
				;
				
				DROP TABLE IF EXISTS w_REG2_err;
				CREATE TEMP TABLE w_REG2_ERR AS
				SELECT REG2.*, NULL::numeric AS IND_DOS2
				FROM prod_sigems.REG2
				LEFT JOIN prod_sigems.DOS2 ON
					ANN_REG2 = DOS2.ANN_DOS2 AND
					COD_REG2 = DOS2.COD_DOS2 AND
					IND_REG2 = DOS2.IND_DOS2
				WHERE DOS2.ANN_DOS2 IS NULL AND
					ANN_REG2 BETWEEN '00' AND '99'
				;

				UPDATE prod_sigems.REG2
				SET IND_REG2 = subview.IND_DOS2
				FROM
				(
				SELECT ANN_REG2, COD_REG2, IND_REG2, MAX(DOS2.IND_DOS2) AS IND_DOS2
				FROM prod_sigems.DOS2
				JOIN w_REG2_err ON 
					ANN_REG2 = DOS2.ANN_DOS2 AND
					COD_REG2 = DOS2.COD_DOS2
				GROUP BY 1,2,3
				) subview
				WHERE REG2.ANN_REG2 = subview.ANN_REG2 AND
					REG2.COD_REG2 = subview.COD_REG2 AND
					REG2.IND_REG2 = subview.IND_REG2
				;
				
				]]></sqlcmd>
		</NODE>
				
		<NODE label="Préparations encaissements et comptes clients">
			<sqlcmd><![CDATA[
			
				

				
				-- Table de travail règlements clinique
				
				DROP TABLE IF EXISTS w_REG4;
				CREATE TEMP TABLE w_REG4 AS
				SELECT *
				FROM prod_sigems.REG
				JOIN prod_sigems.REG4 ON NUM_REG4 = SER_REG;

				CREATE INDEX w_REG4_i1
				  ON w_REG4
				  USING btree
				  (NUM_CLI);
				  
				ANALYSE w_REG4;


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

				CREATE INDEX w_REG3_i1
				  ON w_REG3
				  USING btree
				  (LHO_REG3);

				ANALYSE w_REG3;
				

				
				]]></sqlcmd>
		</NODE>
				
		<NODE label="Identification des séjours">
			<sqlcmd><![CDATA[
				
				-- 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,
					GREATEST(date(DT_MOUV_SIGEMS),CASE WHEN date_part('hour', DT_SIGEMS) < 9 THEN DATE(DT_SIGEMS - INTERVAL '1 day') ELSE date(DT_SIGEMS) END) AS now_sigems,
					GREATEST(date(DT_MOUV_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_sigems.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
					) sub,
					(
					SELECT 1,MAX(DAE_SEJ) as DT_MOUV_SIGEMS
					FROM prod_sigems.SEJOUR
					WHERE 1=1
						AND ANN_SEJ != 'PA'
						AND DAE_SEJ <= now()
					GROUP BY 1
					) sub2;


				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,
                    ''::text AS CMD_DOS
				FROM prod_sigems.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_sigems.SUPPRESSION_DOS 
				WHERE ANN_SELECT = ANNEE AND
					COD_SELECT = CODE;
					
					
				-- Séances pré saisies à tord
                DELETE FROM w_DOSSIER_SELECT
				USING
				(
				SELECT ANN_DOS, COD_DOS
				FROM prod_sigems.DOSSIER
				JOIN prod_sigems.service ON SER_DOS = COD_SER
				LEFT JOIN prod_sigems.SEJOUR ON ANN_SEJ = ANN_DOS AND COD_SEJ = COD_DOS
				LEFT JOIN prod_sigems.DOS2 ON ANN_DOS2 = ANN_DOS AND COD_DOS2 = COD_DOS
				LEFT JOIN prod_sigems.LIG_CLINI ON ANN_LCL = ANN_DOS AND COD_LCL = COD_DOS
				LEFT JOIN prod_sigems.LIG_HONOR ON ANN_LHO = ANN_DOS AND COD_LHO = COD_DOS
				WHERE DMT_SER IN ('198','302') AND
					ANN_DOS <> 'PA' AND
					DSO_DOS IS NULL AND
					DEN_DOS <= now() - interval '10 days' AND
					ANN_SEJ IS NULL AND
					ANN_DOS2 IS NULL AND
					ANN_LCL IS NULL AND
					ANN_LHO IS NULL 
				) subview
				WHERE ANN_SELECT = ANN_DOS AND
					COD_SELECT = COD_DOS
                ;     
                           
                       
				INSERT INTO w_DOSSIER_SELECT
				SELECT 
					ANN_DOS2, 
					COD_DOS2,
					ANN_DOS2 || to_char(COD_DOS2,'FM900000'),
					0::text AS type_t2a,
					0::text AS est_budget_global,
					0::text AS avec_facturation_intermediaire,
                    ''::text AS CMD_DOS
				FROM prod_sigems.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'
					)
				ORDER BY 1,2;



				INSERT INTO w_DOSSIER_SELECT
				SELECT 
					ANN_LCL, 
					COD_LCL,
					ANN_LCL || to_char(COD_LCL,'FM900000'),
					0::text AS type_t2a,
					0::text AS est_budget_global,
					0::text AS avec_facturation_intermediaire,
                    ''::text AS CMD_DOS
				FROM
				(
				SELECT ANN_LCL, COD_LCL FROM prod_sigems.LIG_CLINI
									JOIN prod_sigems.REG4 ON NUM_LCL = NUM_CLI
									JOIN prod_sigems.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_sigems.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 dossiers pour les services ignorés
				DELETE FROM w_DOSSIER_SELECT 
				USING prod_sigems.DOSSIER
				JOIN activite[PX].t_services_facturation ON (DOSSIER.SER_DOS || '_' || MDT_DOS) = t_services_facturation.code_original
				WHERE ANN_SELECT = ANN_DOS AND
					COD_SELECT = COD_DOS AND
					t_services_facturation.type_sejour = '9'
                ;
				
				-- Suppression des prévus non rentrés ou prévus dans plus d'un mois
				DELETE FROM w_DOSSIER_SELECT 
				USING prod_sigems.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_sigems.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);
					
					


				-- Montants 10% SSR sans quantité
				UPDATE prod_sigems.LIG_CLINI
					SET QTE_LCL = QTE_LCL * (date(DFI_LCL) - date(DDE_LCL) + 1)
					WHERE PRO_LCL IN ('MPJ','MPHJ') AND
						date(DFI_LCL) > date(DDE_LCL) AND
						QTE_LCL IN (1, -1)
				;
					
					
			]]></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, 
					COD_PAT 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_sigems.PATIENT
					JOIN (SELECT CPH_DOS, ANN_DOS, COD_DOS FROM prod_sigems.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
				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(NNA_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, 
					code_sexe = CASE WHEN SEX_PAT IN ('F') THEN '2' ELSE '1' END
				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
						p_patients.nom_naissance IS DISTINCT FROM NNA_PAT OR
						p_patients.date_naissance IS DISTINCT FROM date(DNA_PAT) OR
						p_patients.code_sexe IS DISTINCT FROM CASE WHEN SEX_PAT IN ('F') THEN '2' ELSE '1' END
					);

				INSERT INTO activite[PX].p_patients(finess, no_patient, nom, prenom, nom_naissance, date_naissance, code_sexe)
				SELECT '', w_PATIENT.no_patient, MAX(NOM_PAT), MAX(PRE_PAT), MAX(NNA_PAT), MAX(DNA_PAT), MAX(CASE WHEN SEX_PAT IN ('F') THEN '2' ELSE '1' END)
				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_sigems.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_sigems.UN_RUM
						JOIN prod_sigems.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_sigems.UN_RUM
						LEFT JOIN prod_sigems.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_sigems.UN_RUM
					JOIN prod_sigems.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_sigems.LIG_CLINI
				WHERE PRO_LCL IN ('SE1', 'SE2', 'SE3', 'SE4','SE5', 'SE6', 'SE7', '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;	
				
				INSERT INTO activite.t_divers(code, texte, valeur, description)
				SELECT 'SIGETAGRP','Prise en compte état groupage','2','2=Ne traiter que les dossiers validés (si pas validé = equivalent pas groupe)'
				WHERE 'SIGETAGRP' NOT IN (SELECT code FROM activite.t_divers)
                ;

				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 '00010101' 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 '00010101' END]))[2]::date AS DATE_VALIDATION
				FROM prod_sigems.CONTROLE_DIM
				WHERE ETAT <> 2
				GROUP BY 1,2
				ORDER BY 1,2;
				
				UPDATE w_CONTROLE_DIM
				SET DATE_VALIDATION = NULL 
				WHERE DATE_VALIDATION = '00010101'
				;

				UPDATE w_CONTROLE_DIM
				SET DATE_GROUPAGE = NULL 
				WHERE DATE_GROUPAGE = '00010101'
				;

				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 = CASE WHEN DATE_VALIDATION >= DATE_GROUPAGE THEN DATE_VALIDATION ELSE NULL END
				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 CLE_GHM = '', 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
					(CLE_GHM <> '' OR GHS <> 0 OR GHS_BEBE1 <> 0) ;

				UPDATE w_GHS_VALORISE
				SET CLE_GHM = '', GHS = 0, GHS_BEBE1 = 0
				WHERE (ANN_GHSV ,COD_GHSV ) NOT IN (SELECT ANN_CTLD,COD_CTLD FROM w_CONTROLE_DIM)
					AND GHS != 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_sigems.DOSSIER
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_DOS = ANN_SELECT AND COD_DOS = COD_SELECT
					LEFT JOIN prod_sigems.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_sigems.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_sigems.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', 'SE7', 'ATU', 'FPU', 'FFM')
				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_sigems.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')*100 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')*100 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 LENGTH(MSO_DOS) = 2 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_sigems.DOSSIER
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_DOS = ANN_SELECT AND COD_DOS = COD_SELECT
					LEFT JOIN prod_sigems.DOSSIER_X ON DOSSIER.ANN_DOS = DOSSIER_X.ANN_DOX AND DOSSIER.COD_DOS = DOSSIER_X.COD_DOX AND CHP_DOX <> ''
					LEFT JOIN prod_sigems.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_sigems.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;
                
                -- Code chambre particulière demandée selon historique facturation
                UPDATE w_DOSSIER
				SET CHP_DOX = 'P*'||CHP_DOX
				WHERE CHP_DOX <> '' AND CHP_DOX NOT LIKE 'P%' AND CHP_DOX <> 'CC' AND
					CHP_DOX IN 
					(
					SELECT 
						CHP_DOX
					FROM
					(
					SELECT CHP_DOX,
						count(DISTINCT ANN_DOX||to_char(COD_DOX,'FM900000')),
						count(DISTINCT CASE WHEN ACT_PRC IS NOT NULL THEN ANN_DOX||to_char(COD_DOX,'FM900000') ELSE NULL END),
						base.cti_division(
							count(DISTINCT CASE WHEN ACT_PRC IS NOT NULL THEN ANN_DOX||to_char(COD_DOX,'FM900000') ELSE NULL END)::numeric , count(DISTINCT ANN_DOX||to_char(COD_DOX,'FM900000'))) AS pct
					FROM prod_sigems.dossier_x
					JOIN prod_sigems.dos2 ON ann_dox = ann_dos2 AND cod_dox = COD_DOS2 AND ETA_DOS2 >= 4
					LEFT JOIN prod_sigems.lig_clini ON ANN_DOx = ANN_LCL AND COD_LCL = COD_DOX 
					LEFT JOIN prod_sigems.prod_clini ON PRO_LCL = COD_PRC AND (ACT_PRC LIKE 'CP%' OR ACT_PRC = 'SHO')
					WHERE CHP_DOX <> '' AND CHP_DOX NOT LIKE 'P%' AND CHP_DOX <> 'CC'
					GROUP BY 1
					ORDER BY 1
					) subview
					WHERE pct >= 0.75
					)
                ;
				
                UPDATE w_DOSSIER SET
					HEU_DOS = HEU_DOS + HEU_DOS_MIN,
					w_DHSO_DOS = to_timestamp(to_char(COALESCE(DSO_DOS,'20991231'),'YYYYMMDD') || to_char(HEU_DOS+HEU_DOS_MIN,'FM0000'),'YYYYMMDDHH24MI')::timestamp without time zone
				FROM
				(
					SELECT ANN_DOS, COD_DOS, substr(MAX(HEU_SEJ||MIN_SEJ),3,2)::numeric AS HEU_DOS_MIN
					FROM prod_sigems.dossier
					JOIN prod_sigems.sejour ON
						ann_dos = ann_sej AND
						COD_DOS = COD_SEJ
					WHERE DSO_DOS < now() AND
						DSO_DOS = DAS_SEJ AND
						DSO_DOS IS NOT NULL AND
						ANN_DOS NOT LIKE 'P%' 
					GROUP BY 1,2
					HAVING substr(MAX(HEU_SEJ||MIN_SEJ),3,2) <> '00'
				) subview
				WHERE w_DOSSIER.ANN_DOS = subview.ANN_DOS AND
					w_DOSSIER.COD_DOS = subview.COD_DOS
				;
				
				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);



				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', '9') 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 AND type_tiers_payant = '1';

				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 AND type_tiers_payant = '2';

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

				-- Si forcage service séance et groupage dans une autre cmd,
				UPDATE w_DOSSIER_key
				SET  type_sejour_force = '0'
				WHERE type_sejour_force = '5' AND
					substr(cle_ghm,1,2) BETWEEN '01' AND '27'
					;



				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, 
					CPH_DOS as no_patient, 
					DEN_DOS as date_entree, 
					MIN_DOS * 100 as heure_entree, 
					DSO_DOS as date_sortie, 
					HEU_DOS * 100 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%' AND DSO_DOS <= date(now())THEN 1 ELSE 0 END::numeric as code_sorti, 
					CASE 
						WHEN SEJ_DOS LIKE 'P%' THEN 1::numeric 
						WHEN DEN_DOS > date(now()) 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 ANY(string_to_array(t_divers.valeur, ',')) 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 '8'::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,
					COALESCE(SUBSTR(MSO_DOS,1,1)::character(1), '8'::text) as mode_sortie,
					COALESCE(SUBSTR(MSO_DOS,2,1)::character(1), '0'::text) 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
					JOIN activite.t_divers ON t_divers.code = 'SIGEMS_CHPDOX'
					LEFT JOIN prod_sigems.DOSSIER_X ON w_DOSSIER.ANN_DOS = DOSSIER_X.ANN_DOX AND w_DOSSIER.COD_DOS = DOSSIER_X.COD_DOX
					LEFT JOIN prod_sigems.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
				;
					

				--Récupération de l'heure exacte d'entrée via le timestamp du premier mouvement du séjour 
				UPDATE w_sejours
				SET heure_entree = (TO_CHAR(dt_debut, 'HH24MI') || '00')::numeric
				FROM prod_sigems.SEJOUR
				WHERE dt_debut IS NOT NULL AND 
					w_sejours.no_sejour = ANN_SEJ || to_char(COD_SEJ, 'FM900000')
				;




				-- 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');
                    
                -- Forcage '9' pour Séjours ABANDON (prestation ABAN)
                UPDATE w_sejours
                SET type_sejour = '9'
                WHERE type_sejour <> '9' AND no_sejour IN
                (
                SELECT ANN_LCL || to_char(COD_LCL,'FM900000')
				FROM prod_sigems.DOS2 
				JOIN
				(
				SELECT ANN_LCL, COD_LCL
				FROM prod_sigems.LIG_CLINI
				JOIN prod_sigems.DOS2 ON ANN_DOS2 = ANN_LCL AND COD_DOS2 = COD_LCL AND IND_DOS2 = IND_LCL
				WHERE PRO_LCL = 'ABAN' AND ETA_DOS2 >= 4
				GROUP BY 1,2
				) subview ON ANN_DOS2 = ANN_LCL AND COD_DOS2 = COD_LCL 
				GROUP BY 1
				HAVING SUM(SJ1_DOS2+SJ2_DOS2+SJ2_DOS2+HO1_DOS2+HO2_DOS2+HO3_DOS2) = 0
                )
                ;
					
				-- Calcul dates sortie prévisionnelles
				
				DROP TABLE IF EXISTS w_DOSSIER_DMS;
				CREATE TEMP TABLE w_DOSSIER_DMS AS
				SELECT SER_DOS, round(AVG(date(DSO_DOS) - date(DEN_DOS)),0) AS dms
				FROM prod_sigems.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_sigems.DOSSIER ON ANN_SELECT = ANN_DOS AND COD_SELECT = COD_DOS
				JOIN w_DOSSIER_DMS ON DOSSIER.SER_DOS = w_DOSSIER_DMS.SER_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');
									
				-- transferts d'établissements
				INSERT INTO base.t_etablissements (code, texte, texte_court)
				SELECT
					NUM_FINESS,
					NOM,
					NOM
				FROM 
					prod_sigems.ETAB_CONV
				WHERE 1=1 AND
					CODE IN (SELECT DISTINCT ETAB FROM prod_sigems.DOSSIER_Y) AND
					NUM_FINESS NOT IN (SELECT code FROM base.t_etablissements)
				;
				
				INSERT INTO base.t_etablissements (code, texte, texte_court)
				SELECT
					NUM_FINESS,
					NOM,
					NOM
				FROM 
					prod_sigems.ETAB_CONV
				WHERE 1=1 AND
					CODE IN (SELECT DISTINCT CH2 FROM prod_sigems.DOSSIER_Y) AND
					NUM_FINESS NOT IN (SELECT code FROM base.t_etablissements)
				;
				
				INSERT INTO activite[PX].p_sejours_transferts (sejour_id, provenance_id, destination_id)
				SELECT 
					p_sejours.oid,
					MIN(CASE WHEN mode_entree = 7 THEN provenance.oid ELSE null END) AS provenance_id,
					MIN(CASE WHEN mode_sortie = 7 THEN destination.oid ELSE null END) AS destination_id
				FROM
					activite[PX].p_sejours
					JOIN prod_sigems.DOSSIER_Y ON ANNEE || to_char(DOSSIER_Y.CODE,'FM900000') = no_sejour
					LEFT JOIN prod_sigems.ETAB_CONV PROV ON CH2 = PROV.CODE
					LEFT JOIN prod_sigems.ETAB_CONV DEST ON ETAB = DEST.CODE
					LEFT JOIN base.t_etablissements provenance ON PROV.NUM_FINESS = provenance.code
					LEFT JOIN base.t_etablissements destination ON DEST.NUM_FINESS = destination.code
				WHERE 1!=1 OR
					ETAB != '' OR
					CH2 != ''
				GROUP BY 1
				;
				
				-- assurance
				INSERT INTO activite[PX].p_sejours_assurance(
					sejour_id, 
					nom_assure, 
					prenom_assure, 
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					matricule_1, 
					tiers_payant_2_id, 
					matricule_2, 
					tiers_payant_22_id, 
					matricule_22
					)
				SELECT 
					p_sejours.oid AS sejour_id,
					''::text AS nom_assure, 
					''::text prenom_assure,
					MAX(p_sejours.tiers_payant_0_id),
					MAX(p_sejours.tiers_payant_1_id),
					MAX(substr(NC1_DOS,1,13)) AS matricule_1,
					MAX(p_sejours.tiers_payant_2_id),
					MAX(CASE WHEN NC2_DOS <> '' THEN NC2_DOS ELSE substr(NC1_DOS,1,13) END) AS matricule_2,
					MAX(p_sejours.tiers_payant_22_id),
					''::text AS matricule_22
				FROM prod_sigems.DOSSIER
				JOIN activite[PX].p_sejours ON code_original = ANN_DOS || to_char(COD_DOS,'FM900000')
				GROUP BY 1
				;
										
			]]></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(DT_DEBUT, to_timestamp(to_char(DAE_SEJ,'YYYYMMDD') || to_char(MIN_DOS,'FM0000'),'YYYYMMDDHH24MI'),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 || MIN_SEJ,'0000'), HEU_DOS) AS HEU_SEJ,
					COALESCE(DT_FIN, to_timestamp(to_char(DAS_SEJ,'YYYYMMDD') || HEU_SEJ || MIN_SEJ,'YYYYMMDDHH24MI'),w_DHSO_DOS)::timestamp without time zone AS w_DHAS_SEJ
				FROM w_DOSSIER 
					LEFT JOIN prod_sigems.SEJOUR ON ANN_SEJ = ANN_DOS AND COD_SEJ = COD_DOS
					LEFT JOIN prod_sigems.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' OR p_sejours.type_sejour = '2') AND t_lits.chambre_particuliere = 'O' THEN '1' ELSE '0' END AS est_chambre_particuliere,
					CASE WHEN (p_sejours.type_sejour = '1' OR p_sejours.type_sejour = '2') 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_sigems.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
				SELECT base.cti_execute('INSERT INTO activite.t_divers (code, description, texte, valeur) 
					VALUES (''K15_SEANCE'',
							''Création de séances pour les actes K coefficient 15 : 0 = Jamais, 1 = Toujours, 2 = Sauf pour les séjours Hospitalisation'',
							''Règle de création de séances pour les actes K coefficient 15'',
							''1'')',1)
				WHERE (SELECT valeur FROM activite.t_divers WHERE code = 'K15_SEANCE') IS NULL;
							
				DROP TABLE IF EXISTS w_LIG_HONOR_seances;
				
				CREATE TEMP TABLE w_LIG_HONOR_seances AS
				SELECT 
					SEJ_DOS,
					date(dde_lho) AS date,
					1::numeric AS nb_seances
				FROM prod_sigems.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_sigems.PROD_HONOR ON CPH_LHO = COD_PRH
                    LEFT JOIN prod_sigems.CCAM_RUM ON LIG_HONOR.NUM_LHO = CCAM_RUM.NUM_LHO AND date(DDE_LHO) = date(CCAM_RUM.DAT)
					JOIN w_sejours ON SEJ_DOS = no_sejour
					JOIN activite.t_divers ON t_divers.code = 'K15_SEANCE'
				WHERE 
                    (
                    ACT_PRH = 'K' AND 
					(COF_LHO = 30 OR (COF_LHO = 15 AND (valeur = 1 OR (valeur = 2 AND type_sejour != 1)))) AND 
					(CPH_LHO = 'CHI' OR DMT_LHO = '302')
                    ) OR
                    CCAM_RUM.CODE = ANY(Array['JVJF003','JVJF004','JVJF008','GLLP006','GLLP007','ZZNL051','ZZNL063','ZZNL065']) OR
                    DMT_LHO = '796'
 				GROUP BY 1,2
                HAVING SUM(QTE_LHO) > 0;
					
				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;
					
				-- Séances chimio ESPIC
				DROP TABLE IF EXISTS w_LIG_CLINI_seances302;
				CREATE TEMP TABLE w_LIG_CLINI_seances302 AS
				SELECT 
					SEJ_DOS,
					p_calendrier.date AS date,
					SUM(CASE WHEN QTE_LCL > 0 THEN 1 ELSE -1 END) AS nb_seances
				FROM prod_sigems.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
				JOIN base.p_calendrier ON p_calendrier.date BETWEEN date(DDE_LCL) AND COALESCE(DFI_LCL,date(DDE_LCL + (abs(QTE_LCL)-1||' days)')::interval))
				WHERE PRO_LCL IN ('PJ') AND DMT_LCL = '302' AND QTE_LCL <> 0 
				GROUP BY 1,2
				;

				CREATE INDEX w_LIG_CLINI_seances302_i1
				  ON w_LIG_CLINI_seances302
				  USING btree
				  (SEJ_DOS);
				  
				UPDATE w_mouvements_sejour
				SET nb_seances = w_LIG_CLINI_seances302.nb_seances
				FROM w_LIG_CLINI_seances302
				WHERE w_LIG_CLINI_seances302.SEJ_DOS = w_mouvements_sejour.no_sejour AND 
					w_LIG_CLINI_seances302.date = w_mouvements_sejour.date
				;
				
				-- Selon PMSI 
				DROP TABLE IF EXISTS w_ETAT_PMSI_seances;
				CREATE TEMP TABLE w_ETAT_PMSI_seances AS
				SELECT JOINTURE, date(ETAT_PMSI.ENTREE) AS date
				FROM prod_sigems.ETAT_PMSI
				JOIN prod_sigems.UN_RUM ON NUM_RSS = JOINTURE
				JOIN prod_sigems.PMSI_GHM ON UN_RUM.GHM = PMSI_GHM.CODE_GHM
				WHERE CLE_GHM LIKE '28%'
					AND JOINTURE NOT IN (SELECT no_sejour FROM w_mouvements_sejour WHERE nb_seances > 0 )
				;
				
				UPDATE w_mouvements_sejour
				SET nb_seances = 1
				FROM  w_ETAT_PMSI_seances
				WHERE  w_ETAT_PMSI_seances.JOINTURE = w_mouvements_sejour.no_sejour AND 
					 w_ETAT_PMSI_seances.date = w_mouvements_sejour.date
				;
					
				-- Séances dialyse	
				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_sigems.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;			

				WITH update_sejours as (
					SELECT
						w_mouvements_sejour.no_sejour,
						w_mouvements_sejour.date
					FROM w_mouvements_sejour
					JOIN activite[PX].p_sejours ON  w_mouvements_sejour.no_sejour = p_sejours.no_sejour AND w_mouvements_sejour.date = p_sejours.date_entree AND p_sejours.type_sejour = '5'
					WHERE 1=1
						AND nb_seances = 0
						AND w_mouvements_sejour.no_sejour NOT IN (SELECT no_sejour FROM w_mouvements_sejour WHERE nb_seances > 0 )
				)
				UPDATE w_mouvements_sejour
				SET nb_seances = 1
				FROM update_sejours
                WHERE 1=1
					AND w_mouvements_sejour.no_sejour = update_sejours.no_sejour
					AND w_mouvements_sejour.date = update_sejours.date;
				
				-- 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" && "[ENV_WITHPMSI]" == "1"
			]]></condition>
			
			<sqlcmd><![CDATA[
                
                    -- Modification numeros de sejour pmsi selon activite
                    
                    -- Attention aux rss multiples avec seances, modification no sejour administratif PMSI pour enlever date
                    UPDATE pmsi.p_rss
                    SET no_sejour_administratif = trim(substr(trim(no_sejour_administratif),1,length(trim(no_sejour_administratif))-8))
                    WHERE length(trim(no_sejour_administratif)) > 12 AND
                        substr(trim(no_sejour_administratif),length(trim(no_sejour_administratif))-7,8) = to_char(date_entree,'YYYYMMDD')
                        ;
                        
                    UPDATE pmsi.p_rss
                    SET no_sejour_administratif = trim(substr(trim(no_sejour_administratif),1,length(trim(no_sejour_administratif))-8))
                    WHERE length(trim(no_sejour_administratif)) > 12 AND
                        substr(trim(no_sejour_administratif),length(trim(no_sejour_administratif))-7,8) = '00000000'
                        ;
                    
                    -- CAS des sejours pmsi avec 8 caracteres alors qu'ils sont à 7 dans activite               
                    UPDATE pmsi.p_rss
                    SET no_sejour_administratif = trim(substr(no_sejour_administratif,1,2) || substr(no_sejour_administratif,4))
                    FROM activite[PX].p_sejours
                    WHERE length(trim(no_sejour_administratif)) = 8 AND
                        length(no_sejour) = 7 AND
                        substr(no_sejour_administratif,3,1) = '0' AND
                        trim(substr(no_sejour_administratif,1,2) || substr(no_sejour_administratif,4)) = no_sejour AND 
                        (
                        p_rss.date_entree BETWEEN p_sejours.date_entree AND  p_sejours.date_sortie OR
                        p_rss.date_sortie BETWEEN p_sejours.date_entree AND  p_sejours.date_sortie
                        )
                    ;
                    
                    -- Séjours bébés préfixés par 1,2,3
                    UPDATE pmsi.p_rss
                    SET no_sejour_administratif = trim(substr(no_sejour_administratif,2))
                    FROM activite[PX].p_sejours
                    WHERE substr(no_sejour_administratif,1,1) IN ('1','2','3') AND
                        p_rss.date_naissance BETWEEN p_rss.date_entree AND p_rss.date_sortie AND
                        trim(substr(no_sejour_administratif,2)) = no_sejour AND 
                        (
                        p_rss.date_entree BETWEEN p_sejours.date_entree AND  p_sejours.date_sortie OR
                        p_rss.date_sortie BETWEEN p_sejours.date_entree AND  p_sejours.date_sortie
                        )
                    ;
                    UPDATE pmsi.p_rss
                    SET no_sejour_administratif = trim(substr(no_sejour_administratif,2,2)||substr(no_sejour_administratif,5))
                    FROM activite[PX].p_sejours
                    WHERE substr(no_sejour_administratif,1,1) IN ('1','2','3') AND
                        substr(no_sejour_administratif,4,1) = '0' AND
                        length(trim(no_sejour_administratif)) = 9 AND
                        length(no_sejour) = 7 AND
                        p_rss.date_naissance BETWEEN p_rss.date_entree AND p_rss.date_sortie AND
                        trim(substr(no_sejour_administratif,2,2)||substr(no_sejour_administratif,5)) = no_sejour AND 
                        (
                        p_rss.date_entree BETWEEN p_sejours.date_entree AND  p_sejours.date_sortie OR
                        p_rss.date_sortie BETWEEN p_sejours.date_entree AND  p_sejours.date_sortie
                        )
                    ;

                    -- S'il en reste (pb de dates pmsi ou activité discordantes)
                    UPDATE pmsi.p_rss
                    SET no_sejour_administratif = trim(substr(no_sejour_administratif,1,2) || substr(no_sejour_administratif,4))
                    FROM activite[PX].p_sejours
                    JOIN activite[PX].p_patients ON p_sejours.no_patient = p_patients.no_patient
                    WHERE length(trim(no_sejour_administratif)) = 8 AND
                        length(no_sejour) = 7 AND
                        substr(no_sejour_administratif,3,1) = '0' AND
                        trim(substr(no_sejour_administratif,1,2) || substr(no_sejour_administratif,4)) = no_sejour AND 
                        p_rss.date_naissance = p_patients.date_naissance AND
                        trim(no_sejour_administratif) not in (select no_sejour from activite[PX].p_sejours)
                    ;



                    ANALYSE pmsi.p_rss
                    ;

			]]></sqlcmd>
		</NODE>
		
		
		<NODE label="Lien PMSI">
		
			<condition><![CDATA[
				"[TYPE_TRAITEMENT]" == "E"
			]]></condition>
			
			<sqlcmd><![CDATA[
                
					SELECT activite[PX].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_sigems.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_sigems.LIG_CLINI
					JOIN prod_sigems.REG4 ON NUM_LCL = NUM_CLI
					JOIN prod_sigems.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_sigems.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_sigems.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_sigems.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_sigems.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_sigems.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_sigems.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,
                    CMD_DOS = CASE WHEN ghm_id > 0 AND substr(t_ghm.code,1,2) <> '90' THEN substr(t_ghm.code,1,2) ELSE '' 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 service_facturation_id = t_services_facturation.oid
                JOIN base.t_ghm ON ghm_id = t_ghm.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, 
                    CASE WHEN DMT_ANA NOT LIKE '@%' THEN DMT_ANA ELSE '***' END AS DMT_ANA, 
                    CASE WHEN DMT_ANA LIKE '@%' THEN substr(DMT_ANA,2) ELSE '' END AS CMD_ANA, 
                    MDT_ANA, 
                    SER_ANA, 
                    MAX(CPT_ANA) AS CPT_ANA
				FROM prod_sigems.ANALYG
				WHERE CPT_ANA <> ''
				GROUP BY 1,2,3,4,5
				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.*,
					''::text AS CODE_UCD,
					0::bigint AS ucd_id,
					''::text AS CODE_LPP,
					0::bigint AS lpp_id,
					CASE WHEN type_t2a = '2' AND est_budget_global = '1' THEN '1' ELSE '0' END AS BG_SSR,
					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,
					CMD_DOS,
                    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_sigems.LIG_CLINI
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LCL = ANN_SELECT AND COD_LCL = COD_SELECT
					JOIN prod_sigems.DOSSIER ON DOSSIER.ANN_DOS = ANN_LCL AND DOSSIER.COD_DOS = COD_LCL
					LEFT JOIN prod_sigems.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_sigems.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' AND
					SER_LCL <> '*CDL';
					
				UPDATE w_LIG_CLINI
				SET MDT_LCL = '04'
				WHERE MDT_LCL = '23';
				
				ANALYSE w_LIG_CLINI;
				
				UPDATE w_LIG_CLINI
				SET CODE_UCD = UCD_LCL_HON.CODE_UCD, ucd_id = t_ucd.oid
				FROM prod_sigems.UCD_LCL_HON
				JOIN base.t_ucd ON UCD_LCL_HON.CODE_UCD = t_ucd.code
				WHERE NUM_LIGNE = NUM_LCL AND
					UCD_LCL_HON.TYP = 2
				;

				UPDATE w_LIG_CLINI
				SET CODE_LPP = LCL_BIS.COD_LPP, lpp_id = t_lpp.oid
				FROM prod_sigems.LCL_BIS
				JOIN base.t_lpp ON LCL_BIS.COD_LPP = t_lpp.code
				WHERE NUM_LCL = NUM
				;
					
				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 CPT_ANA = w_ANALYG.CPT_ANA,
					key = PRO_LCL || '|' || 
						ACT_LCL ||  '|' || 
						w_ANALYG.CPT_ANA
				FROM w_ANALYG 
				WHERE PRO_LCL = PRD_ANA AND CMD_ANA = CMD_DOS  AND CMD_ANA <> '' AND MDT_ANA = '' AND SER_ANA = '' AND
					w_LIG_CLINI.CPT_ANA IS DISTINCT FROM w_ANALYG.CPT_ANA;	
				  

				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 activite.t_prestations SET
					code = ACT_LCL,
					texte = ACT_LCL,
					texte_court = ACT_LCL
				FROM w_LIG_CLINI_keys
				WHERE code_original = ACT_LCL AND
					(
						code IS DISTINCT FROM ACT_LCL OR
						texte IS DISTINCT FROM ACT_LCL OR
						texte_court IS DISTINCT FROM 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_DOS2_TP;
				CREATE TEMP TABLE w_DOS2_TP AS
				SELECT ANN_DOS2 AS ANN_DOS2_TP, 
					COD_DOS2 AS COD_DOS2_TP, 
					base.cti_array_accum(DISTINCT CASE WHEN CP1_DOS2 <> '' THEN CP1_DOS2 ELSE 'ABCDEFG1' END) AS CP1_DOS2_array,
					base.cti_array_accum(DISTINCT CASE WHEN CA2_DOS2 <> '' THEN CA2_DOS2 ELSE 'ABCDEFG1' END) AS CA2_DOS2_array
				FROM prod_sigems.DOS2
				WHERE ANN_DOS2 <> '' 
				GROUP BY 1,2
				HAVING 
					(
					count(DISTINCT CASE WHEN CP1_DOS2 <> '' THEN CP1_DOS2 ELSE NULL END) > 1 OR
					count(DISTINCT CASE WHEN CA2_DOS2 <> '' THEN CA2_DOS2 ELSE NULL END) > 1
					)
				;
				
				
				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,
					CAI_REG,
					MONT + TVA AS MNT_REG,
					CASE 
					WHEN CAI_REG = '99999999' THEN '3'
					WHEN CAI_REG = CP1_DOS2 AND (MR1_LCL != 0 OR HR1_DOS2 != 0) THEN '1'
					WHEN CAI_REG = CA2_DOS2 THEN '2'
					WHEN CAI_REG = ANY(CP1_DOS2_array) AND CP1_DOS2_array IS NOT NULL THEN '1'
					WHEN CAI_REG = ANY(CA2_DOS2_array) AND CA2_DOS2_array IS NOT NULL THEN '2'
					WHEN CAI_REG = CP1_DOS2 THEN '1'					
					ELSE '3' END AS TTP_LCL,
					CASE WHEN CAI_REG <> '99999999' AND (CAI_REG = CP1_DOS2 OR CAI_REG = ANY(CP1_DOS2_array)) AND (MR1_LCL != 0 OR HR1_DOS2 != 0) THEN DAT_REG ELSE '00010101' END AS DR1_LCL,	
					CASE WHEN CAI_REG <> '99999999' AND (CAI_REG = CA2_DOS2 OR CAI_REG = ANY(CA2_DOS2_array)) AND (CAI_REG <> CP1_DOS2 OR MR1_LCL = 0) THEN DAT_REG ELSE '00010101' END AS DR2_LCL,
					CASE WHEN CAI_REG = '99999999' OR (CAI_REG IS DISTINCT FROM CP1_DOS2 AND CAI_REG IS DISTINCT FROM CA2_DOS2 AND (CAI_REG <> ALL(CP1_DOS2_array) OR CP1_DOS2_array IS NULL) AND (CAI_REG <> ALL(CA2_DOS2_array) OR CA2_DOS2_array IS NULL)) THEN DAT_REG ELSE '00010101' END AS DR3_LCL,
					CASE WHEN CAI_REG <> '99999999' AND (CAI_REG = CP1_DOS2 OR CAI_REG = ANY(CP1_DOS2_array)) AND (MR1_LCL != 0 OR HR1_DOS2 != 0) THEN MONT + TVA ELSE 0 END AS MR1_LCL,	
					CASE WHEN CAI_REG <> '99999999' AND (CAI_REG = CA2_DOS2 OR CAI_REG = ANY(CA2_DOS2_array)) AND (CAI_REG <> CP1_DOS2 OR MR1_LCL = 0) THEN MONT + TVA ELSE 0 END AS MR2_LCL,
					CASE WHEN CAI_REG = '99999999' OR (CAI_REG IS DISTINCT FROM CP1_DOS2 AND CAI_REG IS DISTINCT FROM CA2_DOS2 AND (CAI_REG <> ALL(CP1_DOS2_array) OR CP1_DOS2_array IS NULL) AND (CAI_REG <> ALL(CA2_DOS2_array) OR CA2_DOS2_array IS NULL)) THEN MONT + TVA ELSE 0 END AS MR3_LCL
				FROM prod_sigems.LIG_CLINI
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LCL = ANN_SELECT AND COD_LCL = COD_SELECT
					JOIN prod_sigems.DOS2 ON ANN_LCL = ANN_DOS2 AND COD_LCL = COD_DOS2 AND IND_LCL = IND_DOS2 AND ETA_DOS2 >= 1
					LEFT JOIN w_DOS2_TP ON ANN_LCL = ANN_DOS2_TP AND COD_LCL = COD_DOS2_TP
					JOIN prod_sigems.REG4 ON NUM_LCL = NUM_CLI
					JOIN prod_sigems.REG ON NUM_REG4 = SER_REG;
					
				ANALYSE w_LIG_CLINI_mrx
				;
				
				-- Si pas de ventilation fine, ventiler selon TP1 		
				UPDATE w_LIG_CLINI_mrx SET
					TTP_LCL = '1',
					MR1_LCL = MNT_REG
				FROM prod_sigems.DOS2
				WHERE ANN_LCL = ANN_DOS2 AND
					COD_LCL = COD_DOS2 AND
					IND_LCL = IND_DOS2 AND
					MR1_LCL = 0 AND MR2_LCL = 0 AND MR3_LCL = 0 AND
					CAI_REG = CP1_DOS2
				;

				-- Ajuster montants selon tiers
				UPDATE w_lig_clini_mrx SET
					MR1_LCL = CASE WHEN TTP_LCL = '1' THEN MNT_REG ELSE 0 END,
					MR2_LCL = CASE WHEN TTP_LCL = '2' THEN MNT_REG ELSE 0 END,
					MR3_LCL = CASE WHEN TTP_LCL = '3' THEN MNT_REG ELSE 0 END
				WHERE
					MR1_LCL IS DISTINCT FROM CASE WHEN TTP_LCL = '1' THEN MNT_REG ELSE 0 END OR
					MR2_LCL IS DISTINCT FROM CASE WHEN TTP_LCL = '2' THEN MNT_REG ELSE 0 END OR
					MR3_LCL IS DISTINCT FROM CASE WHEN TTP_LCL = '3' THEN MNT_REG ELSE 0 END
				;

				UPDATE w_LIG_CLINI_mrx SET
					DR1_LCL = '00010101', 
					MR1_LCL = 0
				WHERE TTP_LCL <> '1' AND
					(
					DR1_LCL <> '00010101' OR 
					MR1_LCL <> 0
					)
				;
				UPDATE w_LIG_CLINI_mrx SET
					DR2_LCL = '00010101', 
					MR2_LCL = 0
				WHERE TTP_LCL <> '2' AND
					(
					DR2_LCL <> '00010101' OR 
					MR2_LCL <> 0
					)
				;
				UPDATE w_LIG_CLINI_mrx SET
					DR3_LCL = '00010101', 
					MR3_LCL = 0
				WHERE TTP_LCL <> '3' AND
					(
					DR3_LCL <> '00010101' OR 
					MR3_LCL <> 0
					)
				;

				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,
					CAI_REG,
					MON_REG3 AS MNT_REG,
					CASE 
					WHEN CAI_REG = '99999999' THEN '3'
					WHEN CAI_REG = CP1_DOS2 AND (MR1_LHO != 0 OR HR1_DOS2 != 0) THEN '1'
					WHEN CAI_REG = CA2_DOS2 THEN '2'
					WHEN CAI_REG = ANY(CP1_DOS2_array) AND CP1_DOS2_array IS NOT NULL THEN '1'
					WHEN CAI_REG = ANY(CA2_DOS2_array) AND CA2_DOS2_array IS NOT NULL THEN '2'
					WHEN CAI_REG = CP1_DOS2 THEN '1'					
					ELSE '3' END AS TTP_LHO,
					CASE WHEN CEX_LHO = 'ACOMPT' THEN '1'::text ELSE '0'::text END AS is_acompte,
					CASE WHEN CAI_REG <> '99999999' AND (CAI_REG = CP1_DOS2 OR CAI_REG = ANY(CP1_DOS2_array)) AND (MR1_LHO != 0 OR HR1_DOS2 != 0) THEN DAT_REG ELSE '00010101' END AS DR1_LHO,	
					CASE WHEN CAI_REG <> '99999999' AND (CAI_REG = CA2_DOS2 OR CAI_REG = ANY(CA2_DOS2_array)) AND (CAI_REG <> CP1_DOS2 OR MR1_LHO = 0) THEN DAT_REG ELSE '00010101' END AS DR2_LHO,
					CASE WHEN CAI_REG = '99999999' OR (CAI_REG IS DISTINCT FROM CP1_DOS2 AND CAI_REG IS DISTINCT FROM CA2_DOS2 AND (CAI_REG <> ALL(CP1_DOS2_array) OR CP1_DOS2_array IS NULL) AND (CAI_REG <> ALL(CA2_DOS2_array) OR CA2_DOS2_array IS NULL)) THEN DAT_REG ELSE '00010101' END AS DR3_LHO,
					CASE WHEN CAI_REG <> '99999999' AND (CAI_REG = CP1_DOS2 OR CAI_REG = ANY(CP1_DOS2_array)) AND (MR1_LHO != 0 OR HR1_DOS2 != 0) THEN MON_REG3 ELSE 0 END AS MR1_LHO,	
					CASE WHEN CAI_REG <> '99999999' AND (CAI_REG = CA2_DOS2 OR CAI_REG = ANY(CA2_DOS2_array)) AND (CAI_REG <> CP1_DOS2 OR MR1_LHO = 0) THEN MON_REG3 ELSE 0 END AS MR2_LHO,
					CASE WHEN CAI_REG = '99999999' OR (CAI_REG IS DISTINCT FROM CP1_DOS2 AND CAI_REG IS DISTINCT FROM CA2_DOS2 AND (CAI_REG <> ALL(CP1_DOS2_array) OR CP1_DOS2_array IS NULL) AND (CAI_REG <> ALL(CA2_DOS2_array) OR CA2_DOS2_array IS NULL)) THEN MON_REG3 ELSE 0 END AS MR3_LHO
				FROM prod_sigems.LIG_HONOR
					JOIN w_DOSSIER_SELECT w_DOSSIER_SELECT ON ANN_LHO = ANN_SELECT AND COD_LHO = COD_SELECT
					JOIN prod_sigems.DOS2 ON ANN_LHO = ANN_DOS2 AND COD_LHO = COD_DOS2 AND IND_LHO = IND_DOS2 AND ETA_DOS2 >= 1
					LEFT JOIN w_DOS2_TP ON ANN_LHO = ANN_DOS2_TP AND COD_LHO = COD_DOS2_TP
					JOIN w_REG3 ON NUM_LHO = LHO_REG3;
					
				ANALYSE w_LIG_HONOR_mrx
				;
				
				-- Si pas de ventilation fine, ventiler selon TP1 			
				UPDATE w_LIG_HONOR_mrx SET
					TTP_LHO = '1',
					MR1_LHO = MNT_REG
				FROM prod_sigems.DOS2
				WHERE ANN_LHO = ANN_DOS2 AND
					COD_LHO = COD_DOS2 AND
					IND_LHO = IND_DOS2 AND
					MR1_LHO = 0 AND MR2_LHO = 0 AND MR3_LHO = 0 AND
					CAI_REG = CP1_DOS2
				;
					
				-- Ajuster montants selon tiers
				UPDATE w_LIG_HONOR_mrx SET
					MR1_LHO = CASE WHEN TTP_LHO = '1' THEN MNT_REG ELSE 0 END,
					MR2_LHO = CASE WHEN TTP_LHO = '2' THEN MNT_REG ELSE 0 END,
					MR3_LHO = CASE WHEN TTP_LHO = '3' THEN MNT_REG ELSE 0 END
				WHERE
					MR1_LHO IS DISTINCT FROM CASE WHEN TTP_LHO = '1' THEN MNT_REG ELSE 0 END OR
					MR2_LHO IS DISTINCT FROM CASE WHEN TTP_LHO = '2' THEN MNT_REG ELSE 0 END OR
					MR3_LHO IS DISTINCT FROM CASE WHEN TTP_LHO = '3' THEN MNT_REG ELSE 0 END
				;
					
				UPDATE w_LIG_HONOR_mrx SET
					DR1_LHO = '00010101', 
					MR1_LHO = 0
				WHERE TTP_LHO <> '1' AND
					(
					DR1_LHO <> '00010101' OR 
					MR1_LHO <> 0
					)
				;
				UPDATE w_LIG_HONOR_mrx SET
					DR2_LHO = '00010101', 
					MR2_LHO = 0
				WHERE TTP_LHO <> '2' AND
					(
					DR2_LHO <> '00010101' OR 
					MR2_LHO <> 0
					)
				;
				UPDATE w_LIG_HONOR_mrx SET
					DR3_LHO = '00010101', 
					MR3_LHO = 0
				WHERE TTP_LHO <> '3' AND
					(
					DR3_LHO <> '00010101' OR 
					MR3_LHO <> 0
					)
				;
					
				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_sigems.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 t_tiers_payant_1.type_tiers_payant = 1 AND DOS2.CP1_DOS2 = split_part(t_tiers_payant_1.code_original,'(1)',1)
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON t_tiers_payant_2.type_tiers_payant = 2 AND DOS2.CA2_DOS2 = split_part(t_tiers_payant_2.code_original,'(2)',1)
				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_sigems.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 t_tiers_payant_1.type_tiers_payant = 1 AND DOS2.CP1_DOS2 = split_part(t_tiers_payant_1.code_original,'(1)',1)
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON t_tiers_payant_2.type_tiers_payant = 2 AND DOS2.CA2_DOS2 = split_part(t_tiers_payant_2.code_original,'(2)',1)
				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');
				
								
				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_sigems.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_sigems.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) AND
					SER_LCL <> '*CDL'
				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_sigems.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 CPH_LHO <> 'REGH' 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) AND
					SER_LHO <> '*CDL'
				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,
					montant_comptabilise_2_c = 0,
					montant_comptabilise_2_h = 0,
					montant_regle_2_c = 0,
					montant_regle_2_h = 0
				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,
					ucd_id,
					lpp_id)
				SELECT 
					p_factures.oid AS facture_id,
					p_factures.no_facture AS no_facture,
					CASE 
						WHEN split_part(p_factures.no_facture,'_',2) = '' 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 split_part(p_factures.no_facture,'_',2) = '' 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 split_part(p_factures.no_facture,'_',2) = '' 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 w_LIG_CLINI.PRO_LCL = 'PJ' AND QTE_LCL <> 0 AND (ML1_LCL+ML2_LCL+ML3_LCL) <> 0 THEN (ML1_LCL+ML2_LCL+ML3_LCL)/QTE_LCL 
                        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,
					w_LIG_CLINI.ucd_id,
					w_LIG_CLINI.lpp_id
				FROM w_LIG_CLINI
					JOIN activite[PX].p_factures ON w_LIG_CLINI.no_facture = split_part(p_factures.no_facture,'_',1) 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' 
				;
				
				
				-- Prestations spéciale I01 provenant du PMSI
				INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
					facture_id,
					no_facture, 
					date_debut, 
					date_fin, 
					nb_rubrique, 
					coefficient, 
					coefficient_mco, 
					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.date_debut AS date_debut,
					p_factures.date_debut AS date_fin,
					1::numeric AS nb_rubrique,
					1::numeric AS coefficient, 
					0.9935::numeric AS coefficient_mco, 
					COALESCE(t_rubriques_facturation.oid,0) AS rubrique_facturation_id,
					COALESCE(t_prestations.oid,0) AS prestation_id,
					6047::numeric AS prix_unitaire,
					p_sejours.lieu_sortie_id AS lieu_id
				FROM prod_sigems.GHS_VALORISE
					JOIN activite[PX].p_factures ON JOINTURE = p_factures.no_sejour
					JOIN activite[PX].p_sejours ON JOINTURE = p_sejours.code_original AND p_sejours.etat = ''
					JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original = 'I01'
					JOIN activite.t_prestations ON t_prestations.code = 'I01'
				WHERE p_factures.code_facture <> '1' AND GHS_VALORISE.GHS = 'I01'
				;
                
                -- Suppression de lignes en double (cas d'un dossier de tronquiere en SSR)
                DELETE FROM activite[PX].p_factures_lignes_non_facturees_c  
                USING activite[PX].p_factures
                JOIN activite[PX].p_sejours ON p_sejours.no_sejour = p_factures.no_sejour AND p_factures.date_debut > p_sejours.date_entree
                WHERE p_factures_lignes_non_facturees_c.no_facture = p_factures.no_facture AND
                    p_factures_lignes_non_facturees_c.date_debut NOT BETWEEN p_factures.date_debut AND p_factures.date_fin
                ;

				
				
				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
				LEFT JOIN prod_sigems.DOS2_LIEN_AVOIR DOS2_LIEN_AVOIR_F ON 
					DOS2_LIEN_AVOIR_F.ANN = ANN_LCL AND
					DOS2_LIEN_AVOIR_F.COD = COD_LCL AND
					DOS2_LIEN_AVOIR_F.IND = IND_LCL
				LEFT JOIN prod_sigems.DOS2_LIEN_AVOIR DOS2_LIEN_AVOIR_A ON 
					DOS2_LIEN_AVOIR_A.ANN = ANN_LCL AND
					DOS2_LIEN_AVOIR_A.COD = COD_LCL AND
					DOS2_LIEN_AVOIR_A.IND_AVOIR = IND_LCL
				WHERE PRO_LCL <> 'ECAC' AND
					DOS2_LIEN_AVOIR_F.COD IS NULL AND
					DOS2_LIEN_AVOIR_A.COD IS NULL
				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 + CASE WHEN tiers_payant_1_id = tiers_payant_2_id AND tiers_payant_1_id <> 0 THEN w_LIG_CLINI_tmrx.MR2_LCL ELSE 0 END,
					montant_regle_2_c = CASE WHEN tiers_payant_1_id <> tiers_payant_2_id THEN w_LIG_CLINI_tmrx.MR2_LCL ELSE 0 END,
					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 + CASE WHEN tiers_payant_1_id = tiers_payant_2_id AND tiers_payant_1_id <> 0 THEN w_LIG_CLINI_tmrx.MR2_LCL ELSE 0 END) OR
						montant_regle_2_c <> (CASE WHEN tiers_payant_1_id <> tiers_payant_2_id THEN w_LIG_CLINI_tmrx.MR2_LCL ELSE 0 END) 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_sigems.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.code_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,
						w_LIG_CLINI.ucd_id,
						w_LIG_CLINI.lpp_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 BG_SSR = '0' AND ML1_LCL <> 0 OR 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,
						w_LIG_CLINI.TVA_LCL AS taux_tva,
						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.code_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,
						w_LIG_CLINI.ucd_id,
						w_LIG_CLINI.lpp_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,
						TVA_LCL AS taux_tva,
						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);
				
				  
				-- Remplacement des codes dialyse
                INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'TRANSGHSDXX',
					'Transformation des GHS en Dxx',
					'',
					'Transformation des prestations GHS en Dxx selong GHS, la rubrique de facturation prend la valeur du GHS'
				WHERE 'TRANSGHSDXX' NOT IN (SELECT code FROM activite.t_divers);
                ;
                
                INSERT INTO activite[PX].t_rubriques_facturation (code_original, code, texte, texte_court)
                WITH w_rub AS
                (
                    SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL
                )
                SELECT t_ghs.code::text, t_ghs.code::text, t_ghs.texte, t_ghs.texte
                FROM base.t_ghs
                JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                    LEFT JOIN w_rub ON w_rub.code_original = t_ghs.code::text
                WHERE t_ghs.code IN (9602,9603,9604,9605,9617) AND
                    w_rub.code_original IS NULL
                    ;
                    
                INSERT INTO activite[PX].t_rubriques_facturation (code_original, code, texte, texte_court)
                WITH w_rub AS
                (
                    SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL
                )
                SELECT t_prestations.code::text, t_prestations.code::text, t_prestations.texte, t_prestations.texte
                FROM activite.t_prestations
                JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                    LEFT JOIN w_rub ON w_rub.code_original = t_prestations.code::text
                WHERE t_prestations.code IN ('D11') AND
                    w_rub.code_original IS NULL
                    ;
                    
                DROP TABLE IF EXISTS w_transform_dxx;
                CREATE TEMP TABLE w_transform_dxx AS
                        SELECT p_factures_lignes_c.no_facture,
                    p_factures_lignes_c.CTID AS CTID_source,
                    t_prestations.code,
                    t_ghs.code AS ghs_code,
                    CASE t_ghs.code 
                    WHEN 9602 THEN 'D18'
                    WHEN 9603 THEN 'D19'
                    WHEN 9604 THEN 'D17'
                    WHEN 9605 THEN 'D09'
                    WHEN 9617 THEN 'D10'
                    ELSE '' END AS dxx_prestation_code
                FROM w_factures_lignes_c 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 base.t_ghs ON p_sejours.ghs_id = t_ghs.oid
                JOIN activite.t_prestations ON t_prestations.oid = prestation_id
                JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                WHERE t_prestations.code = 'GHS' AND
                    t_ghs.code IN (9602,9603,9604,9605,9617);

                CREATE INDEX w_transform_dxx_i1
                          ON w_transform_dxx
                          USING btree
                          (no_facture)
                ;

                UPDATE w_factures_lignes_c p_factures_lignes_c SET
                    prestation_id = t_prestations.oid,
                    rubrique_facturation_id = t_rubriques_facturation.oid
                FROM w_transform_dxx
                JOIN activite.t_prestations ON dxx_prestation_code = t_prestations.code 
                JOIN activite[PX].t_rubriques_facturation ON ghs_code = t_rubriques_facturation.code_original
                WHERE p_factures_lignes_c.no_facture = w_transform_dxx.no_facture AND
                    p_factures_lignes_c.CTID = w_transform_dxx.CTID_source
                ; 
				  
				  
				-- 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 p_sejours.type_sejour != '5' 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,
					code_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,
					ucd_id,
					lpp_id,
					taux_tva,
					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,
					code_facture,
					no_sejour,
					date_debut,
					date_fin,
					date_vente,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					prestation_id,
					compte_produit_id,
					ucd_id,
					lpp_id,
					taux_tva,
					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,
					code_facture,
					no_sejour,
					date_debut,
					date_fin,
					date_vente,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					prestation_id,
					compte_produit_id,
					ucd_id,
					lpp_id,
					taux_tva,
					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,
					ucd_id,
					lpp_id,
					taux_tva,
					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,
					ucd_id,
					lpp_id,
					taux_tva,
					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 AND code_facture >= '1';
				
				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_vente,
					rubrique_comptabilisation_id,
					prestation_id,
					SUM(montant_comptabilise),
					SUM(montant_comptabilise_0),
					SUM(montant_comptabilise_1),
					SUM(montant_comptabilise_2),
					SUM(montant_comptabilise_22),
					0,
					0,
					0,
					0,
					0
				FROM w_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(DAT_REG),
					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;
				
				-- Acomptes NOEMIE (85%)
				
				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT '*CTI_ACO85', 'ACO85', 'Acomptes 85%', 'Acomptes 85%'
				WHERE '*CTI_ACO85' NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation);

				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT '*CTI_ACO85', 'ACO85', 'Acomptes 85%', 'Acomptes 85%'
				WHERE '*CTI_ACO85' NOT IN (SELECT code_original FROM activite.t_prestations WHERE code_original IS NOT NULL);
				
				
				DROP TABLE IF EXISTS w_ACOMPTE_NOEMIE;
				CREATE TEMP TABLE w_ACOMPTE_NOEMIE AS
				SELECT *, 
					DATE_CPTA AS ECR_DATE,
					CASE 
					WHEN DATE_CPTA < date(now() - interval '30 days') THEN '1'::text 
					ELSE '0'::text END AS ACOMPTE_EST_COMPTABILISE,
					0::NUMERIC AS MONTANT_REGLE_SI_REPRISE
				FROM prod_sigems.ACOMPTE_NOEMIE
				;
				
				ANALYSE w_ACOMPTE_NOEMIE
				;
				
				CREATE INDEX w_ACOMPTE_NOEMIE_i1
				  ON w_ACOMPTE_NOEMIE
				  USING btree
				  (CODE);
				
				-- Récupérer la vraie date comptable
				UPDATE w_ACOMPTE_NOEMIE ACOMPTE_NOEMIE SET
					ECR_DATE = ECRIT.ECR_DATE,
					ACOMPTE_EST_COMPTABILISE = '1'
				FROM prod_sigems.DOS_ECRIT
				JOIN prod_sigems.ECRIT ON (SERI = ECR_NUM OR SERI = ECR_LIAIS)
				WHERE ACOMPTE_NOEMIE.ANNEE = DOS_ECRIT.ANNEE AND
					ACOMPTE_NOEMIE.CODE = DOS_ECRIT.CODE AND
					ACOMPTE_NOEMIE.INDICE = DOS_ECRIT.INDICE AND
					ECR_CPTE = 'NOEMIE' AND
					ECR_JNAL NOT LIKE 'AN%' AND
					ECR_CREDIT = ACOMPTE_NOEMIE.MONTANT AND
					(
					ACOMPTE_NOEMIE.ECR_DATE IS DISTINCT FROM ECRIT.ECR_DATE OR
					ACOMPTE_EST_COMPTABILISE = '0'
					)
				;
				
				-- Retrouver le montant réglé total si reprise d'acompte nom comptabilisée
				UPDATE w_ACOMPTE_NOEMIE
				SET MONTANT_REGLE_SI_REPRISE = SJ1_DOS2
				FROM prod_sigems.DOS2 
				WHERE ACOMPTE_EST_COMPTABILISE = '0' AND
					MONTANT < 0 AND
					ANNEE = ANN_DOS2 AND
					CODE = COD_DOS2 AND
					INDICE = IND_DOS2 AND
					SR1_DOS2 = 0 AND
					round(base.cti_division(0-MONTANT, SJ1_DOS2)*100.00,0) = 85
				;

				-- Eliminer les anomalies
				DROP TABLE IF EXISTS w_ACOMPTE_NOEMIE_err;
				CREATE TEMP TABLE w_ACOMPTE_NOEMIE_err AS
				SELECT ANNEE AS ANNEE_err, CODE AS CODE_err, INDICE AS INDICE_err
				FROM w_ACOMPTE_NOEMIE ACOMPTE_NOEMIE
				JOIN activite[PX].p_factures ON annee || to_char(code,'FM900000') || '.' || to_char(indice,'FM00') = no_facture
				WHERE ECR_DATE IS NOT NULL
				GROUP BY 1,2,3
				HAVING (
					SUM(MONTANT) <> 0 AND MAX(ECR_DATE) < (now() - interval '1 year') OR
					SUM(MONTANT) <> 0 AND count(*) <> 1 OR
					SUM(MONTANT) < 0
					)
				;
				
				DELETE FROM w_ACOMPTE_NOEMIE
				USING w_ACOMPTE_NOEMIE_err
				WHERE ANNEE = ANNEE_err AND
						CODE = CODE_err AND
						INDICE = INDICE_err
				;

				-- Ecriture d'acompte
				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,
					od_non_comptabilise
				)
				SELECT
					p_factures.oid AS facture_id,
					p_factures.no_facture, 
					date(ECR_DATE) AS date_comptable,
					t_rubriques_facturation.oid AS rubrique_comptabilisation_id, 
					t_prestations.oid AS 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, 
					ACOMPTE_NOEMIE.MONTANT AS montant_regle, 
					0 AS montant_regle_0, 
					ACOMPTE_NOEMIE.MONTANT AS montant_regle_1, 
					0 AS montant_regle_2,  
					0 AS montant_regle_22,
					'1' AS od_non_comptabilise
				FROM w_ACOMPTE_NOEMIE ACOMPTE_NOEMIE
				JOIN activite[PX].p_factures ON annee || to_char(code,'FM900000') || '.' || to_char(indice,'FM00') = no_facture
				JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original = '*CTI_ACO85'
				JOIN activite.t_prestations ON t_prestations.code_original = '*CTI_ACO85'
				WHERE ECR_DATE IS NOT NULL
				;
				
				-- Ecriture de règlement si reprise d'acompte non comptabilisée
				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,
					od_non_comptabilise
				)
				SELECT
					p_factures.oid AS facture_id,
					p_factures.no_facture, 
					date(ECR_DATE) AS date_comptable,
					t_rubriques_facturation.oid AS rubrique_comptabilisation_id, 
					t_prestations.oid AS 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, 
					ACOMPTE_NOEMIE.MONTANT_REGLE_SI_REPRISE AS montant_regle, 
					0 AS montant_regle_0, 
					ACOMPTE_NOEMIE.MONTANT_REGLE_SI_REPRISE AS montant_regle_1, 
					0 AS montant_regle_2,  
					0 AS montant_regle_22,
					'1' AS od_non_comptabilise
				FROM w_ACOMPTE_NOEMIE ACOMPTE_NOEMIE
				JOIN activite[PX].p_factures ON annee || to_char(code,'FM900000') || '.' || to_char(indice,'FM00') = no_facture
				JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original = '*CTI_ACO85'
				JOIN activite.t_prestations ON t_prestations.code_original = '*CTI_ACO85'
				WHERE ECR_DATE IS NOT NULL AND
					ACOMPTE_NOEMIE.MONTANT_REGLE_SI_REPRISE <> 0
				;

				UPDATE activite[PX].p_factures SET
					montant_regle_c = montant_regle_c + montant_acompte,
					montant_regle_1_c = montant_regle_1_c + montant_acompte
				FROM
				(
				SELECT no_facture, SUM(montant_regle_1) AS montant_acompte
				FROM activite[PX].p_factures_soldes_c
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND
					t_prestations.code_original = '*CTI_ACO85' 
				GROUP BY 1
				HAVING SUM(montant_regle_1) <> 0
				) subview
				WHERE p_factures.no_facture = subview.no_facture
				;
				
				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(SUBSTR(TRIM(CCAM_RUM.MODIFICATEUR)||TRIM(CCAM_RUM.MODIF2)||TRIM(CCAM_RUM.MODIF3)||TRIM(CCAM_RUM.MODIF4)||TRIM(CCAM_RUM.MODIF5),1,1),'') AS CCAM_MODIF1,
					COALESCE(SUBSTR(TRIM(CCAM_RUM.MODIFICATEUR)||TRIM(CCAM_RUM.MODIF2)||TRIM(CCAM_RUM.MODIF3)||TRIM(CCAM_RUM.MODIF4)||TRIM(CCAM_RUM.MODIF5),2,1),'') AS CCAM_MODIF2,
					COALESCE(SUBSTR(TRIM(CCAM_RUM.MODIFICATEUR)||TRIM(CCAM_RUM.MODIF2)||TRIM(CCAM_RUM.MODIF3)||TRIM(CCAM_RUM.MODIF4)||TRIM(CCAM_RUM.MODIF5),3,1),'') AS CCAM_MODIF3,
					COALESCE(SUBSTR(TRIM(CCAM_RUM.MODIFICATEUR)||TRIM(CCAM_RUM.MODIF2)||TRIM(CCAM_RUM.MODIF3)||TRIM(CCAM_RUM.MODIF4)||TRIM(CCAM_RUM.MODIF5),4,1),'') 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) || '|' || 
					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_sigems.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_sigems.CCAM_RUM ON LIG_HONOR.NUM_LHO = CCAM_RUM.NUM_LHO AND date(DDE_LHO) = date(CCAM_RUM.DAT)
					LEFT JOIN prod_sigems.PROD_HONOR ON CPH_LHO = COD_PRH
				WHERE 
					CPH_LHO <> 'ECAH' AND 
					SER_LHO <> '*CDL';

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

				WITH update_lig_honor AS (
					SELECT 
						w_LIG_HONOR.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 as new_no_facture
					FROM w_LIG_HONOR
					JOIN w_factures_last ON w_factures_last.no_sejour = w_LIG_HONOR.SEJ_DOS
					LEFT JOIN activite[PX].p_factures ON p_factures.no_facture = w_LIG_HONOR.no_facture
					WHERE p_factures.no_facture IS NULL
				)
				UPDATE w_LIG_HONOR
				SET no_facture = new_no_facture
				FROM update_lig_honor
				WHERE update_lig_honor.no_facture = w_LIG_HONOR.no_facture;

				DROP TABLE IF EXISTS w_LIG_HONOR_keys;
				CREATE TEMP TABLE w_LIG_HONOR_keys AS
				SELECT key,
					ACT_LHO,
					CCAM_ACTE,
					CEX_LHO,
					CPH_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,5;
				
				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;

				UPDATE activite.t_prestations SET
					code = ACT_LHO,
					texte = ACT_LHO,
					texte_court = ACT_LHO
				FROM w_LIG_HONOR_keys
				WHERE code_original = ACT_LHO AND
					(
						code IS DISTINCT FROM ACT_LHO OR
						texte IS DISTINCT FROM ACT_LHO OR
						texte_court IS DISTINCT FROM ACT_LHO
					) 
				;

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


                
				TRUNCATE activite[PX].p_factures_lignes_non_facturees_h
				;

				INSERT INTO activite[PX].p_factures_lignes_non_facturees_h(
					no_facture,
					facture_id,
					date_debut,
					date_fin,
					heure_debut,
					nb_rubrique,
					coefficient,
					medecin_facture_id,
					prestation_id,
					rubrique_facturation_id,		 
					prix_unitaire,
					montant_depassement,
					lieu_id,
					acte_id,
					phase_ccam,
					activite_ccam,
					extension_ccam,
					modificateur_ccam_1,
					modificateur_ccam_2,
					modificateur_ccam_3,
					modificateur_ccam_4
				)
				
				SELECT
					p_factures.no_facture,
					p_factures.oid AS facture_id,
					date(DDE_LHO) AS date_debut,
					date(DDE_LHO) AS date_fin,
					to_number('00' || HEU_LHO, '0000') * 10000 AS heure_debut,
					QTE_LHO AS nb_rubrique,
					round(CASE WHEN COF_LHO <> 0 THEN COF_LHO ELSE 1.00 END::numeric,2) AS coefficient,
					w_LIG_HONOR_keys.medecin_facture_id AS medecin_facture_id,
					w_LIG_HONOR_keys.prestation_id AS prestation_id,
					w_LIG_HONOR_keys.rubrique_facturation_id AS rubrique_facturation_id,													 
					CASE WHEN (ML1_LHO + ML2_LHO + ML3_LHO) <> 0 AND (QTE_LHO * COF_LHO <> 0) THEN base.cti_division(ML1_LHO + ML2_LHO + ML3_LHO,QTE_LHO * COF_LHO) ELSE round(base.cti_division(BAR_LHO, QTE_LHO * COF_LHO),2) END AS prix_unitaire,
					CASE WHEN DEP_LHO IN ('A', 'B', 'C', 'D', 'E', 'F', 'M', 'N') THEN TAR_LHO - BAR_LHO ELSE 0 END AS montant_depassement,
					p_sejours.lieu_sortie_id AS lieu_id,
					w_LIG_HONOR_keys.acte_id AS acte_id,
					CCAM_PHASE AS phase_ccam,
					CCAM_ACTIVITE AS activite_ccam,
					CCAM_EXT_DOC AS extension_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
				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
				WHERE p_factures.code_facture <> '1' AND
                    (CASE WHEN (ML1_LHO + ML2_LHO + ML3_LHO) <> 0 AND (QTE_LHO * COF_LHO <> 0) THEN base.cti_division(ML1_LHO + ML2_LHO + ML3_LHO,QTE_LHO * COF_LHO) ELSE round(base.cti_division(BAR_LHO, QTE_LHO * COF_LHO),2) END) <> 0
				;

                  
				
				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
				LEFT JOIN prod_sigems.DOS2_LIEN_AVOIR DOS2_LIEN_AVOIR_F ON 
					DOS2_LIEN_AVOIR_F.ANN = ANN_LHO AND
					DOS2_LIEN_AVOIR_F.COD = COD_LHO AND
					DOS2_LIEN_AVOIR_F.IND = IND_LHO
				LEFT JOIN prod_sigems.DOS2_LIEN_AVOIR DOS2_LIEN_AVOIR_A ON 
					DOS2_LIEN_AVOIR_A.ANN = ANN_LHO AND
					DOS2_LIEN_AVOIR_A.COD = COD_LHO AND
					DOS2_LIEN_AVOIR_A.IND_AVOIR = IND_LHO
				WHERE ACT_LHO <> 'ECAC' AND
					DOS2_LIEN_AVOIR_F.COD IS NULL AND
					DOS2_LIEN_AVOIR_A.COD IS NULL
				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 + CASE WHEN tiers_payant_1_id = tiers_payant_2_id AND tiers_payant_1_id <> 0 THEN w_LIG_HONOR_tmrx.MR2_LHO ELSE 0 END,
					montant_regle_2_h = CASE WHEN tiers_payant_1_id <> tiers_payant_2_id THEN w_LIG_HONOR_tmrx.MR2_LHO ELSE 0 END,
					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 + CASE WHEN tiers_payant_1_id = tiers_payant_2_id AND tiers_payant_1_id <> 0 THEN w_LIG_HONOR_tmrx.MR2_LHO ELSE 0 END) OR
						montant_regle_2_h <> (CASE WHEN tiers_payant_1_id <> tiers_payant_2_id THEN w_LIG_HONOR_tmrx.MR2_LHO ELSE 0 END) 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_sigems.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,
						p_factures.code_facture,
                        
						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 <> 0 THEN COF_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' AND w_LIG_HONOR.ACT_LHO <> 'REGH') 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 code_facture = '1' AND 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="Transformations honoraires GHM Grenoble">
			<condition><![CDATA[
				"[ENV_FINESS]" == "380012658" 
			]]></condition>
			<sqlcmd><![CDATA[
			
				-- actes réalisés par des libéraux
				-- Transformation de la rubrique en rubrioque-LIB pour isoler du chiffre d'affaires
				DROP TABLE IF EXISTS w_transform_ghm_honlib;
				CREATE TEMP TABLE w_transform_ghm_honlib AS
				SELECT p_factures_lignes_h.no_facture, 
					medecin_facture_id,
					rubrique_facturation_id, 
					0::bigint AS rubrique_facturation_lib_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
				JOIN activite[PX].t_rubriques_facturation ON rubrique_facturation_id = t_rubriques_facturation.oid
				JOIN activite[PX].t_medecins_administratifs ON medecin_facture_id = t_medecins_administratifs.oid
				WHERE  substr(t_medecins_administratifs.code,6,1) = 'L' AND
					code_facture >= '1' AND
					p_factures.no_facture NOT LIKE '%BG' AND
					t_rubriques_facturation.code NOT LIKE '%-TM' AND
					t_rubriques_facturation.code NOT LIKE '%-LIB' AND
					(montant_comptabilise_1 <> 0 OR montant_comptabilise_2 <> 0 OR montant_comptabilise_0 <> 0)
					GROUP BY 1,2,3
				;

				CREATE INDEX w_transform_ghm_honlib_i1
						  ON w_transform_ghm_honlib
						  USING btree
						  (no_facture)
				;
				CREATE INDEX w_transform_ghm_honlib_i2
						  ON w_transform_ghm_honlib
						  USING btree
						  (rubrique_facturation_id)
				;

                    
				INSERT INTO activite[PX].t_rubriques_facturation (code_original, code, texte, texte_court)
				SELECT t_rubriques_facturation.code_original || '-LIB', t_rubriques_facturation.code || '-LIB', 'Libéraux ' || t_rubriques_facturation.texte, 'Libéraux ' || t_rubriques_facturation.texte
				FROM w_transform_ghm_honlib
				JOIN activite[PX].t_rubriques_facturation ON rubrique_facturation_id = t_rubriques_facturation.oid
				WHERE (t_rubriques_facturation.code_original || '-LIB') NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
				;

				UPDATE w_transform_ghm_honlib
				SET rubrique_facturation_lib_id = t_rubriques_facturation_dep.oid
				FROM activite[PX].t_rubriques_facturation
					JOIN activite[PX].t_rubriques_facturation t_rubriques_facturation_dep ON (t_rubriques_facturation.code_original || '-LIB') = t_rubriques_facturation_dep.code_original
				WHERE w_transform_ghm_honlib.rubrique_facturation_id = t_rubriques_facturation.oid
				;


                UPDATE activite[PX].p_factures_lignes_h SET
					rubrique_facturation_id = rubrique_facturation_lib_id,
					rubrique_comptabilisation_id = rubrique_facturation_lib_id
				FROM w_transform_ghm_honlib
				WHERE p_factures_lignes_h.no_facture = w_transform_ghm_honlib.no_facture AND
					p_factures_lignes_h.medecin_facture_id = w_transform_ghm_honlib.medecin_facture_id AND
					p_factures_lignes_h.rubrique_facturation_id = w_transform_ghm_honlib.rubrique_facturation_id
				;
			
				-- ticket modérateur des actes hospitalisés
				-- Transformation de la rubrique en rubrioque-TM pour isoler du chiffre d'affaires
				DROP TABLE IF EXISTS w_transform_ghm_tmhosp;
				CREATE TEMP TABLE w_transform_ghm_tmhosp AS
				SELECT p_factures_lignes_h.no_facture, 
					rubrique_facturation_id, 
					0::bigint AS rubrique_facturation_tm_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
				JOIN activite[PX].t_rubriques_facturation ON rubrique_facturation_id = t_rubriques_facturation.oid
				WHERE type_sejour <> '3' AND 
					type_sejour <> '9' AND 
					code_facture >= '1' AND
					p_factures.no_facture NOT LIKE '%BG' AND
					t_rubriques_facturation.code NOT LIKE '%-TM' AND
					t_rubriques_facturation.code NOT LIKE '%-LIB' AND
					(montant_comptabilise_1 <> 0 OR montant_comptabilise_2 <> 0 OR montant_comptabilise_0 <> 0)
					GROUP BY 1,2
				;

				CREATE INDEX w_transform_ghm_tmhosp_i1
						  ON w_transform_ghm_tmhosp
						  USING btree
						  (no_facture)
				;
				CREATE INDEX w_transform_ghm_tmhosp_i2
						  ON w_transform_ghm_tmhosp
						  USING btree
						  (rubrique_facturation_id)
				;

                    
				INSERT INTO activite[PX].t_rubriques_facturation (code_original, code, texte, texte_court)
				SELECT t_rubriques_facturation.code_original || '-TM', t_rubriques_facturation.code || '-TM', 'Ticket modérateur ' || t_rubriques_facturation.texte, 'Ticket modérateur ' || t_rubriques_facturation.texte
				FROM w_transform_ghm_tmhosp
				JOIN activite[PX].t_rubriques_facturation ON rubrique_facturation_id = t_rubriques_facturation.oid
				WHERE (t_rubriques_facturation.code_original || '-TM') NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
				;

				UPDATE w_transform_ghm_tmhosp
				SET rubrique_facturation_tm_id = t_rubriques_facturation_dep.oid
				FROM activite[PX].t_rubriques_facturation
					JOIN activite[PX].t_rubriques_facturation t_rubriques_facturation_dep ON (t_rubriques_facturation.code_original || '-TM') = t_rubriques_facturation_dep.code_original
				WHERE w_transform_ghm_tmhosp.rubrique_facturation_id = t_rubriques_facturation.oid
				;


                UPDATE activite[PX].p_factures_lignes_h SET
					rubrique_facturation_id = rubrique_facturation_tm_id,
					rubrique_comptabilisation_id = rubrique_facturation_tm_id
				FROM w_transform_ghm_tmhosp
				WHERE p_factures_lignes_h.no_facture = w_transform_ghm_tmhosp.no_facture AND
					p_factures_lignes_h.rubrique_facturation_id = w_transform_ghm_tmhosp.rubrique_facturation_id
				;
			
			]]></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_vente,
					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
                    code_facture = '1' 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,
					od_non_comptabilise

				)
				SELECT
					facture_id,
					no_facture, 
					date(DAT_REG),
					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,
					CASE WHEN is_acompte = '1' THEN '1' ELSE '0' END AS od_non_comptabilise
				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, is_acompte;
				
				-- Montants réguls ou depassement non affectés
				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
					p_factures.oid AS facture_id,
					p_factures.no_facture,
					DAT_REG AS date_comptable,
					0::bigint AS medecin_comptabilise_id, 
					0::bigint AS prestation_id,
					0::bigint AS rubrique_comptabilisee_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(COALESCE(MON_REG2::numeric,0)) AS montant_regle, 
					SUM(CASE WHEN CAI_REG IS DISTINCT FROM CP1_DOS2 AND CAI_REG IS DISTINCT FROM CA2_DOS2 AND (CAI_REG <> ALL(CP1_DOS2_array) OR CP1_DOS2_array IS NULL) AND (CAI_REG <> ALL(CA2_DOS2_array) OR CA2_DOS2_array IS NULL) THEN COALESCE(MON_REG2::numeric,0) ELSE 0 END) AS montant_regle_0, 
					SUM(CASE WHEN CAI_REG = CP1_DOS2 OR CAI_REG = ANY(CP1_DOS2_array) THEN COALESCE(MON_REG2::numeric,0) ELSE 0 END) AS montant_regle_1, 
					SUM(CASE WHEN (CAI_REG = CA2_DOS2 OR CAI_REG = ANY(CA2_DOS2_array)) AND CAI_REG <> CP1_DOS2 THEN COALESCE(MON_REG2::numeric,0) ELSE 0 END) AS montant_regle_2, 
					0::numeric AS montant_regle_22
				FROM prod_sigems.REG2
				JOIN prod_sigems.REG ON SER_REG2 = SER_REG
				JOIN prod_sigems.DOS2 ON ANN_REG2 = ANN_DOS2 AND COD_REG2 = COD_DOS2 AND IND_REG2 = IND_DOS2 AND ETA_DOS2 >= 1
				JOIN activite[PX].p_factures ON no_facture = ANN_REG2 || to_char(COD_REG2,'FM900000') || '.' || to_char(IND_REG2,'FM00')
				LEFT JOIN w_DOS2_TP ON ANN_REG2 = ANN_DOS2_TP AND COD_REG2 = COD_DOS2_TP
				WHERE HOC_REG2 = 'a'
				GROUP BY 1,2,3
				;
				
				
				-- 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_vente,
					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
                    code_facture = '1' 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(DAT_REG),
					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[
			
				-- Correction des GHM/GHS activité selon PMSI
				UPDATE activite[PX].p_sejours SET
					ghm_id = t_ghm.oid,
					ghs_id = t_ghs.oid
				FROM activite[PX].p_sejour_pmsi
				JOIN pmsi.p_rss ON p_sejour_pmsi.rss_id = p_rss.oid
				JOIN pmsi.t_ghm t_ghm_pmsi ON p_rss.ghm_id = t_ghm_pmsi.oid
				JOIN pmsi.t_ghs t_ghs_pmsi ON p_rss.ghs_id = t_ghs_pmsi.oid
				JOIN base.t_ghm ON t_ghm_pmsi.code = t_ghm.code
				JOIN base.t_ghs ON t_ghs_pmsi.code = t_ghs.code
				WHERE p_sejour_pmsi.sejour_id = p_sejours.oid AND
					p_rss.ghm_id  > 0 AND 
					p_sejours.ghm_id <= 0 AND
					t_ghm_pmsi.code NOT LIKE '90%' AND
					t_ghm_pmsi.code NOT LIKE '99%' 
				;
				
				ANALYSE activite[PX].p_sejours;
				ANALYSE activite[PX].p_factures;
				ANALYSE activite[PX].p_factures_lignes_c;
				
				-- Mise à jour date début PMSI pour EXH
				UPDATE pmsi.p_rsf_detail
				SET date_debut = date_debut_new
				FROM
				(
				SELECT rss_id, prestation_id, date_debut, date_fin, nombre, date(date_sortie - (nombre||' days')::interval) AS date_debut_new
				FROM pmsi.p_rsf_detail
				JOIN pmsi.t_prestations on prestation_id = t_prestations.oid
				JOIN pmsi.p_rss ON rss_id = p_rss.oid
				WHERE t_prestations.code = 'EXH' AND 
					date_debut = date_entree AND
					date(date_sortie - (nombre||' days')::interval) > date_entree
				) subview
				WHERE p_rsf_detail.rss_id = subview.rss_id AND
					p_rsf_detail.prestation_id = subview.prestation_id AND
					p_rsf_detail.date_debut = subview.date_debut AND
					p_rsf_detail.date_fin = subview.date_fin AND
					p_rsf_detail.nombre = subview.nombre
				;

				-- 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
					row_number() OVER() AS sequence,
					p_sejours.no_sejour,
					p_sejours.oid AS sejour_id,
					p_sejours.no_sejour || '.BG' AS no_facture,
					0::bigint AS facture_id,
					p_rss.traitement_epmsi,
					CASE WHEN p_rsf_detail.type = 'C' THEN 'H' ELSE 'C' END AS clinique_honoraire,
					p_rsf_detail.date_debut,
					CASE WHEN p_sejours.type_sejour <> '5' THEN p_rsf_detail.date_fin ELSE p_rsf_detail.date_debut END AS 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,
					CASE WHEN p_rss.traitement_epmsi IN ('30','31','32','33') THEN p_rsf_detail.sejour_remboursable ELSE 0 END AS montant_facture,
					0::numeric AS montant_facture_0,
					CASE WHEN p_rss.traitement_epmsi IN ('30','31','32','33') THEN p_rsf_detail.sejour_remboursable ELSE 0 END 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.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
                    p_rss.etat = '' AND
					operation_lamda IS DISTINCT FROM '1' AND
					operation_lamda IS DISTINCT FROM '2' AND 
					p_rsf_detail.fides_detail = 0
					;
					
				-- Eclatement des supplements par jour
				DROP TABLE IF EXISTS w_factures_lignes_pmsi_sup_c;

				CREATE TEMP TABLE w_factures_lignes_pmsi_sup_c AS
				SELECT
					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)||' days')::interval)  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_pmsi.*
				FROM w_factures_lignes_pmsi
					JOIN activite[PX].p_sejours ON w_factures_lignes_pmsi.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 p_sejours.type_sejour != '5' AND date(date_sortie) - date(date_entree) > 1)) 
                ;

				
				UPDATE w_factures_lignes_pmsi_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_pmsi
						JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND code = 'EXH'
					GROUP BY 1) subview
				WHERE w_factures_lignes_pmsi_sup_c.no_facture = subview.no_facture AND
					w_factures_lignes_pmsi_sup_c.prestation_code = 'GHS';

				CREATE INDEX w_factures_lignes_pmsi_sup_c_i1
				  ON w_factures_lignes_pmsi_sup_c
				  USING btree
				  (date_debut);

				DROP TABLE IF EXISTS w_factures_lignes_pmsi_sup_c_sup;

				CREATE TEMP TABLE w_factures_lignes_pmsi_sup_c_sup AS
				SELECT sequence,
					w_factures_lignes_pmsi_sup_c.no_sejour,
					w_factures_lignes_pmsi_sup_c.sejour_id,
					w_factures_lignes_pmsi_sup_c.no_facture,
					w_factures_lignes_pmsi_sup_c.facture_id,
					w_factures_lignes_pmsi_sup_c.traitement_epmsi,
					w_factures_lignes_pmsi_sup_c.clinique_honoraire,
					p_calendrier.date AS date_debut,
					p_calendrier.date AS date_fin,
					CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_rubrique,
					CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation,
					w_factures_lignes_pmsi_sup_c.coefficient,
					w_factures_lignes_pmsi_sup_c.coefficient_mco,
					w_factures_lignes_pmsi_sup_c.rubrique_facturation_id,
					w_factures_lignes_pmsi_sup_c.rubrique_comptabilisation_id,
					w_factures_lignes_pmsi_sup_c.prestation_id,
					round(montant_facture / ABS(nb_det),2) AS montant_facture,
					round(montant_facture_0 / ABS(nb_det),2) AS montant_facture_0,
					round(montant_facture_1 / ABS(nb_det),2) AS montant_facture_1,
					round(montant_facture_2 / ABS(nb_det),2) AS montant_facture_2,
					round(montant_facture_22 / ABS(nb_det),2) AS montant_facture_22,
					w_factures_lignes_pmsi_sup_c.taux_0,
					w_factures_lignes_pmsi_sup_c.taux_1,
					w_factures_lignes_pmsi_sup_c.taux_2,
					w_factures_lignes_pmsi_sup_c.taux_22,
					w_factures_lignes_pmsi_sup_c.prix_unitaire,
					w_factures_lignes_pmsi_sup_c.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,
					w_factures_lignes_pmsi_sup_c.origine_facturation_id,
					round(montant_comptabilise_budget_global_1 / ABS(nb_det),2) AS montant_comptabilise_budget_global_1,
					w_factures_lignes_pmsi_sup_c.protocole_id,
					w_factures_lignes_pmsi_sup_c.compte_produit_id,
					w_factures_lignes_pmsi_sup_c.prestation_code,
					w_factures_lignes_pmsi_sup_c.uf_code,
					w_factures_lignes_pmsi_sup_c.dmt_code,
					w_factures_lignes_pmsi_sup_c.mt_code
				FROM w_factures_lignes_pmsi_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_pmsi_sup_c_sup_tot;

				CREATE TEMP TABLE w_factures_lignes_pmsi_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_pmsi_sup_c_sup
				GROUP BY 1;


				UPDATE w_factures_lignes_pmsi
				SET
					date_fin = w_factures_lignes_pmsi.date_debut,
					nb_rubrique = w_factures_lignes_pmsi.nb_rubrique - w_factures_lignes_pmsi_sup_c_sup_tot.nb_rubrique,
					nb_prestation = w_factures_lignes_pmsi.nb_prestation - w_factures_lignes_pmsi_sup_c_sup_tot.nb_prestation,
					montant_facture = w_factures_lignes_pmsi.montant_facture - w_factures_lignes_pmsi_sup_c_sup_tot.montant_facture,
					montant_facture_0 = w_factures_lignes_pmsi.montant_facture_0 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_facture_0,
					montant_facture_1 = w_factures_lignes_pmsi.montant_facture_1 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_facture_1,
					montant_facture_2 = w_factures_lignes_pmsi.montant_facture_2 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_facture_2,
					montant_facture_22 = w_factures_lignes_pmsi.montant_facture_22 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_facture_22,
					montant_comptabilise = w_factures_lignes_pmsi.montant_comptabilise - w_factures_lignes_pmsi_sup_c_sup_tot.montant_comptabilise,
					montant_comptabilise_0 = w_factures_lignes_pmsi.montant_comptabilise_0 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_comptabilise_0,
					montant_comptabilise_1 = w_factures_lignes_pmsi.montant_comptabilise_1 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_comptabilise_1,
					montant_comptabilise_2 = w_factures_lignes_pmsi.montant_comptabilise_2 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_comptabilise_2,
					montant_comptabilise_22 = w_factures_lignes_pmsi.montant_comptabilise_22 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_comptabilise_22,
					montant_encours = w_factures_lignes_pmsi.montant_encours - w_factures_lignes_pmsi_sup_c_sup_tot.montant_encours,
					montant_encours_0 = w_factures_lignes_pmsi.montant_encours_0 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_encours_0,
					montant_encours_1 = w_factures_lignes_pmsi.montant_encours_1 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_encours_1,
					montant_encours_2 = w_factures_lignes_pmsi.montant_encours_2 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_encours_2,
					montant_encours_22 = w_factures_lignes_pmsi.montant_encours_22 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_encours_22,
					montant_facture_actes_inclus_dans_sejour = w_factures_lignes_pmsi.montant_facture_actes_inclus_dans_sejour - w_factures_lignes_pmsi_sup_c_sup_tot.montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour = w_factures_lignes_pmsi.montant_facture_0_actes_inclus_dans_sejour - w_factures_lignes_pmsi_sup_c_sup_tot.montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour = w_factures_lignes_pmsi.montant_facture_1_actes_inclus_dans_sejour - w_factures_lignes_pmsi_sup_c_sup_tot.montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour = w_factures_lignes_pmsi.montant_facture_2_actes_inclus_dans_sejour - w_factures_lignes_pmsi_sup_c_sup_tot.montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour = w_factures_lignes_pmsi.montant_facture_22_actes_inclus_dans_sejour - w_factures_lignes_pmsi_sup_c_sup_tot.montant_facture_22_actes_inclus_dans_sejour,
					montant_comptabilise_budget_global_1 = w_factures_lignes_pmsi.montant_comptabilise_budget_global_1 - w_factures_lignes_pmsi_sup_c_sup_tot.montant_comptabilise_budget_global_1
				FROM w_factures_lignes_pmsi_sup_c_sup_tot
				WHERE w_factures_lignes_pmsi.sequence = w_factures_lignes_pmsi_sup_c_sup_tot.sequence;
				
				

				INSERT INTO w_factures_lignes_pmsi(
					sequence,
					no_sejour,
					sejour_id,
					no_facture,
					facture_id,
					traitement_epmsi,
					clinique_honoraire,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					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,
					protocole_id,
					compte_produit_id,
					prestation_code,
					uf_code,
					dmt_code,
					mt_code
					)
				SELECT 
					sequence,
					no_sejour,
					sejour_id,
					no_facture,
					facture_id,
					traitement_epmsi,
					clinique_honoraire,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					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,
					protocole_id,
					compte_produit_id,
					prestation_code,
					uf_code,
					dmt_code,
					mt_code
				FROM w_factures_lignes_pmsi_sup_c_sup
				;

				-- 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_sigems.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_sigems.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_sigems.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_sigems.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_sigems.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_sigems.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_sigems.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_sigems.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_sigems.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_sigems.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_sigems.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,
					MAX(CASE WHEN w_factures_lignes_pmsi.traitement_epmsi IN ('30','31','32','33') THEN '1'::text ELSE '0' END) 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 AND 1 <> 1
				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 
                    p_rss.etat = '' AND
					p_rss.traitement_epmsi IN ('30','31','32','33')  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' AND
					  code_facture = '1';

				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 ;
					
					-- Lieu exécution
                    UPDATE activite[PX].p_factures_lignes_c
                    SET lieu_id = p_mouvements_sejour.lieu_id
                    FROM 
                        activite[PX].p_factures , 
                        activite[PX].p_mouvements_sejour
                    WHERE
                        p_factures_lignes_c.no_facture = p_factures.no_facture AND
                        p_factures.no_sejour = p_mouvements_sejour.no_sejour AND
                        p_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
                        p_factures_lignes_c.lieu_id <> p_mouvements_sejour.lieu_id;

					
					-- 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,
						ghs_bebe1_id,
						ghs_bebe2_id,
						ghs_bebe3_id)
					SELECT 
                        p_sejours.oid,
                        p_sejours.no_sejour, 
                        MAX(p_sejours.no_sejour || '.BG'), 
                        MAX(p_sejours.no_sejour || '.BG'), 
                        MAX(p_sejours.date_entree), 
                        MAX(p_sejours.date_sortie), 
                        '0', 
                        '0', 
                        '20991231'::date,
                        MAX(p_sejours.tiers_payant_0_id), 
                        MAX(p_sejours.tiers_payant_1_id), 
                        MAX(p_sejours.tiers_payant_2_id), 
                        MAX(p_sejours.tiers_payant_22_id),
                        MAX(p_sejours.ghs_id),
                        MAX(p_sejours.ghs_bebe1_id),
                        MAX(p_sejours.ghs_bebe2_id),
                        MAX(p_sejours.ghs_bebe3_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'
					JOIN base.t_ghm On p_sejours.ghm_id = t_ghm.oid
                    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 AND 
                        p_sejours.type_sejour IN ('1','2','5') AND
						t_ghm.code NOT IN ('09Z02A')
                    GROUP BY 1,2;
					
					-- 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,
						ghs_bebe1_id,
						ghs_bebe2_id,
						ghs_bebe3_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,
						p_sejours.ghs_bebe1_id,
						p_sejours.ghs_bebe2_id,
						p_sejours.ghs_bebe3_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
					JOIN base.t_ghm On p_sejours.ghm_id = t_ghm.oid
					WHERE p_sejours.est_budget_global = '1' AND
                        p_sejours.type_sejour IN ('1','2','5') AND
						type_t2a = '1' AND
						t_ghm.code NOT IN ('09Z02A') AND
						date_sortie between date(date_trunc('year',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
								p_factures_lignes_c.no_facture NOT LIKE '%BG' AND
								code_facture = '1' AND
								(t_prestations.code = 'PJ' OR t_prestations.code LIKE 'GHS%') AND
								(taux_1 = 100 OR taux_2 = 100 OR taux_0 = 100) 
							GROUP BY 1
							HAVING SUM(montant_facture_1+montant_facture_0+montant_facture_2) > 0
						);
                        
                    -- Séances pour séjour présents	
					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,
						ghs_bebe1_id,
						ghs_bebe2_id,
						ghs_bebe3_id)
					SELECT p_sejours.oid,
						p_sejours.no_sejour, 
						p_sejours.no_sejour || '.BG', 
						p_sejours.no_sejour || '.BG', 
						p_sejours.date_entree, 
						date(date_trunc('month',now()) + interval '1 month' - interval '1 day'), 
						'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,
						p_sejours.ghs_bebe1_id,
						p_sejours.ghs_bebe2_id,
						p_sejours.ghs_bebe3_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 date(date_trunc('year',now() - interval '1 year')) AND  now() AND
						p_sejours.type_sejour IN ('5') 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 base.t_ghm ON p_sejours.ghm_id = t_ghm.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
						p_factures_lignes_c.no_facture NOT LIKE '%BG' AND
						(
                        t_prestations.code = 'PJ' OR
                        t_prestations.code LIKE 'GHS%'  OR
						t_ghm.code IN ('09Z02A') OR
						t_prestations.code IN ('SE1','SE2','SE3','SE4','SE5','SE6','SE7','ATU')
                        ) AND
						(taux_1 + taux_2 + 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
						code_facture = '1',
                        date_facture = date_fin,
						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;
                        
                        
                    -- TRansfert de lignes non facturées vers budget global
                    UPDATE activite[PX].p_factures_lignes_non_facturees_c
                    SET no_facture = subview.no_facture_bg
                    FROM
                    (
                    SELECT p_sejours.no_sejour, t_prestations.code, t_prestations.texte, p_factures_lignes_non_facturees_c.*,
                        p_factures_bg.code_facture,p_factures_bg.no_facture AS no_facture_bg
                    FROM activite[PX].p_factures_lignes_non_facturees_c
                    JOIN activite[PX].p_factures ON p_factures_lignes_non_facturees_c.no_facture = p_factures.no_facture
                    JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour AND type_sejour IN ('1','2','5')
                    JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid 
                    JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid AND type_t2a = '1'
                    JOIN activite.t_prestations ON p_factures_lignes_non_facturees_c.prestation_id = t_prestations.oid
                    JOIN activite[PX].p_factures p_factures_bg ON p_factures_bg.no_sejour = p_factures.no_sejour AND p_factures_bg.no_facture LIKE '%BG' AND
                        p_factures_lignes_non_facturees_c.date_debut BETWEEN p_factures_bg.date_debut AND p_factures_bg.date_fin
                    WHERE p_factures_lignes_non_facturees_c.no_facture NOT LIKE '%BG' AND
                        t_prestations.code IN ('EMI','ETI','PII','PME','PH8','PHU') AND
                        p_factures_bg.code_facture = '0'
                    ) subview
                    WHERE p_factures_lignes_non_facturees_c.no_facture = subview.no_facture and
                        p_factures_lignes_non_facturees_c.prestation_id = subview.prestation_id
                        ;
						
					-- factures ajoutées à tord depuis SIGEMS alors que traitées par PMSI BG
					DROP TABLE IF EXISTS w_factures_00_bg;
					CREATE TEMP TABLE w_factures_00_bg AS
					SELECT p_factures.no_facture
					FROM activite[PX].p_factures
					WHERE p_factures.no_facture LIKE '%.00' AND
						p_factures.code_facture = '0' AND
						p_factures.no_sejour IN (SELECT p_factures_bg.no_sejour FROM activite[PX].p_factures p_factures_bg WHERE  p_factures_bg.no_facture LIKE '%BG' AND p_factures_bg.code_facture = '1') 
						order by 1
						;

					DELETE FROM activite[PX].p_factures_lignes_non_facturees_c
					WHERE no_facture IN (SELECT * FROM w_factures_00_bg)
					;

					DELETE FROM activite[PX].p_factures_lignes_non_facturees_h
					WHERE no_facture IN (SELECT * FROM w_factures_00_bg)
					;

					DELETE FROM activite[PX].p_factures
					WHERE no_facture IN (SELECT * FROM w_factures_00_bg)
					;




					
			]]></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,
						CASE WHEN p_factures_lignes_h.rubrique_facturation_id <> 0 THEN p_factures_lignes_h.rubrique_facturation_id ELSE COALESCE(t_rubriques_facturation.oid,0) END 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,
						CASE WHEN p_factures_lignes_h.rubrique_facturation_id <> 0 THEN p_factures_lignes_h.rubrique_facturation_id ELSE COALESCE(t_rubriques_facturation.oid,0) END 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
						((p_sejours.type_sejour = '3' AND p_factures_lignes_h.no_facture NOT LIKE '%BG') OR 
                        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 (verrouillé)
					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 1<>1 AND
						(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
							split_part(p_factures_lignes_c.no_facture,'.',1) = 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
							split_part(p_factures_lignes_h.no_facture,'.',1) = 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)
						;
                        
					-- 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_non_facturees_h.date_debut,
						p_factures_lignes_non_facturees_h.date_fin,
						p_factures_lignes_non_facturees_h.nb_rubrique,
						p_factures_lignes_non_facturees_h.coefficient,
						p_factures_lignes_non_facturees_h.rubrique_facturation_id,
						p_factures_lignes_non_facturees_h.prestation_id,
						p_factures_lignes_non_facturees_h.prix_unitaire,
						p_factures_lignes_non_facturees_h.lieu_id
					FROM activite[PX].p_factures_lignes_non_facturees_h 
					JOIN activite[PX].p_factures on p_factures_lignes_non_facturees_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
						;
					
					TRUNCATE activite[PX].p_factures_lignes_non_facturees_h
					;
                        
			]]></sqlcmd>
		</NODE>
		
		
		<NODE label="Budget global Externes">
			<condition><![CDATA[
				"[ENV_TYPEETS]" != "1" && "[ENV_WITHPMSI]" == "1"
			]]></condition>
			<sqlcmd><![CDATA[

	
					-- Séjours externes BG qui ne sont pas dans le PMSI
					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
						p_sejours.type_sejour = '3' 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 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
                            WHERE p_factures_lignes_c.no_facture NOT LIKE '%BG' AND montant_comptabilise_1 <> 0
                            )  
					;
					
					-- Sur Externes, Récupérer actes facturés partiellement
					INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
						facture_id,
						no_facture, 
						date_debut,
						rubrique_facturation_id, 
						prestation_id,  
						date_fin, 
						nb_rubrique, 
						coefficient, 
						lieu_id,
						prix_unitaire
						)
					SELECT 
						p_factures_bg.oid AS facture_id,
						p_factures_bg.no_facture AS no_facture,
						p_factures_lignes_c.date_debut,
						p_factures_lignes_c.rubrique_facturation_id,
						p_factures_lignes_c.prestation_id,
						MAX(p_factures_lignes_c.date_fin),
						1,
						1,
						MAX(p_factures_lignes_c.lieu_id),
						(MAX(prix_unitaire) * MAX(coefficient) * SUM(nb_rubrique)) - SUM(montant_facture) AS prix_unitaire
					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_factures p_factures_bg ON p_factures_bg.no_sejour = p_factures.no_sejour and p_factures_bg.no_facture LIKE '%BG'
						JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
					WHERE p_sejours.type_sejour = '3' AND
						p_factures_bg.code_facture = '0' AND
						p_factures_lignes_c.no_facture nOT LIKE '%BG' AND
						montant_encours = 0 AND p_factures_bg.montant_encours_c = 0
					GROUP BY 1,2,3,4,5
					HAVING
						SUM(nb_rubrique) > 0 AND
						((MAX(prix_unitaire) * MAX(coefficient) * SUM(nb_rubrique)) - SUM(montant_facture)) > 1
					;
					
					

					
			]]></sqlcmd>
		</NODE>
        
        <NODE label="Avoirs">
			<sqlcmd><![CDATA[
                -- Le lien entre avoirs et factures vient de la table dos2_lien_avoir
                
                -- Si l'aspirateur n'a pas encore été modifié, il faut la créer pour ne pas avoir d'erreur
                SELECT *
                FROM base.cti_execute('
                    CREATE TABLE prod_sigems.dos2_lien_avoir
                    (
                      ann character varying(2),
                      cod integer,
                      ind integer,
                      ind_avoir integer
                    )
                ',1)
                WHERE 
                (SELECT count(*) FROM pg_tables
                WHERE schemaname = 'prod_sigems' AND 
                    tablename = 'dos2_lien_avoir'
                ) = 0
                ;
                
    
                DROP TABLE IF EXISTS w_lien_avoir;
                CREATE TEMP TABLE w_lien_avoir AS
                SELECT
                    ANN || to_char(COD,'FM900000') || '.' || to_char(IND,'FM00') AS no_facture_annulee,
                    ANN || to_char(COD,'FM900000') || '.' || to_char(IND_AVOIR,'FM00') AS no_facture_avoir
                FROM prod_sigems.DOS2_LIEN_AVOIR
                ;
                
                -- Si table vide, déterminer depuis les factures et avoir 
                -- Cas de l'aspirateur non modifié ou de l'import depuis les fichiers texte
                DROP TABLE IF EXISTS w_sans_dos2_lien;
                CREATE TEMP TABLE w_sans_dos2_lien AS
                SELECT
                    no_sejour,
                    date_debut,
                    date_fin,
                            ''::text AS no_facture_annulee,
                            no_facture AS no_facture_avoir,
                            date_facture AS avoir_date_facture,
                            montant_comptabilise_c AS avoir_montant_comptabilise_c,
                            montant_comptabilise_h AS avoir_montant_comptabilise_h
                        FROM activite[PX].p_factures
                WHERE type_facture = '1' AND
                    (
                    montant_comptabilise_c <> 0 OR
                    montant_comptabilise_h <> 0
                    ) AND
                    (SELECT count(*) FROM prod_sigems.dos2_lien_avoir) = 0
                ;


                UPDATE w_sans_dos2_lien
                SET no_facture_annulee = subview.no_facture_annulee
                FROM
                (
                SELECT p_factures.no_sejour ,
                w_sans_dos2_lien.no_facture_avoir,
                MAX(p_factures.no_facture) AS no_facture_annulee
                FROM activite[PX].p_factures
                JOIN w_sans_dos2_lien ON p_factures.no_sejour = w_sans_dos2_lien.no_sejour
                WHERE p_factures.no_facture <> w_sans_dos2_lien.no_facture_avoir AND
                    p_factures.date_facture <= avoir_date_facture AND
                    p_factures.date_debut BETWEEN w_sans_dos2_lien.date_debut AND w_sans_dos2_lien.date_fin AND 
                    p_factures.no_facture < w_sans_dos2_lien.no_facture_avoir AND
                    p_factures.montant_comptabilise_c = 0-avoir_montant_comptabilise_c AND
                    p_factures.montant_comptabilise_h = 0-avoir_montant_comptabilise_h
                GROUP BY 1,2
                ) subview
                WHERE w_sans_dos2_lien.no_facture_avoir = subview.no_facture_avoir
                ;

                INSERT INTO w_lien_avoir
                SELECT no_facture_annulee, no_facture_avoir
                FROM w_sans_dos2_lien
                WHERE no_facture_annulee <> '' AND
                    no_facture_annulee NOT IN (SELECT no_facture_annulee FROM w_sans_dos2_lien GROUP BY 1 HAVING count(*) > 1)
                ;
                
                -- Traitement
                UPDATE activite[PX].p_factures SET
                    no_facture_od_avoir = no_facture_avoir,
                    facture_od_avoir_id = p_factures_od.oid,

                    montant_regle_c     = p_factures.montant_regle_c    - p_factures_od.montant_comptabilise_c,
                    montant_regle_1_c   = p_factures.montant_regle_1_c  - p_factures_od.montant_comptabilise_1_c,
                    montant_regle_2_c   = p_factures.montant_regle_2_c  - p_factures_od.montant_comptabilise_2_c,
                    montant_regle_22_c  = p_factures.montant_regle_22_c - p_factures_od.montant_comptabilise_22_c,
                    montant_regle_0_c   = p_factures.montant_regle_0_c  - p_factures_od.montant_comptabilise_0_c,
                    montant_regle_h     = p_factures.montant_regle_h    - p_factures_od.montant_comptabilise_h,
                    montant_regle_1_h   = p_factures.montant_regle_1_h  - p_factures_od.montant_comptabilise_1_h,
                    montant_regle_2_h   = p_factures.montant_regle_2_h  - p_factures_od.montant_comptabilise_2_h,
                    montant_regle_22_h  = p_factures.montant_regle_22_h - p_factures_od.montant_comptabilise_22_h,
                    montant_regle_0_h   = p_factures.montant_regle_0_h  - p_factures_od.montant_comptabilise_0_h
                FROM w_lien_avoir
                JOIN activite[PX].p_factures p_factures_od ON p_factures_od.no_facture = no_facture_avoir
                WHERE p_factures.no_facture = no_facture_annulee
                ;

                UPDATE activite[PX].p_factures SET
                    no_facture_od_avoir = no_facture_annulee,
                    facture_od_avoir_id = p_factures_od.oid,
                    
                    montant_regle_c     = p_factures.montant_regle_c    + p_factures.montant_comptabilise_c,
                    montant_regle_1_c   = p_factures.montant_regle_1_c  + p_factures.montant_comptabilise_1_c,
                    montant_regle_2_c   = p_factures.montant_regle_2_c  + p_factures.montant_comptabilise_2_c,
                    montant_regle_22_c  = p_factures.montant_regle_22_c + p_factures.montant_comptabilise_22_c,
                    montant_regle_0_c   = p_factures.montant_regle_0_c  + p_factures.montant_comptabilise_0_c,
                    montant_regle_h     = p_factures.montant_regle_h    + p_factures.montant_comptabilise_h,
                    montant_regle_1_h   = p_factures.montant_regle_1_h  + p_factures.montant_comptabilise_1_h,
                    montant_regle_2_h   = p_factures.montant_regle_2_h  + p_factures.montant_comptabilise_2_h,
                    montant_regle_22_h  = p_factures.montant_regle_22_h + p_factures.montant_comptabilise_22_h,
                    montant_regle_0_h   = p_factures.montant_regle_0_h  + p_factures.montant_comptabilise_0_h
                FROM w_lien_avoir
                JOIN activite[PX].p_factures p_factures_od ON p_factures_od.no_facture = no_facture_annulee
                WHERE p_factures.no_facture = no_facture_avoir
                ;

                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_annulee.no_facture,	
                    p_factures_annulee.oid AS facture_id,
                    p_factures_avoir.date_vente AS date_comptable,	
                    p_factures_soldes_od.rubrique_comptabilisee_id,	
                    p_factures_soldes_od.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,	
                    0-p_factures_soldes_od.montant_comptabilise  AS montant_regle,	
                    0-p_factures_soldes_od.montant_comptabilise_0 AS montant_regle_0,	
                    0-p_factures_soldes_od.montant_comptabilise_1 AS montant_regle_1,	
                    0-p_factures_soldes_od.montant_comptabilise_2 AS montant_regle_2,	
                    0-p_factures_soldes_od.montant_comptabilise_22 AS montant_regle_22,	
                    '1'::text AS od_avoir
                FROM w_lien_avoir
                JOIN activite[PX].p_factures_soldes_c p_factures_soldes_od ON p_factures_soldes_od.no_facture = no_facture_avoir
                JOIN activite[PX].p_factures p_factures_avoir ON p_factures_avoir.no_facture = no_facture_avoir
                JOIN activite[PX].p_factures p_factures_annulee ON p_factures_annulee.no_facture = no_facture_annulee
                WHERE p_factures_soldes_od.montant_comptabilise <> 0
                ;

                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_avoir.no_facture,	
                    p_factures_avoir.oid AS facture_id,
                    p_factures_avoir.date_vente AS date_comptable,	
                    p_factures_soldes_od.rubrique_comptabilisee_id,	
                    p_factures_soldes_od.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,	
                    p_factures_soldes_od.montant_comptabilise  AS montant_regle,	
                    p_factures_soldes_od.montant_comptabilise_0 AS montant_regle_0,	
                    p_factures_soldes_od.montant_comptabilise_1 AS montant_regle_1,	
                    p_factures_soldes_od.montant_comptabilise_2 AS montant_regle_2,	
                    p_factures_soldes_od.montant_comptabilise_22 AS montant_regle_22,	
                    '1'::text AS od_avoir
                FROM w_lien_avoir
                    JOIN activite[PX].p_factures_soldes_c p_factures_soldes_od ON p_factures_soldes_od.no_facture = no_facture_avoir
                    JOIN activite[PX].p_factures p_factures_avoir ON p_factures_avoir.no_facture = no_facture_avoir
                    JOIN activite[PX].p_factures p_factures_annulee ON p_factures_annulee.no_facture = no_facture_annulee
                WHERE p_factures_soldes_od.montant_comptabilise <> 0
                    ;

                    
                    
                INSERT INTO activite[PX].p_factures_soldes_h(
                    no_facture,	
                    facture_id,
                    date_comptable,	
                    medecin_comptabilise_id,
                    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_annulee.no_facture,	
                    p_factures_annulee.oid AS facture_id,
                    p_factures_avoir.date_vente AS date_comptable,	
                    p_factures_soldes_od.medecin_comptabilise_id,
                    p_factures_soldes_od.rubrique_comptabilisee_id,	
                    p_factures_soldes_od.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,	
                    0-p_factures_soldes_od.montant_comptabilise  AS montant_regle,	
                    0-p_factures_soldes_od.montant_comptabilise_0 AS montant_regle_0,	
                    0-p_factures_soldes_od.montant_comptabilise_1 AS montant_regle_1,	
                    0-p_factures_soldes_od.montant_comptabilise_2 AS montant_regle_2,	
                    0-p_factures_soldes_od.montant_comptabilise_22 AS montant_regle_22,	
                    '1'::text AS od_avoir
                FROM w_lien_avoir
                JOIN activite[PX].p_factures_soldes_h p_factures_soldes_od ON p_factures_soldes_od.no_facture = no_facture_avoir
                JOIN activite[PX].p_factures p_factures_avoir ON p_factures_avoir.no_facture = no_facture_avoir
                JOIN activite[PX].p_factures p_factures_annulee ON p_factures_annulee.no_facture = no_facture_annulee
                WHERE p_factures_soldes_od.montant_comptabilise <> 0
                ;

                INSERT INTO activite[PX].p_factures_soldes_h(
                    no_facture,	
                    facture_id,
                    date_comptable,
                    medecin_comptabilise_id,
                    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_avoir.no_facture,	
                    p_factures_avoir.oid AS facture_id,
                    p_factures_avoir.date_vente AS date_comptable,	
                    p_factures_soldes_od.medecin_comptabilise_id,
                    p_factures_soldes_od.rubrique_comptabilisee_id,	
                    p_factures_soldes_od.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,	
                    p_factures_soldes_od.montant_comptabilise  AS montant_regle,	
                    p_factures_soldes_od.montant_comptabilise_0 AS montant_regle_0,	
                    p_factures_soldes_od.montant_comptabilise_1 AS montant_regle_1,	
                    p_factures_soldes_od.montant_comptabilise_2 AS montant_regle_2,	
                    p_factures_soldes_od.montant_comptabilise_22 AS montant_regle_22,	
                    '1'::text AS od_avoir
                FROM w_lien_avoir
                    JOIN activite[PX].p_factures_soldes_h p_factures_soldes_od ON p_factures_soldes_od.no_facture = no_facture_avoir
                    JOIN activite[PX].p_factures p_factures_avoir ON p_factures_avoir.no_facture = no_facture_avoir
                    JOIN activite[PX].p_factures p_factures_annulee ON p_factures_annulee.no_facture = no_facture_annulee
                WHERE p_factures_soldes_od.montant_comptabilise <> 0
                    ;
					
				-- Ecarts total réglé et detail regle par OD
				DROP TABLE IF EXISTS w_factures_solde;
				CREATE TEMP TABLE w_factures_solde AS
				SELECT 
					ANN_DOS2|| to_char(COD_DOS2,'FM900000') || '.' || to_char(IND_DOS2,'FM00') AS no_facture,
					date(DFA_DOS2) AS DFA_DOS2,
					CASE WHEN SJ1_DOS2 = SR1_DOS2 THEN '1' ELSE '0' END AS solde1c,
					CASE WHEN SJ2_DOS2 = SR2_DOS2 THEN '1' ELSE '0' END AS solde2c,
					CASE WHEN SJ3_DOS2 = SR3_DOS2 THEN '1' ELSE '0' END AS solde0c,
					CASE WHEN HO1_DOS2 = HR1_DOS2 THEN '1' ELSE '0' END AS solde1h,
					CASE WHEN HO2_DOS2 = HR2_DOS2 THEN '1' ELSE '0' END AS solde2h,
					CASE WHEN HO3_DOS2 = HR3_DOS2 THEN '1' ELSE '0' END AS solde0h
				FROM prod_sigems.DOS2
				;

				INSERT INTO activite[PX].p_factures_soldes_c(
					facture_id,
					no_facture, 
					date_comptable, 
					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,
					od_non_comptabilise
				)
				SELECT 
					facture_id,
					p_factures_soldes_c.no_facture, 
					MAX(date_comptable), 
					prestation_id,
					rubrique_comptabilisee_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(CASE WHEN solde0c = '1' THEN montant_comptabilise_0-montant_regle_0 ELSE 0 END)+
					SUM(CASE WHEN solde1c = '1' THEN montant_comptabilise_1-montant_regle_1 ELSE 0 END)+
					SUM(CASE WHEN solde2c = '1' THEN montant_comptabilise_2-montant_regle_2 ELSE 0 END) AS montant_regle,
					SUM(CASE WHEN solde0c = '1' THEN montant_comptabilise_0-montant_regle_0 ELSE 0 END) AS montant_regle_0,
					SUM(CASE WHEN solde1c = '1' THEN montant_comptabilise_1-montant_regle_1 ELSE 0 END) AS montant_regle_1,
					SUM(CASE WHEN solde2c = '1' THEN montant_comptabilise_2-montant_regle_2 ELSE 0 END) AS montant_regle_2,
					0 AS montant_regle_22,
					'1' AS od_non_comptabilise
				FROM activite[PX].p_factures_soldes_c
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				JOIN w_factures_solde ON w_factures_solde.no_facture = p_factures_soldes_c.no_facture
				WHERE t_prestations.code_original <> '*CTI_ACO85'
				GROUP BY 1,2,4,5,6
				HAVING SUM(montant_comptabilise-montant_regle) <> 0
				;


				
				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,
					od_non_comptabilise
				)
				SELECT 
					facture_id,
					p_factures_soldes_h.no_facture, 
					MAX(date_comptable), 
					medecin_comptabilise_id, 
					prestation_id,
					rubrique_comptabilisee_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(CASE WHEN solde0h = '1' THEN montant_comptabilise_0-montant_regle_0 ELSE 0 END)+
					SUM(CASE WHEN solde1h = '1' THEN montant_comptabilise_1-montant_regle_1 ELSE 0 END)+
					SUM(CASE WHEN solde2h = '1' THEN montant_comptabilise_2-montant_regle_2 ELSE 0 END) AS montant_regle,
					SUM(CASE WHEN solde0h = '1' THEN montant_comptabilise_0-montant_regle_0 ELSE 0 END) AS montant_regle_0,
					SUM(CASE WHEN solde1h = '1' THEN montant_comptabilise_1-montant_regle_1 ELSE 0 END) AS montant_regle_1,
					SUM(CASE WHEN solde2h = '1' THEN montant_comptabilise_2-montant_regle_2 ELSE 0 END) AS montant_regle_2,
					0 AS montant_regle_22,
					'1' AS od_non_comptabilise
				FROM activite[PX].p_factures_soldes_h
				JOIN w_factures_solde ON w_factures_solde.no_facture = p_factures_soldes_h.no_facture
				WHERE p_factures_soldes_h.no_facture NOT IN (SELECT no_facture FROM activite[PX].p_factures_soldes_h WHERE medecin_comptabilise_id = 0)
				GROUP BY 1,2,4,5,6
				HAVING SUM(montant_comptabilise-montant_regle) <> 0 AND
					(
					SUM(CASE WHEN solde0h = '1' THEN montant_comptabilise_0-montant_regle_0 ELSE 0 END)+
					SUM(CASE WHEN solde1h = '1' THEN montant_comptabilise_1-montant_regle_1 ELSE 0 END)+
					SUM(CASE WHEN solde2h = '1' THEN montant_comptabilise_2-montant_regle_2 ELSE 0 END)
					) <> 0
				;

				UPDATE activite[PX].p_factures SET
					montant_regle_0_c = CASE WHEN solde0c = '1' THEN montant_comptabilise_0_c ELSE p_factures.montant_regle_0_c END,
					montant_regle_1_c = CASE WHEN solde1c = '1' THEN montant_comptabilise_1_c ELSE p_factures.montant_regle_1_c END,
					montant_regle_2_c = CASE WHEN solde2c = '1' THEN montant_comptabilise_2_c ELSE p_factures.montant_regle_2_c END,
					montant_regle_0_h = CASE WHEN solde0h = '1' THEN montant_comptabilise_0_h ELSE p_factures.montant_regle_0_h END,
					montant_regle_1_h = CASE WHEN solde1h = '1' THEN montant_comptabilise_1_h ELSE p_factures.montant_regle_1_h END,
					montant_regle_2_h = CASE WHEN solde2h = '1' THEN montant_comptabilise_2_h ELSE p_factures.montant_regle_2_h END
				FROM w_factures_solde
				WHERE w_factures_solde.no_facture = p_factures.no_facture AND
					(
					montant_regle_0_c IS DIStinct from CASE WHEN solde0c = '1' THEN montant_comptabilise_0_c ELSE p_factures.montant_regle_0_c END OR
					montant_regle_1_c IS DIStinct from CASE WHEN solde1c = '1' THEN montant_comptabilise_1_c ELSE p_factures.montant_regle_1_c END OR
					montant_regle_2_c IS DIStinct from CASE WHEN solde2c = '1' THEN montant_comptabilise_2_c ELSE p_factures.montant_regle_2_c END OR
					montant_regle_0_h IS DIStinct from CASE WHEN solde0h = '1' THEN montant_comptabilise_0_h ELSE p_factures.montant_regle_0_h END OR
					montant_regle_1_h IS DIStinct from CASE WHEN solde1h = '1' THEN montant_comptabilise_1_h ELSE p_factures.montant_regle_1_h END OR
					montant_regle_2_h IS DIStinct from CASE WHEN solde2h = '1' THEN montant_comptabilise_2_h ELSE p_factures.montant_regle_2_h END
					)
				;

				UPDATE activite[PX].p_factures SET
					montant_regle_c = montant_regle_0_c+montant_regle_1_c+montant_regle_2_c,
					montant_regle_h = montant_regle_0_h+montant_regle_1_h+montant_regle_2_h
				WHERE 
					(
					montant_regle_c IS DISTINCT FROM montant_regle_0_c+montant_regle_1_c+montant_regle_2_c OR
					montant_regle_h IS DISTINCT FROM montant_regle_0_h+montant_regle_1_h+montant_regle_2_h
					)
				;
               ]]></sqlcmd>
		</NODE>
	
    
    
		<NODE label="Factures de référence">
			<sqlcmd><![CDATA[
			
				-- Correction date de fin facture pour séjours présents si un GHS est dans les lignes 'saisies'
				UPDATE activite[PX].p_factures SET
					date_fin = subview.DFI_LCL
				FROM
				(
				SELECT p_factures.no_facture, DFI_LCL, type_sejour, date_debut, date_fin, SER_LCL
				FROM activite[PX].p_factures
				JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				JOIN 
					(
					SELECT ANN_LCL || to_char(COD_LCL,'FM900000') AS SEJ_LCL,
						date(MAX(DFI_LCL)) AS DFI_LCL,
						MAX(SER_LCL) AS SER_LCL
					FROM prod_sigems.DOSSIER
					JOIN prod_sigems.LIG_CLINI ON 
						ANN_LCL = ANN_DOS AND
						COD_LCL = COD_DOS
					WHERE DSO_DOS IS NULL AND 
						DFI_LCL IS NOT NULL AND
						PRO_LCL = 'GHS' AND
						DDE_LCL = DEN_DOS 
					GROUP BY 1
					) subview
				ON p_factures.no_sejour = SEJ_LCL AND
					p_factures.code_facture = '0' AND
					p_sejours.code_sorti = '0' AND
					type_sejour <> '9' AND
					p_factures.date_fin >= date(now() - interval '2 days') AND
					DFI_LCL <> date_fin
				) subview
				WHERE p_factures.no_facture = subview.no_facture
				;
				
				
				-- 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 label="Réorientation prestations FSD">
			<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';


				
	
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Réorientation prestations médecins salariés">
			<sqlcmd><![CDATA[
					
				-- Les médecins salarié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,
					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.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].t_medecins_administratifs ON medecin_comptabilise_id = t_medecins_administratifs.oid
				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_medecin_salarie = 1 AND
					p_factures_lignes_h.montant_comptabilise <> 0
					;

				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_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].t_medecins_administratifs ON medecin_comptabilise_id = t_medecins_administratifs.oid
				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_medecin_salarie = 1 AND
					p_factures_lignes_h.montant_comptabilise <> 0
				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_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_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;

				UPDATE activite[PX].p_factures_lignes_h
				SET 
					montant_comptabilise = 0,
					montant_comptabilise_0 = 0,
					montant_comptabilise_1 = 0,
					montant_comptabilise_2 = 0,
					montant_comptabilise_22 = 0
				FROM activite[PX].t_medecins_administratifs
				WHERE medecin_comptabilise_id = t_medecins_administratifs.oid AND
					est_medecin_salarie = 1 AND
					p_factures_lignes_h.montant_comptabilise <> 0;

				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_medecins_administratifs ON medecin_comptabilise_id = t_medecins_administratifs.oid
				WHERE est_medecin_salarie = 1 AND
					(
					p_factures_soldes_h.montant_comptabilise <> 0 OR
					p_factures_soldes_h.montant_regle <> 0
					)
				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,
					od_non_comptabilise
					)
				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,
					'1'::text AS od_non_comptabilise
				FROM activite[PX].p_factures_soldes_h
				JOIN activite[PX].t_medecins_administratifs ON medecin_comptabilise_id = t_medecins_administratifs.oid
				WHERE est_medecin_salarie = 1 AND
					(
					p_factures_soldes_h.montant_comptabilise <> 0 OR
					p_factures_soldes_h.montant_regle <> 0
					);

				DELETE FROM activite[PX].p_factures_soldes_h
				USING activite[PX].t_medecins_administratifs
				WHERE medecin_comptabilise_id = t_medecins_administratifs.oid AND
					est_medecin_salarie = 1 AND
					(
					p_factures_soldes_h.montant_comptabilise <> 0 OR
					p_factures_soldes_h.montant_regle <> 0
					)
				;


			]]></sqlcmd>
		</NODE>
		

		
	</NODE>
	
	<NODE name="CHIFFRIER" label="CREATION DU CHIFFRIER">
	
		<NODE label="Ecritures comptables">
			<sqlcmd><![CDATA[
			
				-- Ecritures comptables
				DROP TABLE IF EXISTS w_STE;
				CREATE TEMP TABLE w_STE AS
				SELECT (MAX(ARRAY[to_char(nb,'FM000000000000'),ECR_STE]))[2] AS ECR_STE_cli
				FROM
				(
				SELECT ECR_STE, count(*) AS nb
				FROM prod_sigems.ecrit
				WHERE ECR_DATE >= date_trunc('year',now())-interval '1 year'
				GROUP BY 1
				) subview
				;

				DROP TABLE IF EXISTS w_ECRIT_CLI;
				CREATE TEMP TABLE w_ECRIT_CLI AS
				SELECT ''::text AS ANNEE,
					0::numeric AS CODE,
					0::numeric AS INDICE,
					''::text AS no_sejour,
					''::text AS no_facture,
					ECRIT.*,
					COALESCE(ECR_LIBEL,'') AS ECR_LIBEL,
					COALESCE(SER_REG,0) AS SER_REG,
					'0'::text AS ECR_ACOMPTE,
					0::bigint AS medecin_administratif_id,
					0::bigint AS tiers_payant_id,
					''::text AS mode_reglement_code
				FROM prod_sigems.ECRIT
				JOIN w_STE ON ECR_STE = ECR_STE_cli
				LEFT JOIN prod_sigems.ECRIT_COMPTALIBEL ON ECRIT.ECR_NUM = ECRIT_COMPTALIBEL.ECR_NUM
				LEFT JOIN prod_sigems.MAGIC ON ECRIT.ECR_NUM = MAGIC.NUM_ECR
				WHERE ECR_DATE >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					ECRIT.ECR_JNAL <> 'AN' AND
					ECRIT.ECR_JNAL <> 'ANH' AND
					ECRIT.ECR_JNAL <> 'ACHAT' AND
					ECRIT.ECR_JNAL <> 'ACHA' AND
					ECRIT.ECR_JNAL <> 'SITU' AND
					ECRIT.ECR_ANNUL <> 'S' AND
					ECRIT.ECR_PIECE <> 'CENTRALI' AND
					ECRIT.ECR_PLAN NOT IN ('A','B')
				;


				UPDATE w_ECRIT_CLI
				SET ECR_CEMT = ECR_CPTE
				WHERE ECR_CEMT = ''
				;

				UPDATE w_ECRIT_CLI SET
					ANNEE = DOS_ECRIT.ANNEE,
					CODE = DOS_ECRIT.CODE,
					INDICE = DOS_ECRIT.INDICE,
					no_sejour = DOS_ECRIT.ANNEE || to_char(DOS_ECRIT.CODE, 'FM900000'),
					no_facture = DOS_ECRIT.ANNEE || to_char(DOS_ECRIT.CODE, 'FM900000') || '.' || to_char(DOS_ECRIT.INDICE,'FM00')
				FROM prod_sigems.DOS_ECRIT
				WHERE SERI = ECR_NUM
				;

				
				UPDATE w_ECRIT_CLI SET
					ANNEE = subview.ANNEE,
					CODE = subview.CODE,
					INDICE = subview.INDICE,
					no_sejour = subview.no_sejour,
					no_facture = subview.no_facture
				FROM 
					(
					SELECT SER_REG, ECR_JNAL, ECR_DATE, 
						MAX(ANNEE) AS ANNEE, 
						MAX(CODE) AS CODE, 
						MAX(INDICE) AS INDICE,
						MAX(no_sejour) AS no_sejour,
						MAX(no_facture) AS no_facture
					FROM w_ECRIT_CLI
					GROUP BY 1,2,3
					HAVING MAX(CODE) > 0 AND MIN(CODE) = 0 AND
						count(DISTINCT CASE WHEN no_facture <> '' THEN no_facture ELSE NULL END) = 1
					) subview
				WHERE w_ECRIT_CLI.SER_REG = subview.SER_REG AND
					w_ECRIT_CLI.ECR_JNAL = subview.ECR_JNAL AND
					w_ECRIT_CLI.ECR_DATE = subview.ECR_DATE AND
					w_ECRIT_CLI.CODE = 0
				;


				UPDATE w_ECRIT_CLI SET
					ANNEE = subview.ANNEE,
					CODE = subview.CODE,
					INDICE = subview.INDICE,
					no_sejour = subview.no_sejour,
					no_facture = subview.no_facture
				FROM 
					(
					SELECT ECR_PIECE, ECR_JNAL, ECR_DATE, 
						MAX(ANNEE) AS ANNEE, 
						MAX(CODE) AS CODE, 
						MAX(INDICE) AS INDICE,
						MAX(no_sejour) AS no_sejour,
						MAX(no_facture) AS no_facture
					FROM w_ECRIT_CLI
					GROUP BY 1,2,3
					HAVING MAX(CODE) > 0 AND MIN(CODE) = 0 AND
						count(DISTINCT CASE WHEN no_facture <> '' THEN no_facture ELSE NULL END) = 1
					) subview
				WHERE w_ECRIT_CLI.ECR_PIECE = subview.ECR_PIECE AND
					w_ECRIT_CLI.ECR_JNAL = subview.ECR_JNAL AND
					w_ECRIT_CLI.ECR_DATE = subview.ECR_DATE AND
					w_ECRIT_CLI.CODE = 0
				;



				UPDATE w_ECRIT_CLI
				SET ECR_ACOMPTE = '1'
				WHERE ECR_CEMT LIKE '41%' AND SER_REG IN 
				(
				SELECT SER_REG
				FROM w_ECRIT_CLI
				WHERE 
					ecr_jnal NOT LIKE 'VEN%' AND ecr_plan <> 'C' AND ecr_plan <> 'G'
				GROUP BY 1
				HAVING SUM(CASE WHEN ECR_CEMT LIKE '41%' THEN ECR_CREDIT-ECR_DEBIT ELSE 0 END) =
					SUM(CASE WHEN ECR_CPTE = 'ACOMPT' THEN ECR_DEBIT-ECR_CREDIT ELSE 0 END) AND
					SUM(CASE WHEN ECR_CPTE = 'ACOMPT' THEN 1 ELSE 0 END) > 0
				)
				;



				UPDATE w_ECRIT_CLI
				SET medecin_administratif_id = t_medecins_administratifs.oid
				FROM activite[PX].t_medecins_administratifs
				WHERE ECR_PLAN = 'M' AND
					ECR_CPTE = t_medecins_administratifs.code_original
				;
				
				UPDATE w_ECRIT_CLI
				SET tiers_payant_id = 
					CASE substr(ECR_CPTE,4,1)
					WHEN '1' THEN tiers_payant_1_id
					WHEN '2' THEN tiers_payant_2_id
					WHEN '3' THEN tiers_payant_0_id
					END
				FROM activite[PX].p_factures
				WHERE w_ECRIT_CLI.no_facture = p_factures.no_facture AND 
					tiers_payant_id = 0 AND
					ECR_PLAN = ANY(ARRAY['C','P']) AND substr(ECR_CPTE,4,1) IN ('1','2','3')
				;
				
				UPDATE w_ECRIT_CLI
				SET tiers_payant_id = 
					CASE substr(ECR_CPTE,4,1)
					WHEN '1' THEN tiers_payant_1_id
					WHEN '2' THEN tiers_payant_2_id
					WHEN '3' THEN tiers_payant_0_id
					END
				FROM activite[PX].p_sejours
				WHERE w_ECRIT_CLI.no_sejour = p_sejours.no_sejour AND 
					tiers_payant_id = 0 AND
					ECR_PLAN = ANY(ARRAY['C','P']) AND substr(ECR_CPTE,4,1) IN ('1','2','3')
				;


				UPDATE w_ECRIT_CLI
				SET tiers_payant_id = tiers_payant_0_id
				FROM activite[PX].p_sejours,
					prod_sigems.REG
				WHERE w_ECRIT_CLI.no_sejour = p_sejours.no_sejour AND 
					w_ECRIT_CLI.SER_REG = REG.SER_REG AND
					CAI_REG = '99999999' AND
					tiers_payant_id = 0 AND
					ECR_PLAN = ANY(ARRAY['C','P'])
				;

				

				UPDATE w_ECRIT_CLI
				SET tiers_payant_id = t_tiers_payant.oid
				FROM activite[PX].t_tiers_payant 
				WHERE t_tiers_payant.code_original = 'PATIENT' AND
					tiers_payant_id = 0 AND
					ECR_PLAN = ANY(ARRAY['C','P']) AND
					ANNEE = 'PA'
				;


				UPDATE w_ECRIT_CLI
				SET tiers_payant_id = tiers_payant_1_id
				FROM activite[PX].p_factures
				WHERE w_ECRIT_CLI.no_facture = p_factures.no_facture AND 
					tiers_payant_id = 0 AND
					ECR_PLAN = ANY(ARRAY['C','P']) AND
					ECR_CPTE = 'NOEMIE'
				;

			
				-- Journal
				INSERT INTO activite[PX].t_journal (code_original, code, texte)
				SELECT CODEJ,
					CODEJ,
					MAX(LIBEL)
				FROM prod_sigems.JNAL
				WHERE CODEJ NOT IN (SELECT code_original FROM activite[PX].t_journal WHERE code_original IS NOT NULL)
				GROUP BY 1,2
				;

				INSERT INTO activite[PX].t_journal (code_original, code, texte)
				SELECT ECR_JNAL, ECR_JNAL, ECR_JNAL
				FROM w_ECRIT_cli
				WHERE ECR_JNAL NOT IN (SELECT code_original FROM activite[PX].t_journal WHERE code_original IS NOT NULL)
				GROUP BY 1
				;


				INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
				SELECT NUM, NUM, (MIN(ARRAY[TYP,INT1]))[2], (MIN(ARRAY[TYP,INT1||INT2]))[2]
				FROM prod_sigems.COMPTE
				WHERE TYP IN ('G','H') AND
					NUM IN (SELECT ECR_CEMT FROM w_ECRIT_cli) AND
					NUM <> '' AND
					NUM <> '0' AND
					NUM NOT LIKE '0' AND
					NUM IS NOT NULL AND
					NUM NOT IN (SELECT code_original FROM activite[PX].t_compte)
				GROUP BY 1
				ORDER BY 1
				;

				WITH comptes AS (
					SELECT NUM,
					(MIN(ARRAY[TYP,INT1]))[2] AS texte,
					(MIN(ARRAY[TYP,INT1||INT2]))[2] AS texte_court
					FROM prod_sigems.COMPTE
					WHERE TYP IN ('G','H') AND
						NUM IN (SELECT ECR_CEMT FROM w_ECRIT_cli) AND
						NUM <> '' AND
						NUM <> '0' AND
						NUM NOT LIKE '0' AND
						NUM IS NOT NULL
					GROUP BY 1
					ORDER BY 1
				)
				UPDATE activite[PX].t_compte SET
					code = comptes.NUM,
					texte = comptes.texte,
					texte_court = comptes.texte_court
				FROM comptes
				WHERE NUM = code_original AND
					(
						t_compte.code IS DISTINCT FROM NUM OR 
						t_compte.texte IS DISTINCT FROM comptes.texte OR
						t_compte.texte_court IS DISTINCT FROM comptes.texte_court
					)
				;

				INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
				SELECT ECR_CEMT, ECR_CEMT, ECR_CEMT, ECR_CEMT
				FROM w_ECRIT_CLI
				WHERE ECR_CEMT <> '' AND
				ECR_CEMT NOT LIKE '0' AND
				ECR_CEMT IS NOT NULL AND
				ECR_CEMT NOT IN (SELECT code_original FROM activite[PX].t_compte)
				GROUP BY 1
				ORDER BY 1
				;
				
				-- Mode règlement
				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = 'CHQ'
				WHERE (ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%') AND
					ECR_REDUI = 'c'
				;
				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = 'CB'
				WHERE (ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%') AND
					ECR_REDUI = 'b'
				;
				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = 'ESP'
				WHERE (ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%') AND
					ECR_REDUI = 'e'
				;
				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = 'VIR'
				WHERE (ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%') AND
					ECR_REDUI = 'v'
				;

				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = 'VIR'
				WHERE (ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%') AND
					mode_reglement_code = '' AND
					(ECR_CHEQ ILIKE 'V%' OR ECR_LIBEL ILIKE 'VRT%' OR ECR_PIECE ILIKE 'VRT%' OR ECR_LIBEL ILIKE 'VIREMENT%')
				;

				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = 'CHQ'
				WHERE (ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%') AND
					mode_reglement_code = '' AND
					length(ECR_CHEQ) = 7 AND
					to_char(base.cti_to_number(ECR_CHEQ),'FM0000000') = ECR_CHEQ
				;

				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = 'CHQ'
				WHERE (ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%') AND
					mode_reglement_code = '' AND
					(ECR_LIBEL ILIKE 'REMISE CHQ%' OR ECR_PIECE LIKE 'CHQ%')
				;

				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = 'CB'
				WHERE (ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%') AND
					mode_reglement_code = '' AND
					ECR_LIBEL ILIKE 'REMISE C.B%'
				;


				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = 'VIR'
				FROM
				(
				SELECT ECR_DATE, ECR_JNAL, ECR_PIECE
				FROM w_ECRIT_CLI
				GROUP BY 1,2,3
				HAVING MAX(CASE WHEN ECR_CPTE = 'NOEMIE' THEN 1 ELSE 0 END) > 0 AND
					MAX(CASE WHEN ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%' THEN 1 ELSE 0 END) > 0
				) subview
				WHERE w_ECRIT_CLI.ECR_DATE = subview.ECR_DATE AND
					w_ECRIT_CLI.ECR_JNAL = subview.ECR_JNAL AND
					w_ECRIT_CLI.ECR_PIECE = subview.ECR_PIECE AND
					mode_reglement_code = '' AND
					(w_ECRIT_CLI.ECR_CEMT LIKE '51%' OR w_ECRIT_CLI.ECR_CEMT LIKE '53%')
				;
				
				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = 'VIR'
				WHERE (ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%') AND
					mode_reglement_code = '' AND
					ECR_REDUI = '1'
				;
				
				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = 'ESP'
				WHERE (ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%') AND
					mode_reglement_code = '' AND
					ECR_LIBEL LIKE '%ESPECE%' 
				;
				
				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = 'CHQ'
				WHERE (ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%') AND
					mode_reglement_code = '' AND
					ECR_LIBEL LIKE '%CHEQUE%' 
				;


				UPDATE w_ECRIT_CLI
				SET mode_reglement_code = subview.mode_reglement_code
				FROM
				(
				SELECT ECR_DATE, ECR_JNAL, ECR_PIECE, MAX(mode_reglement_code) AS mode_reglement_code
				FROM w_ECRIT_CLI
				WHERE (ECR_CEMT LIKE '51%' OR ECR_CEMT LIKE '53%')
				GROUP BY 1,2,3
				HAVING count(DISTINCT CASE WHEN mode_reglement_code <> '' THEN mode_reglement_code ELSE NULL END) = 1 AND
					MAX(CASE WHEN mode_reglement_code = '' THEN 1 ELSE 0 END) > 0 
				) subview
				WHERE w_ECRIT_CLI.ECR_DATE = subview.ECR_DATE AND
					w_ECRIT_CLI.ECR_JNAL = subview.ECR_JNAL AND
					w_ECRIT_CLI.ECR_PIECE = subview.ECR_PIECE AND
					w_ECRIT_CLI.mode_reglement_code = '' AND
					(w_ECRIT_CLI.ECR_CEMT LIKE '51%' OR w_ECRIT_CLI.ECR_CEMT LIKE '53%')
				;

				

				DROP TABLE IF EXISTS w_ecriture_comptable;
				CREATE TEMP TABLE w_ecriture_comptable AS
				SELECT 
					ECR_NUM::text AS code_original,
					date(ECR_DATE) AS date_comptable,
					CASE 
					WHEN t_journal.type_journal = 'VE' AND ECR_CEMT LIKE '411%' THEN 'VCLI'
					WHEN t_journal.type_journal = 'VE' AND ECR_CEMT LIKE '412%' THEN 'VCLI'
					WHEN t_journal.type_journal = 'VE' AND ECR_CEMT LIKE '445%' THEN 'VTVA'
					WHEN t_journal.type_journal = 'VE' AND ECR_PLAN = 'G' THEN 'VPRD'
					WHEN t_journal.type_journal = 'VE' AND ECR_PLAN = 'M' THEN 'VHON'
					WHEN ECR_CEMT LIKE '758%' THEN 'PEPR'
					WHEN ECR_CEMT LIKE '658%' THEN 'PEPR'
					WHEN t_journal.type_journal <> 'VE' AND ECR_CEMT LIKE '468%' THEN 'ATT'
					WHEN t_journal.type_journal <> 'VE' AND ECR_CEMT LIKE '471%' THEN 'ATT'
					WHEN t_journal.type_journal <> 'VE' AND ECR_CPTE LIKE 'ACOMPT%' THEN 'ACPT'
					WHEN t_journal.type_journal <> 'VE' AND ECR_CPTE LIKE 'NOEMIE%' THEN 'RNOE'
					WHEN t_journal.type_journal <> 'VE' AND ECR_CEMT LIKE '411%' THEN 'RCLI'
					WHEN t_journal.type_journal <> 'VE' AND ECR_CEMT LIKE '412%' THEN 'RCLI'
					WHEN t_journal.type_journal <> 'VE' AND ECR_CEMT LIKE '419%' THEN 'ACPT'
					WHEN t_journal.type_journal <> 'VE' AND ECR_CEMT LIKE '51%' THEN 'BANQ'
					WHEN t_journal.type_journal <> 'VE' AND ECR_CEMT LIKE '531%' THEN 'BANQ'
					WHEN t_journal.type_journal <> 'VE' AND ECR_CEMT LIKE '466%' THEN 'PHON'
					WHEN t_journal.type_journal <> 'VE' AND ECR_CEMT LIKE '7%' THEN 'XPRD'
					WHEN t_journal.type_journal <> 'VE' AND ECR_CEMT LIKE '445%' THEN 'XTVA'
					ELSE '?'||ECR_JNAL END AS type_ecriture,
					CASE 
						WHEN t_journal.type_journal = 'VE' THEN 'VENTE'
						ELSE t_journal.type_journal END AS type_piece,
					ECR_PIECE||'-'||ECR_JNAL||'-'||to_char(ECR_DATE,'YYYYMMDD') AS piece, 
					CASE WHEN JNAL.REFBASE = 'H' THEN 'H' ELSE 'C' END AS clinique_honoraire,
					COALESCE(t_compte.oid,0) AS compte_id, 
					COALESCE(t_journal.oid,0) AS journal_id, 
					COALESCE(p_sejours.oid,0::bigint) AS sejour_id, 
					COALESCE(p_sejours.no_sejour,''::text) AS no_sejour, 
					COALESCE(p_factures.oid,0::bigint) AS facture_id, 
					COALESCE(p_factures.no_facture,'')::text AS no_facture,
					medecin_administratif_id, 
					tiers_payant_id,
					mode_reglement_code,
					ECR_LIBEL AS texte,
					ECR_DEBIT AS montant_debit,
					ECR_CREDIT AS montant_credit
				FROM w_ECRIT_CLI
				JOIN prod_sigems.JNAL ON ECR_JNAL = JNAL.CODEJ
				JOIN activite[PX].t_journal ON ECR_JNAL = t_journal.code_original
				LEFT JOIN activite[PX].t_compte ON ECR_CEMT = t_compte.code
				LEFT JOIN activite[PX].p_sejours ON w_ECRIT_CLI.no_sejour = p_sejours.no_sejour AND w_ECRIT_CLI.no_sejour <> ''
				LEFT JOIN activite[PX].p_factures ON w_ECRIT_CLI.no_facture = p_factures.no_facture AND w_ECRIT_CLI.no_facture <> ''
				WHERE ECR_DATE >= '[ENV_ADM_ANNEEDEBUT]0101'
				;	


				TRUNCATE activite[PX].p_ecriture_comptable;
				INSERT INTO activite[PX].p_ecriture_comptable(
					code_original, 
					date_comptable, 
					type_ecriture, 
					type_piece, 
					piece, 
					mode_reglement_code,
					clinique_honoraire, 
					compte_id, 
					journal_id, 
					sejour_id, 
					no_sejour, 
					facture_id, 
					no_facture, 
					medecin_id, 
					tiers_payant_id, 
					texte, 
					montant_credit, 
					montant_debit,
					est_comptabilise)
				SELECT 
					code_original, 
					date_comptable, 
					type_ecriture, 
					type_piece, 
					piece, 
					mode_reglement_code,
					clinique_honoraire, 
					compte_id, 
					journal_id, 
					sejour_id, 
					no_sejour, 
					facture_id, 
					no_facture, 
					medecin_administratif_id, 
					tiers_payant_id, 
					texte, 
					montant_credit, 
					montant_debit,
					'1'::text AS est_comptabilise
				FROM w_ecriture_comptable
				;
				
				

				ANALYSE activite[PX].p_ecriture_comptable
				;
				REINDEX TABLE activite[PX].p_ecriture_comptable
				;
				
				UPDATE activite[PX].p_ecriture_comptable
				SET code_erreur = 'EQP'
				FROM
				(
				SELECT provider_id, clinique_honoraire, piece
				FROM activite[PX].p_ecriture_comptable
				GROUP BY 1,2,3
				HAVING SUM(montant_debit-montant_credit) <> 0
				) subview
				WHERE p_ecriture_comptable.provider_id = subview.provider_id AND
					p_ecriture_comptable.piece = subview.piece AND
					p_ecriture_comptable.clinique_honoraire = subview.clinique_honoraire
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET code_erreur = 'FAC'
				FROM
				(
				SELECT p_ecriture_comptable.provider_id AS provider_id,
					p_ecriture_comptable.piece AS piece, 
					p_ecriture_comptable.clinique_honoraire AS clinique_honoraire
				FROM activite[PX].p_ecriture_comptable
				JOIN 
				(
				SELECT p_ecriture_comptable.provider_id,
					p_ecriture_comptable.no_facture,
					CASE WHEN SUM(CASE WHEN type_ecriture IN ('VPRD','VTVA') THEN montant_credit-montant_debit ELSE 0 END) IS DISTINCT FROM MAX(montant_comptabilise_c) THEN '1' ELSE '0' END AS erreur_vente_c,
					CASE WHEN SUM(CASE WHEN type_ecriture IN ('VHON') THEN montant_credit-montant_debit ELSE 0 END) IS DISTINCT FROM MAX(montant_comptabilise_h) THEN '1' ELSE '0' END AS erreur_vente_h
				FROM activite[PX].p_ecriture_comptable
				LEFT JOIN activite[PX].p_factures ON p_factures.no_facture = p_ecriture_comptable.no_facture
				WHERE type_ecriture IN ('VPRD','VTVA','VHON') 
				GROUP BY 1,2
				) subview ON
					p_ecriture_comptable.provider_id = subview.provider_id AND
					p_ecriture_comptable.no_facture = subview.no_facture
				WHERE p_ecriture_comptable.type_ecriture IN ('VPRD','VTVA','VHON','VCLI') AND
					(
					p_ecriture_comptable.clinique_honoraire = 'C' AND erreur_vente_c = '1' OR
					p_ecriture_comptable.clinique_honoraire = 'H' AND erreur_vente_h = '1' 
					)
				GROUP BY 1,2,3
				) subview
				WHERE p_ecriture_comptable.provider_id = subview.provider_id AND
					p_ecriture_comptable.piece = subview.piece AND
					p_ecriture_comptable.clinique_honoraire = subview.clinique_honoraire
				;

				
				-- Recherche taux TVA
				
				-- D'après paramétrage
				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = t_compte.taux_tva
				FROM activite[PX].t_compte
				WHERE p_ecriture_comptable.compte_id = t_compte.oid AND
					t_compte.taux_tva <> 0 
				;

				


				
				-- D'abord dans les lignes en 1 pour 1 entre produit et TVA
				DROP TABLE IF EXISTS w_ecriture_comptable_tva;
				CREATE TEMP TABLE w_ecriture_comptable_tva AS
				SELECT p_ecriture_comptable_tva.code_original AS code_original_tva,
					p_ecriture_comptable_ht.code_original AS code_original_ht,
					p_ecriture_comptable_tva.no_facture,
					p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit AS montant_tva,
					p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit AS montant_ht,
					CASE 
					WHEN round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2,2) = p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit THEN 20
					WHEN round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.021,2) = p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit THEN 2.1
					ELSE 0 END AS taux_tva
				FROM activite[PX].p_ecriture_comptable p_ecriture_comptable_tva
				JOIN activite[PX].p_ecriture_comptable p_ecriture_comptable_ht ON 
					p_ecriture_comptable_tva.no_facture = p_ecriture_comptable_ht.no_facture AND
					p_ecriture_comptable_tva.piece = p_ecriture_comptable_ht.piece AND
					p_ecriture_comptable_tva.journal_id = p_ecriture_comptable_ht.journal_id AND
					p_ecriture_comptable_tva.clinique_honoraire = p_ecriture_comptable_ht.clinique_honoraire
				WHERE p_ecriture_comptable_tva.type_ecriture IN ('VTVA','XTVA') AND
					p_ecriture_comptable_tva.taux_tva = 0 AND
					p_ecriture_comptable_ht.taux_tva = 0 AND
					p_ecriture_comptable_ht.type_ecriture IN ('VPRD','XPRD') AND
					(
						round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2,2) = p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit OR 
						round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.021,2) = p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit
					)
				;

				DELETE FROM w_ecriture_comptable_tva
				USING
				(
				SELECT code_original_tva, MIN(code_original_ht) AS code_original_ht
				FROM w_ecriture_comptable_tva
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE w_ecriture_comptable_tva.code_original_tva = subview.code_original_tva AND
					w_ecriture_comptable_tva.code_original_ht <> subview.code_original_ht
				;

				DELETE FROM w_ecriture_comptable_tva
				USING
				(
				SELECT code_original_ht, MIN(code_original_tva) AS code_original_tva
				FROM w_ecriture_comptable_tva
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE w_ecriture_comptable_tva.code_original_ht = subview.code_original_ht AND
					w_ecriture_comptable_tva.code_original_tva <> subview.code_original_tva
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = w_ecriture_comptable_tva.taux_tva
				FROM w_ecriture_comptable_tva
				WHERE p_ecriture_comptable.code_original = w_ecriture_comptable_tva.code_original_tva AND
					w_ecriture_comptable_tva.taux_tva <> 0
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = w_ecriture_comptable_tva.taux_tva
				FROM w_ecriture_comptable_tva
				WHERE p_ecriture_comptable.code_original = w_ecriture_comptable_tva.code_original_ht AND
					w_ecriture_comptable_tva.taux_tva <> 0
				;


				-- Ensuite dans les lignes en 1 pour 1 entre produit et TVA (cas de montants en double)
				DROP TABLE IF EXISTS w_ecriture_comptable_tva;
				CREATE TEMP TABLE w_ecriture_comptable_tva AS
				SELECT p_ecriture_comptable_tva.code_original AS code_original_tva,
					p_ecriture_comptable_ht.code_original AS code_original_ht,
					p_ecriture_comptable_tva.no_facture,
					p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit AS montant_tva,
					p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit AS montant_ht,
					CASE 
					WHEN round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2,2) = p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit THEN 20
					WHEN round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.021,2) = p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit THEN 2.1
					ELSE 0 END AS taux_tva
				FROM activite[PX].p_ecriture_comptable p_ecriture_comptable_tva
				JOIN activite[PX].p_ecriture_comptable p_ecriture_comptable_ht ON 
					p_ecriture_comptable_tva.no_facture = p_ecriture_comptable_ht.no_facture AND
					p_ecriture_comptable_tva.piece = p_ecriture_comptable_ht.piece AND
					p_ecriture_comptable_tva.journal_id = p_ecriture_comptable_ht.journal_id AND
					p_ecriture_comptable_tva.clinique_honoraire = p_ecriture_comptable_ht.clinique_honoraire
				WHERE p_ecriture_comptable_tva.type_ecriture IN ('VTVA','XTVA') AND
					p_ecriture_comptable_tva.taux_tva = 0 AND
					p_ecriture_comptable_ht.taux_tva = 0 AND
					p_ecriture_comptable_ht.type_ecriture IN ('VPRD','XPRD') AND
					(
						round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2,2) = p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit OR
						round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.021,2) = p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit
					)
				;

				DELETE FROM w_ecriture_comptable_tva
				USING
				(
				SELECT code_original_tva, MIN(code_original_ht) AS code_original_ht
				FROM w_ecriture_comptable_tva
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE w_ecriture_comptable_tva.code_original_tva = subview.code_original_tva AND
					w_ecriture_comptable_tva.code_original_ht <> subview.code_original_ht
				;

				DELETE FROM w_ecriture_comptable_tva
				USING
				(
				SELECT code_original_ht, MIN(code_original_tva) AS code_original_tva
				FROM w_ecriture_comptable_tva
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE w_ecriture_comptable_tva.code_original_ht = subview.code_original_ht AND
					w_ecriture_comptable_tva.code_original_tva <> subview.code_original_tva
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = w_ecriture_comptable_tva.taux_tva
				FROM w_ecriture_comptable_tva
				WHERE p_ecriture_comptable.code_original = w_ecriture_comptable_tva.code_original_tva AND
					w_ecriture_comptable_tva.taux_tva <> 0
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = w_ecriture_comptable_tva.taux_tva
				FROM w_ecriture_comptable_tva
				WHERE p_ecriture_comptable.code_original = w_ecriture_comptable_tva.code_original_ht AND
					w_ecriture_comptable_tva.taux_tva <> 0
				;



				
				-- Dans les pieces avec plusieurs lignes de TVA pour une seule ligne de produits
				DROP TABLE IF EXISTS w_ecriture_comptable_2;
				CREATE TEMP TABLE w_ecriture_comptable_2 AS
				SELECT clinique_honoraire,
					piece,
					journal_id,
					no_facture,
					type_ecriture,
					CASE WHEN type_ecriture IN ('VTVA','XTVA') THEN 0 ELSE compte_id END AS compte_id,
					taux_tva,
					base.cti_array_accum(code_original) AS code_original_array,
					SUM(montant_credit) AS montant_credit,
					SUM(montant_debit) AS montant_debit
				FROM activite[PX].p_ecriture_comptable
				WHERE taux_tva = 0 AND type_ecriture IN ('VPRD','VTVA','XPRD','XTVA')
				GROUP BY 1,2,3,4,5,6,7
				;

				ANALYSE w_ecriture_comptable_2
				;

				DROP TABLE IF EXISTS w_ecriture_comptable_tva;
				CREATE TEMP TABLE w_ecriture_comptable_tva AS
				SELECT p_ecriture_comptable_tva.code_original_array AS code_original_array_tva,
					p_ecriture_comptable_ht.code_original_array AS code_original_array_ht,
					p_ecriture_comptable_tva.no_facture,
					p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit AS montant_tva,
					p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit AS montant_ht,
					CASE 
					WHEN round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2,0) = round(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit,0) THEN 20
					WHEN floor((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2) = floor(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit) THEN 20
					WHEN round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.021,1) = round(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit,1) THEN 2.1
					ELSE 0 END AS taux_tva
				FROM w_ecriture_comptable_2 p_ecriture_comptable_tva
				JOIN w_ecriture_comptable_2 p_ecriture_comptable_ht ON 
					p_ecriture_comptable_tva.no_facture = p_ecriture_comptable_ht.no_facture AND
					p_ecriture_comptable_tva.piece = p_ecriture_comptable_ht.piece AND
					p_ecriture_comptable_tva.journal_id = p_ecriture_comptable_ht.journal_id AND
					p_ecriture_comptable_tva.clinique_honoraire = p_ecriture_comptable_ht.clinique_honoraire
				WHERE p_ecriture_comptable_tva.type_ecriture IN ('VTVA','XTVA') AND
					p_ecriture_comptable_tva.taux_tva = 0 AND
					p_ecriture_comptable_ht.taux_tva = 0 AND
					p_ecriture_comptable_ht.type_ecriture IN ('VPRD','XPRD') AND
					(
						round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2,0) = round(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit,0) OR
						floor((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2) = floor(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit) OR
						round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.021,1) = round(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit,1)
					)
				;

				DELETE FROM w_ecriture_comptable_tva
				WHERE code_original_array_tva IN
				(
				SELECT code_original_array_tva
				FROM w_ecriture_comptable_tva
				GROUP BY 1
				HAVING count(*) > 1
				)
				;

				DELETE FROM w_ecriture_comptable_tva
				WHERE code_original_array_ht IN
				(
				SELECT code_original_array_ht
				FROM w_ecriture_comptable_tva
				GROUP BY 1
				HAVING count(*) > 1
				)
				;

				ANALYSE w_ecriture_comptable_tva
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = w_ecriture_comptable_tva.taux_tva
				FROM w_ecriture_comptable_tva
				WHERE p_ecriture_comptable.code_original = ANY(w_ecriture_comptable_tva.code_original_array_tva) AND
					type_ecriture IN ('VTVA','XTVA') AND
					w_ecriture_comptable_tva.taux_tva <> 0
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = w_ecriture_comptable_tva.taux_tva
				FROM w_ecriture_comptable_tva
				WHERE p_ecriture_comptable.code_original = ANY(w_ecriture_comptable_tva.code_original_array_ht) AND
					type_ecriture IN ('VPRD','XPRD') AND
					w_ecriture_comptable_tva.taux_tva <> 0
				;

				-- Dans les pieces avec plusieurs lignes de TVA et plusieurs lignes de produit (Avec TVA paramétrée)
				DROP TABLE IF EXISTS w_ecriture_comptable_2;
				CREATE TEMP TABLE w_ecriture_comptable_2 AS
				SELECT clinique_honoraire,
					piece,
					journal_id,
					no_facture,
					type_ecriture,
					CASE WHEN t_compte.taux_tva <> 0 THEN '1' ELSE '0' END AS has_tva,
					p_ecriture_comptable.taux_tva,
					base.cti_array_accum(p_ecriture_comptable.code_original) AS code_original_array,
					SUM(montant_credit) AS montant_credit,
					SUM(montant_debit) AS montant_debit
				FROM activite[PX].p_ecriture_comptable
				JOIN activite[PX].t_compte ON compte_id = t_compte.oid
				WHERE p_ecriture_comptable.taux_tva = 0 AND 
					(
					type_ecriture IN ('VPRD','XPRD') AND t_compte.taux_tva <> 0 OR
					type_ecriture IN ('VTVA','XTVA')
					)
				GROUP BY 1,2,3,4,5,6,7
				;

				ANALYSE w_ecriture_comptable_2
				;

				DROP TABLE IF EXISTS w_ecriture_comptable_tva;
				CREATE TEMP TABLE w_ecriture_comptable_tva AS
				SELECT p_ecriture_comptable_tva.code_original_array AS code_original_array_tva,
					p_ecriture_comptable_ht.code_original_array AS code_original_array_ht,
					p_ecriture_comptable_tva.no_facture,
					p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit AS montant_tva,
					p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit AS montant_ht,
					CASE 
					WHEN round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2,0) = round(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit,0) THEN 20
					WHEN floor((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2) = floor(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit) THEN 20
					WHEN round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.021,1) = round(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit,1) THEN 2.1
					ELSE 0 END AS taux_tva
				FROM w_ecriture_comptable_2 p_ecriture_comptable_tva
				JOIN w_ecriture_comptable_2 p_ecriture_comptable_ht ON 
					p_ecriture_comptable_tva.no_facture = p_ecriture_comptable_ht.no_facture AND
					p_ecriture_comptable_tva.piece = p_ecriture_comptable_ht.piece AND
					p_ecriture_comptable_tva.journal_id = p_ecriture_comptable_ht.journal_id AND
					p_ecriture_comptable_tva.clinique_honoraire = p_ecriture_comptable_ht.clinique_honoraire
				WHERE p_ecriture_comptable_tva.type_ecriture IN ('VTVA','XTVA') AND
					p_ecriture_comptable_tva.taux_tva = 0 AND
					p_ecriture_comptable_ht.taux_tva = 0 AND
					p_ecriture_comptable_ht.type_ecriture IN ('VPRD','XPRD') AND
					(
						round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2,0) = round(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit,0) OR
						floor((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2) = floor(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit) OR
						round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.021,1) = round(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit,1) 
					)
				;

				DELETE FROM w_ecriture_comptable_tva
				WHERE code_original_array_tva IN
				(
				SELECT code_original_array_tva
				FROM w_ecriture_comptable_tva
				GROUP BY 1
				HAVING count(*) > 1
				)
				;

				DELETE FROM w_ecriture_comptable_tva
				WHERE code_original_array_ht IN
				(
				SELECT code_original_array_ht
				FROM w_ecriture_comptable_tva
				GROUP BY 1
				HAVING count(*) > 1
				)
				;

				ANALYSE w_ecriture_comptable_tva
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = w_ecriture_comptable_tva.taux_tva
				FROM w_ecriture_comptable_tva
				WHERE p_ecriture_comptable.code_original = ANY(w_ecriture_comptable_tva.code_original_array_tva) AND
					type_ecriture IN ('VTVA','XTVA') AND
					w_ecriture_comptable_tva.taux_tva <> 0
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = w_ecriture_comptable_tva.taux_tva
				FROM w_ecriture_comptable_tva
				WHERE p_ecriture_comptable.code_original = ANY(w_ecriture_comptable_tva.code_original_array_ht) AND
					type_ecriture IN ('VPRD','XPRD') AND
					w_ecriture_comptable_tva.taux_tva <> 0
				;
				
				
				-- Dans les pieces avec plusieurs lignes de TVA et plusieurs lignes de produit (avec nombre significatif > 100)
				DROP TABLE IF EXISTS w_ecriture_comptable_2;
				CREATE TEMP TABLE w_ecriture_comptable_2 AS
				SELECT clinique_honoraire,
					piece,
					journal_id,
					no_facture,
					type_ecriture,
					CASE WHEN t_compte.taux_tva <> 0 THEN '1' ELSE '0' END AS has_tva,
					p_ecriture_comptable.taux_tva,
					base.cti_array_accum(code_original) AS code_original_array,
					SUM(montant_credit) AS montant_credit,
					SUM(montant_debit) AS montant_debit
				FROM activite[PX].p_ecriture_comptable
				JOIN (SELECT compte_id AS oid, MAX(p_ecriture_comptable.taux_tva) AS taux_tva FROm activite[PX].p_ecriture_comptable WHERE p_ecriture_comptable.taux_tva <> 0 GROUP BY 1 HAVING count(*) > 100) t_compte ON p_ecriture_comptable.compte_id = t_compte.oid
				WHERE p_ecriture_comptable.taux_tva = 0 AND 
					(
					type_ecriture IN ('VPRD','XPRD') AND t_compte.taux_tva <> 0 OR
					type_ecriture IN ('VTVA','XTVA')
					)
				GROUP BY 1,2,3,4,5,6,7
				;

				ANALYSE w_ecriture_comptable_2
				;

				DROP TABLE IF EXISTS w_ecriture_comptable_tva;
				CREATE TEMP TABLE w_ecriture_comptable_tva AS
				SELECT p_ecriture_comptable_tva.code_original_array AS code_original_array_tva,
					p_ecriture_comptable_ht.code_original_array AS code_original_array_ht,
					p_ecriture_comptable_tva.no_facture,
					p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit AS montant_tva,
					p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit AS montant_ht,
					CASE 
					WHEN round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2,0) = round(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit,0) THEN 20
					WHEN floor((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2) = floor(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit) THEN 20
					ELSE 0 END AS taux_tva
				FROM w_ecriture_comptable_2 p_ecriture_comptable_tva
				JOIN w_ecriture_comptable_2 p_ecriture_comptable_ht ON 
					p_ecriture_comptable_tva.no_facture = p_ecriture_comptable_ht.no_facture AND
					p_ecriture_comptable_tva.piece = p_ecriture_comptable_ht.piece AND
					p_ecriture_comptable_tva.journal_id = p_ecriture_comptable_ht.journal_id AND
					p_ecriture_comptable_tva.clinique_honoraire = p_ecriture_comptable_ht.clinique_honoraire
				WHERE p_ecriture_comptable_tva.type_ecriture IN ('VTVA','XTVA') AND
					p_ecriture_comptable_tva.taux_tva = 0 AND
					p_ecriture_comptable_ht.taux_tva = 0 AND
					p_ecriture_comptable_ht.type_ecriture IN ('VPRD','XPRD') AND
					(
						round((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2,0) = round(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit,0) OR
						floor((p_ecriture_comptable_ht.montant_credit-p_ecriture_comptable_ht.montant_debit)*0.2) = floor(p_ecriture_comptable_tva.montant_credit-p_ecriture_comptable_tva.montant_debit)
					)
				;

				DELETE FROM w_ecriture_comptable_tva
				WHERE code_original_array_tva IN
				(
				SELECT code_original_array_tva
				FROM w_ecriture_comptable_tva
				GROUP BY 1
				HAVING count(*) > 1
				)
				;

				DELETE FROM w_ecriture_comptable_tva
				WHERE code_original_array_ht IN
				(
				SELECT code_original_array_ht
				FROM w_ecriture_comptable_tva
				GROUP BY 1
				HAVING count(*) > 1
				)
				;

				ANALYSE w_ecriture_comptable_tva
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = w_ecriture_comptable_tva.taux_tva
				FROM w_ecriture_comptable_tva
				WHERE p_ecriture_comptable.code_original = ANY(w_ecriture_comptable_tva.code_original_array_tva) AND
					type_ecriture IN ('VTVA','XTVA') AND
					w_ecriture_comptable_tva.taux_tva <> 0
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = w_ecriture_comptable_tva.taux_tva
				FROM w_ecriture_comptable_tva
				WHERE p_ecriture_comptable.code_original = ANY(w_ecriture_comptable_tva.code_original_array_ht) AND
					type_ecriture IN ('VPRD','XPRD') AND
					w_ecriture_comptable_tva.taux_tva <> 0
				;


				-- Taux par defaut TVA
				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = subview.taux_tva	
				FROM
				(
				SELECT compte_id, MAX(taux_tva) AS taux_tva
				FROM activite[PX].p_ecriture_comptable
				WHERE type_ecriture IN ('VTVA','XTVA') AND taux_tva <> 0
				GROUP BY 1
				) subview
				WHERE type_ecriture IN ('VTVA','XTVA') AND p_ecriture_comptable.taux_tva = 0 AND
					p_ecriture_comptable.compte_id = subview.compte_id
				;

				-- Taux par defaut produits
				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = t_compte.taux_tva
				FROM activite[PX].t_compte,
					(
					SELECT clinique_honoraire, journal_id, piece, no_facture, MAX(taux_tva) AS taux_tva
					FROM activite[PX].p_ecriture_comptable
					WHERE type_ecriture IN ('VTVA','XTVA')
					GROUP BY 1,2,3,4
					) subview
				WHERE p_ecriture_comptable.compte_id = t_compte.oid AND
					t_compte.taux_tva <> 0 AND
					p_ecriture_comptable.clinique_honoraire = subview.clinique_honoraire AND
					p_ecriture_comptable.journal_id = subview.journal_id AND
					p_ecriture_comptable.piece = subview.piece AND
					p_ecriture_comptable.no_facture = subview.no_facture AND
					p_ecriture_comptable.taux_tva = 0
				;
				
				-- Taux de TVA qui ne devraient pas être (pieces sans TVA)
				DROP TABLE IF EXISTS w_ecriture_piece_calc_tva;
				CREATE TEMP TABLE w_ecriture_piece_calc_tva AS
				SELECT clinique_honoraire, 
					piece,
					SUM(COALESCE(total_tva,0)) AS total_tva,
					SUM(COALESCE(total_tva_calc,0)) AS total_tva_calc,
					SUM(COALESCE(total_tva_calc_021,0)) AS total_tva_calc_021,
					SUM(COALESCE(total_tva_calc_20,0)) AS total_tva_calc_20,
					SUM(COALESCE(total_tva_calc_10,0)) AS total_tva_calc_10,
					SUM(COALESCE(total_tva_calc_55,0)) AS total_tva_calc_55
				FROM
				(
				SELECT clinique_honoraire, 
					piece, 
					t_compte.code,
					t_compte.texte,
					SUM(montant_credit-montant_debit) ,
					SUM(CASE WHEN t_compte.code LIKE '445%' THEN montant_credit-montant_debit ELSE NULL END) AS total_tva,
					SUM(CASE WHEN t_compte.code NOT LIKE '445%' AND p_ecriture_comptable.taux_tva <> 0 THEN (montant_credit-montant_debit)*p_ecriture_comptable.taux_tva/100 ELSE null END ) AS total_tva_calc,
					SUM(CASE WHEN t_compte.code NOT LIKE '445%' AND p_ecriture_comptable.taux_tva = 2.1 THEN (montant_credit-montant_debit)*p_ecriture_comptable.taux_tva/100 ELSE null END ) AS total_tva_calc_021,
					SUM(CASE WHEN t_compte.code NOT LIKE '445%' AND p_ecriture_comptable.taux_tva = 20 THEN (montant_credit-montant_debit)*p_ecriture_comptable.taux_tva/100 ELSE null END ) AS total_tva_calc_20,
					SUM(CASE WHEN t_compte.code NOT LIKE '445%' AND p_ecriture_comptable.taux_tva = 10 THEN (montant_credit-montant_debit)*p_ecriture_comptable.taux_tva/100 ELSE null END ) AS total_tva_calc_10,
					SUM(CASE WHEN t_compte.code NOT LIKE '445%' AND p_ecriture_comptable.taux_tva = 5.5 THEN (montant_credit-montant_debit)*p_ecriture_comptable.taux_tva/100 ELSE null END ) AS total_tva_calc_55
				FROM activite[PX].p_ecriture_comptable
				JOIN activite[PX].t_compte ON compte_id = t_compte.oid
				WHERE type_ecriture IN ('VPRD','VTVA') 
				GROUP BY 1,2,3,4
				ORDER BY 1,2,4
				) subview
				GROUP BY 1,2
				HAVING abs(sum(COALESCE(total_tva,0)) - sum(COALESCE(total_tva_calc,0))) > 1
				;

				ANALYSE w_ecriture_piece_calc_tva
				;
				
				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = 0
				FROM w_ecriture_piece_calc_tva
				WHERE p_ecriture_comptable.clinique_honoraire = w_ecriture_piece_calc_tva.clinique_honoraire AND
					p_ecriture_comptable.piece = w_ecriture_piece_calc_tva.piece AND
					p_ecriture_comptable.taux_tva <> 0 AND
					total_tva = 0
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = 0
				FROM w_ecriture_piece_calc_tva
				WHERE p_ecriture_comptable.clinique_honoraire = w_ecriture_piece_calc_tva.clinique_honoraire AND
					p_ecriture_comptable.piece = w_ecriture_piece_calc_tva.piece AND
					p_ecriture_comptable.taux_tva = 2.1 AND
					(
					round(total_tva,0) = round(total_tva_calc_20+total_tva_calc_10+total_tva_calc_55,0) OR
					floor(total_tva) = floor(total_tva_calc_20+total_tva_calc_10+total_tva_calc_55)
					)
				;
										
			]]></sqlcmd>
		</NODE>
		
		<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_sigems.ECRIT;
				
				DROP TABLE IF EXISTS w_ECRIT_comptes_clients;
				CREATE TEMP TABLE w_ECRIT_comptes_clients AS
				SELECT ECR_PLAN, ECR_CEMT AS ECR_CPTE
				FROM w_ECRIT_CLI
				JOIN prod_sigems.COMPTE ON COMPTE.NUM = ECR_CPTE AND ECR_PLAN = COMPTE.TYP
				WHERE ECR_PLAN IN ('C','P') AND
					w_ECRIT_CLI.ECR_AGE <> '*S' -- specifique ELSAN pour ignorer ecritures calabet dans esquirol
				GROUP BY 1,2
				;
				
				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 ECRIT.ANNEE <> '' THEN ECRIT.ANNEE || to_char(ECRIT.CODE,'FM900000') || '.' || to_char(ECRIT.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 JNAL.REFBASE = 'G' AND ECR_JNAL LIKE 'VEN%' THEN ECR_DEBIT - ECR_CREDIT ELSE 0 END) AS montant_ventes_c, 
					SUM(CASE WHEN JNAL.REFBASE = 'G' AND ECR_JNAL NOT LIKE 'VEN%' THEN ECR_CREDIT - ECR_DEBIT  ELSE 0 END) AS montant_reglements_c, 
					SUM(CASE WHEN JNAL.REFBASE = 'H' AND ECR_JNAL LIKE 'VEN%' THEN ECR_DEBIT - ECR_CREDIT ELSE 0 END) AS montant_ventes_h, 
					SUM(CASE WHEN JNAL.REFBASE = 'H' AND ECR_JNAL NOT LIKE 'VEN%' THEN ECR_CREDIT - ECR_DEBIT  ELSE 0 END) AS montant_reglements_h
				FROM w_ECRIT_cli ECRIT
				JOIN prod_sigems.JNAL ON ECR_JNAL = JNAL.CODEJ
				JOIN w_ECRIT_comptes_clients ON 
						ECRIT.ECR_CEMT = w_ECRIT_comptes_clients.ECR_CPTE AND 
						ECRIT.ECR_PLAN = w_ECRIT_comptes_clients.ECR_PLAN
				WHERE 
					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' AND
					ECRIT.ECR_JNAL <> 'OD' AND
					ECRIT.ECR_PLAN = ANY(ARRAY['C','P']) AND
					ECRIT.ECR_AGE <> '*S' -- specifique ELSAN pour ignorer ecritures calabet dans esquirol   
				GROUP BY 1,2,3;
				
				-- Dans certains cas, les honoraires des médecins salariés ne sont pas dans la comptabilisée
				-- On ajoute alors fictivement ces honoraires aux montants retrouvés en compta pour que le chiffrier soit juste
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'SIGEMS_CPTMEDSAL',
					'Comptabilisation honoraires des médecins salariés',
					'0',
					'1=Honoraires non comptabilisés, ajout fictif dans chiffrier'
				WHERE 'SIGEMS_CPTMEDSAL' NOT IN (SELECT code FROM activite.t_divers);
                ;
				
				INSERT INTO w_factures_comptables
				SELECT 
					0::bigint AS facture_id,
					p_factures.no_facture AS no_facture,
					p_factures.date_vente AS date_comptable,
					SUM(p_factures_lignes_c.montant_comptabilise) AS montant_ventes_c, 
					0::numeric AS montant_reglements_c, 
					0::numeric AS montant_ventes_h, 
					0::numeric AS montant_reglements_h
				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.t_divers ON 
					t_divers.code = 'SIGEMS_CPTMEDSAL' AND
					t_divers.valeur = '1'
				WHERE p_factures.date_vente >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					p_factures.date_vente <= date(now()) AND
					p_factures_lignes_c.montant_comptabilise <> 0 AND
					p_factures_lignes_c.montant_facture = 0
				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 no_facture IS NOT NULL AND
					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_sigems.DOSSIER
					JOIN prod_sigems.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_sigems.SEJOUR
					JOIN prod_sigems.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_sigems.DOSSIER
				JOIN prod_sigems.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_sigems.SEJOUR
				JOIN prod_sigems.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_sigems.DOSSIER ALTER COLUMN SER_DOS TYPE text;

				UPDATE prod_sigems.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_sigems.SEJOUR ALTER COLUMN SER_SEJ TYPE text;

				UPDATE prod_sigems.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_sigems.LIG_CLINI ALTER COLUMN SER_LCL TYPE text;

				UPDATE prod_sigems.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_sigems.LIG_HONOR ALTER COLUMN SER_LHO TYPE text;

				UPDATE prod_sigems.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_sigems.SERVICE 
					ALTER COLUMN COD_SER TYPE text,
					ALTER COLUMN NOM_SER TYPE text;

				INSERT INTO prod_sigems.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_sigems.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_sigems.SERVICE);

				ALTER TABLE prod_sigems.ANALYG ALTER COLUMN SER_ANA TYPE text;
				
				INSERT INTO prod_sigems.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_sigems.ANALYG
				JOIN prod_sigems.SERVICE ON SER_ANA = substr(COD_SER,1,4) AND
					substr(COD_SER,5,1) IN ('E', 'O')
				LEFT JOIN prod_sigems.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);
				
				-- Corrections double affectation AMO/AMC suite mauvaise initialisation
				UPDATE activite[PX].t_tiers_payant
				SET code_original = replace(code_original,'(2)','(1)')
				WHERE code_original like '%(2)' AND
					type_tiers_payant <> '2' AND
					replace(code_original,'(2)','(1)') NOT IN (select code_original FROM activite[PX].t_tiers_payant)
				;

				UPDATE activite[PX].t_tiers_payant
				SET code_original = replace(code_original,'(1)','(2)')
				WHERE code_original like '%(1)' AND
					type_tiers_payant <> '1' AND
					replace(code_original,'(1)','(2)') NOT IN (select code_original FROM activite[PX].t_tiers_payant)
				;
					

				INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
				SELECT 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_sigems.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
				HAVING COD_TPA || MAX(CASE WHEN length(COD_TPA) = 8 AND substr(COD_TPA,1,2) BETWEEN '01' AND '99' THEN '(1)' ELSE '(2)' END) 
					NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant WHERE code_original IS NOT NULL)
				;
					
														
				WITH tiers_payant_sìgems AS (
					SELECT COD_TPA,
					MAX(NOM_TPA) AS NOM_TPA
					FROM prod_sigems.TIERS_PAYANT
					GROUP BY 1
				)
				UPDATE activite[PX].t_tiers_payant SET
					code = COD_TPA,
					texte = NOM_TPA,
					texte_court = NOM_TPA
				FROM tiers_payant_sìgems
				WHERE COD_TPA = code_original AND
					(
						code IS DISTINCT FROM COD_TPA OR 
						texte IS DISTINCT FROM NOM_TPA OR
						texte_court IS DISTINCT FROM NOM_TPA
					)
				;

				-- Si tiers payant mutuelle utilisé dans AMO ajout
				INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
				SELECT
					COD_TPA || '(1)',
					COD_TPA,
					'1'::text,
					MAX(NOM_TPA )|| ' (AMO)',
					MAX(NOM_TPA) || ' (AMO)'
				FROM prod_sigems.TIERS_PAYANT
					JOIN activite[PX].t_tiers_payant current ON current.code = COD_TPA AND current.type_tiers_payant = '2'
				WHERE 1=1 AND 
					COD_TPA IN (SELECT CP1_DOS2 from prod_sigems.DOS2 GROUP BY 1) AND
					COD_TPA NOT IN (SELECT code FROM activite[PX].t_tiers_payant WHERE type_tiers_payant = '1')
					GROUP BY 1,2
					ORDER BY 1
				;
				
				-- Si tiers payant amo utilisé dans AMC ajout
				INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
				SELECT 
					COD_TPA || '(2)',
					COD_TPA,
					'2'::text,
					MAX(NOM_TPA )|| ' (AMC)',
					MAX(NOM_TPA) || ' (AMC)'
				FROM prod_sigems.TIERS_PAYANT
					JOIN activite[PX].t_tiers_payant current ON current.code = COD_TPA AND current.type_tiers_payant = '1'
				WHERE 1=1 AND 
					COD_TPA IN (SELECT CA2_DOS2 from prod_sigems.DOS2 GROUP BY 1) AND
					COD_TPA NOT IN (SELECT code FROM activite[PX].t_tiers_payant WHERE type_tiers_payant = '2')
					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)
				;
				
				INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
				SELECT CPO_TPA, MAX(VIL_TPA), MAX(VIL_TPA), MAX(t_departements.oid)
				FROM prod_SIGEMS.TIERS_PAYANT
				LEFT JOIN base.t_codes_postaux ON CPO_TPA = t_codes_postaux.code
				JOIN base.t_departements ON 
					CPO_TPA NOT LIKE '97%' AND substr(CPO_TPA,1,2) = t_departements.code OR
					CPO_TPA LIKE '97%' AND substr(CPO_TPA,1,3) = t_departements.code 
				WHERE  CPO_TPA <> '' AND
					length(CPO_TPA) = 5 AND 
					t_codes_postaux.code IS NULL
				GROUP BY 1
				;
			
				UPDATE activite[PX].t_tiers_payant SET
					adresse = AD1_TPA || ' ' ||  AD2_TPA,
					code_postal_id = COALESCE(t_codes_postaux.oid,0),
					ville = VIL_TPA,
					telephone = AGR_TPA,
					fax = COALESCE(TIERS_PAYANT_COMPL.FAX,''),
					email = COALESCE(TIERS_PAYANT_COMPL.MAIL,'')
				FROM prod_SIGEMS.TIERS_PAYANT
				LEFT JOIN prod_SIGEMS.TIERS_PAYANT_COMPL ON TIERS_PAYANT.COD_TPA = TIERS_PAYANT_COMPL.COD_TPA
				LEFT JOIN base.t_codes_postaux ON CPO_TPA = t_codes_postaux.code
				WHERE (
					t_tiers_payant.code_original = TIERS_PAYANT.COD_TPA OR
					t_tiers_payant.code_original = TIERS_PAYANT.COD_TPA||'(1)' OR
					t_tiers_payant.code_original = TIERS_PAYANT.COD_TPA||'(2)'
					) AND
					(
					t_tiers_payant.adresse IS DISTINCT FROM (AD1_TPA || ' ' ||  AD2_TPA) OR
					t_tiers_payant.code_postal_id IS DISTINCT FROM COALESCE(t_codes_postaux.oid,0) OR
					ville IS DISTINCT FROM VIL_TPA OR
					t_tiers_payant.telephone IS DISTINCT FROM  AGR_TPA OR
					t_tiers_payant.fax IS DISTINCT FROM COALESCE(TIERS_PAYANT_COMPL.FAX,'') OR
					t_tiers_payant.email IS DISTINCT FROM COALESCE(TIERS_PAYANT_COMPL.MAIL,'')
					)
				;
										
										
			]]></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_sigems.PRATICIEN
					LEFT JOIN prod_sigems.SPECIALITE ON CSP_PRA = COD_SPE
					LEFT JOIN base.t_specialites_medecin spe on spe.code::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_sigems.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 code = COD_PRA,
					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.code <> COD_PRA OR
					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;
                
                -- no_adeli
				UPDATE activite[PX].t_medecins_administratifs
				SET no_adeli = NID_PRA
				FROM prod_sigems.PRATICIEN
				WHERE t_medecins_administratifs.code_original = COD_PRA AND
					t_medecins_administratifs.NO_ADELI IS DISTINCT FROM NID_PRA
				;
				
                -- Code RPPS
                UPDATE base.t_medecins
                SET code_rpps = subview.RPPS
                FROM
                (
                SELECT medecin_id, count(DISTINCT rpps), MAX(RPPS) AS RPPS
                FROM activite[PX].t_medecins_administratifs
                JOIN base.t_medecins ON t_medecins_administratifs.medecin_id = t_medecins.oid
                JOIN prod_sigems.PRAT_COMPL ON code_original = COD_PRA
                WHERE RPPS <> '' AND 
                    t_medecins.code_rpps = '' AND 
                    medecin_id <> 0
                GROUP BY 1
                HAVING count(DISTINCT rpps) = 1
                ) subview
                WHERE t_medecins.oid = subview.medecin_id
                ;
				
				-- Adresse
				INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
				SELECT CPO_PRA, MAX(VIL_PRA), MAX(VIL_PRA), MAX(t_departements.oid)
				FROM prod_sigems.PRATICIEN
				LEFT JOIN base.t_codes_postaux ON CPO_PRA = t_codes_postaux.code
				JOIN base.t_departements ON 
					CPO_PRA NOT LIKE '97%' AND substr(CPO_PRA,1,2) = t_departements.code OR
					CPO_PRA LIKE '97%' AND substr(CPO_PRA,1,3) = t_departements.code 
				WHERE  CPO_PRA <> '' AND
					length(CPO_PRA) = 5 AND
					t_codes_postaux.code is NULL
				GROUP BY 1
				;
			
				UPDATE activite[PX].t_medecins_administratifs SET
					adresse = AD1_PRA || ' ' ||  AD2_PRA,
					code_postal_id = COALESCE(t_codes_postaux.oid,0),
					ville = VIL_PRA,
					telephone = COALESCE(trim(PRAT_COMPL.TEL||' '||PRAT_COMPL.PORTABLE),''),
					email = COALESCE(PRAT_COMPL.MAIL,'')
				FROM prod_sigems.PRATICIEN
				LEFT JOIN prod_sigems.PRAT_COMPL ON PRATICIEN.COD_PRA = PRAT_COMPL.COD_PRA
				LEFT JOIN base.t_codes_postaux ON CPO_PRA = t_codes_postaux.code
				WHERE t_medecins_administratifs.code_original = PRATICIEN.COD_PRA AND
					(
					t_medecins_administratifs.adresse IS DISTINCT FROM (AD1_PRA || ' ' ||  AD2_PRA) OR
					t_medecins_administratifs.code_postal_id IS DISTINCT FROM COALESCE(t_codes_postaux.oid,0) OR
					t_medecins_administratifs.ville IS DISTINCT FROM VIL_PRA OR
					t_medecins_administratifs.telephone IS DISTINCT FROM COALESCE(trim(PRAT_COMPL.TEL||' '||PRAT_COMPL.PORTABLE),'') OR
					t_medecins_administratifs.email IS DISTINCT FROM COALESCE(PRAT_COMPL.MAIL,'')
					)
				;
										
										
			]]></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_sigems.DOSSIER
					JOIN prod_sigems.SERVICE ON SER_DOS = COD_SER
					LEFT JOIN prod_sigems.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_sigems.DOSSIER
					JOIN prod_sigems.SEJOUR ON ANN_SEJ = ANN_DOS AND COD_SEJ = COD_DOS
					JOIN prod_sigems.SERVICE ON SER_SEJ = COD_SER
					LEFT JOIN prod_sigems.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
					code = COD_SER,
					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
					(
						code IS DISTINCT FROM COD_SER OR
						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_sigems.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
					code = COD_SER,
					texte = NOM_SER,
					texte_court = CASE WHEN texte_court = texte THEN NOM_SER ELSE texte_court END
				FROM prod_SIGEMS.SERVICE
				WHERE COD_SER = code_original AND
					(
						code IS DISTINCT FROM COD_SER OR 
						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_sigems.UNITE_MEDICALE
								WHERE CODE NOT IN (SELECT code_original FROM activite[PX].t_unites_medicales)
								ORDER BY CODE;
				
				UPDATE activite[PX].t_unites_medicales SET
					code = UM.CODE,
					texte = LIB,
					texte_court = LIB
				FROM prod_SIGEMS.UNITE_MEDICALE UM
				WHERE UM.CODE = code_original AND
					(
						t_unites_medicales.code IS DISTINCT FROM UM.CODE OR 
						texte IS DISTINCT FROM UM.LIB OR
						texte_court IS DISTINCT FROM UM.LIB
					);


				-- 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::text, CHAMBRE
				FROM prod_sigems.CHAMBRE
				WHERE COD_CHA <> '' AND
					COD_CHA <> '0'
				GROUP BY 1,2,3,4,5,6;
				
				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_sigems.DOSSIER
				JOIN prod_sigems.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 NOT IN ('','0','NULL')
				GROUP BY 1
				ORDER BY 1;
				
				INSERT INTO w_CHAMBRE
				SELECT NCH_SEJ, NCH_SEJ, '', 0, MAX(SECT_ENTREE), NCH_SEJ
				FROM prod_sigems.SEJOUR
				JOIN prod_sigems.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 NOT IN ('','0','NULL')
				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_sigems.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 NOT IN ('','0','NULL')
				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_sigems.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 NOT IN ('','0','NULL')
				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_sigems.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 NOT IN ('','0','NULL')
				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_sigems.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 NOT IN ('','0','NULL')
				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_sigems.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 NOT IN ('','0','NULL')
				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_sigems.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 NOT IN ('','0','NULL')
				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_sigems.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 NOT IN ('','0','NULL')
				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_sigems.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 NOT IN ('','0','NULL')
				GROUP BY 1
				ORDER BY 1;

				DELETE FROM w_CHAMBRE
				USING
				(
				SELECT COD_CHA, MIN(CTID) AS keep_CTID
				FROM w_CHAMBRE
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE w_CHAMBRE.COD_CHA = subview.COD_CHA AND
					w_CHAMBRE.CTID <> keep_CTID
				;
				

				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;


				UPDATE activite[PX].t_etages SET
					code = SER_CHA,
					texte = SER_CHA,
					texte_court = SER_CHA
				FROM w_CHAMBRE
				WHERE SER_CHA <> '' AND
					SER_CHA = code_original AND
					(
						code IS DISTINCT FROM SER_CHA OR 
						texte IS DISTINCT FROM SER_CHA OR
						texte_court IS DISTINCT FROM SER_CHA
					)
				;

				UPDATE activite[PX].t_etages SET
					code = COD_SER,
					texte = NOM_SER,
					texte_court = NOM_SER
				FROM prod_sigems.SERVICE 
				WHERE COD_SER <> '' AND 
					NOM_SER <> '' AND
					COD_SER = code_original AND
					(
						code IS DISTINCT FROM COD_SER OR 
						texte IS DISTINCT FROM NOM_SER OR
						texte_court IS DISTINCT FROM NOM_SER
					)
				;

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

				UPDATE activite[PX].t_lits SET
					code = COD_CHA,
					texte = NOM_CHA,
					texte_court = NOM_CHA
				FROM w_CHAMBRE
				WHERE COD_CHA || '|' || COD_CHA = code_original AND
					(
						code IS DISTINCT FROM COD_CHA OR 
						texte IS DISTINCT FROM NOM_CHA OR
						texte_court IS DISTINCT FROM NOM_CHA
					)
				;
									
			]]></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_sigems.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_sigems.PROD_HONOR
				WHERE trim(COD_PRH) NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
				GROUP BY 1,2
				ORDER BY 1;


				WITH prod_clini AS (
					SELECT trim(COD_PRC) AS COD_PRC,
					MAX(LIB_PRC) AS LIB_PRC
					FROM prod_sigems.PROD_CLINI
					GROUP BY trim(COD_PRC)
				)
				UPDATE activite[PX].t_rubriques_facturation SET
					code = COD_PRC,
					texte = LIB_PRC,
					texte_court = LIB_PRC
				FROM prod_clini
				WHERE COD_PRC = code_original AND
					(
						code IS DISTINCT FROM COD_PRC OR 
						texte IS DISTINCT FROM LIB_PRC OR
						texte_court IS DISTINCT FROM LIB_PRC
					)
				;

				WITH prod_honor AS (
					SELECT trim(COD_PRH) AS COD_PRH,
					MAX(LIB_PRH) AS LIB_PRH
					FROM prod_sigems.PROD_HONOR
					GROUP BY trim(COD_PRH)
				)
				UPDATE activite[PX].t_rubriques_facturation SET
					code = COD_PRH,
					texte = LIB_PRH,
					texte_court = LIB_PRH
				FROM prod_honor
				WHERE COD_PRH = code_original AND
					(
						code IS DISTINCT FROM COD_PRH OR 
						texte IS DISTINCT FROM LIB_PRH OR
						texte_court IS DISTINCT FROM LIB_PRH
					)
				;

				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_sigems.PROD_CLINI
				WHERE ACT_PRC NOT IN (SELECT code_original FROM activite.t_prestations)
					AND ACT_PRC <> ''
				GROUP BY 1,2
				ORDER BY ACT_PRC;

				WITH prod_clini AS 
				(
					SELECT 
						ACT_PRC AS code_prod_clini,
						MAX(ACT_PRC) AS texte_prod_clini
					FROM prod_sigems.PROD_CLINI
					WHERE ACT_PRC <> ''
					GROUP BY 1
				)
				UPDATE activite.t_prestations SET
					code = code_prod_clini,
					texte = texte_prod_clini,
					texte_court = texte_prod_clini
				FROM prod_clini
				WHERE code_original = code_prod_clini AND
					(
						code IS DISTINCT FROM code_prod_clini OR
						texte IS DISTINCT FROM texte_prod_clini OR
						texte_court IS DISTINCT FROM texte_prod_clini
					) 
				;

				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_sigems.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;
				
				WITH prod_honor AS 
				(
					SELECT 
						CASE WHEN ACT_PRH <> '' THEN ACT_PRH ELSE COD_PRH END AS code_prod_honor,
						MAX(CASE WHEN ACT_PRH <> '' THEN ACT_PRH ELSE COD_PRH END) AS texte_prod_honor
					FROM prod_sigems.PROD_HONOR
					GROUP BY 1
				)
				UPDATE activite.t_prestations SET
					code = code_prod_honor,
					texte = texte_prod_honor,
					texte_court = texte_prod_honor
				FROM prod_honor
				WHERE code_prod_honor NOT IN
					(
						SELECT code
						FROM base.t_ccam_regroupements
						WHERE code NOT IN ('NGAP','CCAM','CDAM') AND
							length(code) = 3 AND
							oid IN (SELECT ccam_regroupement_id_1 FROM base.t_actes) AND
							code <> ''
					) AND 
					code_original = code_prod_honor AND
					(
						code IS DISTINCT FROM code_prod_honor OR
						texte IS DISTINCT FROM texte_prod_honor OR
						texte_court IS DISTINCT FROM texte_prod_honor
					) 
				;
				
				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(COALESCE(INT1,AFA_PRC)), MAX(COALESCE(INT1,AFA_PRC))
				FROM prod_sigems.PROD_CLINI
				LEFT JOIN prod_sigems.COMPTE ON AFA_PRC = NUM				
				WHERE AFA_PRC <> '' AND AFA_PRC NOT IN (SELECT code_original 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(COALESCE(INT1,CPT_ANA)), MAX(COALESCE(INT1,CPT_ANA))
				FROM prod_sigems.ANALYG
				LEFT JOIN prod_sigems.COMPTE ON CPT_ANA = num AND ANALYG.TYP_ANA = COMPTE.TYP 
				WHERE CPT_ANA NOT IN (SELECT code_original FROM activite[PX].t_compte)
				GROUP BY 1
				ORDER BY 1;


				WITH comptes AS (
					SELECT trim(AFA_PRC) AS AFA_PRC,
					MAX(COALESCE(INT1,AFA_PRC)) AS INT1
					FROM prod_sigems.PROD_CLINI
					LEFT JOIN prod_sigems.COMPTE ON AFA_PRC = NUM	
					GROUP BY trim(AFA_PRC)
				)
				UPDATE activite[PX].t_compte SET
					code = AFA_PRC,
					texte = INT1,
					texte_court = INT1
				FROM comptes
				WHERE AFA_PRC = code_original AND
					(
						code IS DISTINCT FROM AFA_PRC OR 
						texte IS DISTINCT FROM INT1 OR
						texte_court IS DISTINCT FROM INT1
					)
				;

							
				WITH comptes_analytique AS (
					SELECT trim(CPT_ANA) AS CPT_ANA,
					MAX(COALESCE(INT1,CPT_ANA)) AS INT1
						FROM prod_sigems.ANALYG
						LEFT JOIN prod_sigems.COMPTE ON CPT_ANA = num AND ANALYG.TYP_ANA = COMPTE.TYP	
					GROUP BY trim(CPT_ANA)
				)
				UPDATE activite[PX].t_compte SET
					code = CPT_ANA,
					texte = INT1,
					texte_court = INT1
				FROM comptes_analytique
				WHERE CPT_ANA = code_original AND
					(
						code IS DISTINCT FROM CPT_ANA OR 
						texte IS DISTINCT FROM INT1 OR
						texte_court IS DISTINCT FROM INT1
					)
				;
                
                -- 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
                ;
                
                -- Motifs non facturation
				INSERT INTO activite[PX].t_motif_non_facturation(code_original, code, texte, texte_court)
				SELECT NUM, NUM, MAX(LIB), MAX(LIB)
				FROM prod_sigems.MOTIF_ATTENTE
				WHERE NUM <> '' AND NUM NOT IN (SELECT code FROM activite[PX].t_motif_non_facturation)
				GROUP BY 1
				ORDER BY 1
				;
                
										
			]]></sqlcmd>
		</NODE>
		
	</NODE>
		
	<NODE name="POST" label="TRAITEMENTS COMPLEMENTAIRES">
			
		<NODE name="Compléments patients">
			<sqlcmd><![CDATA[
				DROP TABLE IF EXISTS w_medecins;
				CREATE TEMP TABLE w_medecins AS
				SELECT 
					COD_PRA,
					MAX(NOM_PRA) as nom_pra, 
					MAX(PRE_PRA) as pre_pra
				FROM prod_sigems.PRATICIEN
				GROUP BY 1;
				
				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,
					CASE WHEN (CMT_DOS IS NULL OR CMT_DOS LIKE 'DIVERS%'  OR CMT_DOS = '') AND ME1_DOS <> '' AND ME1_DOS IS NOT NULL THEN ME1_DOS || ' ' || ME2_DOS ELSE COALESCE(CMT_DOS,'') END AS CMT_DOS,
					CASE WHEN  ME1_DOS <> '' AND ME1_DOS IS NOT NULL THEN ME1_DOS ELSE COALESCE(CMT_DOS,'') END AS nom_med,
					CASE WHEN ME2_DOS <> '' AND ME2_DOS IS NOT NULL THEN  ME2_DOS ELSE '' END AS pre_med
				FROM prod_sigems.dossier
				left join prod_sigems.dossier_x on (dossier.ann_dos = dossier_x.ann_dox and dossier.cod_dos = dossier_x.cod_dox)
				WHERE DSO_DOS >= '20120101' OR DSO_DOS IS NULL;
				
				UPDATE w_DOSSIER_SELECT SET
					nom_med = w_medecins.nom_pra,
					pre_med = w_medecins.pre_pra
				FROM w_medecins
				WHERE
					CMT_DOS = w_medecins.COD_PRA
					AND (nom_med <> w_medecins.nom_pra OR pre_med <> w_medecins.pre_pra)
				;
				
				UPDATE w_DOSSIER_SELECT SET
					pre_med = CMT_DOS
				WHERE
					CMT_DOS IN ('DIVERS', '', '?', '0')
					AND nom_med = CMT_DOS
					and pre_med != CMT_DOS
				;

				CREATE INDEX w_DOSSIER_SELECT_i1
								  ON w_DOSSIER_SELECT
								  USING btree
								  (no_sejour_SELECT);
		
								  
				-- 	Ajout médecins traitants dans ACTIVITE (Ajouter dans BASE)
				INSERT INTO activite[PX].t_medecins_traitants_administratifs(code_original, code, nom, prenom, specialite_id, no_rpps)
                    SELECT trim(CMT_DOS), trim(CMT_DOS), MAX(nom_med), MAX(pre_med), 0, ''
                    FROM w_DOSSIER_SELECT
                    WHERE TRUE
                        AND trim(CMT_DOS) NOT IN (SELECT code_original FROM activite[PX].t_medecins_traitants_administratifs)
                        AND CMT_DOS <> 0
                        AND trim(CMT_DOS) <> ''
						AND trim(CMT_DOS) <> '0'
                        AND CMT_DOS IS NOT NULL
                    GROUP BY trim(CMT_DOS)
                ;



				WITH medecins AS (
					SELECT trim(CMT_DOS) AS CMT_DOS,
						MAX(nom_med) AS nom_med,
						MAX(pre_med) AS pre_med
					FROM w_DOSSIER_SELECT
					GROUP BY trim(CMT_DOS)
				)
				UPDATE activite[PX].t_medecins_traitants_administratifs SET
					code = CMT_DOS,
					nom = nom_med,
					prenom = pre_med
				FROM medecins
				WHERE CMT_DOS = code_original AND
					(
						code IS DISTINCT FROM CMT_DOS OR 
						nom IS DISTINCT FROM nom_med OR
						prenom IS DISTINCT FROM pre_med
					)
				;


				--  maj code rpps
				UPDATE activite[PX].t_medecins_traitants_administratifs
				SET no_rpps = rpps
				FROM prod_sigems.PRAT_COMPL 
				WHERE PRAT_COMPL.COD_PRA = t_medecins_traitants_administratifs.code
					AND (t_medecins_traitants_administratifs.no_rpps IS NULL OR t_medecins_traitants_administratifs.no_rpps = ''
					AND rpps IS not NULL AND rpps <>'' );

					
				-- maj id médecin_traitant dans séjours
				UPDATE activite[PX].p_sejours
				SET medecin_traitant_id = t_medecins_traitants_administratifs.oid
				FROM w_DOSSIER_SELECT, activite[PX].t_medecins_traitants_administratifs
				WHERE w_DOSSIER_SELECT.no_sejour_SELECT = p_sejours.no_sejour AND
					w_DOSSIER_SELECT.CMT_DOS = t_medecins_traitants_administratifs.code AND
					w_DOSSIER_SELECT.CMT_DOS IS NOT NULL AND w_DOSSIER_SELECT.CMT_DOS <> '' AND
					medecin_traitant_id IS DISTINCT FROM t_medecins_traitants_administratifs.oid
				;

				-- 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[
							
				-- Motifs non facturation
                DROP TABLE IF EXISTS w_DOSSIER_ATTENTE;
                CREATE TEMP TABLE w_DOSSIER_ATTENTE AS
                SELECT 
                    DOSSIER_ATTENTE.ANNEE || to_char(DOSSIER_ATTENTE.CODE,'FM900000') AS no_sejour,
                    (MAX(ARRAY[DAT::text, COALESCE(t_motif_non_facturation.oid::text,t_motif_non_facturation_autres.oid::text)]))[2]::bigint AS motif_non_facturation_id,
                    (MAX(ARRAY[DAT::text, DOSSIER_ATTENTE.LIB::text]))[2] AS motif_non_facturation_comment
                FROM prod_sigems.DOSSIER_ATTENTE
                LEFT JOIN activite[PX].t_motif_non_facturation ON t_motif_non_facturation.code_original = CODE_MOTIF
                JOIN activite[PX].t_motif_non_facturation t_motif_non_facturation_autres ON t_motif_non_facturation_autres.code_original = '*CTIZZZ'
                GROUP BY 1
                ;


                UPDATE activite[PX].p_factures
                SET motif_non_facturation_id = w_DOSSIER_ATTENTE.motif_non_facturation_id,
                    motif_non_facturation_comment = w_DOSSIER_ATTENTE.motif_non_facturation_comment
                FROM w_DOSSIER_ATTENTE
                WHERE p_factures.no_sejour = w_DOSSIER_ATTENTE.no_sejour
                ;
			
                -- Dates
				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="Réaffectation des règlements si AMO = AMC">

			<sqlcmd><![CDATA[

				INSERT INTO activite[PX].p_factures_soldes_c(
					facture_id,
					no_facture, 
					date_comptable, 
					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,
					od_non_comptabilise
				)
				SELECT
					p_factures_soldes_c.facture_id,
					p_factures_soldes_c.no_facture,
					MAX(date_comptable) AS date_comptable,
					p_factures_soldes_c.prestation_id,
					p_factures_soldes_c.rubrique_comptabilisee_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_regle, 
					0::numeric AS montant_regle_0, 
					SUM(montant_comptabilise_1)-SUM(montant_regle_1),
					SUM(montant_comptabilise_2)-SUM(montant_regle_2),
					0::numeric AS montant_regle_22,
					'1' AS od_non_comptabilise
				FROM activite[PX].p_factures_soldes_c
				JOIN activite[PX].p_factures ON p_factures_soldes_c.no_facture = p_factures.no_facture
				JOIN activite[PX].t_tiers_payant t_tiers_payant_1 ON tiers_payant_1_id = t_tiers_payant_1.oid
				JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON tiers_payant_2_id = t_tiers_payant_2.oid
				WHERE t_tiers_payant_1.code = t_tiers_payant_2.code
				GROUP BY 1,2,4,5
				HAVING SUM(montant_comptabilise_1)+SUM(montant_comptabilise_2)=SUM(montant_regle_1)+SUM(montant_regle_2) AND
					SUM(montant_comptabilise_1) <> SUM(montant_regle_1)
				;

				INSERT INTO activite[PX].p_factures_soldes_h(
					facture_id,
					no_facture, 
					date_comptable, 
					prestation_id,
					rubrique_comptabilisee_id,
					medecin_comptabilise_id,
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22,
					od_non_comptabilise
				)
				SELECT
					p_factures_soldes_h.facture_id,
					p_factures_soldes_h.no_facture,
					MAX(date_comptable) AS date_comptable,
					p_factures_soldes_h.prestation_id,
					p_factures_soldes_h.rubrique_comptabilisee_id,
					p_factures_soldes_h.medecin_comptabilise_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_regle, 
					0::numeric AS montant_regle_0, 
					SUM(montant_comptabilise_1)-SUM(montant_regle_1),
					SUM(montant_comptabilise_2)-SUM(montant_regle_2),
					0::numeric AS montant_regle_22,
					'1' AS od_non_comptabilise
				FROM activite[PX].p_factures_soldes_h
				JOIN activite[PX].p_factures ON p_factures_soldes_h.no_facture = p_factures.no_facture
				JOIN activite[PX].t_tiers_payant t_tiers_payant_1 ON tiers_payant_1_id = t_tiers_payant_1.oid
				JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON tiers_payant_2_id = t_tiers_payant_2.oid
				WHERE t_tiers_payant_1.code = t_tiers_payant_2.code
				GROUP BY 1,2,4,5,6
				HAVING SUM(montant_comptabilise_1)+SUM(montant_comptabilise_2)=SUM(montant_regle_1)+SUM(montant_regle_2) AND
					SUM(montant_comptabilise_1) <> SUM(montant_regle_1)
				;
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Dépassements honoraires">
			<NODE label="Report du paramétrage des médecins">
				<condition><![CDATA[
					"[PX]" != ""
				]]></condition>
				<sqlcmd><![CDATA[
						
					-- Report du paramétrage des médecins depuis le schéma activite sur le schéma activite du prestataire dans le cas d'une FUSION
					UPDATE activite[PX].t_medecins_administratifs AS t_medecins_administratifs_prestataire
					SET 
						KIWEE_SIGEMS_HONPATCPT = t_medecins_administratifs_activite.KIWEE_SIGEMS_HONPATCPT,
						KIWEE_SIGEMS_HONPATCPTDEP = t_medecins_administratifs_activite.KIWEE_SIGEMS_HONPATCPTDEP
					FROM activite.t_medecins_administratifs AS t_medecins_administratifs_activite
					WHERE UPPER('[PX]') || '_' || t_medecins_administratifs_prestataire.code_original = t_medecins_administratifs_activite.code_original
					;

				]]></sqlcmd>
			</NODE>
			<NODE label="Suppression des dépassements honoraires">
				<condition><![CDATA[
					SELECT count(*) > 0
					FROM activite[PX].t_medecins_administratifs
					WHERE KIWEE_SIGEMS_HONPATCPT = '0' OR
						KIWEE_SIGEMS_HONPATCPTDEP = '0' ;
				]]></condition>
				<sqlcmd><![CDATA[
						
					-- Lancement de la fonction depuis le schéma activite du prestataire
					-- Ceci est nécessaire pour réaliser les modifications sur les bonnes tables dans le cas d'une FUSION
					SELECT activite[PX].cti_kiwee_sigems_honpatcpt()
					;
					
				]]></sqlcmd>
			</NODE>
		</NODE>
		
		<NODE label="Tables répliquées">
			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>
			
			<sqlcmd><![CDATA[

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