<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
    
    
    <NODE name="INIT" label="INITIALISATIONS">
        
        <NODE label="Reports CORA" comment="Report des données CORA vers CEGI si CORA">
            <condition><![CDATA[
                "[WITH_CORA]" != "0"
            ]]></condition>
            <sqlcmd><![CDATA[
            
                -- Table sejour 
                
                TRUNCATE prod_cegi.cj_sejour;
                INSERT INTO prod_cegi.cj_sejour (
                    sej_id, 
                    pat_id, 
                    etb_id, 
                    sej_dt_entree, 
                    sej_dt_sortie, 
                    sej_numdos, 
                    sej_cp,
					sej_uage,
					sej_creat_appli
                )
                SELECT 
                    MAX(id_sejour) , 
                    MAX(id_patient), 
                    '1',  
                    MAX(date_entree), 
                    MAX(date_sortie), 
                    no_sejour, 
					'',
					'',
                    ''
                FROM prod_cora.tb_sejour
                GROUP BY 6;



                -- Table patient
                TRUNCATE prod_cegi.cj_patient;
                INSERT INTO prod_cegi.cj_patient(
                    pat_id, 
                    per_id, 
                    pat_ipp, 
                    pat_sexe, 
                    per_nom, 
                    per_nomjf, 
                    per_prenom, 
                    per_naissance, 
                    per_cp,
					per_nvoie,
					per_nomvoie,
					per_compvoie,
					pat_tel1,
					pat_tel2,
					pat_email)
				SELECT 
					id_patient, 
					0, 
					ipp_patient, 
					sexe, 
                    nom_usuel_patient, 
                    nom_naissance,  
                    prenom_patient, 
                    date_nais, 
                    code_postal,
					'',
					'',
					'',
					'',
					'',
					''
				FROM prod_cora.tb_patient; 
                
                -- RSS
				INSERT INTO prod_cegi.RSS(
					n_pmsi,
					n_rss,
					n_doss,
					c_etat,
					c_err,
					c_att,
					d_e_etablt,
					d_s_etablt,
					nb_seances,
					poids,
					n_lot,
					n_ss,
					cle_ss,
					ver_classif,
					ver_rss,
					ver_rum,
					pat_id,
					sej_id,
					c_ghm_ccam,
					c_err_ccam,
					dt_env_adm,
					valide,
					ghs_numero)
				SELECT
					0-TB_SYNTH_RSS.ID_RSS AS N_PMSI,
					base.cti_to_number(TB_SYNTH_RSS.NO_RSS) AS N_RSS,
					base.cti_to_number(TB_SYNTH_RSS.NO_SEJOUR) AS N_DOSS,
					'0'::text AS C_ETAT,
					0::numeric AS C_ERR,
					''::text AS C_ATT,
					DATE_DEBUT AS D_E_ETABLT,
					DATE_FIN AS D_S_ETABLT,
					0::numeric AS NB_SEANCES,
					0::numeric AS POIDS,
					0::numeric AS N_LOT,
					''::text AS N_SS,
					''::text AS CLE_SS,
					''::text AS VER_CLASSIF,
					''::text AS VER_RSS,
					''::text AS VER_RUM,
					ID_PATIENT AS PAT_ID,
					ID_SEJOUR AS SEJ_ID,
					GHM_INITIAL AS  C_GHM_CCAM,
					0::numeric AS C_ERR_CCAM,
					DATE_FABRICATION AS DT_ENV_ADM,
					1::numeric AS VALIDE,
					CODE_GHS AS GHS_NUMERO
				FROM prod_cora.TB_SYNTH_RSS
				WHERE TB_SYNTH_RSS.NO_SEJOUR NOT IN 
					(SELECT N_DOSS FROM prod_cegi.RSS)

                ]]></sqlcmd>
        </NODE>
    
        <NODE label="Détection activité FIRST">

           	<NODE label="Détection logiciel facturation par séjour (CEGI)">
               
               <condition><![CDATA[
                "[CEGILOGHOS_PRESENT]" == "OUI"
                ]]></condition>

               <sqlcmd><![CDATA[
                
                    UPDATE prod_cegi.CJ_SEJOUR
                    SET SEJ_UAGE = ''
                    WHERE SEJ_UAGE <> '';
                    
                    UPDATE prod_cegi.CJ_SEJOUR
                    SET SEJ_UAGE = 'H'
                    FROM prod_cegiloghos.OPERA_SEJ
                    WHERE SEJ_NUMDOS = NO_DOSSIER AND
                        (
                        ETB_ID::text = ANY (string_to_array('[ID_ETAB]'::text,',')) OR
                        '[ID_ETAB]' = '' OR
                        '[ID_ETAB]' = '-1'
                        );
						
					ANALYSE prod_cegi.CJ_SEJOUR
					;

                   
				]]></sqlcmd>
			</NODE>
			<NODE label="Détection logiciel facturation par séjour (CEGI FIRST)">
				<condition><![CDATA[
					"[CJFIRST_PRESENT]" == "OUI"
				]]></condition>
				<sqlcmd><![CDATA[
				
                     DROP TABLE IF EXISTS w_LOGHOS1st_date;
					CREATE TEMP TABLE w_LOGHOS1st_date AS
                    SELECT date(date_trunc('month',SEJ_DT_SORTIE)) AS CEGIFIRSTSTART_significativedate
                    FROM prod_cegi.CJ_SEJOUR
                    WHERE SEJ_CREAT_APPLI = 'LOGHOS1st' AND SEJ_DT_SORTIE IS NOT NULL
                    GROUP BY 1
                    HAVING count(*) > 10
                    ORDER BY 1
                    LIMIT 1
                    ;
                
					DROP TABLE IF EXISTS w_CEGIFIRSTSTART;
					CREATE TEMP TABLE w_CEGIFIRSTSTART AS
					SELECT 
                        date(min(CASE WHEN SEJ_CREAT_APPLI = 'LOGHOS1st' AND SEJ_DT_SORTIE >= CEGIFIRSTSTART_significativedate THEN SEJ_DT_SORTIE ELSE NULL END)) AS CEGIFIRSTSTART_date,
                        date(min(CASE WHEN SEJ_UAGE = 'H' THEN SEJ_DT_SORTIE ELSE NULL END)) AS CEGILOGHOSSTART_date
                    FROM prod_cegi.CJ_SEJOUR
                    LEFT JOIN w_LOGHOS1st_date ON 1=1
					;
				
				-- Si pas de LOGHOS, tout est en first
					UPDATE prod_cegi.CJ_SEJOUR
                    SET SEJ_UAGE = 'F'
                    FROM w_CEGIFIRSTSTART
                    WHERE CEGIFIRSTSTART_date IS NULL AND
                        SEJ_UAGE IS DISTINCT FROM 'H' AND
                        (
                        ETB_ID::text = ANY (string_to_array('[ID_ETAB]'::text,',')) OR
                        '[ID_ETAB]' = '' OR
                        '[ID_ETAB]' = '-1'
                        );

					UPDATE prod_cegi.CJ_SEJOUR
                    SET SEJ_UAGE = 'F'
                    FROM w_CEGIFIRSTSTART
                    WHERE COALESCE(SEJ_DT_SORTIE,'20991231') >= CEGIFIRSTSTART_date AND
                        SEJ_DT_ENTREE >= CEGIFIRSTSTART_date AND
                        SEJ_UAGE IS DISTINCT FROM 'H' AND
                        (
							ETB_ID::text = ANY (string_to_array('[ID_ETAB]'::text,',')) OR
							'[ID_ETAB]' = '' OR
							'[ID_ETAB]' = '-1'
                        );
                        
                    UPDATE prod_cegi.CJ_SEJOUR
                    SET SEJ_UAGE = 'F'
                    WHERE SEJ_UAGE IS DISTINCT FROM 'F' AND
                        SEJ_ID IN (SELECT SEJ_ID FROM prod_cegi.CJ_EFS) AND
                        (
                        ETB_ID::text = ANY (string_to_array('[ID_ETAB]'::text,',')) OR
                        '[ID_ETAB]' = '' OR
                        '[ID_ETAB]' = '-1'
                        )
                        ;
						
					ANALYSE prod_cegi.CJ_SEJOUR
					;					

                        
                ]]></sqlcmd>
            </NODE>
            
            
        </NODE>     
        
        <NODE label="*LOGHOS*">
            
            <condition><![CDATA[
                "[CEGILOGHOS_PRESENT]" == "OUI"
            ]]></condition>
        
            <NODE label="Identification des séjours">
                <sqlcmd><![CDATA[

                
                    -- Table des séjours à créer
                    DROP TABLE IF EXISTS w_OPERA_SEJ_select;

                    CREATE TEMP TABLE w_OPERA_SEJ_select AS
                    SELECT 
                        OPERA_SEJ.*,
                        DATE_ENTREE_SEJOUR 
                            + date_part('hour',to_timestamp(to_char(HEURE_ENTREE_SEJOUR, 'FM0000'),'HH24MI')) * '1 HOUR'::interval
                            + date_part('minute',to_timestamp(to_char(HEURE_ENTREE_SEJOUR, 'FM0000'),'HH24MI')) * '1 MINUTE'::interval AS DATE_HEURE_ENTREE_SEJOUR,
                        DATE_SORTIE_SEJOUR 
                            + date_part('hour',to_timestamp(to_char(HEURE_SORTIE_SEJOUR, 'FM0000'),'HH24MI')) * '1 HOUR'::interval
                            + date_part('minute',to_timestamp(to_char(HEURE_SORTIE_SEJOUR, 'FM0000'),'HH24MI')) * '1 MINUTE'::interval AS DATE_HEURE_SORTIE_SEJOUR,
                        OPERA_PSDISC.CODE_SERVICE_TARIFAIRE AS CODE_SERVICE_TARIFAIRE_ENTREE,
                        CODE_SERVICE_DISCIPLINE AS CODE_SERVICE_DISCIPLINE_ENTREE,
                        MT AS MT_ENTREE,
                        DMT AS DMT_ENTREE,
                        PAT_ID,
                        COALESCE(t_codes_postaux.oid, 0) as code_postal_id
                    FROM prod_cegiloghos.OPERA_SEJ
                        LEFT JOIN prod_cegiloghos.OPERA_PSDISC ON CODE_SERVICE_ENTREE = CODE_SERVICE_DISCIPLINE
                        LEFT JOIN prod_cegiloghos.OPERA_PSTARF ON OPERA_PSDISC.CODE_SERVICE_TARIFAIRE = OPERA_PSTARF.CODE_SERVICE_TARIFAIRE
                        JOIN prod_cegi.CJ_SEJOUR ON SEJ_NUMDOS = NO_DOSSIER AND SEJ_UAGE = 'H'
                        LEFT JOIN (
						  SELECT
                            PAT_ID as w_PAT_ID,
                            MAX(PER_CP) as w_PER_CP
                        FROM
                            prod_cegi.CJ_PATIENT
                        GROUP BY CJ_PATIENT.PAT_ID
						) cp ON w_PAT_ID = cj_sejour.PAT_ID
						LEFT JOIN base.t_codes_postaux on w_PER_CP = t_codes_postaux.code
                        JOIN prod_cegi.cj_etb ON cj_etb.etb_id = CJ_SEJOUR.etb_id
                        JOIN base.t_finess ON t_finess.code = cj_etb.etb_finess
                    WHERE DATE_SORTIE_SEJOUR >= '[ENV_ADM_ANNEEDEBUT]0101' OR 
                        DATE_SORTIE_SEJOUR IS NULL OR
                        DATE_SORTIE_SEJOUR <= '00010101' OR
                        NO_DOSSIER IN  
						(
							(
								SELECT 
									DISTINCT NO_DOSSIER
								FROM 
									prod_cegiloghos.OPERA_FAC
								WHERE
									DATE_CALCUL_FACTURE IS NULL OR 
									DATE_CALCUL_FACTURE >= '[ENV_ADM_ANNEEDEBUT]0101' OR
									DATE_ENVOI_CETELIC_FACT_AMO >= '[ENV_ADM_ANNEEDEBUT]0101' OR
									DATE_ENVOI_CETELIC_FACT_AMC >= '[ENV_ADM_ANNEEDEBUT]0101' 
							)
							UNION
							(
								SELECT 
									DISTINCT NO_DOSSIER
								FROM 
									prod_cegiloghos.OPERA_REG
								WHERE
									DATE_REGLEMENT >= '[ENV_ADM_ANNEEDEBUT]0101' 
							)
						)
                        ;
                        
                    UPDATE w_OPERA_SEJ_select
                    SET DATE_SORTIE_SEJOUR = '20991231', DATE_HEURE_SORTIE_SEJOUR = '20991231'
                    WHERE TYPE_DOSSIER NOT IN('A', 'E', 'I', 'Q') AND (DATE_SORTIE_SEJOUR IS NULL OR DATE_SORTIE_SEJOUR <= '00010101');
                    
                    UPDATE w_OPERA_SEJ_select
                    SET DATE_SORTIE_SEJOUR = DATE_ENTREE_SEJOUR, DATE_HEURE_SORTIE_SEJOUR = DATE_HEURE_ENTREE_SEJOUR
                    WHERE (DATE_SORTIE_SEJOUR IS NULL OR DATE_SORTIE_SEJOUR <= '00010101');
                    
                    -- Suppression des dossiers sans numéro de dossier
                    DELETE FROM w_OPERA_SEJ_select WHERE trim(NO_DOSSIER) = '' OR NO_DOSSIER IS NULL;
                    
                    -- Suppression éventuelle dossiers en double
                    DELETE FROM w_OPERA_SEJ_select
                    USING (
                        SELECT NO_DOSSIER, MAX(CTID) AS CTID_ok
                        FROM w_OPERA_SEJ_select
                        GROUP BY 1
                        HAVING count(*) > 1
                    ) subview
                    WHERE w_OPERA_SEJ_select.NO_DOSSIER = subview.NO_DOSSIER AND 
                        w_OPERA_SEJ_select.CTID IS DISTINCT FROM subview.CTID_OK;

                    ALTER TABLE w_OPERA_SEJ_select ADD CONSTRAINT w_OPERA_SEJ_select_pkey PRIMARY KEY(NO_DOSSIER);


                    DROP TABLE IF EXISTS w_OPERA_ACT_annee;
                    CREATE TEMP TABLE w_OPERA_ACT_annee AS
                    SELECT 
                        OPERA_ACT.NO_DOSSIER, 
                        OPERA_ACT.NO_FACTURE, 
                        MAX(OPERA_ACT.PERIODE_ANNEE) AS PERIODE_ANNEE,
                        date(MIN(CASE WHEN CODE_PRESTA IN ('PJ') THEN DATE_ACTE_DEBUT ELSE NULL END)) AS DATE_FACT_DEBUT_PJ,
                        date(MAX(CASE WHEN CODE_PRESTA IN ('PJ') THEN DATE_ACTE_FIN ELSE NULL END)) AS DATE_FACT_FIN_PJ
                    FROM prod_cegiloghos.OPERA_ACT
                        JOIN w_OPERA_SEJ_select ON OPERA_ACT.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                    WHERE NO_FACTURE <> '000000000'
                    GROUP BY 1,2;
                    
                    ALTER TABLE w_OPERA_ACT_annee ADD CONSTRAINT w_OPERA_ACT_annee_pkey PRIMARY KEY(NO_FACTURE);
                    
                    
                    UPDATE w_OPERA_ACT_annee
                    SET DATE_FACT_DEBUT_PJ = date(DATE_ENTREE_SEJOUR)
                    FROM prod_cegiloghos.OPERA_SEJ
                    WHERE OPERA_SEJ.NO_DOSSIER = w_OPERA_ACT_annee.NO_DOSSIER AND
                    ABS(date(DATE_ENTREE_SEJOUR)-DATE_FACT_DEBUT_PJ) = 1;


                    UPDATE w_OPERA_ACT_annee
                    SET DATE_FACT_FIN_PJ = date(DATE_SORTIE_SEJOUR)
                    FROM prod_cegiloghos.OPERA_SEJ
                    WHERE OPERA_SEJ.NO_DOSSIER = w_OPERA_ACT_annee.NO_DOSSIER AND
                    ABS(date(DATE_SORTIE_SEJOUR)-DATE_FACT_FIN_PJ) = 1;


                    DROP TABLE IF EXISTS w_OPERA_REG_annee;
                    CREATE TEMP TABLE w_OPERA_REG_annee AS
                    SELECT 
                        OPERA_REG.NO_FACTURE, 
                        MAX(OPERA_REG.PERIODE_ANNEE) AS PERIODE_ANNEE
                    FROM prod_cegiloghos.OPERA_REG
                        JOIN w_OPERA_SEJ_select ON OPERA_REG.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                    WHERE NO_FACTURE <> '000000000' AND TYPE_REGLEMENT IN ('1', 'S')
                    GROUP BY 1;
                    
                    ALTER TABLE w_OPERA_REG_annee ADD CONSTRAINT w_OPERA_REG_annee_pkey PRIMARY KEY(NO_FACTURE);
                    
					-- Correction code UCD à 13
					UPDATE prod_cegiloghos.OPERA_ACT
					SET CODE_UCD = substr(CODE_UCD,7)
					WHERE length(CODE_UCD) = 13 AND substr(CODE_UCD,1,6) = '000000'
					;
                    

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

        <NODE label="*FIRST*">
            
            <condition><![CDATA[
                "[CJFIRST_PRESENT]" == "OUI"
            ]]></condition>
                
            <NODE label="Correction table règlements">
                <sqlcmd><![CDATA[
                
                    -- Corrections pour acomptes sans facture renseignée
                    DROP TABLE IF EXISTS w_CJ_TER;
                    CREATE TEMP TABLE w_CJ_TER AS
                    SELECT
                        TER_ID, 
                        MAX(EFT_TER_TYPE) AS EFT_TER_TYPE
                    FROM prod_cegi.CJ_EFT
                    GROUP BY 1;

                    UPDATE prod_cegi.CJ_XECF 
                    SET EFT_ID = subview.EFT_ID
                    FROM
                    (   
                    SELECT SEJ_ID, TER_ID, MND_ID, MAX(EFT_ID) AS EFT_ID
                    FROM prod_cegi.CJ_EFT
                    WHERE EFT_ID_AVOIR = 0 AND EFT_ETAT = 'F' 
                    GROUP BY 1,2,3
                    HAVING count(*) = 1
                    ) subview,
                    prod_cegi.CJ_XECE
                    WHERE CJ_XECF.XECE_ID = CJ_XECE.XECE_ID AND
                        CJ_XECF.SEJ_ID = subview.SEJ_ID AND
                        CJ_XECF.TER_ID = subview.TER_ID AND
                        CJ_XECF.EFT_ID <> subview.EFT_ID AND
                        CJ_XECF.MND_ID = subview.MND_ID AND
                        (CJ_XECF.XECF_PLC LIKE '411%' OR CJ_XECF.XECF_PLC LIKE '412%' OR CJ_XECF.XECF_PLC LIKE '419%')
                    ;

                    UPDATE prod_cegi.CJ_XECF 
                    SET EFT_ID = subview.EFT_ID
                    FROM
                    (   
                    SELECT SEJ_ID, TER_ID, MND_ID, MAX(EFT_ID) AS EFT_ID
                    FROM prod_cegi.CJ_EFT
                    WHERE EFT_ID_AVOIR = 0 AND EFT_ETAT = 'F' AND EFT_TTC <> 0
                    GROUP BY 1,2,3
                    HAVING count(*) = 1
                    ) subview,
                    prod_cegi.CJ_XECE
                    WHERE CJ_XECF.XECE_ID = CJ_XECE.XECE_ID AND
                        CJ_XECF.SEJ_ID = subview.SEJ_ID AND
                        CJ_XECF.TER_ID = subview.TER_ID AND
                        CJ_XECF.EFT_ID <> subview.EFT_ID AND
                        CJ_XECF.MND_ID = subview.MND_ID AND
                        (CJ_XECF.XECF_PLC LIKE '411%' OR CJ_XECF.XECF_PLC LIKE '412%' OR CJ_XECF.XECF_PLC LIKE '419%')
                    ;

                    

                    UPDATE prod_cegi.CJ_XECF 
                    SET EFT_ID = subview.EFT_ID
                    FROM
                    (   
                    SELECT SEJ_ID, EFT_TER_TYPE, MND_ID, MAX(EFT_ID) AS EFT_ID
                    FROM prod_cegi.CJ_EFT
                    WHERE EFT_ID_AVOIR = 0 AND EFT_ETAT = 'F'
                    GROUP BY 1,2,3
                    HAVING count(*) = 1
                    ) subview,
                    prod_cegi.CJ_XECE
                    LEFT JOIN w_CJ_TER ON CJ_XECE.TER_ID = w_CJ_TER.TER_ID
                    WHERE CJ_XECF.XECE_ID = CJ_XECE.XECE_ID AND
                        CJ_XECF.SEJ_ID = subview.SEJ_ID AND
                        COALESCE(w_CJ_TER.EFT_TER_TYPE,'DBT') = subview.EFT_TER_TYPE AND
                        CJ_XECF.EFT_ID <> subview.EFT_ID AND
                        CJ_XECF.MND_ID = subview.MND_ID AND
                        (CJ_XECF.XECF_PLC LIKE '411%' OR CJ_XECF.XECF_PLC LIKE '412%' OR CJ_XECF.XECF_PLC LIKE '419%')
                    ;

                    UPDATE prod_cegi.CJ_XECF 
                    SET EFT_ID = subview.EFT_ID
                    FROM
                    (   
                    SELECT SEJ_ID, MND_ID, MAX(EFT_ID) AS EFT_ID
                    FROM prod_cegi.CJ_EFT
                    GROUP BY 1,2
                    HAVING count(*) = 1
                    ) subview,
                    prod_cegi.CJ_XECE
                    WHERE CJ_XECF.XECE_ID = CJ_XECE.XECE_ID AND
                        CJ_XECF.SEJ_ID = subview.SEJ_ID AND
                        CJ_XECF.EFT_ID = 0 AND
                        CJ_XECF.MND_ID = subview.MND_ID AND
                        (CJ_XECF.XECF_PLC LIKE '411%' OR CJ_XECF.XECF_PLC LIKE '412%' OR CJ_XECF.XECF_PLC LIKE '419%')
                    ;
					
					ANALYSE prod_cegi.CJ_XECF
					;
					
					DROP TABLE IF EXISTS CJ_XECF_TER 
					;
					CREATE TEMP TABLE CJ_XECF_TER AS
					SELECT *
					FROM prod_cegi.CJ_XECF 
					WHERE EFT_ID <> 0 AND
						SEJ_ID IN (SELECT SEJ_ID FROM prod_cegi.CJ_XECF WHERE EFT_ID = 0)
                    ;

                    ANALYSE CJ_XECF_TER
					;
                        
					CREATE INDEX CJ_XECF_TER_sej_id ON CJ_XECF_TER USING btree (sej_id)
					;


                    SELECT base.cti_execute('
                    
                    UPDATE prod_cegi.CJ_XECF 
                    SET EFT_ID = subview.EFT_ID
                    FROM
                    (   
                        SELECT SEJ_ID, XECE_ID, TER_ID, MND_ID, MAX(EFT_ID) AS EFT_ID
                        FROM prod_cegi.CJ_XECF 
                        WHERE EFT_ID <> 0
                        GROUP BY 1,2,3,4
                        HAVING count(DISTINCT EFT_ID) = 1
                    ) subview
                    WHERE CJ_XECF.SEJ_ID = subview.SEJ_ID AND
                        CJ_XECF.TER_ID = subview.TER_ID AND
                        CJ_XECF.MND_ID = subview.MND_ID AND
                        CJ_XECF.XECE_ID = subview.XECE_ID AND
                        CJ_XECF.EFT_ID = 0 AND
                        (CJ_XECF.XECF_PLC LIKE ''411%'' OR CJ_XECF.XECF_PLC LIKE ''412%'' OR CJ_XECF.XECF_PLC LIKE ''419%'')
                    .,
                    UPDATE prod_cegi.CJ_XECF 
                    SET EFT_ID = CJ_XECF_TER.EFT_ID
                    FROM CJ_XECF_TER  
                    WHERE CJ_XECF.EFT_ID = 0  AND
                        CJ_XECF.SEJ_ID = CJ_XECF_TER.SEJ_ID AND
                        Cj_XECF.XECF_PLC = CJ_XECF_TER.XECF_PLC AND
                        Cj_XECF.TER_ID = CJ_XECF_TER.TER_ID AND
                        Cj_XECF.XECF_MONT = 0-CJ_XECF_TER.XECF_MONT AND
                        CJ_XECF_TER.EFT_ID <> 0
                    ',3)
                    ;

                    UPDATE prod_cegi.CJ_XECF 
                    SET EFT_ID = subview.EFT_ID
                    FROM
                    (   
                    SELECT SEJ_ID, TER_ID, MND_ID, MAX(EFT_ID) AS EFT_ID
                    FROM prod_cegi.CJ_EFT
                    WHERE EFT_ID_AVOIR = 0 AND EFT_ETAT = 'F' 
                    GROUP BY 1,2,3
                    ) subview,
                    prod_cegi.CJ_XECE
                    WHERE CJ_XECF.XECE_ID = CJ_XECE.XECE_ID AND
                        CJ_XECF.SEJ_ID = subview.SEJ_ID AND
                        CJ_XECF.TER_ID = subview.TER_ID AND
                        CJ_XECF.EFT_ID = 0 AND
                        CJ_XECF.MND_ID = subview.MND_ID AND
                        (CJ_XECF.XECF_PLC LIKE '411%' OR CJ_XECF.XECF_PLC LIKE '412%' OR CJ_XECF.XECF_PLC LIKE '419%')
                    ;

                    UPDATE prod_cegi.CJ_XECF 
                    SET EFT_ID = subview.EFT_ID
                    FROM
                    (   
                    SELECT SEJ_ID, EFT_TER_TYPE, MND_ID, MAX(EFT_ID) AS EFT_ID
                    FROM prod_cegi.CJ_EFT
                    WHERE EFT_ID_AVOIR = 0 AND EFT_ETAT = 'F' 
                    GROUP BY 1,2,3
                    ) subview,
                    prod_cegi.CJ_XECE
                    LEFT JOIN w_CJ_TER ON CJ_XECE.TER_ID = w_CJ_TER.TER_ID
                    WHERE CJ_XECF.XECE_ID = CJ_XECE.XECE_ID AND
                        CJ_XECF.SEJ_ID = subview.SEJ_ID AND
                        COALESCE(w_CJ_TER.EFT_TER_TYPE,'DBT') = subview.EFT_TER_TYPE AND
                        CJ_XECF.EFT_ID = 0 AND
                        CJ_XECF.MND_ID = subview.MND_ID AND
                        (CJ_XECF.XECF_PLC LIKE '411%' OR CJ_XECF.XECF_PLC LIKE '412%' OR CJ_XECF.XECF_PLC LIKE '419%')
                    ;

                    UPDATE prod_cegi.CJ_XECF 
                    SET EFT_ID = subview.EFT_ID
                    FROM
                    (   
                    SELECT SEJ_ID, MND_ID, MAX(EFT_ID) AS EFT_ID
                    FROM prod_cegi.CJ_EFT
                    GROUP BY 1,2
                    ) subview,
                    prod_cegi.CJ_XECE
                    WHERE CJ_XECF.XECE_ID = CJ_XECE.XECE_ID AND
                        CJ_XECF.SEJ_ID = subview.SEJ_ID AND
                        CJ_XECF.EFT_ID = 0 AND
                        CJ_XECF.MND_ID = subview.MND_ID AND
                        (CJ_XECF.XECF_PLC LIKE '411%' OR CJ_XECF.XECF_PLC LIKE '412%' OR CJ_XECF.XECF_PLC LIKE '419%')
                    ;


                    UPDATE prod_cegi.CJ_XECF
                    SET XECF_TYPE = 0 - XECF_TYPE
                    WHERE CJ_XECF.XECF_TYPE >= 0 AND
                        XECF_PLC LIKE '4197%'
                    ;


                    
                    DROP TABLE IF EXISTS w_CJ_EFT_TIE;
					CREATE TEMP TABLE w_CJ_EFT_TIE AS
                    SELECT EFS_ID, EFT_SEJHON,
						MAX(CASE WHEN EFT_TER_TYPE = 'CAI' THEN EFT_ID ELSE 0 END) AS EFT_ID_CAI,
						MAX(CASE WHEN EFT_TER_TYPE = 'CAI' THEN EFT_TIE_CENTR ELSE '' END) AS EFT_TIE_CENTR_CAI,
						MAX(CASE WHEN EFT_TER_TYPE = 'MUT' THEN EFT_ID ELSE 0 END) AS EFT_ID_MUT,
						MAX(CASE WHEN EFT_TER_TYPE = 'MUT' THEN EFT_TIE_CENTR ELSE '' END) AS EFT_TIE_CENTR_MUT,
						MAX(CASE WHEN EFT_TER_TYPE = 'DBT' THEN EFT_ID ELSE 0 END) AS EFT_ID_DBT,
						MAX(CASE WHEN EFT_TER_TYPE = 'DBT' THEN EFT_TIE_CENTR ELSE '' END) AS EFT_TIE_CENTR_DBT
					FROM prod_cegi.CJ_EFT
					GROUP BY 1,2
					;

					UPDATE prod_cegi.CJ_XECF 
					SET EFT_ID = EFT_ID_MUT
					FROM prod_cegi.CJ_EFT 
					JOIN w_CJ_EFT_TIE ON CJ_EFT.EFS_ID = w_CJ_EFT_TIE.EFS_ID AND
						CJ_EFT.EFT_SEJHON = w_CJ_EFT_TIE.EFT_SEJHON
					WHERE CJ_EFT.EFT_ID = CJ_XECF.EFT_ID AND
						EFT_TER_TYPE = 'CAI' AND
						XECF_PLC <> EFT_TIE_CENTR_CAI AND
						XECF_PLC = EFT_TIE_CENTR_MUT AND
						EFT_ID_MUT <> 0
					;

					UPDATE prod_cegi.CJ_XECF 
					SET EFT_ID = EFT_ID_DBT
					FROM prod_cegi.CJ_EFT 
					JOIN w_CJ_EFT_TIE ON CJ_EFT.EFS_ID = w_CJ_EFT_TIE.EFS_ID AND
						CJ_EFT.EFT_SEJHON = w_CJ_EFT_TIE.EFT_SEJHON
					WHERE CJ_EFT.EFT_ID = CJ_XECF.EFT_ID AND
						EFT_TER_TYPE = 'CAI' AND
						XECF_PLC <> EFT_TIE_CENTR_CAI AND
						XECF_PLC = EFT_TIE_CENTR_DBT AND
						EFT_ID_DBT <> 0
					;

					UPDATE prod_cegi.CJ_XECF 
					SET EFT_ID = EFT_ID_CAI
					FROM prod_cegi.CJ_EFT 
					JOIN w_CJ_EFT_TIE ON CJ_EFT.EFS_ID = w_CJ_EFT_TIE.EFS_ID AND
						CJ_EFT.EFT_SEJHON = w_CJ_EFT_TIE.EFT_SEJHON
					WHERE CJ_EFT.EFT_ID = CJ_XECF.EFT_ID AND
						EFT_TER_TYPE = 'MUT' AND
						XECF_PLC <> EFT_TIE_CENTR_MUT AND
						XECF_PLC = EFT_TIE_CENTR_CAI AND
						EFT_ID_CAI <> 0
					;

					UPDATE prod_cegi.CJ_XECF 
					SET EFT_ID = EFT_ID_DBT
					FROM prod_cegi.CJ_EFT 
					JOIN w_CJ_EFT_TIE ON CJ_EFT.EFS_ID = w_CJ_EFT_TIE.EFS_ID AND
						CJ_EFT.EFT_SEJHON = w_CJ_EFT_TIE.EFT_SEJHON
					WHERE CJ_EFT.EFT_ID = CJ_XECF.EFT_ID AND
						EFT_TER_TYPE = 'MUT' AND
						XECF_PLC <> EFT_TIE_CENTR_MUT AND
						XECF_PLC = EFT_TIE_CENTR_DBT AND
						EFT_ID_DBT <> 0
					;

					UPDATE prod_cegi.CJ_XECF 
					SET EFT_ID = EFT_ID_CAI
					FROM prod_cegi.CJ_EFT 
					JOIN w_CJ_EFT_TIE ON CJ_EFT.EFS_ID = w_CJ_EFT_TIE.EFS_ID AND
						CJ_EFT.EFT_SEJHON = w_CJ_EFT_TIE.EFT_SEJHON
					WHERE CJ_EFT.EFT_ID = CJ_XECF.EFT_ID AND
						EFT_TER_TYPE = 'DBT' AND
						XECF_PLC <> EFT_TIE_CENTR_DBT AND
						XECF_PLC = EFT_TIE_CENTR_CAI AND
						EFT_ID_CAI <> 0
					;

					UPDATE prod_cegi.CJ_XECF 
					SET EFT_ID = EFT_ID_MUT
					FROM prod_cegi.CJ_EFT 
					JOIN w_CJ_EFT_TIE ON CJ_EFT.EFS_ID = w_CJ_EFT_TIE.EFS_ID AND
						CJ_EFT.EFT_SEJHON = w_CJ_EFT_TIE.EFT_SEJHON
					WHERE CJ_EFT.EFT_ID = CJ_XECF.EFT_ID AND
						EFT_TER_TYPE = 'DBT' AND
						XECF_PLC <> EFT_TIE_CENTR_DBT AND
						XECF_PLC = EFT_TIE_CENTR_MUT AND
						EFT_ID_MUT <> 0
					;
                    
                    DROP TABLE IF EXISTS w_DFT_PLC_TYPE;
					CREATE TEMP TABLE w_DFT_PLC_TYPE AS
					SELECT XECF_PLC, EFT_SEJHON, (MAX(Array[to_char(nb,'FM000000000'),EFT_TER_TYPE]))[2] AS DFT_EFT_TER_TYPE
					FROM
					(
					SELECT XECF_PLC, EFT_SEJHON, EFT_TER_TYPE, count(*) AS nb
					FROM prod_cegi.CJ_XECF 
					JOIN prod_cegi.CJ_XECE ON CJ_XECF.XECE_ID = CJ_XECE.XECE_ID
					JOIN prod_cegi.CJ_EFT ON CJ_EFT.EFT_ID = CJ_XECF.EFT_ID 
					WHERE EFT_TER_TYPE IN ('CAI','MUT','DBT')
					GROUP BY 1,2,3
					) subview
					GROUP BY 1,2
					;


					UPDATE prod_cegi.CJ_XECF
					SET EFT_ID = CASE 
						WHEN DFT_EFT_TER_TYPE = 'CAI' AND EFT_ID_CAI <> 0 THEN EFT_ID_CAI 
						WHEN DFT_EFT_TER_TYPE = 'MUT' AND EFT_ID_MUT <> 0 THEN EFT_ID_MUT 
						WHEN DFT_EFT_TER_TYPE = 'DBT' AND EFT_ID_DBT <> 0 THEN EFT_ID_DBT 
						ELSE CJ_XECF.EFT_ID END
					FROM w_DFT_PLC_TYPE,prod_cegi.CJ_EFT  
					JOIN w_CJ_EFT_TIE ON CJ_EFT.EFS_ID = w_CJ_EFT_TIE.EFS_ID AND
						CJ_EFT.EFT_SEJHON = w_CJ_EFT_TIE.EFT_SEJHON
					WHERE CJ_XECF.XECF_PLC = w_DFT_PLC_TYPE.XECF_PLC AND
						CJ_EFT.EFT_SEJHON = w_DFT_PLC_TYPE.EFT_SEJHON AND
						CJ_EFT.EFT_ID = CJ_XECF.EFT_ID AND
						EFT_TER_TYPE = 'CAI' AND
						CJ_XECF.XECF_PLC <> EFT_TIE_CENTR_CAI AND
						EFT_TER_TYPE <> DFT_EFT_TER_TYPE
						
					;

					UPDATE prod_cegi.CJ_XECF
					SET EFT_ID = CASE 
						WHEN DFT_EFT_TER_TYPE = 'CAI' AND EFT_ID_CAI <> 0 THEN EFT_ID_CAI 
						WHEN DFT_EFT_TER_TYPE = 'MUT' AND EFT_ID_MUT <> 0 THEN EFT_ID_MUT 
						WHEN DFT_EFT_TER_TYPE = 'DBT' AND EFT_ID_DBT <> 0 THEN EFT_ID_DBT 
						ELSE CJ_XECF.EFT_ID END
					FROM w_DFT_PLC_TYPE,prod_cegi.CJ_EFT  
					JOIN w_CJ_EFT_TIE ON CJ_EFT.EFS_ID = w_CJ_EFT_TIE.EFS_ID AND
						CJ_EFT.EFT_SEJHON = w_CJ_EFT_TIE.EFT_SEJHON
					WHERE CJ_XECF.XECF_PLC = w_DFT_PLC_TYPE.XECF_PLC AND
						CJ_EFT.EFT_SEJHON = w_DFT_PLC_TYPE.EFT_SEJHON AND
						CJ_EFT.EFT_ID = CJ_XECF.EFT_ID AND
						EFT_TER_TYPE = 'MUT' AND
						CJ_XECF.XECF_PLC <> EFT_TIE_CENTR_MUT AND
						EFT_TER_TYPE <> DFT_EFT_TER_TYPE
						
					;

					UPDATE prod_cegi.CJ_XECF
					SET EFT_ID = CASE 
						WHEN DFT_EFT_TER_TYPE = 'CAI' AND EFT_ID_CAI <> 0 THEN EFT_ID_CAI 
						WHEN DFT_EFT_TER_TYPE = 'MUT' AND EFT_ID_MUT <> 0 THEN EFT_ID_MUT 
						WHEN DFT_EFT_TER_TYPE = 'DBT' AND EFT_ID_DBT <> 0 THEN EFT_ID_DBT 
						ELSE CJ_XECF.EFT_ID END
					FROM w_DFT_PLC_TYPE,prod_cegi.CJ_EFT  
					JOIN w_CJ_EFT_TIE ON CJ_EFT.EFS_ID = w_CJ_EFT_TIE.EFS_ID AND
						CJ_EFT.EFT_SEJHON = w_CJ_EFT_TIE.EFT_SEJHON
					WHERE CJ_XECF.XECF_PLC = w_DFT_PLC_TYPE.XECF_PLC AND
						CJ_EFT.EFT_SEJHON = w_DFT_PLC_TYPE.EFT_SEJHON AND
						CJ_EFT.EFT_ID = CJ_XECF.EFT_ID AND
						EFT_TER_TYPE = 'DBT' AND
						CJ_XECF.XECF_PLC <> EFT_TIE_CENTR_DBT AND
						EFT_TER_TYPE <> DFT_EFT_TER_TYPE
						
					;
                    ]]></sqlcmd>
            </NODE>
            <NODE label="Identification des séjours">
                <sqlcmd><![CDATA[

                    DROP TABLE IF EXISTS w_CJ_AFF;
                    CREATE TEMP TABLE w_CJ_AFF AS
                    SELECT 
                        CJ_SEJOUR.SEJ_ID, 
                        MAX(CASE WHEN AFF_TYPE = 'C' THEN COALESCE(w_CJ_ORG.tiers_payant_id,0) ELSE 0 END) AS tiers_payant_1_id,
                        MAX(CASE WHEN AFF_TYPE = 'M' THEN COALESCE(w_CJ_ORG.tiers_payant_id,0) ELSE 0 END) AS tiers_payant_2_id,
                        0::bigint AS tiers_payant_0_id,
                        ''::text AS OK
                    FROM prod_cegi.CJ_SEJOUR
                        LEFT JOIN prod_cegi.CJ_AFF ON CJ_SEJOUR.SEJ_ID = CJ_AFF.SEJ_ID AND (AFF_TYPE = 'C' OR AFF_TYPE = 'M')
                        LEFT JOIN w_CJ_ORG ON CJ_AFF.TER_ID = w_CJ_ORG.TER_ID
                    WHERE SEJ_UAGE = 'F' 
                    GROUP BY 1
                    ORDER BY 1;

                    UPDATE w_CJ_AFF
                    SET tiers_payant_0_id = t_tiers_payant.oid
                    FROM activite.t_tiers_payant 
                    WHERE t_tiers_payant.code_original = 'PATIENT'
                    ;
					
					ANALYSE w_CJ_AFF
					;
					
					DROP TABLE IF EXISTS w_PATIENT_cp;
					CREATE TEMP TABLE w_PATIENT_CP AS
					SELECT
						PAT_ID as w_PAT_ID,
						MAX(COALESCE(t_codes_postaux.oid,0)) as code_postal_id
					FROM prod_cegi.CJ_PATIENT
					LEFT JOIN base.t_codes_postaux ON PER_CP = t_codes_postaux.code
					GROUP BY 1
					;

					ANALYSE w_PATIENT_cp
					;


                    DROP TABLE IF EXISTS w_CJ_SEJOUR_select;
                    CREATE TEMP TABLE w_CJ_SEJOUR_select AS
                    SELECT 
                        CJ_SEJOUR.*,
                        SEJ_DT_ENTREE +
                            COALESCE(SEJ_HR_ENTREE-date_trunc('day',SEJ_HR_ENTREE),'00:00:00') AS SEJ_DTHR_ENTREE,
                        SEJ_DT_SORTIE  +
                            COALESCE(SEJ_HR_SORTIE-date_trunc('day',SEJ_HR_SORTIE),'00:00:00') AS SEJ_DTHR_SORTIE,
                        COALESCE(w_PATIENT_cp.code_postal_id,0) AS code_postal_id,
                        TYD_LIBC,
                        0::numeric AS medecin_sejour_id,
                        '8'::text AS mode_entree,
                        ''::text AS provenance,
                        '8'::text AS mode_sortie,
                        ''::text AS destination,
                        COALESCE(CJ_MTR.MTR_LIBC,'') AS MTR_LIBC,
                        coalesce(t_modes_traitement.oid,0) AS mode_traitement_id,
                        tiers_payant_0_id,
                        tiers_payant_1_id,
                        tiers_payant_2_id,
                        ''::text AS OK
                    FROM prod_cegi.CJ_SEJOUR
                        JOIN w_CJ_AFF ON CJ_SEJOUR.SEJ_ID = w_CJ_AFF.SEj_ID
                        JOIN prod_cegi.CJ_TYD ON CJ_SEJOUR.TYD_ID = CJ_TYD.TYD_ID
                        LEFT JOIN prod_cegi.CJ_MTR ON CJ_SEJOUR.MTR_ID = CJ_MTR.MTR_ID
                        LEFT JOIN base.t_modes_traitement ON CJ_MTR.MTR_LIBC = t_modes_traitement.code
                        LEFT JOIN w_PATIENT_cp ON w_PATIENT_cp.w_PAT_ID = cj_sejour.PAT_ID
                        JOIN prod_cegi.cj_etb ON cj_etb.etb_id = CJ_SEJOUR.etb_id
                        JOIN base.t_finess ON t_finess.code = cj_etb.etb_finess
                    WHERE SEJ_UAGE = 'F' AND
                        (
                        (SEJ_ACTIF = 1 AND TYD_LIBC <> 'NF') OR
                        CJ_SEJOUR.SEJ_ID IN (SELECT DISTINCT SEJ_ID FROM prod_cegi.CJ_EFS WHERE efs_ttc <> 0)
                        ) AND
                        SEJ_NUMDOS NOT LIKE 'TMP%'
                    ORDER BY SEJ_DT_ENTREE
                        ;
						
					ANALYSE w_CJ_SEJOUR_select
					;
                        
                    UPDATE w_CJ_SEJOUR_select
                    SET SEJ_DT_SORTIE = NULL, SEJ_DTHR_SORTIE = NULL
                    WHERE SEJ_DT_SORTIE < SEJ_DT_ENTREE;
                        
                    UPDATE w_CJ_SEJOUR_select
                    SET SEJ_DT_SORTIE = '20991231', SEJ_DTHR_SORTIE = '20991231'
                    WHERE TYD_LIBC NOT IN('A', 'U', 'E', 'I', 'Q') AND (SEJ_DT_SORTIE IS NULL OR SEJ_DT_SORTIE <= '00010101');
                    

                    UPDATE w_CJ_SEJOUR_select
                    SET SEJ_DT_SORTIE = SEJ_DT_ENTREE, SEJ_DTHR_SORTIE = SEJ_DTHR_ENTREE
                    WHERE (SEJ_DT_SORTIE IS NULL OR SEJ_DT_SORTIE <= '00010101');
					
					UPDATE w_CJ_SEJOUR_select
					SET OK ='O' 
					WHERE SEJ_DT_SORTIE >= '[ENV_ADM_ANNEEDEBUT]0101' OR SEJ_DT_ENTREE >= '[ENV_ADM_ANNEEDEBUT]0101'
					;

					UPDATE w_CJ_SEJOUR_select
					SET OK ='O' 
					FROM prod_cegi.CJ_EFS
					WHERE w_CJ_SEJOUR_select.SEJ_ID = CJ_EFS.SEJ_ID AND
						OK <> 'O' AND
						EFS_DT_FAC >= '[ENV_ADM_ANNEEDEBUT]0101'
					;


					DROP TABLE IF EXISTS w_CJ_EFS_ns;
                    CREATE TEMP TABLE w_CJ_EFS_ns AS
                    SELECT 
                        CJ_EFS.SEJ_ID,
                        SUM(XECF_MONT) AS XECF_MONT,
                        MIN(XECE_DATE) AS XECE_DATE,
                        MAX(EFS_CPTA_TTC+EFS_CPTA_HON_TTC) AS EFS_CPTA_TTC
                    FROM prod_cegi.CJ_XECF
                    JOIN prod_cegi.CJ_XECE ON CJ_XECF.XECE_ID = CJ_XECE.XECE_ID
                    JOIN prod_cegi.CJ_EFT ON CJ_EFT.EFT_ID = CJ_XECF.EFT_ID 
                    JOIN prod_cegi.CJ_EFS ON CJ_EFT.EFS_ID = CJ_EFS.EFS_ID
                    WHERE CJ_XECF.EFT_ID <> 0 AND
                        XECF_TYPE > 0 AND
                        CJ_XECE.JNL_CODE <> ALL(SELECT JNL_CODE FROM prod_cegi.CJ_JNLNUMFAC)
                    GROUP BY 1
                    HAVING MIN(XECE_DATE) >= '[ENV_ADM_ANNEEDEBUT]0101' OR
						round(MAX(EFS_CPTA_TTC+EFS_CPTA_HON_TTC)::numeric,2) <> round(SUM(XECF_MONT)::numeric,2)
                    ;

                    ANALYSE w_CJ_EFS_ns
                    ;

                    UPDATE w_CJ_SEJOUR_select
					SET OK ='O' 
					FROM w_CJ_EFS_ns
					WHERE w_CJ_SEJOUR_select.SEJ_ID = w_CJ_EFS_ns.SEJ_ID AND
						OK <> 'O' 
					;
					
					-- Séjours non concernés
					DELETE FROM w_CJ_SEJOUR_select
					WHERE OK <> 'O'
					;
                    
					-- Supression élements en trop
					DELETE FROM w_CJ_SEJOUR_select
					USING (SELECT SEJ_ID, MIN(ctid) AS to_del FROM w_CJ_SEJOUR_select GROUP BY 1 HAVING count(*) > 1) sub
					WHERE ctid = to_del
					;
                    -- Doublons dans les numéros de séjour
                    UPDATE w_CJ_SEJOUR_select
                    SET SEJ_NUMDOS = new_SEJ_NUMDOS
                    FROM
                    (
                    SELECT ctid, 
                        SEJ_NUMDOS || CASE WHEN rank() OVER (PARTITION BY SEJ_NUMDOS ORDER BY SEJ_DT_ENTREE, ctid) > 1 THEN 
                         '_' || rank() OVER (PARTITION BY SEJ_ID,SEJ_NUMDOS ORDER BY SEJ_DT_ENTREE,ctid) ELSE '' END AS new_SEJ_NUMDOS
                    FROM w_CJ_SEJOUR_select
                    WHERE SEJ_NUMDOS = ANY (SELECT SEJ_NUMDOS FROM  w_CJ_SEJOUR_select GROUP BY 1 HAVING count(*) > 1)
                    ) subview
                    WHERE w_CJ_SEJOUR_select.ctid = subview.ctid
                    ;


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

    <NODE name="SEJOUR" label="RECUPERATION DES SEJOURS">
    
        <NODE label="*LOGHOS*">
        
            <condition><![CDATA[
                "[CEGILOGHOS_PRESENT]" == "OUI"
            ]]></condition>
        
           <NODE label="Patients">
				<sqlcmd><![CDATA[
				
					DROP TABLE IF EXISTS w_CJ_PATIENT;
					CREATE TEMP TABLE w_CJ_PATIENT AS
					SELECT 
						CJ_PATIENT.PAT_ID,
						NO_DOSSIER AS SEJ_NUMDOS,
						MAX(PAT_IPP) AS no_patient,
						MAX(PER_NOM) AS PER_NOM, 
						MAX(PER_PRENOM) AS PER_PRENOM, 
						MAX(PER_NOMJF) AS PER_NOMJF, 
                        MAX(PER_CP) AS PER_CP, 
                        MAX(PER_VILLE) AS PER_VILLE, 
						MAX(date(PER_NAISSANCE)) AS PER_NAISSANCE,
						MAX(CASE WHEN PAT_SEXE IN ('F') THEN '2' ELSE '1' END) AS PAT_SEXE,
						MAX(CASE WHEN PER_NVOIE != '' THEN PER_NVOIE || ' ' ELSE '' END || PER_NOMVOIE || CASE WHEN PER_COMPVOIE != '' THEN '-' || PER_COMPVOIE ELSE '' END) AS PER_NOMVOIE,
						MAX(PAT_TEL1) AS PAT_TEL_FIXE,
						MAX(PAT_TEL2) AS PAT_TEL_PORT,
						MAX(PAT_EMAIL) AS PAT_EMAIL
					FROM prod_cegi.CJ_PATIENT 
					JOIN w_OPERA_SEJ_select ON CJ_PATIENT.PAT_ID = w_OPERA_SEJ_select.PAT_ID
					GROUP BY 1,2;

					--ALTER TABLE w_CJ_PATIENT ADD CONSTRAINT w_CJ_PATIENT_pkey PRIMARY KEY(PAT_ID);
					
					
					INSERT INTO w_CJ_PATIENT
					SELECT 
						COALESCE(w_OPERA_SEJ_select.PAT_ID,0 - to_number(w_OPERA_SEJ_select.NO_DOSSIER, '0000000000')),
						w_OPERA_SEJ_select.NO_DOSSIER AS SEJ_NUMDOS,
						COALESCE('W' || w_OPERA_SEJ_select.PAT_ID::text,'W' || w_OPERA_SEJ_select.NO_DOSSIER) AS no_patient,
						'Indisponible' AS PER_NOM, 
						'' AS PER_PRENOM, 
						'' AS PER_NOMJF, 
                        '' AS PER_CP, 
						'' AS PER_VILLE, 
						'19620418'::date AS PER_NAISSANCE,
						'1' AS PAT_SEXE,
						'' AS PAT_TEL_FIXE,
						'' AS PAT_TEL_PORT,
						'' AS PAT_EMAIL
					FROM w_OPERA_SEJ_select
					LEFT JOIN w_CJ_PATIENT ON w_OPERA_SEJ_select.PAT_ID = w_CJ_PATIENT.PAT_ID
					WHERE w_CJ_PATIENT.PAT_ID IS NULL
					GROUP BY 1,2,3;

					CREATE INDEX w_CJ_PATIENT_i1
						  ON w_CJ_PATIENT
						  USING btree
						  (no_patient);

					
					  
					UPDATE activite[PX].p_patients
					SET 
						nom = PER_NOM, 
						nom_naissance = PER_NOMJF, 
						prenom = PER_PRENOM, 
						date_naissance = PER_NAISSANCE,
						code_sexe = PAT_SEXE
					FROM w_CJ_PATIENT 
					WHERE p_patients.no_patient = w_CJ_PATIENT.no_patient
						AND (
							p_patients.nom IS DISTINCT FROM PER_NOM OR 
							p_patients.prenom IS DISTINCT FROM PER_PRENOM OR
							p_patients.nom_naissance IS DISTINCT FROM PER_NOMJF OR
							p_patients.date_naissance IS DISTINCT FROM date(PER_NAISSANCE) OR
							p_patients.code_sexe IS DISTINCT FROM PAT_SEXE
						);

					INSERT INTO activite[PX].p_patients(finess, no_patient, nom, prenom, nom_naissance, date_naissance, code_sexe)
					SELECT '', w_CJ_PATIENT.no_patient, MAX(PER_NOM), MAX(PER_PRENOM), MAX(PER_NOMJF), MAX(PER_NAISSANCE), MAX(PAT_SEXE)
					FROM w_CJ_PATIENT 
						LEFT JOIN activite[PX].p_patients ON (w_CJ_PATIENT.no_patient = p_patients.no_patient)
					WHERE p_patients.no_patient IS NULL
					GROUP BY w_CJ_PATIENT.no_patient;
											
											
				]]></sqlcmd>
			</NODE>
                    
            <NODE label="Séjours">
                <sqlcmd><![CDATA[

                    DROP TABLE IF EXISTS w_RSS;
                    CREATE TEMP TABLE w_RSS AS          
                    SELECT 
                        NO_DOSSIER AS NO_DOSSIER,
                        MAX(GHS_NUMERO) AS GHS_NUMERO,
                        MAX(C_GHM_CCAM) AS C_GHM_CCAM,
                        MAX(DT_ENV_ADM) AS DT_ENV_ADM
                    FROM prod_cegi.RSS 
                    JOIN w_OPERA_SEJ_select ON to_char(N_DOSS, 'FM000000000') = NO_DOSSIER
                    WHERE GHS_NUMERO <> '' AND GHS_NUMERO <> '9999'
                    GROUP BY 1;



                    ALTER TABLE w_RSS ADD CONSTRAINT w_RSS_pkey PRIMARY KEY(NO_DOSSIER);
                    
                    
                    INSERT INTO w_RSS
                    SELECT 
                        w_OPERA_SEJ_select.NO_DOSSIER AS NO_DOSSIER,
                        CODE_GHS AS GHS_NUMERO,
                        '20991231'::date AS DT_ENV_ADM
                    FROM w_OPERA_SEJ_select
                    LEFT JOIN w_RSS ON w_RSS.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                    WHERE w_RSS.NO_DOSSIER IS NULL AND CODE_GHS <> '' AND CODE_GHS <> '9999';


                
                    DROP TABLE IF EXISTS w_OPERA_OCC;
                    CREATE TEMP TABLE w_OPERA_OCC AS
                    SELECT 
                        w_OPERA_SEJ_select.NO_DOSSIER,
                        w_OPERA_SEJ_select.TYPE_DOSSIER,
                        w_OPERA_SEJ_select.MODE_ENTREE,
                        DATE_HEURE_ENTREE_SEJOUR,
                        DATE_HEURE_SORTIE_SEJOUR,
                        CODE_SERVICE_ENTREE,
                        CODE_SERVICE_TARIFAIRE_ENTREE,
                        CODE_SERVICE_DISCIPLINE_ENTREE,
                        MT_ENTREE,
                        DMT_ENTREE,
                        DATE_MOUVEMENT_ENTREE
                            + date_part('hour',to_timestamp(to_char(HEURE_MOUVEMENT_ENTREE, 'FM0000'),'HH24MI')) * '1 HOUR'::interval
                            + date_part('minute',to_timestamp(to_char(HEURE_MOUVEMENT_ENTREE, 'FM0000'),'HH24MI')) * '1 MINUTE'::interval AS DATE_HEURE_MOUVEMENT_ENTREE,
                        DATE_MOUVEMENT_SORTIE
                            + date_part('hour',to_timestamp(to_char(HEURE_MOUVEMENT_SORTIE, 'FM0000'),'HH24MI')) * '1 HOUR'::interval
                            + date_part('minute',to_timestamp(to_char(HEURE_MOUVEMENT_SORTIE, 'FM0000'),'HH24MI')) * '1 MINUTE'::interval AS DATE_HEURE_MOUVEMENT_SORTIE,
                        'A'::text AS TYPE_MOUVEMENT,
                        OPERA_OCC.CODE_LIT AS CODE_LIT_MOUVEMENT,
                        OPERA_OCC.CODE_SERVICE_DISCIPLINE AS CODE_SERVICE_MOUVEMENT,
                        OPERA_PSDISC.CODE_SERVICE_TARIFAIRE AS CODE_SERVICE_TARIFAIRE_MOUVEMENT,
                        OPERA_OCC.CODE_SERVICE_DISCIPLINE AS CODE_SERVICE_DISCIPLINE_MOUVEMENT,
                        MT AS MT_MOUVEMENT,
                        DMT AS DMT_MOUVEMENT,
                        ''::text AS CODE_UM_MOUVEMENT
                    FROM w_OPERA_SEJ_select
                        LEFT JOIN prod_cegiloghos.OPERA_OCC ON OPERA_OCC.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER AND OPERA_OCC.PERIODE_ANNEE = w_OPERA_SEJ_select.PERIODE_ANNEE
                        LEFT JOIN prod_cegiloghos.OPERA_PSDISC ON OPERA_OCC.CODE_SERVICE_DISCIPLINE = OPERA_PSDISC.CODE_SERVICE_DISCIPLINE
                        LEFT JOIN prod_cegiloghos.OPERA_PSTARF ON OPERA_PSDISC.CODE_SERVICE_TARIFAIRE = OPERA_PSTARF.CODE_SERVICE_TARIFAIRE;

                    INSERT INTO w_OPERA_OCC
                    SELECT 
                        w_OPERA_SEJ_select.NO_DOSSIER,
                        w_OPERA_SEJ_select.TYPE_DOSSIER,
                        w_OPERA_SEJ_select.MODE_ENTREE,
                        DATE_HEURE_ENTREE_SEJOUR,
                        DATE_HEURE_SORTIE_SEJOUR,
                        CODE_SERVICE_ENTREE,
                        CODE_SERVICE_TARIFAIRE_ENTREE,
                        CODE_SERVICE_DISCIPLINE_ENTREE,
                        MT_ENTREE,
                        DMT_ENTREE,
                        D_E 
                            + date_part('hour',hr_entree) * '1 HOUR'::interval
                            + date_part('minute',hr_entree) * '1 MINUTE'::interval AS DATE_HEURE_MOUVEMENT_ENTREE,
                        D_S 
                            + date_part('hour',hr_sortie) * '1 HOUR'::interval
                            + date_part('minute',hr_sortie) * '1 MINUTE'::interval AS DATE_HEURE_MOUVEMENT_SORTIE,
                        'P'::text AS TYPE_MOUVEMENT,
                        ''::text AS CODE_LIT_MOUVEMENT,
                        ''::text AS CODE_SERVICE_MOUVEMENT,
                        ''::text AS CODE_SERVICE_TARIFAIRE_MOUVEMENT,
                        ''::text AS CODE_SERVICE_DISCIPLINE_MOUVEMENT,
                        ''::text AS MT_MOUVEMENT,
                        ''::text AS DMT_MOUVEMENT,
                        C_UM AS CODE_UM_MOUVEMENT
                    FROM prod_cegi.RUM 
                        JOIN prod_cegi.RSS ON RUM.N_PMSI = RSS.N_PMSI
                        JOIN w_OPERA_SEJ_select ON to_char(N_DOSS, 'FM000000000') = w_OPERA_SEJ_select.NO_DOSSIER;

                    CREATE INDEX w_OPERA_OCC_i1
                          ON w_OPERA_OCC
                          USING btree
                          (NO_DOSSIER);

                    INSERT INTO w_OPERA_OCC
                    SELECT 
                        w_OPERA_SEJ_select.NO_DOSSIER,
                        w_OPERA_SEJ_select.TYPE_DOSSIER,
                        w_OPERA_SEJ_select.MODE_ENTREE,
                        w_OPERA_SEJ_select.DATE_HEURE_ENTREE_SEJOUR,
                        w_OPERA_SEJ_select.DATE_HEURE_SORTIE_SEJOUR,
                        w_OPERA_SEJ_select.CODE_SERVICE_ENTREE,
                        w_OPERA_SEJ_select.CODE_SERVICE_TARIFAIRE_ENTREE,
                        w_OPERA_SEJ_select.CODE_SERVICE_DISCIPLINE_ENTREE,
                        w_OPERA_SEJ_select.MT_ENTREE,
                        w_OPERA_SEJ_select.DMT_ENTREE,
                        w_OPERA_SEJ_select.DATE_HEURE_ENTREE_SEJOUR
                            + date_part('hour',to_timestamp(to_char(HEURE_ENTREE_SEJOUR, 'FM0000'),'HH24MI')) * '1 HOUR'::interval
                            + date_part('minute',to_timestamp(to_char(HEURE_ENTREE_SEJOUR, 'FM0000'),'HH24MI')) * '1 MINUTE'::interval AS DATE_HEURE_MOUVEMENT_ENTREE,
                        w_OPERA_SEJ_select.DATE_HEURE_SORTIE_SEJOUR
                            + date_part('hour',to_timestamp(to_char(HEURE_SORTIE_SEJOUR, 'FM0000'),'HH24MI')) * '1 HOUR'::interval
                            + date_part('minute',to_timestamp(to_char(HEURE_SORTIE_SEJOUR, 'FM0000'),'HH24MI')) * '1 MINUTE'::interval AS DATE_HEURE_MOUVEMENT_SORTIE,
                        'E'::text AS TYPE_MOUVEMENT,
                        ''::text AS CODE_LIT_MOUVEMENT,
                        w_OPERA_SEJ_select.CODE_SERVICE_ENTREE AS CODE_SERVICE_MOUVEMENT,
                        w_OPERA_SEJ_select.CODE_SERVICE_TARIFAIRE_ENTREE AS CODE_SERVICE_TARIFAIRE_MOUVEMENT,
                        w_OPERA_SEJ_select.CODE_SERVICE_DISCIPLINE_ENTREE AS CODE_SERVICE_DISCIPLINE_MOUVEMENT,
                        w_OPERA_SEJ_select.MT_ENTREE AS MT_MOUVEMENT,
                        w_OPERA_SEJ_select.DMT_ENTREE AS DMT_MOUVEMENT,
                        ''::text AS CODE_UM_MOUVEMENT
                    FROM w_OPERA_SEJ_select
                        LEFT JOIN w_OPERA_OCC ON w_OPERA_SEJ_select.NO_DOSSIER = w_OPERA_OCC.NO_DOSSIER AND
                                w_OPERA_SEJ_select.DATE_HEURE_ENTREE_SEJOUR = w_OPERA_OCC.DATE_HEURE_MOUVEMENT_ENTREE
                    WHERE w_OPERA_OCC.NO_DOSSIER IS NULL;
                    


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



                    DROP TABLE IF EXISTS w_OPERA_OCC_mouvement;
                    CREATE TEMP TABLE w_OPERA_OCC_mouvement AS
                    SELECT NO_DOSSIER,
                        TYPE_DOSSIER,
                        MODE_ENTREE,
                        DATE_HEURE_ENTREE_SEJOUR,
                        DATE_HEURE_SORTIE_SEJOUR,
                        DATE_HEURE_MOUVEMENT_ENTREE,
                        nextval('w_OPERA_OCC_mouvement_seq'::regclass) AS sequence ,

                        COALESCE(CODE_SERVICE,'') AS CODE_SERVICE,
                        COALESCE(CODE_SERVICE_TARIFAIRE,'') AS CODE_SERVICE_TARIFAIRE,
                        COALESCE(CODE_SERVICE_DISCIPLINE,'') AS CODE_SERVICE_DISCIPLINE,
                        COALESCE(MT,'') AS MT,
                        COALESCE(DMT,'') AS DMT,
                        COALESCE(CODE_LIT,'') AS CODE_LIT,
                        COALESCE(CODE_UM,'') AS CODE_UM
                    FROM
                        (SELECT 
                            NO_DOSSIER,
                            TYPE_DOSSIER,
                            MODE_ENTREE,
                            DATE_HEURE_MOUVEMENT_ENTREE,
                            DATE_HEURE_ENTREE_SEJOUR,
                            DATE_HEURE_SORTIE_SEJOUR,
                            (MAX(CASE WHEN TYPE_MOUVEMENT <> 'A' THEN NULL ELSE 
                                array[
                                CASE WHEN DATE_HEURE_MOUVEMENT_ENTREE IS NOT NULL THEN DATE_HEURE_MOUVEMENT_ENTREE::text ELSE DATE_HEURE_ENTREE_SEJOUR::text END, 
                                CASE WHEN DATE_HEURE_MOUVEMENT_ENTREE IS NOT NULL THEN CODE_SERVICE_MOUVEMENT ELSE CODE_SERVICE_ENTREE END
                                ] END))[2] AS CODE_SERVICE,
                            (MAX(CASE WHEN TYPE_MOUVEMENT <> 'A' THEN NULL ELSE 
                            array[
                                CASE WHEN DATE_HEURE_MOUVEMENT_ENTREE IS NOT NULL THEN DATE_HEURE_MOUVEMENT_ENTREE::text ELSE DATE_HEURE_ENTREE_SEJOUR::text END, 
                                CASE WHEN DATE_HEURE_MOUVEMENT_ENTREE IS NOT NULL THEN CODE_SERVICE_TARIFAIRE_MOUVEMENT ELSE CODE_SERVICE_TARIFAIRE_ENTREE END
                                ] END))[2] AS CODE_SERVICE_TARIFAIRE,
                            (MAX(CASE WHEN TYPE_MOUVEMENT <> 'A' THEN NULL ELSE 
                            array[
                                CASE WHEN DATE_HEURE_MOUVEMENT_ENTREE IS NOT NULL THEN DATE_HEURE_MOUVEMENT_ENTREE::text ELSE DATE_HEURE_ENTREE_SEJOUR::text END, 
                                CASE WHEN DATE_HEURE_MOUVEMENT_ENTREE IS NOT NULL THEN CODE_SERVICE_DISCIPLINE_MOUVEMENT ELSE CODE_SERVICE_DISCIPLINE_ENTREE END
                                ] END))[2] AS CODE_SERVICE_DISCIPLINE,
                            (MAX(CASE WHEN TYPE_MOUVEMENT <> 'A' THEN NULL ELSE 
                            array[
                                CASE WHEN DATE_HEURE_MOUVEMENT_ENTREE IS NOT NULL THEN DATE_HEURE_MOUVEMENT_ENTREE::text ELSE DATE_HEURE_ENTREE_SEJOUR::text END, 
                                CASE WHEN DATE_HEURE_MOUVEMENT_ENTREE IS NOT NULL THEN MT_MOUVEMENT ELSE MT_ENTREE END
                                ] END))[2] AS MT,
                            (MAX(CASE WHEN TYPE_MOUVEMENT <> 'A' THEN NULL ELSE 
                            array[
                                CASE WHEN DATE_HEURE_MOUVEMENT_ENTREE IS NOT NULL THEN DATE_HEURE_MOUVEMENT_ENTREE::text ELSE DATE_HEURE_ENTREE_SEJOUR::text END, 
                                CASE WHEN DATE_HEURE_MOUVEMENT_ENTREE IS NOT NULL THEN DMT_MOUVEMENT ELSE DMT_ENTREE END
                                ] END))[2] AS DMT,
                            (MAX(CASE WHEN TYPE_MOUVEMENT <> 'A' THEN NULL ELSE 
                            array[DATE_HEURE_MOUVEMENT_ENTREE::text,CODE_LIT_MOUVEMENT
                                ] END))[2] AS CODE_LIT,
                            (MAX(CASE WHEN TYPE_MOUVEMENT IN ('E', 'A') THEN NULL ELSE 
                            array[DATE_HEURE_MOUVEMENT_ENTREE::text,CODE_UM_MOUVEMENT
                                ] END))[2] AS CODE_UM

                        FROM w_OPERA_OCC
                        GROUP BY 1,2,3,4,5,6
                        ORDER BY 1,4) subview;

                        CREATE INDEX w_OPERA_OCC_mouvement_i1
                          ON w_OPERA_OCC_mouvement
                          USING btree
                          (NO_DOSSIER);


                        SELECT base.cti_execute('UPDATE w_OPERA_OCC_mouvement
                        SET CODE_UM = w_OPERA_OCC_mouvement_before.CODE_UM
                        FROM w_OPERA_OCC_mouvement w_OPERA_OCC_mouvement_before
                        WHERE w_OPERA_OCC_mouvement.NO_DOSSIER = w_OPERA_OCC_mouvement_before.NO_DOSSIER AND
                            w_OPERA_OCC_mouvement.sequence = w_OPERA_OCC_mouvement_before.sequence + 1 AND
                            (w_OPERA_OCC_mouvement.CODE_UM = '''') AND
                            w_OPERA_OCC_mouvement_before.CODE_UM <> ''''',20);

                        SELECT base.cti_execute('UPDATE w_OPERA_OCC_mouvement
                        SET CODE_UM = w_OPERA_OCC_mouvement_next.CODE_UM
                        FROM w_OPERA_OCC_mouvement w_OPERA_OCC_mouvement_next
                        WHERE w_OPERA_OCC_mouvement.NO_DOSSIER = w_OPERA_OCC_mouvement_next.NO_DOSSIER AND
                            w_OPERA_OCC_mouvement.sequence = w_OPERA_OCC_mouvement_next.sequence - 1 AND
                            (w_OPERA_OCC_mouvement.CODE_UM = '''') AND
                            w_OPERA_OCC_mouvement_next.CODE_UM <> ''''',20);


                        SELECT base.cti_execute('UPDATE w_OPERA_OCC_mouvement
                        SET 
                            CODE_SERVICE = w_OPERA_OCC_mouvement_before.CODE_SERVICE,
                            CODE_SERVICE_TARIFAIRE = w_OPERA_OCC_mouvement_before.CODE_SERVICE_TARIFAIRE,
                            CODE_SERVICE_DISCIPLINE = w_OPERA_OCC_mouvement_before.CODE_SERVICE_DISCIPLINE,
                            MT = w_OPERA_OCC_mouvement_before.MT,
                            DMT = w_OPERA_OCC_mouvement_before.DMT,
                            CODE_LIT = w_OPERA_OCC_mouvement_before.CODE_LIT
                        FROM w_OPERA_OCC_mouvement w_OPERA_OCC_mouvement_before
                        WHERE w_OPERA_OCC_mouvement.NO_DOSSIER = w_OPERA_OCC_mouvement_before.NO_DOSSIER AND
                            w_OPERA_OCC_mouvement.sequence = w_OPERA_OCC_mouvement_before.sequence + 1 AND
                            (w_OPERA_OCC_mouvement.CODE_SERVICE = '''') AND 
                            w_OPERA_OCC_mouvement_before.CODE_SERVICE <> ''''',20);

                        SELECT base.cti_execute('UPDATE w_OPERA_OCC_mouvement
                        SET 
                            CODE_SERVICE = w_OPERA_OCC_mouvement_next.CODE_SERVICE,
                            CODE_SERVICE_TARIFAIRE = w_OPERA_OCC_mouvement_next.CODE_SERVICE_TARIFAIRE,
                            CODE_SERVICE_DISCIPLINE = w_OPERA_OCC_mouvement_next.CODE_SERVICE_DISCIPLINE,
                            MT = w_OPERA_OCC_mouvement_next.MT,
                            DMT = w_OPERA_OCC_mouvement_next.DMT,
                            CODE_LIT = w_OPERA_OCC_mouvement_next.CODE_LIT
                        FROM w_OPERA_OCC_mouvement w_OPERA_OCC_mouvement_next
                        WHERE w_OPERA_OCC_mouvement.NO_DOSSIER = w_OPERA_OCC_mouvement_next.NO_DOSSIER AND
                            w_OPERA_OCC_mouvement.sequence = w_OPERA_OCC_mouvement_next.sequence - 1 AND
                            (w_OPERA_OCC_mouvement.CODE_SERVICE = '''') AND 
                            w_OPERA_OCC_mouvement_next.CODE_SERVICE <> ''''',20);


                        SELECT base.cti_execute('UPDATE w_OPERA_OCC_mouvement
                        SET 
                            CODE_LIT = w_OPERA_OCC_mouvement_before.CODE_LIT
                        FROM w_OPERA_OCC_mouvement w_OPERA_OCC_mouvement_before
                        WHERE w_OPERA_OCC_mouvement.NO_DOSSIER = w_OPERA_OCC_mouvement_before.NO_DOSSIER AND
                            w_OPERA_OCC_mouvement.sequence = w_OPERA_OCC_mouvement_before.sequence + 1 AND
                            (w_OPERA_OCC_mouvement.CODE_LIT = '''') AND 
                            w_OPERA_OCC_mouvement_before.CODE_LIT <> ''''',20);

                        SELECT base.cti_execute('UPDATE w_OPERA_OCC_mouvement
                        SET 
                            CODE_LIT = w_OPERA_OCC_mouvement_next.CODE_LIT
                        FROM w_OPERA_OCC_mouvement w_OPERA_OCC_mouvement_next
                        WHERE w_OPERA_OCC_mouvement.NO_DOSSIER = w_OPERA_OCC_mouvement_next.NO_DOSSIER AND
                            w_OPERA_OCC_mouvement.sequence = w_OPERA_OCC_mouvement_next.sequence - 1 AND
                            (w_OPERA_OCC_mouvement.CODE_LIT = '''') AND 
                            w_OPERA_OCC_mouvement_next.CODE_LIT <> ''''',20);




                    DROP TABLE IF EXISTS w_OPERA_OCC_sortie;
                    CREATE TEMP TABLE w_OPERA_OCC_sortie AS
                    SELECT 
                        NO_DOSSIER,
                        MIN(sequence) AS sequence_entree,
                        MAX(sequence) AS sequence_sortie,
                        (MAX(array[DATE_HEURE_MOUVEMENT_ENTREE::text, CODE_SERVICE]))[2] AS CODE_SERVICE_SORTIE,
                        (MAX(array[DATE_HEURE_MOUVEMENT_ENTREE::text, CODE_SERVICE_TARIFAIRE]))[2] AS CODE_SERVICE_TARIFAIRE_SORTIE,
                        (MAX(array[DATE_HEURE_MOUVEMENT_ENTREE::text, CODE_SERVICE_DISCIPLINE]))[2] AS CODE_SERVICE_DISCIPLINE_SORTIE,
                        (MAX(array[DATE_HEURE_MOUVEMENT_ENTREE::text, MT]))[2] AS MT_SORTIE,
                        (MAX(array[DATE_HEURE_MOUVEMENT_ENTREE::text, DMT]))[2] AS DMT_SORTIE,
                        (MAX(array[DATE_HEURE_MOUVEMENT_ENTREE::text, CODE_LIT]))[2] AS CODE_LIT_SORTIE,
                        (MAX(array[DATE_HEURE_MOUVEMENT_ENTREE::text, CODE_UM]))[2] AS CODE_UM_SORTIE
                    FROM w_OPERA_OCC_mouvement
                    GROUP BY 1;




                    ALTER TABLE w_OPERA_OCC_sortie ADD CONSTRAINT w_OPERA_OCC_sortie_pkey PRIMARY KEY(NO_DOSSIER);


                    DELETE FROM w_OPERA_OCC_mouvement
                    WHERE DATE_HEURE_MOUVEMENT_ENTREE < DATE_HEURE_ENTREE_SEJOUR;


                    
                    DELETE FROM w_OPERA_OCC_mouvement
                    WHERE DATE_HEURE_MOUVEMENT_ENTREE > DATE_HEURE_SORTIE_SEJOUR AND DATE_HEURE_SORTIE_SEJOUR IS NOT NULL;

                    


                    DROP TABLE IF EXISTS w_OPERA_FAC_tp;
                    CREATE TEMP TABLE w_OPERA_FAC_tp AS 
                    SELECT 
                        w_OPERA_SEJ_select.NO_DOSSIER,
                        (MAX(array[DATE_CALCUL_FACTURE::text,TIERS_FACT_AMO]))[2] AS TIERS_FACT_AMO,
                        (MAX(array[DATE_CALCUL_FACTURE::text,TIERS_FACT_AMC]))[2] AS TIERS_FACT_AMC,
                        (MAX(array[DATE_CALCUL_FACTURE::text,TIERS_FACT_IPP]))[2] AS TIERS_FACT_IPP
                    FROM prod_cegiloghos.OPERA_FAC
                        JOIN w_OPERA_SEJ_select ON OPERA_FAC.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                    GROUP BY 1;

                    ALTER TABLE w_OPERA_FAC_tp ADD CONSTRAINT w_OPERA_FAC_tp_pkey PRIMARY KEY(NO_DOSSIER);


                    -- Plage d'actes pour externes
                    DROP TABLE IF EXISTS w_OPERA_ACT_dureex;
                    CREATE TEMP TABLE w_OPERA_ACT_dureex AS 
                    SELECT 
                        OPERA_ACT.NO_DOSSIER,
                        date(MAX(DATE_ACTE_FIN)) - date(MIN(DATE_ACTE_DEBUT))
                    FROM prod_cegiloghos.OPERA_ACT
                    JOIN w_OPERA_SEJ_select ON OPERA_ACT.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                    GROUP BY 1
                    HAVING date(MAX(DATE_ACTE_FIN)) - date(MIN(DATE_ACTE_DEBUT)) <= 1
                    ;

                    ALTER TABLE w_OPERA_ACT_dureex ADD CONSTRAINT w_OPERA_ACT_dureex_pkey PRIMARY KEY(NO_DOSSIER);

                    DROP TABLE IF EXISTS w_OPERA_ACT_externes;
                    CREATE TEMP TABLE w_OPERA_ACT_externes AS 
                    SELECT 
                        w_OPERA_SEJ_select.NO_DOSSIER,
                        '07'::text AS MT,
                        ''::text AS DMT
                    FROM prod_cegiloghos.OPERA_ACT
                    JOIN w_OPERA_SEJ_select ON OPERA_ACT.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                    WHERE CODE_PRESTA IN ('SE1', 'SE2', 'SE3', 'SE4','SE5', 'SE6', 'SE7', 'ATU', 'FPU','FFM') AND
                        w_OPERA_SEJ_select.NO_DOSSIER IN (SELECT NO_DOSSIER FROM w_OPERA_ACT_dureex)
                    GROUP BY 1,2
                    HAVING SUM(CASE WHEN MONTANT_ACTE < 0 AND QTE_ACTE > 0 THEN 0 - QTE_ACTE ELSE QTE_ACTE END) > 0;

                    ALTER TABLE w_OPERA_ACT_externes ADD CONSTRAINT w_OPERA_ACT_externes_pkey PRIMARY KEY(NO_DOSSIER);

                    
                    -- Seances selon GHS pmsi
                    DROP TABLE IF EXISTS w_ghs_seances;
                    CREATE TEMP TABLE w_ghs_seances AS
                    SELECT to_char(t_ghs.code,'FM0000') AS code
                    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;
                    
                    ALTER TABLE w_ghs_seances ADD CONSTRAINT w_ghs_seances_pkey PRIMARY KEY(code);

                    DROP TABLE IF EXISTS w_OPERA_ACT_hospit;
                    CREATE TEMP TABLE w_OPERA_ACT_hospit AS 
                    SELECT 
                        w_OPERA_SEJ_select.NO_DOSSIER,
                        MAX(CASE WHEN OPERA_ACT.CODE_GHS IN (SELECT code FROM w_ghs_seances) THEN '19'::text ELSE '03'::text END) AS MT,
                        MAX(CASE WHEN OPERA_ACT.CODE_GHS IN (SELECT code FROM w_ghs_seances) THEN '302'::text ELSE ''::text END) AS DMT

                    FROM prod_cegiloghos.OPERA_ACT
                        JOIN w_OPERA_SEJ_select ON OPERA_ACT.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                    WHERE CODE_PRESTA IN ('GHS')
                    GROUP BY 1
                    HAVING SUM(CASE WHEN MONTANT_ACTE < 0 AND QTE_ACTE > 0 THEN 0 - QTE_ACTE ELSE QTE_ACTE END) > 0;

                    ALTER TABLE w_OPERA_ACT_hospit ADD CONSTRAINT w_OPERA_ACT_hospit_pkey PRIMARY KEY(NO_DOSSIER);


                    DROP TABLE IF EXISTS w_OPERA_SEJ;
                    CREATE TEMP TABLE w_OPERA_SEJ AS
                    SELECT 
                        w_OPERA_SEJ_select.*,
                        COALESCE(CODE_SERVICE_SORTIE,'') AS CODE_SERVICE_SORTIE,
                        COALESCE(CODE_SERVICE_TARIFAIRE_SORTIE,'') AS CODE_SERVICE_TARIFAIRE_SORTIE,
                        COALESCE(CODE_SERVICE_DISCIPLINE_SORTIE,'') AS CODE_SERVICE_DISCIPLINE_SORTIE,
                        COALESCE(MT_SORTIE,'') AS MT_SORTIE,
                        COALESCE(DMT_SORTIE,'') AS DMT_SORTIE,
                        COALESCE(CODE_LIT_SORTIE,'') AS CODE_LIT_SORTIE,
                        COALESCE(CODE_UM_SORTIE,'') AS CODE_UM_SORTIE,
                        COALESCE(w_OPERA_ACT_externes.MT, w_OPERA_ACT_hospit.MT, '') AS ACT_MT,
                        COALESCE(w_OPERA_ACT_externes.DMT, w_OPERA_ACT_hospit.DMT, '') AS ACT_DMT,
                        COALESCE(TIERS_FACT_AMO,'') AS TIERS_FACT_AMO,
                        COALESCE(TIERS_FACT_AMC,'') AS TIERS_FACT_AMC,
                        COALESCE(DT_ENV_ADM,'20991231'::date) AS DATE_GROUPAGE,
                        COALESCE(GHS_NUMERO,'') AS GHS,
                        COALESCE(C_GHM_CCAM,'') AS C_GHM_CCAM,
                        0 AS GHS_BEBE1,
                        CODE_MED_RESP_SEJOUR || '|' || 
                        COALESCE(CODE_SERVICE_SORTIE,'') || '|' || 
                        COALESCE(CODE_SERVICE_DISCIPLINE_SORTIE,'') || '|' || 
                        COALESCE(MT_SORTIE,'') || '|' || 
                        COALESCE(DMT_SORTIE,'') || '|' || 
                        COALESCE(CODE_LIT_SORTIE,'') || '|' || 
                        COALESCE(CODE_UM_SORTIE,'') || '|' || 
                        COALESCE(TIERS_FACT_AMO,'') || '|' || 
                        COALESCE(TIERS_FACT_AMC,'') || '|' || 
                        COALESCE(C_GHM_CCAM,'') || '|' || 
                        COALESCE(GHS_NUMERO,'') AS key
                    FROM w_OPERA_SEJ_select
                        LEFT JOIN w_OPERA_OCC_sortie ON w_OPERA_OCC_sortie.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                        LEFT JOIN w_OPERA_FAC_tp ON w_OPERA_FAC_tp.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                        LEFT JOIN w_OPERA_ACT_externes ON w_OPERA_ACT_externes.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                        LEFT JOIN w_OPERA_ACT_hospit ON w_OPERA_ACT_hospit.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                        LEFT JOIN w_RSS ON w_RSS.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER;


                    

                    DROP TABLE IF EXISTS w_OPERA_SEJ_key;
                    CREATE TEMP TABLE w_OPERA_SEJ_key AS
                    SELECT
                        key,
                        CODE_MED_RESP_SEJOUR,
                        CODE_SERVICE_SORTIE,
                        CODE_SERVICE_DISCIPLINE_SORTIE,
                        MT_SORTIE,
                        DMT_SORTIE,
                        CODE_LIT_SORTIE,
                        ''::text AS CODE_ETAGELIT_SORTIE,
                        ''::text AS CODE_ETAGE_SORTIE,
                        CODE_UM_SORTIE,
                        TIERS_FACT_AMO,
                        TIERS_FACT_AMC,
                        GHS,
                        C_GHM_CCAM,
                        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 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_OPERA_SEJ
                    GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15;


                    UPDATE w_OPERA_SEJ_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 = CODE_SERVICE_DISCIPLINE_SORTIE;

                    UPDATE w_OPERA_SEJ_key SET
                        CODE_ETAGELIT_SORTIE = CASE WHEN CODE_LIT_SORTIE <> '' THEN CASE WHEN CODE_ETAGE <> '' THEN CODE_ETAGE ELSE SUBSTR(CODE_LIT,1,1) END || '|' || CODE_LIT_SORTIE ELSE '' END,
                        CODE_ETAGE_SORTIE = CASE WHEN CODE_LIT_SORTIE <> '' THEN CASE WHEN CODE_ETAGE <> '' THEN CODE_ETAGE ELSE SUBSTR(CODE_LIT,1,1) END ELSE '' END
                    FROM prod_cegiloghos.OPERA_PLIT
                    WHERE OPERA_PLIT.CODE_LIT = CODE_LIT_SORTIE;

                    
                    UPDATE w_OPERA_SEJ_key
                        set medecin_sejour_id = t_medecins_administratifs.oid
                    FROM activite[PX].t_medecins_administratifs
                    WHERE CODE_MED_RESP_SEJOUR <> '' AND code_original = CODE_MED_RESP_SEJOUR;

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

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

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

                    UPDATE w_OPERA_SEJ_key
                        set ghs_id = t_ghs.oid
                    FROM base.t_ghs
                    WHERE GHS <> '' AND t_ghs.code_text = GHS;
					
					UPDATE w_OPERA_SEJ_key
                        set ghs_id = t_ghs.oid
                    FROM base.t_ghs
                    WHERE ghs_id = 0 AND GHS <> '' AND to_char(t_ghs.code,'FM0000') = GHS;
					

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

                    UPDATE w_OPERA_SEJ_key
                        set ghm_id = t_ghm.oid
                    FROM base.t_ghm
                    WHERE 1=1
                        AND C_GHM_CCAM <> '' 
                        AND t_ghm.code = C_GHM_CCAM 
                        AND t_ghm.code NOT LIKE '90%'
                    ;

                    INSERT INTO activite[PX].t_lieux(
                                code_original_1, code_original_2, code_original_3, code_original_4, code_original_5, code_original_6)
                    SELECT CODE_SERVICE_DISCIPLINE_SORTIE, '', CODE_ETAGE_SORTIE, CODE_ETAGELIT_SORTIE, CODE_UM_SORTIE , CODE_SERVICE_SORTIE
                    FROM w_OPERA_SEJ_key
                        LEFT JOIN activite[PX].t_lieux ON (
                            code_original_1 = CODE_SERVICE_DISCIPLINE_SORTIE AND
                            code_original_2 = '' AND
                            code_original_3 = CODE_ETAGE_SORTIE AND
                            code_original_4 = CODE_ETAGELIT_SORTIE AND
                            code_original_5 = CODE_UM_SORTIE AND
                            code_original_6 = CODE_SERVICE_SORTIE
                        )
                    WHERE t_lieux.oid IS NULL
                    GROUP BY 1,2,3,4,5,6;

                    UPDATE w_OPERA_SEJ_key
                        set lieu_id = t_lieux.oid
                    FROM activite[PX].t_lieux
                    WHERE code_original_1 = CODE_SERVICE_DISCIPLINE_SORTIE AND
                        code_original_2 = '' AND
                        code_original_3 = CODE_ETAGE_SORTIE AND
                        code_original_4 = CODE_ETAGELIT_SORTIE AND
                        code_original_5 = CODE_UM_SORTIE AND
                        code_original_6 = CODE_SERVICE_SORTIE;

                    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_medicale_id = COALESCE(t_unites_medicales.oid,0)
                    FROM
                        activite[PX].t_unites_medicales
                    WHERE code_original_5 = t_unites_medicales.code_original
                        AND unite_medicale_id <> COALESCE(t_unites_medicales.oid,0);
                    

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

                    



                    DROP TABLE IF EXISTS w_sejours;
                    CREATE TEMP TABLE w_sejours AS
                    SELECT 
                        NO_DOSSIER as no_sejour, 
                        NO_DOSSIER as code_original, 
                        COALESCE(no_patient,'W' || NO_DOSSIER) as no_patient, 
                        date(DATE_HEURE_ENTREE_SEJOUR) as date_entree, 
                        HEURE_ENTREE_SEJOUR * 100 as heure_entree, 
                        date(DATE_HEURE_SORTIE_SEJOUR) as date_sortie, 
                        HEURE_SORTIE_SEJOUR * 100 as heure_sortie, 
                        CASE WHEN PAT_SEXE IN ('F', '2') THEN '2' ELSE '1' END as code_sexe,
                        0 AS age, 
                        CASE WHEN DATE_HEURE_SORTIE_SEJOUR IS NOT NULL AND DATE_HEURE_SORTIE_SEJOUR < '20991231' THEN 1 ELSE 0 END::numeric as code_sorti, 
                        0::numeric AS code_prevu,
                        CASE 
							WHEN trim(t_divers_CEGILOGHOS_TDI.valeur) <> '' AND TYPE_DOSSIER <> '' AND TYPE_DOSSIER = ANY(string_to_array(replace(t_divers_CEGILOGHOS_TDI.valeur,' ',''),',')) THEN '9'
                            WHEN type_sejour_force <> '0' THEN type_sejour_force
                            WHEN ACT_MT IN ('03') AND date(DATE_HEURE_ENTREE_SEJOUR) = date(DATE_HEURE_SORTIE_SEJOUR) THEN '2' 
                            WHEN ACT_MT IN ('03') THEN '1' 
                            WHEN ACT_MT IN ('07') THEN '3' 
                            WHEN ACT_MT IN ('19') AND ACT_DMT IN ('302') THEN '5' 
                            WHEN mode_traitement_code IN ('07') OR dmt_code IN ('958') THEN '3' 
                            WHEN mode_traitement_code IN ('19', '23') THEN '2' 
                            WHEN mode_traitement_code IN ('04') AND date(DATE_HEURE_ENTREE_SEJOUR) = date(DATE_HEURE_SORTIE_SEJOUR) THEN '2' 
                            WHEN mode_traitement_code IN ('03') AND date(DATE_HEURE_ENTREE_SEJOUR) = date(DATE_HEURE_SORTIE_SEJOUR) THEN '2' 
                            WHEN mode_traitement_code IN ('03') THEN '1' 
                            WHEN date(DATE_HEURE_ENTREE_SEJOUR) = date(DATE_HEURE_SORTIE_SEJOUR) THEN '2' 
                            ELSE '1' END as type_sejour,
                        lieu_id AS lieu_sortie_id,
                        w_OPERA_SEJ_key.medecin_sejour_id AS medecin_sejour_id,
                        w_OPERA_SEJ_key.ghs_id,
                        w_OPERA_SEJ_key.ghm_id,
                        w_OPERA_SEJ_key.ghs_bebe1_id,
                        0::numeric AS ghs_bebe2_id,
                        0::numeric AS ghs_bebe3_id,
                        DATE_GROUPAGE,
                        '0'::text AS code_cp_demandee,
                        mode_traitement_id,
                        CODE_PMSI_MODE_ENTREE as mode_entree,
                        SUBSTR(CODE_PROVENANCE,1,1) AS provenance,
                        CODE_PMSI_MODE_SORTIE as mode_sortie,
                        SUBSTR(CODE_DESTINATION,1,1) as destination,
                        tiers_payant_0_id,
                        tiers_payant_1_id,
                        tiers_payant_2_id,
                        tiers_payant_22_id,
                        0 AS est_budget_global,
                        w_OPERA_SEJ.code_postal_id
                    FROM w_OPERA_SEJ
                        JOIN w_OPERA_SEJ_key ON w_OPERA_SEJ.key = w_OPERA_SEJ_key.key
						JOIN activite.t_divers t_divers_CEGILOGHOS_TDI ON t_divers_CEGILOGHOS_TDI.code = 'CEGILOGHOS_TDI'
                        LEFT JOIN w_CJ_PATIENT ON w_OPERA_SEJ.PAT_ID = w_CJ_PATIENT.PAT_ID AND w_OPERA_SEJ.NO_DOSSIER = w_CJ_PATIENT.SEJ_NUMDOS
					;

                    ALTER TABLE w_sejours ADD CONSTRAINT w_sejours_pkey PRIMARY KEY(no_sejour);
                    
                    -- 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');


                    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
                        provider_id = 2,
                        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
                    FROM w_sejours
                    WHERE w_sejours.no_sejour = p_sejours.no_sejour
                    AND (
                        p_sejours.provider_id IS DISTINCT FROM 2 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
                    );      


                    INSERT INTO activite[PX].p_sejours (
                        no_sejour, 
                        provider_id,
                        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
                    ) 
                    SELECT 
                        w_sejours.no_sejour, 
                        2::bigint AS provider_id,
                        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

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

                    UPDATE activite[PX].p_sejours
                    SET etat = ''
                    WHERE etat = 'I' AND 
                        no_sejour NOT IN (SELECT no_sejour FROM activite.t_sejour WHERE est_ignore = '1') AND
                        '[PX]' = '';
                    
                    -- Médecin séjour forcé
                    UPDATE activite[PX].p_sejours
                    SET medecin_sejour_id = t_sejour.medecin_sejour_id
                    FROM activite.t_sejour
                    WHERE t_sejour.no_sejour = p_sejours.no_sejour AND
                        t_sejour.medecin_sejour_id <> 0 AND
                        p_sejours.medecin_sejour_id IS DISTINCT FROM t_sejour.medecin_sejour_id AND
                        '[PX]' = '';
                    
                    -- recréation index
                    SELECT base.cti_enable_index('activite[PX]', 'i_sejours_2');
                    SELECT base.cti_enable_index('activite[PX]', 'i_sejours_3');
                    SELECT base.cti_enable_index('activite[PX]', 'i_sejours_4');
                    SELECT base.cti_enable_index('activite[PX]', 'i_sejours_5');
                    SELECT base.cti_enable_index('activite[PX]', 'i_sejours_6');
                    SELECT base.cti_enable_index('activite[PX]', 'i_sejours_7');
                    SELECT base.cti_enable_index('activite[PX]', 'i_sejours_8');
                    SELECT base.cti_enable_index('activite[PX]', 'i_sejours_9');
                    SELECT base.cti_enable_index('activite[PX]', 'i_sejours_10');
                    SELECT base.cti_enable_index('activite[PX]', 'i_sejours_11');
                    SELECT base.cti_enable_index('activite[PX]', 'i_sejours_12');
                    SELECT base.cti_enable_index('activite[PX]', 'i_sejours_13');
                                        
                                            
                ]]></sqlcmd>
            </NODE>
            
            <NODE label="Mouvements">
                <sqlcmd><![CDATA[

                    DROP TABLE IF EXISTS w_OPERA_OCC_mouvement2;
                    CREATE TEMP TABLE w_OPERA_OCC_mouvement2 AS
                    SELECT
                        w_OPERA_OCC_mouvement.*,
            
                        COALESCE(DATE_HEURE_SORTIE_SEJOUR, now()) AS DATE_HEURE_MOUVEMENT_SORTIE,

                        CASE WHEN DATE_HEURE_ENTREE_SEJOUR = DATE_HEURE_MOUVEMENT_ENTREE THEN '1'::text ELSE '0'::text END AS q_entree,
                        CASE WHEN DATE_HEURE_SORTIE_SEJOUR IS NOT NULL THEN '1'::text ELSE '0'::text END AS q_sortie,

                        ''::text AS CODE_SERVICE_before,
                        ''::text AS CODE_SERVICE_DISCIPLINE_before,
                        ''::text AS CODE_ETAGE_before,
                        ''::text AS CODE_UM_before,

                        ''::text AS CODE_SERVICE_after,
                        ''::text AS CODE_SERVICE_DISCIPLINE_after,
                        ''::text AS CODE_ETAGE_after,
                        ''::text AS CODE_UM_after,

                        CODE_SERVICE || '|' ||
                        CODE_SERVICE_DISCIPLINE || '|' ||
                        MT || '|' ||
                        DMT || '|' ||
                        CODE_LIT || '|' ||
                        CODE_UM || '|' ||
                        TYPE_DOSSIER || '|' ||
                        MODE_ENTREE AS key
                    FROM w_OPERA_OCC_mouvement
                    ORDER BY NO_DOSSIER, sequence;

                    DROP TABLE IF EXISTS w_OPERA_OCC_mouvement_key;
                    CREATE TEMP TABLE w_OPERA_OCC_mouvement_key AS
                    SELECT
                        key,
                        CODE_SERVICE,
                        CODE_SERVICE_DISCIPLINE,
                        MT,
                        DMT,
                        CODE_LIT,
                        ''::text AS CODE_ETAGELIT,
                        ''::text AS CODE_ETAGE,
                        CODE_UM,
                        TYPE_DOSSIER,
                        MODE_ENTREE,
                        '0'::text AS chambre_particuliere,
                        0 AS mode_traitement_id,
                        ''::text AS mode_traitement_code,
                        ''::text AS dmt_code,
                        ''::text AS code_urgence,
                        0::bigint AS lieu_id
                    FROM w_OPERA_OCC_mouvement2
                    GROUP BY 1,2,3,4,5,6,7,8,9,10,11;



                    UPDATE w_OPERA_OCC_mouvement_key SET
                        mode_traitement_id = t_modes_traitement.oid,
                        mode_traitement_code = t_modes_traitement.code,
                        dmt_code = t_dmt.code,
                        code_urgence = CASE WHEN 
                            t_divers.valeur IN ('2', '4', '6') AND TYPE_DOSSIER = 'U' OR 
                            t_divers.valeur IN ('3', '5', '6') AND TYPE_DOSSIER = '8U' OR 
                            t_divers.valeur IN ('1', '4', '5', '6') AND t_dmt.code IN ('401', '402', '403', '404', '405', '406', '407', '408', '409') 
                            THEN '1' 
                            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
					JOIN activite.t_divers ON t_divers.code = 'URGENCES_CEGI'
                    WHERE t_services_facturation.code_original = CODE_SERVICE_DISCIPLINE;

                    UPDATE w_OPERA_OCC_mouvement_key SET
                        CODE_ETAGELIT = CASE WHEN w_OPERA_OCC_mouvement_key.CODE_LIT <> '' THEN CASE WHEN OPERA_PLIT.CODE_ETAGE <> '' THEN OPERA_PLIT.CODE_ETAGE ELSE SUBSTR(w_OPERA_OCC_mouvement_key.CODE_LIT,1,1) END || '|' || w_OPERA_OCC_mouvement_key.CODE_LIT ELSE '' END,
                        CODE_ETAGE = CASE WHEN w_OPERA_OCC_mouvement_key.CODE_LIT <> '' THEN CASE WHEN OPERA_PLIT.CODE_ETAGE <> '' THEN OPERA_PLIT.CODE_ETAGE ELSE SUBSTR(w_OPERA_OCC_mouvement_key.CODE_LIT,1,1) END ELSE '' END
                    FROM prod_cegiloghos.OPERA_PLIT
                    WHERE OPERA_PLIT.CODE_LIT = w_OPERA_OCC_mouvement_key.CODE_LIT;

                    UPDATE w_OPERA_OCC_mouvement_key SET
                        chambre_particuliere = t_lits.chambre_particuliere
                    FROM activite[PX].t_lits
                    WHERE t_lits.code_original = CODE_ETAGELIT;


                    INSERT INTO activite[PX].t_lieux(
                                code_original_1, code_original_2, code_original_3, code_original_4, code_original_5, code_original_6)
                    SELECT CODE_SERVICE_DISCIPLINE, '', CODE_ETAGE, CODE_ETAGELIT, CODE_UM , CODE_SERVICE
                    FROM w_OPERA_OCC_mouvement_key
                        LEFT JOIN activite[PX].t_lieux ON (
                            code_original_1 = CODE_SERVICE_DISCIPLINE AND
                            code_original_2 = '' AND
                            code_original_3 = CODE_ETAGE AND
                            code_original_4 = CODE_ETAGELIT AND
                            code_original_5 = CODE_UM AND
                            code_original_6 = CODE_SERVICE
                        )
                    WHERE t_lieux.oid IS NULL
                    GROUP BY 1,2,3,4,5,6;

                    UPDATE w_OPERA_OCC_mouvement_key
                        set lieu_id = t_lieux.oid
                    FROM activite[PX].t_lieux
                    WHERE code_original_1 = CODE_SERVICE_DISCIPLINE AND
                        code_original_2 = '' AND
                        code_original_3 = CODE_ETAGE AND
                        code_original_4 = CODE_ETAGELIT AND
                        code_original_5 = CODE_UM AND
                        code_original_6 = CODE_SERVICE;

                    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_medicale_id = COALESCE(t_unites_medicales.oid,0)
                    FROM
                        activite[PX].t_unites_medicales
                    WHERE code_original_5 = t_unites_medicales.code_original
                        AND unite_medicale_id <> COALESCE(t_unites_medicales.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)
                        ;



                    UPDATE w_OPERA_OCC_mouvement2
                    SET 
                        q_sortie = '0',
                        DATE_HEURE_MOUVEMENT_SORTIE = w_OPERA_OCC_mouvement2_after.DATE_HEURE_MOUVEMENT_ENTREE - interval '1 SECOND'
                    FROM w_OPERA_OCC_mouvement2 w_OPERA_OCC_mouvement2_after
                    WHERE w_OPERA_OCC_mouvement2.NO_DOSSIER = w_OPERA_OCC_mouvement2_after.NO_DOSSIER AND 
                        w_OPERA_OCC_mouvement2.sequence = w_OPERA_OCC_mouvement2_after.sequence - 1;


                    UPDATE w_OPERA_OCC_mouvement2
                    SET 
                        CODE_SERVICE_after = w_OPERA_OCC_mouvement2_after.CODE_SERVICE,
                        CODE_SERVICE_DISCIPLINE_after = w_OPERA_OCC_mouvement2_after.CODE_SERVICE_DISCIPLINE,
                        CODE_ETAGE_after = w_OPERA_OCC_mouvement_key_after.CODE_ETAGE,
                        CODE_UM_after = w_OPERA_OCC_mouvement2_after.CODE_UM
                    FROM w_OPERA_OCC_mouvement_key,
                        w_OPERA_OCC_mouvement2 w_OPERA_OCC_mouvement2_after
                        JOIN w_OPERA_OCC_mouvement_key w_OPERA_OCC_mouvement_key_after ON w_OPERA_OCC_mouvement2_after.key = w_OPERA_OCC_mouvement_key_after.key
                    WHERE w_OPERA_OCC_mouvement2.key = w_OPERA_OCC_mouvement_key.key AND
                        w_OPERA_OCC_mouvement2.NO_DOSSIER = w_OPERA_OCC_mouvement2_after.NO_DOSSIER AND
                        w_OPERA_OCC_mouvement2.sequence = w_OPERA_OCC_mouvement2_after.sequence - 1;

                    UPDATE w_OPERA_OCC_mouvement2
                    SET 
                        CODE_SERVICE_before = w_OPERA_OCC_mouvement2_before.CODE_SERVICE,
                        CODE_SERVICE_DISCIPLINE_before = w_OPERA_OCC_mouvement2_before.CODE_SERVICE_DISCIPLINE,
                        CODE_ETAGE_before = w_OPERA_OCC_mouvement_key_before.CODE_ETAGE,
                        CODE_UM_before = w_OPERA_OCC_mouvement2_before.CODE_UM
                    FROM w_OPERA_OCC_mouvement_key,
                        w_OPERA_OCC_mouvement2 w_OPERA_OCC_mouvement2_before
                        JOIN w_OPERA_OCC_mouvement_key w_OPERA_OCC_mouvement_key_before ON w_OPERA_OCC_mouvement2_before.key = w_OPERA_OCC_mouvement_key_before.key
                    WHERE w_OPERA_OCC_mouvement2.key = w_OPERA_OCC_mouvement_key.key AND
                        w_OPERA_OCC_mouvement2.NO_DOSSIER = w_OPERA_OCC_mouvement2_before.NO_DOSSIER AND
                        w_OPERA_OCC_mouvement2.sequence = w_OPERA_OCC_mouvement2_before.sequence + 1;

            




                    DROP TABLE IF EXISTS w_mouvements_sejour;

                    CREATE TEMP TABLE w_mouvements_sejour AS
                    SELECT 
                        NO_DOSSIER,
                        NO_DOSSIER 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(DATE_HEURE_MOUVEMENT_ENTREE) THEN extract('hour' from DATE_HEURE_MOUVEMENT_ENTREE) * 10000 + extract('minute' from DATE_HEURE_MOUVEMENT_ENTREE) * 100 + extract('second' from DATE_HEURE_MOUVEMENT_ENTREE) ELSE 0 END AS heure_debut,
                        CASE WHEN p_calendrier.date = date(DATE_HEURE_MOUVEMENT_SORTIE) THEN extract('hour' from DATE_HEURE_MOUVEMENT_SORTIE) * 10000 + extract('minute' from DATE_HEURE_MOUVEMENT_SORTIE) * 100 + extract('second' from DATE_HEURE_MOUVEMENT_SORTIE) ELSE 240000 END AS heure_fin,
                        CASE WHEN q_entree = '1' AND p_calendrier.date =  date(DATE_HEURE_ENTREE_SEJOUR) AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_entrees_directes,
                        CASE WHEN q_sortie = '1' AND p_calendrier.date =  date(DATE_HEURE_SORTIE_SEJOUR) AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_sorties_directes,
                        CASE WHEN q_entree = '1' AND p_calendrier.date =  date(DATE_HEURE_ENTREE_SEJOUR) AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_entree,
                        CASE WHEN q_sortie = '1' AND p_calendrier.date =  date(DATE_HEURE_SORTIE_SEJOUR) 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 q_entree = '1' AND p_calendrier.date =  date(DATE_HEURE_ENTREE_SEJOUR) AND p_sejours.type_sejour = '2' THEN 1 ELSE 0 END AS nb_ambulatoires,
                        CASE WHEN q_entree = '1' AND p_calendrier.date =  date(DATE_HEURE_ENTREE_SEJOUR) AND p_sejours.type_sejour = '3' THEN 1 ELSE 0 END AS nb_externes,
                        CASE WHEN code_urgence = '1' AND p_calendrier.date =  date(DATE_HEURE_ENTREE_SEJOUR) AND q_entree = '1' THEN 1 ELSE 0 END AS nb_urgences,
                        0 as nb_seances,

                        CASE WHEN p_calendrier.date = date(DATE_HEURE_MOUVEMENT_ENTREE) AND p_sejours.type_sejour = '1' AND q_entree <> '1' AND w_OPERA_OCC_mouvement2.CODE_SERVICE_DISCIPLINE <> CODE_SERVICE_DISCIPLINE_before THEN 1 ELSE 0 END AS nb_entrees_mutation_service,
                        CASE WHEN p_calendrier.date = date(DATE_HEURE_MOUVEMENT_SORTIE) AND p_sejours.type_sejour = '1' AND q_sortie <> '1' AND w_OPERA_OCC_mouvement2.CODE_SERVICE_DISCIPLINE <> CODE_SERVICE_DISCIPLINE_after THEN 1 ELSE 0 END AS nb_sorties_mutation_service,
                        CASE WHEN p_calendrier.date = date(DATE_HEURE_MOUVEMENT_ENTREE) AND p_sejours.type_sejour = '1' AND q_entree <> '1' AND w_OPERA_OCC_mouvement_key.CODE_ETAGE <> CODE_ETAGE_before THEN 1 ELSE 0 END AS nb_entrees_mutation_etage,
                        CASE WHEN p_calendrier.date = date(DATE_HEURE_MOUVEMENT_SORTIE) AND p_sejours.type_sejour = '1' AND q_sortie <> '1' AND w_OPERA_OCC_mouvement_key.CODE_ETAGE <> CODE_ETAGE_after THEN 1 ELSE 0 END AS nb_sorties_mutation_etage,
                        0 AS nb_entrees_mutation_activite,
                        0 AS nb_sorties_mutation_activite,
                        CASE WHEN p_calendrier.date = date(DATE_HEURE_MOUVEMENT_ENTREE) AND p_sejours.type_sejour = '1' AND q_entree <> '1' AND w_OPERA_OCC_mouvement2.CODE_UM <> CODE_UM_before THEN 1 ELSE 0 END AS nb_entrees_mutation_unite_medicale,
                        CASE WHEN p_calendrier.date = date(DATE_HEURE_MOUVEMENT_SORTIE) AND p_sejours.type_sejour = '1' AND q_sortie <> '1' AND w_OPERA_OCC_mouvement2.CODE_UM <> CODE_UM_after THEN 1 ELSE 0 END 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(DATE_HEURE_SORTIE_SEJOUR) THEN 1 ELSE 0 END AS nb_jours_js_non_inclus,

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

                        0 AS nb_bebes,

                        w_OPERA_OCC_mouvement_key.lieu_id,

                        p_sejours.medecin_sejour_id as medecin_sejour_id

                    FROM w_OPERA_OCC_mouvement2
                        JOIN w_OPERA_OCC_mouvement_key ON w_OPERA_OCC_mouvement2.key = w_OPERA_OCC_mouvement_key.key
                        JOIN activite[PX].p_sejours ON w_OPERA_OCC_mouvement2.NO_DOSSIER = p_sejours.code_original AND p_sejours.etat = ''
                        JOIN base.p_calendrier ON (p_calendrier.date BETWEEN date(DATE_HEURE_MOUVEMENT_ENTREE) AND date(DATE_HEURE_MOUVEMENT_SORTIE) AND p_calendrier.date <= now() )
                    WHERE p_sejours.code_prevu <> 1
                    ORDER BY sequence, p_calendrier.date;
                    
                    
                    
                    -- bébés
                        -- première salve, d'après les actes honoraires
                    DROP TABLE IF EXISTS w_OPERA_ACT_bebes;
                    
                    CREATE TEMP TABLE w_OPERA_ACT_bebes AS
                    SELECT 
                        prod_cegiloghos.OPERA_ACT.NO_DOSSIER,
                        MAX(DATE_ACTE_DEBUT)::date as date_accouchement,
                        MAX(CASE WHEN t_actes.texte ILIKE '%multiple%' THEN 2 ELSE 1 END) AS nb_bebes
                    FROM prod_cegiloghos.OPERA_ACT
                        JOIN w_OPERA_SEJ_select ON OPERA_ACT.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                        JOIN base.t_actes ON t_actes.code = substring(CODE_CCAM, 1, 7) AND 
                            CODE_CCAM LIKE 'JQG%' AND 
                            t_actes.texte ILIKE 'accouchement%' 
                    WHERE CODE_PRESTA = 'ACO' 
                    GROUP BY 1;

                    CREATE INDEX w_OPERA_ACT_bebes_i1
                      ON w_OPERA_ACT_bebes
                      USING btree
                      (NO_DOSSIER);

                        -- on stocke dans w_deja_bebes les numéros de séjours pour lesquels on 
                        -- vient de trouver des bébés afin de ne pas leur coller des bébés supplémentaires
                    DROP TABLE IF EXISTS w_deja_bebes;
                    CREATE TEMP TABLE w_deja_bebes AS 
                    WITH w_updated AS (
                        UPDATE w_mouvements_sejour 
                        SET nb_bebes = w_OPERA_ACT_bebes.nb_bebes
                        FROM w_OPERA_ACT_bebes
                        WHERE w_OPERA_ACT_bebes.NO_DOSSIER = w_mouvements_sejour.no_sejour AND
                            w_OPERA_ACT_bebes.date_accouchement = w_mouvements_sejour.date AND
                            w_mouvements_sejour.nb_bebes = 0 AND
                            (nb_entrees_directes = 1 OR nb_externes = 1 OR nb_ambulatoires = 1 OR heure_debut = 0)
                        RETURNING w_mouvements_sejour.no_sejour
                    )
                    SELECT no_sejour as deja_no_sejour FROM w_updated;
                    
                        -- deuxième salve, d'après le codage des actes CCAM du PMSI
                    DROP TABLE IF EXISTS w_LSCCAM_bebes;
                    
                    CREATE TEMP TABLE w_LSCCAM_bebes AS
                    SELECT 
                        SEJ_NUMDOS,
                        MAX(CASE WHEN t_actes.texte ILIKE '%multiple%' THEN 2 ELSE 1 END) AS nb_bebes
                    FROM prod_cegi.CJ_SEJOUR
                        JOIN w_OPERA_SEJ_select ON CJ_SEJOUR.SEJ_NUMDOS = w_OPERA_SEJ_select.NO_DOSSIER
                        JOIN prod_cegi.CJ_LSRGP ON CJ_LSRGP.SEJ_ID = CJ_SEJOUR.SEJ_ID AND LSR_ACTIF = 1
                        JOIN prod_cegi.CJ_LSCCAM ON CJ_LSCCAM.LSR_ID = CJ_LSRGP.LSR_ID AND LSCA_ACTIF = 1
                        JOIN prod_cegi.CJ_CCAM ON CJ_CCAM.CCAM_ID = CJ_LSCCAM.CCAM_ID AND CCAM_ACTV = '1'
                        JOIN base.t_actes ON t_actes.code = substring(CCAM_CODE, 1, 7) AND 
                            CCAM_CODE LIKE 'JQG%' AND 
                            t_actes.texte ILIKE 'accouchement%' 
                        LEFT JOIN w_deja_bebes ON w_deja_bebes.deja_no_sejour = CJ_SEJOUR.SEJ_NUMDOS
                    WHERE w_deja_bebes.deja_no_sejour IS NULL
                    GROUP BY 1;
                    
                    CREATE INDEX w_LSCCAM_bebes_i1
                      ON w_LSCCAM_bebes
                      USING btree
                      (SEJ_NUMDOS);
                    
                        -- on ajoute à w_deja_bebes les nouveaux séjours impactés
                    WITH w_encore_bebes AS (
                        UPDATE w_mouvements_sejour 
                        SET nb_bebes = w_LSCCAM_bebes.nb_bebes
                        FROM w_LSCCAM_bebes 
                        WHERE SEJ_NUMDOS = w_mouvements_sejour.no_sejour AND
                            w_mouvements_sejour.no_sejour != ALL (ARRAY(SELECT w_mouvements_sejour.no_sejour as w_no_sejour FROM w_mouvements_sejour WHERE nb_bebes = 1 GROUP BY 1)::text[]) AND
                            (nb_entrees_directes = 1 OR nb_externes = 1 OR nb_ambulatoires = 1)
                        RETURNING w_mouvements_sejour.no_sejour
                    )
                    INSERT INTO w_deja_bebes
                    SELECT no_sejour FROM w_encore_bebes;
                    
                    DROP TABLE IF EXISTS w_OPERA_ACT_bebes;
                    CREATE TEMP TABLE w_OPERA_ACT_bebes AS
                    SELECT 
                        prod_cegiloghos.OPERA_ACT.NO_DOSSIER,
                        1 AS nb_bebes,
                        MAX(DATE_ACTE_DEBUT)::date as date_accouchement
                    FROM prod_cegiloghos.OPERA_ACT
                        JOIN w_OPERA_SEJ_select ON OPERA_ACT.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                        LEFT JOIN w_deja_bebes ON w_deja_bebes.deja_no_sejour = OPERA_ACT.NO_DOSSIER
                    WHERE CODE_PRESTA = 'GHS' AND
                        OPERA_ACT.CODE_GHS IN (SELECT to_char(code, 'FM0000') FROM base.t_ghs WHERE texte ILIKE 'nouveau-n%')
                        AND w_deja_bebes.deja_no_sejour IS NULL
                    GROUP BY 1;
                    
                    CREATE INDEX w_OPERA_ACT_bebes_i1
                      ON w_OPERA_ACT_bebes
                      USING btree
                      (NO_DOSSIER);
                    
                    UPDATE w_mouvements_sejour 
                    SET nb_bebes = w_OPERA_ACT_bebes.nb_bebes
                    FROM w_OPERA_ACT_bebes
                    WHERE w_OPERA_ACT_bebes.NO_DOSSIER = w_mouvements_sejour.no_sejour AND
                        w_mouvements_sejour.nb_bebes = 0 AND
                        w_mouvements_sejour.date = date_accouchement AND
                        (nb_entrees_directes = 1 OR nb_externes = 1 OR nb_ambulatoires = 1);
                    
                        -- dernière opération, on met un bébé supplémentaire là où on n'en a mis qu'un
                        -- mais où le GHS contient le mot 'multiple'
                    UPDATE w_mouvements_sejour SET
                        nb_bebes = 2
                    FROM
                        prod_cegiloghos.OPERA_ACT
                        JOIN base.t_ghs ON to_char(t_ghs.code, 'FM0000') = OPERA_ACT.CODE_GHS
                    WHERE 1=1
                        AND w_mouvements_sejour.nb_bebes = 1
                        AND OPERA_ACT.NO_DOSSIER = w_mouvements_sejour.no_sejour
                        AND t_ghs.texte like '%multiple%';
                    
                    -- Séances
                    DROP TABLE IF EXISTS w_OPERA_ACT_seances;
                    
                    CREATE TEMP TABLE w_OPERA_ACT_seances AS
                    SELECT 
                        OPERA_ACT.NO_DOSSIER,
                        date(DATE_ACTE_DEBUT) AS date,
                        SUM(CASE WHEN MONTANT_ACTE < 0 AND QTE_ACTE > 0 THEN 0 - QTE_ACTE ELSE QTE_ACTE END) AS nb_seances
                    FROM prod_cegiloghos.OPERA_ACT 
                        JOIN w_OPERA_SEJ_select ON OPERA_ACT.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                    WHERE CODE_PRESTA = 'K' AND TYPE_PRESTA = 'H' AND
                        
                        (COEFF_ACTE IN (15) OR DMT_ACTE = '302')
                        
                    GROUP BY 1,2;

                        
                    CREATE INDEX w_OPERA_ACT_seances_i1
                      ON w_OPERA_ACT_seances
                      USING btree
                      (NO_DOSSIER);
                      
                    UPDATE w_mouvements_sejour
                    SET nb_seances = w_OPERA_ACT_seances.nb_seances
                    FROM w_OPERA_ACT_seances
                    WHERE w_OPERA_ACT_seances.NO_DOSSIER = w_mouvements_sejour.no_sejour AND 
                        w_OPERA_ACT_seances.date = w_mouvements_sejour.date;
                        
                        
                    -- Séjours sans séances trouvées dans les actes 
                    DROP TABLE IF EXISTS w_sejours_sans_seance;
                    CREATE TEMP TABLE w_sejours_sans_seance AS 
                    SELECT p_sejours.no_sejour, date_entree, heure_entree 
                        FROM activite[PX].p_sejours
                        LEFT JOIN w_mouvements_sejour ON p_sejours.no_sejour = w_mouvements_sejour.no_sejour and nb_seances > 0
                        WHERE p_sejours.type_sejour = 5 AND w_mouvements_sejour.no_sejour IS NULL;

                    UPDATE w_mouvements_sejour
                    SET nb_seances = 1 
                    FROM w_sejours_sans_seance
                    WHERE w_mouvements_sejour.no_sejour = w_sejours_sans_seance.no_sejour AND
                        w_mouvements_sejour.date = w_sejours_sans_seance.date_entree AND
                        w_mouvements_sejour.heure_debut = w_sejours_sans_seance.heure_entree;
                        
                    
                    -- 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, 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, 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>
    
        
        <NODE label="*FIRST*">
            
            <condition><![CDATA[
                "[CJFIRST_PRESENT]" == "OUI"
            ]]></condition>
            
            <NODE label="Patients">
				<sqlcmd><![CDATA[
				
					DROP TABLE IF EXISTS w_CJ_PATIENT;
					CREATE TEMP TABLE w_CJ_PATIENT AS
					SELECT 
						CJ_PATIENT.PAT_ID,
						SEJ_NUMDOS,
						MAX(PAT_IPP) AS no_patient,
						MAX(PER_NOM) AS PER_NOM, 
						MAX(PER_PRENOM) AS PER_PRENOM, 
						MAX(PER_NOMJF) AS PER_NOMJF, 
                        MAX(PER_CP) AS PER_CP, 
                        MAX(PER_VILLE) AS PER_VILLE, 
						MAX(date(PER_NAISSANCE)) AS PER_NAISSANCE,
						MAX(CASE WHEN PAT_SEXE IN ('F') THEN '2' ELSE '1' END) AS PAT_SEXE,
						MAX(CASE WHEN PER_NVOIE != '' THEN PER_NVOIE || ' ' ELSE '' END || PER_NOMVOIE || CASE WHEN PER_COMPVOIE != '' THEN ' - ' || PER_COMPVOIE ELSE '' END) AS PER_NOMVOIE,
						MAX(PAT_TEL1) AS PAT_TEL_FIXE,
						MAX(PAT_TEL2) AS PAT_TEL_PORT,
						MAX(PAT_EMAIL) AS PAT_EMAIL
					FROM prod_cegi.CJ_PATIENT 
					JOIN w_CJ_SEJOUR_select ON CJ_PATIENT.PAT_ID = w_CJ_SEJOUR_select.PAT_ID
					GROUP BY 1,2;

				--	ALTER TABLE w_CJ_PATIENT ADD CONSTRAINT w_CJ_PATIENT_pkey PRIMARY KEY(PAT_ID);
					
					
					INSERT INTO w_CJ_PATIENT
					SELECT 
						COALESCE(w_CJ_SEJOUR_select.PAT_ID,0 - to_number(w_CJ_SEJOUR_select.SEJ_NUMDOS, '0000000000')),
						w_CJ_SEJOUR_select.SEJ_NUMDOS,
						COALESCE('W' || w_CJ_SEJOUR_select.PAT_ID::text,'W' || w_CJ_SEJOUR_select.SEJ_NUMDOS) AS no_patient,
						'Indisponible' AS PER_NOM, 
						'' AS PER_PRENOM, 
						'' AS PER_NOMJF, 
                        '' AS PER_CP, 
						'' AS PER_VILLE, 
						'19620418'::date AS PER_NAISSANCE,
						'1' AS PAT_SEXE,
						'' AS PAT_TEL_FIXE,
						'' AS PAT_TEL_PORT,
						'' AS PAT_EMAIL
					FROM w_CJ_SEJOUR_select
					LEFT JOIN w_CJ_PATIENT ON w_CJ_SEJOUR_select.PAT_ID = w_CJ_PATIENT.PAT_ID
					WHERE w_CJ_PATIENT.PAT_ID IS NULL
					GROUP BY 1,2,3;

					CREATE INDEX w_CJ_PATIENT_i1
						  ON w_CJ_PATIENT
						  USING btree
						  (no_patient);

					
					  
					UPDATE activite[PX].p_patients
					SET 
						nom = PER_NOM, 
						nom_naissance = PER_NOMJF, 
						prenom = PER_PRENOM, 
						date_naissance = PER_NAISSANCE
					FROM w_CJ_PATIENT 
					WHERE p_patients.no_patient = w_CJ_PATIENT.no_patient
						AND (
							p_patients.nom IS DISTINCT FROM PER_NOM OR 
							p_patients.prenom IS DISTINCT FROM PER_PRENOM OR
							p_patients.nom_naissance IS DISTINCT FROM PER_NOMJF OR
							p_patients.date_naissance IS DISTINCT FROM date(PER_NAISSANCE)
						);

					INSERT INTO activite[PX].p_patients(finess, no_patient, nom, prenom, nom_naissance, date_naissance)
					SELECT '', w_CJ_PATIENT.no_patient, MAX(PER_NOM), MAX(PER_PRENOM), MAX(PER_NOMJF), MAX(PER_NAISSANCE)
					FROM w_CJ_PATIENT 
						LEFT JOIN activite[PX].p_patients ON (w_CJ_PATIENT.no_patient = p_patients.no_patient)
					WHERE p_patients.no_patient IS NULL
					GROUP BY w_CJ_PATIENT.no_patient;
							
			]]></sqlcmd>
			</NODE>
                    
            <NODE label="Séjours">
                <sqlcmd><![CDATA[

                    -- Séjours
                    DROP TABLE IF EXISTS w_RSS;
                    CREATE TEMP TABLE w_RSS AS          
                    SELECT 
                        w_CJ_SEJOUR_select.SEJ_ID,
                        SEJ_NUMDOS,
                        MAX(GHS_NUMERO) AS GHS_NUMERO,
                        MAX(C_GHM_CCAM) AS C_GHM_CCAM,
                        MAX(DT_ENV_ADM) AS DT_ENV_ADM,
                        0::bigint AS ghs_id,
                        0::bigint AS ghm_id,
                        (MIN(Array[to_char(I_RUM,'FM00000')::text,C_MODE_E]))[2] AS C_MODE_E,
                        (MIN(Array[to_char(I_RUM,'FM00000')::text,C_PROV]))[2] AS C_PROV,
                        (MAX(Array[to_char(I_RUM,'FM00000')::text,C_MODE_S]))[2] AS C_MODE_S,
                        (MAX(Array[to_char(I_RUM,'FM00000')::text,C_DEST]))[2] AS C_DEST
                    FROM prod_cegi.RSS 
                    JOIN w_CJ_SEJOUR_select ON RSS.SEJ_ID = w_CJ_SEJOUR_select.SEJ_ID
                    JOIN prod_cegi.RUM ON RUM.N_PMSI = RSS.N_PMSI
                    WHERE GHS_NUMERO <> '' AND GHS_NUMERO <> '9999' 
                    GROUP BY 1,2;

                    ALTER TABLE w_RSS ADD CONSTRAINT w_RSS_pkey PRIMARY KEY(SEJ_ID);

                    
                    
                    INSERT INTO w_RSS
                    SELECT w_CJ_SEJOUR_select.SEJ_ID,
                        w_CJ_SEJOUR_select.SEJ_NUMDOS, 
                        (MAX(Array[COALESCE(SEJGHS_MODIF_DATE,SEJGHS_DATE)::text,SEJGHS_GHS]))[2] AS GHS_NUMERO,
                        ''::text AS C_GHM_CCAM,
                        MAX(COALESCE(SEJGHS_MODIF_DATE,SEJGHS_DATE)) AS DT_ENV_ADM,
                        0::bigint AS ghs_id,
                        0::bigint AS ghm_id,
                        '8' AS C_MODE_E,
                        '' AS C_PROV,
                        '8'  AS C_MODE_S,
                        '' AS C_DEST
                    FROM prod_cegi.CJ_SEJGHS
                    JOIN w_CJ_SEJOUR_select ON CJ_SEJGHS.SEJ_ID = w_CJ_SEJOUR_select.SEJ_ID
                    LEFT JOIN w_RSS ON w_RSS.SEJ_ID = CJ_SEJGHS.SEJ_ID
                    WHERE w_RSS.SEJ_ID IS NULL AND
                        SEJGHS_GHS <> '' AND SEJGHS_GHS <> '9999' 
                    GROUP BY 1,2;

                    UPDATE w_RSS
                    SET ghm_id = t_ghm.oid
                    FROM base.t_ghm
                    WHERE C_GHM_CCAM = t_ghm.code;

                    UPDATE w_RSS
                    SET ghs_id = t_ghs.oid
                    FROM base.t_ghs
                    WHERE GHS_NUMERO = t_ghs.code_text;
                    
                    UPDATE w_RSS
                    SET ghs_id = t_ghs.oid
                    FROM base.t_ghs
                    WHERE ghs_id = 0 AND GHS_NUMERO <> '' AND GHS_NUMERO = to_char(t_ghs.code,'FM0000');

                    -- Modes entrée-sortie
                    UPDATE w_CJ_SEJOUR_select
                    SET mode_entree = MEN_PMSI
                    FROM prod_cegi.CJ_MEN
                    WHERE w_CJ_SEJOUR_select.MEN_ID = CJ_MEN.MEN_ID AND
                        MEN_PMSI IN ('0','6','7')
                    ;

                    UPDATE w_CJ_SEJOUR_select
                    SET mode_sortie = MSO_PMSI
                    FROM prod_cegi.CJ_MSO
                    WHERE w_CJ_SEJOUR_select.MSO_ID = CJ_MSO.MSO_ID AND
                        MSO_PMSI IN ('0','6','7','9')
                    ;


                    
                    
                    



                    DROP TABLE IF EXISTS w_CHGNVE_all;
                    CREATE TEMP TABLE w_CHGNVE_all AS
                    SELECT 
                        CJ_CHGNVE.SEJ_ID,
                        w_CJ_SEJOUR_select.SEJ_NUMDOS,
                        CJ_CHGNVE.CHGNVE_ID,
                        CJ_NVE.NVE_TYPE,
                        CJ_CHGNVE.NVE_ID,
                        CJ_NVE.NVE_LIBC::text AS NVE_original,
                        CHGNVE_DATE,
                        CHGNVE_ACTIF,
                        COALESCE((CHGNVE_HEURE - date_trunc('day',CHGNVE_HEURE)),'00:00:00') AS CHGNVE_HEURE,
                        CJ_DMT.DMT_LIBC,
                        CJ_MTR.MTR_LIBC
                    FROM prod_cegi.CJ_CHGNVE
                        JOIN w_CJ_SEJOUR_select ON w_CJ_SEJOUR_select.SEJ_ID = CJ_CHGNVE.SEJ_ID
                        JOIN prod_cegi.CJ_NVE ON CJ_NVE.NVE_ID = CJ_CHGNVE.NVE_ID
                        LEFT JOIN prod_cegi.CJ_DMT ON CJ_NVE.DMT_ID = CJ_DMT.DMT_ID
                        LEFt JOIN prod_cegi.CJ_MTR ON CJ_NVE.MTR_ID = CJ_MTR.MTR_ID
                    WHERE CHGNVE_ANNUL_DH IS NULL AND
                        CHGNVE_ACTIF = 1;

                    INSERT INTO w_CHGNVE_all
                    SELECT 
                        RSS.SEJ_ID,
                        w_CJ_SEJOUR_select.SEJ_NUMDOS,
                        0::numeric AS CHGNVE_ID,
                        'UM'::text AS NVE_TYPE,
                        0::numeric AS NVE_ID,
                        RUM.C_UM AS NVE_original,
                        RUM.D_E,
                        1::numeric AS CHGNVE_ACTIF,
                        (HR_ENTREE - date_trunc('day',HR_ENTREE)) AS CHGNVE_HEURE,
                        ''::text AS DMT_LIBC,
                        ''::text AS MTR_LIBC
                    FROM prod_cegi.RUM 
                        JOIN prod_cegi.RSS ON RUM.N_PMSI = RSS.N_PMSI
                        JOIN w_CJ_SEJOUR_select ON RSS.SEJ_ID = w_CJ_SEJOUR_select.SEJ_ID;







                        

                    DROP SEQUENCE IF EXISTS w_CHGNVE_seq;
                    CREATE TEMP SEQUENCE w_CHGNVE_seq;

                    DROP TABLE IF EXISTS w_CHGNVE;
                    CREATE TEMP TABLE w_CHGNVE AS
                    SELECT nextval('w_CHGNVE_seq'::regclass) AS CHGNVE_seq,
                        subview.*,
                        CHGNVE_DATE + CHGNVE_HEURE AS CHGNVE_DATE_HEURE,
                        NULL::date AS CHGNVE_DATE_FIN,
                        NULL::interval AS CHGNVE_HEURE_FIN,
                        NULL::timestamp without time zone AS CHGNVE_DATE_HEURE_FIN,
                        0::bigint AS lieu_id,
                        '0'::text AS q_entree,
                        '0'::text AS q_sortie,
                        'N'::text AS chambre_particuliere,

                        ''::text AS NVE_SAD_avant,
                        ''::text AS NVE_ETA_avant,
                        ''::text AS NVE_UF_avant,
                        ''::text AS NVE_UM_avant,

                        ''::text AS NVE_SAD_apres,
                        ''::text AS NVE_ETA_apres,
                        ''::text AS NVE_UF_apres,
                        ''::text AS NVE_UM_apres
                        
                    FROM
                        (
                         SELECT SEJ_ID, 
                            SEJ_NUMDOS,
                            date(CHGNVE_DATE) AS CHGNVE_DATE,
                            
                            (MAX(Array[to_char(CASE WHEN NVE_TYPE = 'SAD' THEN @CHGNVE_ID ELSE 0 END,'FM000000000000'),CASE WHEN NVE_TYPE = 'SAD' THEN NVE_original ELSE '' END]))[2] AS NVE_SAD,
                            (MAX(Array[to_char(CASE WHEN NVE_TYPE = 'SAD' THEN @CHGNVE_ID ELSE 0 END,'FM000000000000'),CASE WHEN NVE_TYPE = 'SAD' THEN NVE_original ELSE '' END]))[2] AS NVE_UF,
                            (MAX(Array[to_char(CASE WHEN NVE_TYPE = 'LIT' THEN @CHGNVE_ID ELSE 0 END,'FM000000000000'),CASE WHEN NVE_TYPE = 'LIT' THEN NVE_original ELSE '' END]))[2] AS NVE_LIT,
                            (MAX(Array[to_char(CASE WHEN NVE_TYPE = 'UM' THEN @CHGNVE_ID ELSE 0 END,'FM000000000000'),CASE WHEN NVE_TYPE = 'UM' THEN NVE_original ELSE '' END]))[2] AS NVE_UM,
                            ''::text AS NVE_ETA,
                            (MAX(Array[to_char(CASE WHEN NVE_TYPE = 'SAD' THEN @CHGNVE_ID ELSE 0 END,'FM000000000000'),CASE WHEN NVE_TYPE = 'SAD' THEN DMT_LIBC ELSE '' END]))[2] AS NVE_DMT,
                            (MAX(Array[to_char(CASE WHEN NVE_TYPE = 'SAD' THEN @CHGNVE_ID ELSE 0 END,'FM000000000000'),CASE WHEN NVE_TYPE = 'SAD' THEN MTR_LIBC ELSE '' END]))[2] AS NVE_MTR,
                            
                            (MAX(Array[CASE WHEN NVE_TYPE = 'SAD' THEN @CHGNVE_ID ELSE 0 END,CASE WHEN NVE_TYPE = 'SAD' THEN NVE_ID ELSE -1 END]))[2] AS NVE_ID_SAD,
                            (MAX(Array[CASE WHEN NVE_TYPE = 'SAD' THEN @CHGNVE_ID ELSE 0 END,CASE WHEN NVE_TYPE = 'SAD' THEN NVE_ID ELSE -1 END]))[2] AS NVE_ID_UF,
                            (MAX(Array[CASE WHEN NVE_TYPE = 'LIT' THEN @CHGNVE_ID ELSE 0 END,CASE WHEN NVE_TYPE = 'LIT' THEN NVE_ID ELSE -1 END]))[2] AS NVE_ID_LIT,
                            0::numeric AS NVE_ID_UM,
                            0::numeric AS NVE_ID_ETA,
                            
                            MAX(CHGNVE_HEURE) AS CHGNVE_HEURE
                        FROM w_CHGNVE_all
                        GROUP BY 1,2,3
                        ORDER BY 1,2,3
                        ) subview;



                    SELECT base.cti_execute(
                        'UPDATE w_CHGNVE SET
                            NVE_ID_SAD = CASE WHEN w_CHGNVE.NVE_ID_SAD >= 0 THEN w_CHGNVE.NVE_ID_SAD ELSE w_CHGNVE_avant.NVE_ID_SAD END,
                            NVE_SAD = CASE WHEN w_CHGNVE.NVE_ID_SAD >= 0 THEN w_CHGNVE.NVE_SAD ELSE w_CHGNVE_avant.NVE_SAD END,
                            NVE_MTR = CASE WHEN w_CHGNVE.NVE_ID_SAD >= 0 THEN w_CHGNVE.NVE_MTR ELSE w_CHGNVE_avant.NVE_MTR END,
                            NVE_DMT = CASE WHEN w_CHGNVE.NVE_ID_SAD >= 0 THEN w_CHGNVE.NVE_DMT ELSE w_CHGNVE_avant.NVE_DMT END,
                            NVE_ID_UF = CASE WHEN w_CHGNVE.NVE_ID_UF >= 0 THEN w_CHGNVE.NVE_ID_UF ELSE w_CHGNVE_avant.NVE_ID_UF END,
                            NVE_UF = CASE WHEN w_CHGNVE.NVE_ID_UF >= 0 THEN w_CHGNVE.NVE_UF ELSE w_CHGNVE_avant.NVE_UF END,
                            NVE_ID_LIT = CASE WHEN w_CHGNVE.NVE_ID_LIT >= 0 THEN w_CHGNVE.NVE_ID_LIT ELSE w_CHGNVE_avant.NVE_ID_LIT END,
                            NVE_LIT = CASE WHEN w_CHGNVE.NVE_ID_LIT >= 0 THEN w_CHGNVE.NVE_LIT ELSE w_CHGNVE_avant.NVE_LIT END
                        FROM w_CHGNVE w_CHGNVE_avant
                        WHERE w_CHGNVE.SEJ_ID = w_CHGNVE_avant.SEJ_ID AND
                            w_CHGNVE.CHGNVE_seq = w_CHGNVE_avant.CHGNVE_seq + 1 AND
                                (
                                w_CHGNVE.NVE_ID_SAD < 0 AND w_CHGNVE_avant.NVE_ID_SAD >= 0 OR
                                w_CHGNVE.NVE_ID_UF < 0 AND w_CHGNVE_avant.NVE_ID_UF >= 0 OR
                                w_CHGNVE.NVE_ID_LIT < 0 AND w_CHGNVE_avant.NVE_ID_LIT >= 0
                                )',100);
                                
                                
                            
                    SELECT base.cti_execute(
                        'UPDATE w_CHGNVE SET
                            NVE_ID_SAD = CASE WHEN w_CHGNVE.NVE_ID_SAD >= 0 THEN w_CHGNVE.NVE_ID_SAD ELSE w_CHGNVE_apres.NVE_ID_SAD END,
                            NVE_SAD = CASE WHEN w_CHGNVE.NVE_ID_SAD >= 0 THEN w_CHGNVE.NVE_SAD ELSE w_CHGNVE_apres.NVE_SAD END,
                            NVE_MTR = CASE WHEN w_CHGNVE.NVE_ID_SAD >= 0 THEN w_CHGNVE.NVE_MTR ELSE w_CHGNVE_apres.NVE_MTR END,
                            NVE_DMT = CASE WHEN w_CHGNVE.NVE_ID_SAD >= 0 THEN w_CHGNVE.NVE_DMT ELSE w_CHGNVE_apres.NVE_DMT END,
                            NVE_ID_UF = CASE WHEN w_CHGNVE.NVE_ID_UF >= 0 THEN w_CHGNVE.NVE_ID_UF ELSE w_CHGNVE_apres.NVE_ID_UF END,
                            NVE_UF = CASE WHEN w_CHGNVE.NVE_ID_UF >= 0 THEN w_CHGNVE.NVE_UF ELSE w_CHGNVE_apres.NVE_UF END,
                            NVE_ID_LIT = CASE WHEN w_CHGNVE.NVE_ID_LIT >= 0 THEN w_CHGNVE.NVE_ID_LIT ELSE w_CHGNVE_apres.NVE_ID_LIT END,
                            NVE_LIT = CASE WHEN w_CHGNVE.NVE_ID_LIT >= 0 THEN w_CHGNVE.NVE_LIT ELSE w_CHGNVE_apres.NVE_LIT END
                        FROM w_CHGNVE w_CHGNVE_apres
                        WHERE w_CHGNVE.SEJ_ID = w_CHGNVE_apres.SEJ_ID AND
                            w_CHGNVE.CHGNVE_seq = w_CHGNVE_apres.CHGNVE_seq - 1 AND
                                (
                                w_CHGNVE.NVE_ID_SAD < 0 AND w_CHGNVE_apres.NVE_ID_SAD >= 0 OR
                                w_CHGNVE.NVE_ID_UF < 0 AND w_CHGNVE_apres.NVE_ID_UF >= 0 OR
                                w_CHGNVE.NVE_ID_LIT < 0 AND w_CHGNVE_apres.NVE_ID_LIT >= 0
                                )',100);
                

                    UPDATE w_CHGNVE
                    SET NVE_UM = CJ_SADUM.CODE
                    FROM prod_cegi.CJ_SADUM
                    WHERE NVE_ID_SAD = CJ_SADUM.NVE_ID AND
                        NVE_UM = '';

                    UPDATE w_CHGNVE SET
                        NVE_ETA = w_LITS.code_etage,
                        NVE_LIT = w_LITS.code_etage || '|' || w_LITS.code_lit
                    FROM w_LITS
                    WHERE NVE_ID_LIT = w_LITS.NVE_ID;


                    UPDATE w_CHGNVE SET
                        CHGNVE_HEURE = COALESCE((SEJ_HR_ENTREE - date_trunc('day',SEJ_HR_ENTREE)),'00:00:00'),
                        CHGNVE_DATE_HEURE = CHGNVE_DATE + COALESCE((SEJ_HR_ENTREE - date_trunc('day',SEJ_HR_ENTREE)),'00:00:00')
                    FROM w_CJ_SEJOUR_select
                    WHERE w_CJ_SEJOUR_select.SEJ_ID = w_CHGNVE.SEJ_ID AND
                        date(CHGNVE_DATE) = date(SEJ_DT_ENTREE);


                    UPDATE w_CHGNVE SET
                        CHGNVE_HEURE = '10:00:00'::interval,
                        CHGNVE_DATE_HEURE = CHGNVE_DATE + '10:00:00'::interval
                    WHERE CHGNVE_HEURE = '00:00:00'::interval;


                    UPDATE w_CHGNVE SET
                        q_entree = '1'
                    FROM w_CJ_SEJOUR_select
                        JOIN (
                            SELECT SEJ_ID, MIN(CHGNVE_seq) AS CHGNVE_seq_entree
                            FROM w_CHGNVE
                            GROUP BY 1
                            ) subview ON w_CJ_SEJOUR_select.SEJ_ID = subview.SEJ_ID
                    WHERE w_CJ_SEJOUR_select.SEJ_ID = w_CHGNVE.SEJ_ID AND
                        w_CHGNVE.CHGNVE_seq = CHGNVE_seq_entree;

                    UPDATE w_CHGNVE SET
                        q_sortie = '1'
                    FROM w_CJ_SEJOUR_select
                        JOIN (
                            SELECT SEJ_ID, MAX(CHGNVE_seq) AS CHGNVE_seq_sortie
                            FROM w_CHGNVE
                            GROUP BY 1
                            ) subview ON w_CJ_SEJOUR_select.SEJ_ID = subview.SEJ_ID
                    WHERE w_CJ_SEJOUR_select.SEJ_ID = w_CHGNVE.SEJ_ID AND
                        w_CHGNVE.CHGNVE_seq = CHGNVE_seq_sortie;


                    
                    UPDATE w_CHGNVE SET
                        CHGNVE_DATE_HEURE_FIN = w_CHGNVE_apres.CHGNVE_DATE_HEURE - interval '1 second',
                        CHGNVE_DATE_FIN = date(w_CHGNVE_apres.CHGNVE_DATE_HEURE - interval '1 second'),
                        CHGNVE_HEURE_FIN = w_CHGNVE_apres.CHGNVE_DATE_HEURE - interval '1 second'-date_trunc('day',w_CHGNVE_apres.CHGNVE_DATE_HEURE - interval '1 second')
                    FROM w_CHGNVE w_CHGNVE_apres
                    WHERE w_CHGNVE.SEJ_ID = w_CHGNVE_apres.SEJ_ID AND
                        w_CHGNVE.CHGNVE_seq = w_CHGNVE_apres.CHGNVE_seq - 1;

                    UPDATE w_CHGNVE SET
                        CHGNVE_DATE_HEURE_FIN = SEJ_DTHR_SORTIE,
                        CHGNVE_DATE_FIN = date(SEJ_DTHR_SORTIE),
                        CHGNVE_HEURE_FIN = SEJ_DTHR_SORTIE-date_trunc('day',SEJ_DTHR_SORTIE)
                    FROM w_CJ_SEJOUR_select
                        JOIN (
                            SELECT SEJ_ID, MAX(CHGNVE_seq) AS CHGNVE_seq_sortie
                            FROM w_CHGNVE
                            GROUP BY 1
                            ) subview ON w_CJ_SEJOUR_select.SEJ_ID = subview.SEJ_ID
                    WHERE w_CJ_SEJOUR_select.SEJ_ID = w_CHGNVE.SEJ_ID AND
                        w_CHGNVE.CHGNVE_seq = CHGNVE_seq_sortie;



                    UPDATE w_CHGNVE SET
                        NVE_SAD_apres = w_CHGNVE_apres.NVE_SAD,
                        NVE_ETA_apres = w_CHGNVE_apres.NVE_ETA,
                        NVE_UF_apres = w_CHGNVE_apres.NVE_UF,
                        NVE_UM_apres = w_CHGNVE_apres.NVE_UM
                    FROM w_CHGNVE w_CHGNVE_apres
                    WHERE w_CHGNVE.SEJ_ID = w_CHGNVE_apres.SEJ_ID AND
                        w_CHGNVE.CHGNVE_seq = w_CHGNVE_apres.CHGNVE_seq - 1;

                    UPDATE w_CHGNVE SET
                        NVE_SAD_avant = w_CHGNVE_avant.NVE_SAD,
                        NVE_ETA_avant = w_CHGNVE_avant.NVE_ETA,
                        NVE_UF_avant = w_CHGNVE_avant.NVE_UF,
                        NVE_UM_avant = w_CHGNVE_avant.NVE_UM
                    FROM w_CHGNVE w_CHGNVE_avant
                    WHERE w_CHGNVE.SEJ_ID = w_CHGNVE_avant.SEJ_ID AND
                        w_CHGNVE.CHGNVE_seq = w_CHGNVE_avant.CHGNVE_seq + 1;




                        
                    INSERT INTO activite[PX].t_lieux(
                                code_original_1, code_original_2, code_original_3, code_original_4, code_original_5, code_original_6)
                    SELECT NVE_SAD, '', NVE_ETA, NVE_LIT, NVE_UM , NVE_UF
                    FROM w_CHGNVE
                        LEFT JOIN activite[PX].t_lieux ON (
                            code_original_1 = NVE_SAD AND
                            code_original_2 = '' AND
                            code_original_3 = NVE_ETA AND
                            code_original_4 = NVE_LIT AND
                            code_original_5 = NVE_UM AND
                            code_original_6 = NVE_UF
                        )
                    WHERE t_lieux.oid IS NULL
                    GROUP BY 1,2,3,4,5,6;


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

                    UPDATE activite[PX].t_lieux SET
                        unite_medicale_id = COALESCE(t_unites_medicales.oid,0)
                    FROM
                        activite[PX].t_unites_medicales
                    WHERE code_original_5 = t_unites_medicales.code_original
                        AND unite_medicale_id <> COALESCE(t_unites_medicales.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)
                        ;


                    UPDATE w_CHGNVE SET
                        lieu_id = t_lieux.oid,
                        chambre_particuliere = t_lits.chambre_particuliere
                    FROM activite[PX].t_lieux
                    JOIN activite[PX].t_lits ON lit_id = t_lits.oid
                    WHERE code_original_1 = NVE_SAD AND
                        code_original_2 = '' AND
                        code_original_3 = NVE_ETA AND
                        code_original_4 = NVE_LIT AND
                        code_original_5 = NVE_UM AND
                        code_original_6 = NVE_UF;

                    DROP TABLE IF EXISTS w_CHGNVE_sortie;
                    CREATE TEMP TABLE w_CHGNVE_sortie AS
                    SELECT
                        w_CJ_SEJOUR_select.SEJ_ID,
                        COALESCE((MAX(Array[CHGNVE_seq,lieu_id]))[2],0) AS lieu_sortie_id,
                        COALESCE((MAX(Array[to_char(CHGNVE_seq,'FM000000000000'),NVE_MTR]))[2],'') AS MTR_LIBC,
                        COALESCE((MAX(Array[to_char(CHGNVE_seq,'FM000000000000'),NVE_DMT]))[2],'') AS DMT_LIBC,
                        ''::text AS type_sejour_force
                    FROM w_CJ_SEJOUR_select
                    LEFT JOIN w_CHGNVE ON w_CJ_SEJOUR_select.SEJ_ID = w_CHGNVE.SEJ_ID
                    GROUP BY 1;

                    UPDATE w_CHGNVE_sortie SET
                        type_sejour_force = CASE WHEN t_services_facturation.type_sejour IN ('1','2','3','5','6', '9', '31') THEN t_services_facturation.type_sejour ELSE '' END,
                        MTR_LIBC = CASE WHEN t_modes_traitement.code <> MTR_LIBC AND t_services_facturation.mode_traitement_id <> 0 THEN t_modes_traitement.code ELSE MTR_LIBC END,
                        DMT_LIBC = CASE WHEN t_dmt.code <> DMT_LIBC AND t_services_facturation.dmt_id <> 0 THEN t_dmt.code ELSE dmt_LIBC END
                    FROM activite[PX].t_lieux 
                    JOIN activite[PX].t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid
                    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 lieu_sortie_id = t_lieux.oid AND
                        (
                        t_services_facturation.type_sejour IN ('1','2','3','5','6','9','31') AND type_sejour_force = '' OR
                        t_modes_traitement.code <> MTR_LIBC AND t_services_facturation.mode_traitement_id <> 0 OR
                        t_dmt.code <> DMT_LIBC AND t_services_facturation.dmt_id <> 0
                        )
                        
                        ;



                    UPDATE w_CJ_SEJOUR_select
                    SET medecin_sejour_id = subview.medecin_sejour_id
                    FROM
                    (
                        SELECT w_CJ_SEJOUR_select.SEJ_ID, 
                            (MAX(ARRAY[CASE WHEN SPE_LIBC = '02' THEN '0' ELSE '1' END || SEJPRA_DATE::text,w_CJ_PRA.medecin_administratif_id::text]))[2]::bigint AS medecin_sejour_id
                        FROM w_CJ_SEJOUR_select
                        JOIN prod_cegi.CJ_SEJPRA ON w_CJ_SEJOUR_select.SEJ_ID = CJ_SEJPRA.SEJ_ID AND SEJPRA_QUALITE = 'R'
                        JOIN w_CJ_PRA ON CJ_SEJPRA.PRA_ID = w_CJ_PRA.PRA_ID
                        GROUP BY 1
                        ORDER BY 1
                    ) subview
                    WHERE w_CJ_SEJOUR_select.SEJ_ID = subview.SEJ_ID;


                    DROP TABLE IF EXISTS w_sejours;
                    CREATE TEMP TABLE w_sejours AS
                    SELECT 
                        w_CJ_SEJOUR_select.SEJ_NUMDOS as no_sejour, 
                        w_CJ_SEJOUR_select.SEJ_NUMDOS as code_original, 
                        COALESCE(no_patient,'W' || w_CJ_SEJOUR_select.SEJ_NUMDOS) as no_patient, 
                        date(SEJ_DTHR_ENTREE) as date_entree, 
                        date_part('hour', SEJ_DTHR_ENTREE)*10000 + date_part('minute', SEJ_DTHR_ENTREE)*100 as heure_entree, 
                        date(SEJ_DTHR_SORTIE) as date_sortie, 
                        date_part('hour', SEJ_DTHR_SORTIE)*10000 + date_part('minute', SEJ_DTHR_SORTIE)*100 as heure_sortie, 
                        CASE WHEN PAT_SEXE IN ('F', '2') THEN '2' ELSE '1' END as code_sexe,
                        0 AS age, 
                        CASE WHEN SEJ_DTHR_SORTIE IS NOT NULL AND SEJ_DTHR_SORTIE < '20991231' AND SEJ_DTHR_SORTIE <= (SELECT MAX(SEJ_MODIF_DH) FROM prod_cegi.CJ_SEJOUR) THEN 1 ELSE 0 END::numeric as code_sorti, 
                        CASE WHEN SEJ_RESA = 1 OR w_CJ_SEJOUR_select.SEJ_NUMDOS LIKE 'R%' OR SEJ_DTHR_ENTREE > now() THEN 1::numeric ELSE 0::numeric END AS code_prevu,
                        CASE 
                            WHEN SEJ_ACTIF <> 1 THEN '9'
                            WHEN trim(t_divers_CEGIFIRST_TDI.valeur) <> '' AND TYD_LIBC <> '' AND TYD_LIBC = ANY(string_to_array(replace(t_divers_CEGIFIRST_TDI.valeur,' ',''),',')) THEN '9'
                            WHEN type_sejour_force IN ('1','2','3','5','6','9') THEN type_sejour_force
                            WHEN type_sejour_force = '31' AND date(SEJ_DTHR_SORTIE) - date(SEJ_DTHR_ENTREE) > 1 THEN '1'
                            WHEN type_sejour_force = '31' THEN '3'
                            WHEN w_CHGNVE_sortie.MTR_LIBC IN ('03') AND date(SEJ_DTHR_ENTREE) = date(SEJ_DTHR_SORTIE) THEN '2' 
                            WHEN w_CHGNVE_sortie.MTR_LIBC IN ('03') THEN '1' 
                            WHEN w_CHGNVE_sortie.MTR_LIBC IN ('07') THEN '3' 
                            WHEN w_CHGNVE_sortie.MTR_LIBC IN ('19') AND w_CHGNVE_sortie.DMT_LIBC IN ('302') THEN '5' 
                            WHEN w_CHGNVE_sortie.MTR_LIBC IN ('07') OR w_CHGNVE_sortie.DMT_LIBC IN ('958') THEN '3' 
                            WHEN w_CHGNVE_sortie.MTR_LIBC IN ('19', '23') AND date(SEJ_DTHR_ENTREE) = date(SEJ_DTHR_SORTIE) THEN '2' 
                            WHEN w_CHGNVE_sortie.MTR_LIBC IN ('04') AND date(SEJ_DTHR_ENTREE) = date(SEJ_DTHR_SORTIE) THEN '2' 
                            WHEN w_CHGNVE_sortie.MTR_LIBC IN ('03') AND date(SEJ_DTHR_ENTREE) = date(SEJ_DTHR_SORTIE) THEN '2' 
                            WHEN w_CHGNVE_sortie.MTR_LIBC IN ('03') THEN '1' 
                            WHEN date(SEJ_DTHR_ENTREE) = date(SEJ_DTHR_SORTIE) THEN '2' 
                            ELSE '1' END as type_sejour,
                        w_CHGNVE_sortie.lieu_sortie_id AS lieu_sortie_id,
                        w_CJ_SEJOUR_select.medecin_sejour_id AS medecin_sejour_id,
                        COALESCE(w_RSS.ghs_id,0) AS ghs_id,
                        COALESCE(w_RSS.ghm_id,0) AS ghm_id,
                        0::numeric AS ghs_bebe1_id,
                        0::numeric AS ghs_bebe2_id,
                        0::numeric AS ghs_bebe3_id,
                        COALESCE(DT_ENV_ADM,'20991231') AS date_groupage,
                        CASE WHEN SEJ_CP = '1' AND cegi_demande_cp = 1 THEN '1' ELSE '0' END::text AS code_cp_demandee,
                        w_CJ_SEJOUR_select.mode_traitement_id,
                        w_CJ_SEJOUR_select.mode_entree AS mode_entree,
                        COALESCE(w_RSS.C_PROV, w_CJ_SEJOUR_select.provenance) AS provenance,
                        w_CJ_SEJOUR_select.mode_sortie as mode_sortie,
                        COALESCE(w_RSS.C_DEST, w_CJ_SEJOUR_select.destination ) as destination,
                        w_CJ_SEJOUR_select.tiers_payant_0_id,
                        w_CJ_SEJOUR_select.tiers_payant_1_id,
                        w_CJ_SEJOUR_select.tiers_payant_2_id,
                        0::bigint AS tiers_payant_22_id,
                        0::bigint AS est_budget_global,
                        w_CJ_SEJOUR_select.code_postal_id
                    FROM w_CJ_SEJOUR_select
						JOIN activite.t_divers t_divers_CEGIFIRST_TDI ON t_divers_CEGIFIRST_TDI.code = 'CEGIFIRST_TDI'
                        LEFT JOIN w_CHGNVE_sortie ON w_CJ_SEJOUR_select.SEJ_ID = w_CHGNVE_sortie.SEJ_ID
                        LEFT JOIN w_RSS ON w_CJ_SEJOUR_select.SEJ_ID = w_RSS.SEJ_ID
                        LEFT JOIN w_CJ_PATIENT ON w_CJ_SEJOUR_select.PAT_ID = w_CJ_PATIENT.PAT_ID AND w_CJ_SEJOUR_select.SEJ_NUMDOS = w_CJ_PATIENT.SEJ_NUMDOS
						LEFT JOIN (SELECT count(*) AS cegi_demande_cp FROM activite.t_divers WHERE t_divers.code = 'ENCOURSVALOCP' AND valeur = '1') sub ON 1=1;
                        
                        
                    -- 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');
						
					-- Code CP demandée selon CJ_GSH
					-- On ne peut préfixer t_rubriques_facturation car liste sur environnement fusionné uniquement
					UPDATE w_sejours p_sejours
					SET code_cp_demandee = '1'
					FROM prod_cegi.CJ_GSH
					JOIN prod_cegi.CJ_SEJOUR ON CJ_GSH.SEJ_ID = CJ_SEJOUR.SEJ_ID
					JOIN prod_cegi.CJ_PST ON CJ_GSH.PST_ID = CJ_PST.PST_ID
					JOIN activite.t_rubriques_facturation ON 
						CJ_PST.PST_LIBC = t_rubriques_facturation.code_original OR
						'CJ_'||CJ_PST.PST_LIBC ILIKE t_rubriques_facturation.code_original
					JOIN activite.t_listes_contenu ON t_rubriques_facturation.oid = to_id
					JOIN activite.t_listes ON liste_id = t_listes.oid
					WHERE SEJ_NUMDOS = p_sejours.no_sejour  AND
						t_listes.code = 'CTI_SHO_R' AND
						p_sejours.code_cp_demandee <> '1' AND
						code_prevu <> '1' 
					;
                        
                        

                    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
                        provider_id = 0, 
                        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
                    FROM w_sejours
                    WHERE w_sejours.no_sejour = p_sejours.no_sejour
                    AND (
                        p_sejours.provider_id IS DISTINCT FROM 0 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
                    );      


                    INSERT INTO activite[PX].p_sejours (
                        no_sejour, 
                        provider_id,
                        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
                    ) 
                    SELECT 
                        w_sejours.no_sejour, 
                        0::bigint AS provider_id,
                        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

                    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;


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

                    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
                        '' = '';
                    
                    -- 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
                        '' = '';
                    
					-- 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 
						FNS_FINESS,
						FNS_NOM,
						FNS_NOM
					FROM prod_cegi.CJ_FINESS 
					WHERE FNS_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,
						MAX(COALESCE(provenance.oid,0)),
						MAX(COALESCE(destination.oid,0))
					FROM
						activite[PX].p_sejours
						JOIN prod_cegi.CJ_SEJOUR ON SEJ_NUMDOS = no_sejour AND
							SEJ_UAGE <> ''
						LEFT JOIN prod_cegi.CJ_FINESS CJ_FINESS_ENT ON FNS_ID_ENT = CJ_FINESS_ENT.FNS_ID
						LEFT JOIN prod_cegi.CJ_FINESS CJ_FINESS_SOR ON FNS_ID_SOR = CJ_FINESS_SOR.FNS_ID
						LEFT JOIN base.t_etablissements provenance ON CJ_FINESS_ENT.FNS_FINESS = provenance.code
						LEFT JOIN base.t_etablissements destination ON CJ_FINESS_SOR.FNS_FINESS = destination.code
					WHERE 1!=1 OR
						FNS_ID_ENT NOT IN (0,10000) OR
						FNS_ID_SOR NOT IN (0,10000)
                    GROUP BY p_sejours.oid					            
					;
					
					-- Assurance
					SELECT base.cti_execute('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,
						MAX(PASS_NOM) AS nom_assure, 
						MAX(PASS_PRENOM) prenom_assure,
						MAX(p_sejours.tiers_payant_0_id),
						MAX(p_sejours.tiers_payant_1_id),
						MAX(substr(PASS_NUMSS,1,13)) AS matricule_1,
						MAX(p_sejours.tiers_payant_2_id),
						MAX(CASE WHEN AMC_NUMERO <> '''' THEN AMC_NUMERO ELSE substr(PASS_NUMSS,1,13) END) AS matricule_2,
						MAX(p_sejours.tiers_payant_22_id),
						''''::text AS matricule_22
					FROM prod_cegi.PAMLF_SEJ
					JOIN w_CJ_SEJOUR_select ON w_CJ_SEJOUR_select.SEJ_ID = PAMLF_SEJ.SEJ_ID
					JOIN activite[PX].p_sejours ON code_original = w_CJ_SEJOUR_select.SEJ_NUMDOS
					GROUP BY 1
					',1)
					WHERE (SELECT count(*) FROM information_schema.tables WHERE table_name = 'PAMLF_SEJ' 
						AND TABLE_SCHEMA = 'prod_cegi') > 0
					;

					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,
						MAX(PER_NOM) AS nom_assure, 
						MAX(PER_PRENOM) prenom_assure,
						MAX(p_sejours.tiers_payant_0_id),
						MAX(p_sejours.tiers_payant_1_id),
						MAX(substr(AFF_NUMERO,1,13)) AS matricule_1,
						MAX(p_sejours.tiers_payant_2_id),
						MAX(substr(AFF_NUMERO,1,13)) AS matricule_2,
						MAX(p_sejours.tiers_payant_22_id),
						''::text AS matricule_22
					FROM prod_cegi.CJ_AFF
						JOIN prod_cegi.CJ_PATIENT ON CJ_PATIENT.PAT_ID = CJ_AFF.PAT_ID
						JOIN w_CJ_SEJOUR_select ON w_CJ_SEJOUR_select.SEJ_ID = CJ_AFF.SEJ_ID
						JOIN activite[PX].p_sejours ON code_original = w_CJ_SEJOUR_select.SEJ_NUMDOS
					WHERE p_sejours.oid NOT IN (SELECT sejour_id FROM activite[PX].p_sejours_assurance)
					GROUP BY 1
					;

					            
                ]]></sqlcmd>
            </NODE>
            
            <NODE label="Mouvements">
                <sqlcmd><![CDATA[

                    DROP TABLE IF EXISTS w_mouvements_sejour;

                    CREATE TEMP TABLE w_mouvements_sejour AS
                    SELECT 
                        SEJ_ID,
                        SEJ_NUMDOS AS no_sejour,
                        p_sejours.oid AS sejour_id,
                        CHGNVE_seq,
                        p_calendrier.date, 
                        p_calendrier.jour_semaine,
                        p_calendrier.is_weekend,
                        CASE WHEN p_calendrier.date = date(CHGNVE_DATE_HEURE) THEN extract('hour' from CHGNVE_DATE_HEURE) * 10000 + extract('minute' from CHGNVE_DATE_HEURE) * 100 + extract('second' from CHGNVE_DATE_HEURE) ELSE 0 END AS heure_debut,
                        CASE WHEN p_calendrier.date = date(CHGNVE_DATE_HEURE_FIN) THEN extract('hour' from CHGNVE_DATE_HEURE_FIN) * 10000 + extract('minute' from CHGNVE_DATE_HEURE_FIN) * 100 + extract('second' from CHGNVE_DATE_HEURE_FIN) ELSE 240000 END AS heure_fin,
                        CASE WHEN q_entree = '1' AND p_calendrier.date =  p_sejours.date_entree AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_entrees_directes,
                        CASE WHEN q_sortie = '1' AND p_calendrier.date =  p_sejours.date_sortie AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_sorties_directes,
                        CASE WHEN q_entree = '1' AND p_calendrier.date =  p_sejours.date_entree AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_entree,
                        CASE WHEN q_sortie = '1' AND p_calendrier.date =  p_sejours.date_sortie AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_sortie,
                        CASE WHEN p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_hospitalisation,
                        CASE WHEN q_entree = '1' AND p_calendrier.date =  p_sejours.date_entree AND p_sejours.type_sejour = '2' THEN 1 ELSE 0 END AS nb_ambulatoires,
                        CASE WHEN q_entree = '1' AND p_calendrier.date =  p_sejours.date_entree AND p_sejours.type_sejour = '3' THEN 1 ELSE 0 END AS nb_externes,
                        CASE WHEN NVE_DMT IN ('401', '402', '403', '404', '405', '406', '407', '408', '409') AND p_calendrier.date =  p_sejours.date_entree AND q_entree = '1' THEN 1 ELSE 0 END AS nb_urgences,
                        0 as nb_seances,

                        CASE WHEN p_calendrier.date = date(CHGNVE_DATE_HEURE) AND p_sejours.type_sejour = '1' AND q_entree <> '1' AND w_CHGNVE.NVE_SAD <> NVE_SAD_avant THEN 1 ELSE 0 END AS nb_entrees_mutation_service,
                        CASE WHEN p_calendrier.date = date(CHGNVE_DATE_HEURE_FIN) AND p_sejours.type_sejour = '1' AND q_sortie <> '1' AND w_CHGNVE.NVE_SAD <> NVE_SAD_apres THEN 1 ELSE 0 END AS nb_sorties_mutation_service,
                        CASE WHEN p_calendrier.date = date(CHGNVE_DATE_HEURE) AND p_sejours.type_sejour = '1' AND q_entree <> '1' AND w_CHGNVE.NVE_ETA <> NVE_ETA_avant THEN 1 ELSE 0 END AS nb_entrees_mutation_etage,
                        CASE WHEN p_calendrier.date = date(CHGNVE_DATE_HEURE_FIN) AND p_sejours.type_sejour = '1' AND q_sortie <> '1' AND w_CHGNVE.NVE_ETA <> NVE_ETA_apres THEN 1 ELSE 0 END AS nb_sorties_mutation_etage,
                        0 AS nb_entrees_mutation_activite,
                        0 AS nb_sorties_mutation_activite,
                        CASE WHEN p_calendrier.date = date(CHGNVE_DATE_HEURE) AND p_sejours.type_sejour = '1' AND q_entree <> '1' AND w_CHGNVE.NVE_UM <> NVE_UM_avant THEN 1 ELSE 0 END AS nb_entrees_mutation_unite_medicale,
                        CASE WHEN p_calendrier.date = date(CHGNVE_DATE_HEURE_FIN) AND p_sejours.type_sejour = '1' AND q_sortie <> '1' AND w_CHGNVE.NVE_UM <> w_CHGNVE.NVE_UM_apres THEN 1 ELSE 0 END 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 <> p_sejours.date_sortie THEN 1 ELSE 0 END AS nb_jours_js_non_inclus,

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

                        0 AS nb_bebes,

                        w_CHGNVE.lieu_id,

                        p_sejours.medecin_sejour_id as medecin_sejour_id

                    FROM w_CHGNVE
                        JOIN activite[PX].p_sejours ON w_CHGNVE.SEJ_NUMDOS = p_sejours.code_original AND p_sejours.etat = ''
                        JOIN base.p_calendrier ON (p_calendrier.date BETWEEN date(CHGNVE_DATE_HEURE) AND date(CHGNVE_DATE_HEURE_FIN) AND p_calendrier.date <= now() )
                    WHERE p_sejours.code_prevu <> 1
                    ORDER BY CHGNVE_seq, p_calendrier.date;

                    
                    -- bébés
                    DROP TABLE IF EXISTS w_LSCCAM_bebes;
                    
                    CREATE TEMP TABLE w_LSCCAM_bebes AS
                    SELECT 
                        SEJ_NUMDOS,
                        MAX(CASE WHEN t_actes.texte ILIKE '%multiple%' THEN 2 ELSE 1 END) AS nb_bebes
                    FROM w_CJ_SEJOUR_select
                        JOIN prod_cegi.CJ_LSRGP ON CJ_LSRGP.SEJ_ID = w_CJ_SEJOUR_select.SEJ_ID AND LSR_ACTIF = 1
                        JOIN prod_cegi.CJ_LSCCAM ON CJ_LSCCAM.LSR_ID = CJ_LSRGP.LSR_ID AND LSCA_ACTIF = 1
                        JOIN prod_cegi.CJ_CCAM ON CJ_CCAM.CCAM_ID = CJ_LSCCAM.CCAM_ID AND CCAM_ACTV = '1'
                        JOIN base.t_actes ON t_actes.code = substring(CCAM_CODE, 1, 7) AND 
                            CCAM_CODE LIKE 'JQG%' AND 
                            t_actes.texte ILIKE 'accouchement%' 
                    GROUP BY 1;

                    CREATE INDEX w_LSCCAM_bebes_i1
                      ON w_LSCCAM_bebes
                      USING btree
                      (SEJ_NUMDOS);

                    UPDATE w_mouvements_sejour 
                    SET nb_bebes = w_LSCCAM_bebes.nb_bebes
                    FROM w_LSCCAM_bebes 
                    WHERE SEJ_NUMDOS = w_mouvements_sejour.no_sejour AND
                        (nb_entrees_directes = 1 OR nb_externes = 1 OR nb_ambulatoires = 1);
                        

                    -- Séances d'après les actes
                    DROP TABLE IF EXISTS w_CJ_LCS_seances;
                    
                    CREATE TEMP TABLE w_CJ_LCS_seances AS
                    SELECT 
                        p_sejours.no_sejour,
                        date(LCS_DT_DEB) AS date,
                        CASE WHEN SUM(CASE WHEN LCS_TTC < 0 AND LCS_QTE > 0 THEN 0 - LCS_QTE ELSE LCS_QTE END) > 0 THEN 1 ELSE 0 END AS nb_seances
                    FROM prod_cegi.CJ_LCS
                    JOIN prod_cegi.CJ_SEJOUR ON CJ_SEJOUR.SEJ_ID = CJ_LCS.SEJ_ID
                    JOIN activite[PX].p_sejours ON SEJ_NUMDOS = p_sejours.code_original
                    LEFT JOIN base.t_ghm ON p_sejours.ghm_id = t_ghm.oid
                    WHERE LCS_SEJHON = 1 AND
                        LCS_CODE = 'K' AND
                        (
                        LCS_COEFF = 15 OR
                        t_ghm.code LIKE '28%'
                        ) 
                    GROUP BY 1,2
                    ;

                    CREATE INDEX w_CJ_LCS_seances_i1
                      ON w_CJ_LCS_seances
                      USING btree
                      (no_sejour);
                      
                    UPDATE w_mouvements_sejour
                    SET nb_seances = w_CJ_LCS_seances.nb_seances
                    FROM w_CJ_LCS_seances
                    WHERE w_CJ_LCS_seances.no_sejour = w_mouvements_sejour.no_sejour AND 
                        w_CJ_LCS_seances.date = w_mouvements_sejour.date AND
                        w_mouvements_sejour.nb_seances <> w_CJ_LCS_seances.nb_seances;
						
					-- Séances d'après les ghs chimio
                    DROP TABLE IF EXISTS w_CJ_LCS_seances;
                    
                    CREATE TEMP TABLE w_CJ_LCS_seances AS
                    SELECT 
                        p_sejours.no_sejour,
                        date(LCS_DT_DEB) AS date,
                        CASE WHEN SUM(CASE WHEN LCS_TTC < 0 AND LCS_QTE > 0 THEN 0 - LCS_QTE ELSE LCS_QTE END) > 0 THEN 1 ELSE 0 END AS nb_seances
                    FROM prod_cegi.CJ_LCS
                    JOIN prod_cegi.CJ_SEJOUR ON CJ_SEJOUR.SEJ_ID = CJ_LCS.SEJ_ID
                    JOIN activite[PX].p_sejours ON SEJ_NUMDOS = p_sejours.code_original
                    WHERE LCS_SEJHON = 0 AND
                        LCS_CODE = 'GHS' AND
                        LCS_GHS = '9606'
                    GROUP BY 1,2
                    HAVING SUM(CASE WHEN LCS_TTC < 0 AND LCS_QTE > 0 THEN 0 - LCS_QTE ELSE LCS_QTE END) > 0
                    ;

                    CREATE INDEX w_CJ_LCS_seances_i1
                      ON w_CJ_LCS_seances
                      USING btree
                      (no_sejour);
                      
                    UPDATE w_mouvements_sejour
                    SET nb_seances = w_CJ_LCS_seances.nb_seances
                    FROM w_CJ_LCS_seances
                    WHERE w_CJ_LCS_seances.no_sejour = w_mouvements_sejour.no_sejour AND 
                        w_CJ_LCS_seances.date = w_mouvements_sejour.date AND
                        w_mouvements_sejour.nb_seances <> w_CJ_LCS_seances.nb_seances;
                        
                        
                    -- Séjours sans séances trouvées dans les actes 
                    DROP TABLE IF EXISTS w_sejours_sans_seance;
                    CREATE TEMP TABLE w_sejours_sans_seance AS 
                    SELECT p_sejours.no_sejour, date_entree, heure_entree 
                        FROM activite[PX].p_sejours
                        LEFT JOIN w_mouvements_sejour ON p_sejours.no_sejour = w_mouvements_sejour.no_sejour and nb_seances > 0
                        WHERE p_sejours.type_sejour = 5 AND w_mouvements_sejour.no_sejour IS NULL;

                    UPDATE w_mouvements_sejour
                    SET nb_seances = 1 
                    FROM w_sejours_sans_seance
                    WHERE w_mouvements_sejour.no_sejour = w_sejours_sans_seance.no_sejour AND
                        w_mouvements_sejour.date = w_sejours_sans_seance.date_entree AND
                        w_mouvements_sejour.heure_debut = w_sejours_sans_seance.heure_entree;
                        
                    
                    -- 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(
                                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, jour_semaine, is_weekend)
                    SELECT 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, jour_semaine, is_weekend
                    FROM w_mouvements_sejour 
                    ORDER BY no_sejour, CHGNVE_seq;
                    
                    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>
    
    </NODE>

    <NODE name="FACTURE" label="RECUPERATION DES FACTURES">
    
        <NODE label="*LOGHOS*">
        
                <condition><![CDATA[
                "[CEGILOGHOS_PRESENT]" == "OUI"
                    ]]></condition>
        
            <NODE label="Préparation">
                <sqlcmd><![CDATA[

                    
                    DROP TABLE IF EXISTS w_OPERA_FAC_complet CASCADE;
                    CREATE TEMP TABLE w_OPERA_FAC_complet AS
                    SELECT 
                        OPERA_FAC.PERIODE_ANNEE,
                        w_OPERA_ACT_annee.PERIODE_ANNEE AS PERIODE_ANNEE_ACT,
                        OPERA_FAC.NO_FACTURE AS NO_FACTURE_ACT,
                        w_OPERA_REG_annee.PERIODE_ANNEE AS PERIODE_ANNEE_REG,
                        OPERA_FAC.NO_DOSSIER,
                        OPERA_FAC.NO_FACTURE,
                        OPERA_FAC.NO_FACTURE AS NO_FACTURE_REFERENCE,
                        ''::text AS NO_FACTURE_OD_AVOIR,
                        w_OPERA_SEJ_select.CODE_GHS AS GHS,
                        ''::text AS GHS_BEBE1,
                        COALESCE(w_OPERA_ACT_annee.DATE_FACT_DEBUT_PJ,DATE_ENTREE_SEJOUR) AS DATE_FACT_DEBUT,
                        COALESCE(w_OPERA_ACT_annee.DATE_FACT_FIN_PJ,DATE_SORTIE_SEJOUR) AS DATE_FACT_FIN,
                        DATE_CALCUL_FACTURE,
                        DATE_ENVOI_CETELIC_FACT_AMO,
                        DATE_ENVOI_CETELIC_FACT_AMC,
                        NO_LOT_CETELIC_FACT_AMO,
                        NO_LOT_CETELIC_FACT_AMC,
                        MONTANT_FACT_AMO + MONTANT_FACT_AMC + MONTANT_FACT_IPP AS MONTANT_TOTAL_FACTURE,
                        TYPE_FACTURE,
                        CASE WHEN TYPE_FACTURE = 'A' THEN -1 ELSE 1 END AS COEFTF,
                        TIERS_FACT_AMO,
                        TIERS_FACT_AMC,
                        TIERS_FACT_IPP,
                        MONTANT_FACT_AMO,
                        MONTANT_FACT_AMO_CLI AS MONTANT_FACT_AMO_C,
                        MONTANT_FACT_AMO_HON AS MONTANT_FACT_AMO_H,
                        MONTANT_FACT_AMC,
                        MONTANT_FACT_AMC_CLI AS MONTANT_FACT_AMC_C,
                        MONTANT_FACT_AMC_HON AS MONTANT_FACT_AMC_H,
                        MONTANT_FACT_IPP,
                        MONTANT_FACT_IPP_CLI AS MONTANT_FACT_IPP_C,
                        MONTANT_FACT_IPP_HON AS MONTANT_FACT_IPP_H,
                        TOP_FIN_SEJOUR,
                        0::numeric AS MONTANT_REGLEMENT_C,
                        0::numeric AS MONTANT_REGLEMENT_H,
                        0::numeric AS MONTANT_REGLEMENT_AMO_C,
                        0::numeric AS MONTANT_REGLEMENT_AMO_H,
                        0::numeric AS MONTANT_REGLEMENT_AMC_C,
                        0::numeric AS MONTANT_REGLEMENT_AMC_H,
                        0::numeric AS MONTANT_REGLEMENT_IPP_C,
                        0::numeric AS MONTANT_REGLEMENT_IPP_H,
                        '00010101'::date AS DATE_REGLEMENT_MAX,
                        '00010101'::date AS DATE_REGLEMENT_MAX_C,
                        '00010101'::date AS DATE_REGLEMENT_MAX_AMO_C,
                        '00010101'::date AS DATE_REGLEMENT_MAX_AMC_C,
                        '00010101'::date AS DATE_REGLEMENT_MAX_IPP_C,
                        '00010101'::date AS DATE_REGLEMENT_MAX_H,
                        '00010101'::date AS DATE_REGLEMENT_MAX_AMO_H,
                        '00010101'::date AS DATE_REGLEMENT_MAX_AMC_H,
                        '00010101'::date AS DATE_REGLEMENT_MAX_IPP_H,
                        TIERS_FACT_AMO || '|' || 
                        TIERS_FACT_AMC || '|' || 
                        w_OPERA_SEJ_select.CODE_GHS AS key
                    FROM prod_cegiloghos.OPERA_FAC
                        JOIN w_OPERA_SEJ_select ON OPERA_FAC.NO_DOSSIER = w_OPERA_SEJ_select.NO_DOSSIER
                        LEFT JOIN w_OPERA_ACT_annee ON OPERA_FAC.NO_FACTURE = w_OPERA_ACT_annee.NO_FACTURE
                        LEFT JOIN w_OPERA_REG_annee ON OPERA_FAC.NO_FACTURE = w_OPERA_REG_annee.NO_FACTURE;


                    ALTER TABLE w_OPERA_FAC_complet ADD CONSTRAINT w_OPERA_FAC_complet_pkey PRIMARY KEY(NO_FACTURE);




                    CREATE INDEX w_OPERA_FAC_complet_i1
                    ON w_OPERA_FAC_complet
                    USING btree
                    (NO_DOSSIER);

                    CREATE INDEX w_OPERA_FAC_complet_i2
                    ON w_OPERA_FAC_complet
                    USING btree
                    (NO_FACTURE);

                    CREATE INDEX w_OPERA_FAC_complet_i3
                    ON w_OPERA_FAC_complet
                    USING btree
                    (NO_FACTURE_ACT);

                    CREATE INDEX w_OPERA_FAC_complet_i4
                    ON w_OPERA_FAC_complet
                    USING btree
                    (KEY);


                    DROP TABLE IF EXISTS w_OPERA_FAC_references;
                    CREATE TEMP TABLE w_OPERA_FAC_references AS
                    SELECT
                        NO_DOSSIER,
                        MAX(DATE_FACT_FIN) AS DATE_FACT_FIN,
                        (MAX(array[COALESCE(DATE_CALCUL_FACTURE,'20991231')::text,NO_FACTURE]))[2] AS NO_FACTURE_LAST,
                        (MAX(CASE WHEN TYPE_FACTURE = 'F' THEN array[COALESCE(DATE_CALCUL_FACTURE,'20991231')::text,NO_FACTURE] ELSE NULL END))[2] AS NO_FACTURE_REFERENCE_LAST
                    FROM w_OPERA_FAC_complet
                    GROUP BY 1;

                    ALTER TABLE w_OPERA_FAC_references ADD CONSTRAINT w_OPERA_FAC_references_pkey PRIMARY KEY(NO_DOSSIER);


                    UPDATE w_OPERA_FAC_complet
                    SET NO_FACTURE_REFERENCE = COALESCE(NO_FACTURE_REFERENCE_LAST,NO_FACTURE_LAST)
                    FROM w_OPERA_FAC_references
                    WHERE w_OPERA_FAC_references.NO_DOSSIER = w_OPERA_FAC_complet.NO_DOSSIER AND
                        NO_FACTURE_REFERENCE IS DISTINCT FROM COALESCE(NO_FACTURE_REFERENCE_LAST,NO_FACTURE_LAST);
                        
                    UPDATE w_OPERA_FAC_complet
                    SET PERIODE_ANNEE_REG = subview.PERIODE_ANNEE_REG
                    FROM (
                        SELECT NO_DOSSIER, MAX(PERIODE_ANNEE_REG) AS PERIODE_ANNEE_REG
                        FROM w_OPERA_FAC_complet
                        WHERE PERIODE_ANNEE_REG IS NOT NULL OR PERIODE_ANNEE_REG = 0
                        GROUP BY 1) subview
                    WHERE w_OPERA_FAC_complet.NO_DOSSIER = subview.NO_DOSSIER AND
                        (w_OPERA_FAC_complet.PERIODE_ANNEE_REG IS NULL OR
                        w_OPERA_FAC_complet.PERIODE_ANNEE_REG IS NULL);


                    DROP SEQUENCE IF EXISTS w_OPERA_REG_sequence;
                    CREATE TEMP SEQUENCE w_OPERA_REG_sequence;


                    DROP TABLE IF EXISTS w_OPERA_REG_complet;
                    CREATE TEMP TABLE w_OPERA_REG_complet AS
                    SELECT
                        nextval('w_OPERA_REG_sequence'::regclass) AS oid,

                        OPERA_REG.NO_DOSSIER,
                        COALESCE(OPERA_REG.NO_FACTURE,w_OPERA_FAC_complet_ref.NO_FACTURE) AS NO_FACTURE,
                        DATE_REGLEMENT,
                        TYPE_REGLEMENT,
                        MONTANT_REGLEMENT,
                        COALESCE(w_OPERA_FAC_complet.COEFTF,1) AS COEFTF,
                        TIERS_REGLEMENT,
                        TYPE_TIERS_REGLEMENT,
                        COALESCE(t_tiers_payant.type_tiers_payant,'0') AS type_tiers_payant,


                        CASE WHEN TYPE_REGLEMENT = 'S' THEN date(DATE_REGLEMENT) ELSE NULL END AS DATE_REGLEMENT_C,
                        CASE WHEN TYPE_REGLEMENT = 'S' AND TYPE_TIERS_REGLEMENT = 'O' AND TIERS_REGLEMENT = ANY(ARRAY[w_OPERA_FAC_complet.TIERS_FACT_AMO,w_OPERA_FAC_complet_ref.TIERS_FACT_AMO]) THEN date(DATE_REGLEMENT) ELSE NULL END AS DATE_REGLEMENT_AMO_C,
                        CASE WHEN TYPE_REGLEMENT = 'S' AND TYPE_TIERS_REGLEMENT = 'O' AND TIERS_REGLEMENT = ANY(ARRAY[w_OPERA_FAC_complet.TIERS_FACT_AMC,w_OPERA_FAC_complet_ref.TIERS_FACT_AMC]) THEN date(DATE_REGLEMENT) ELSE NULL END AS DATE_REGLEMENT_AMC_C,
                        CASE WHEN TYPE_REGLEMENT = 'S' AND TYPE_TIERS_REGLEMENT = 'A' THEN date(DATE_REGLEMENT) ELSE NULL END AS DATE_REGLEMENT_IPP_C,

                        CASE WHEN TYPE_REGLEMENT = 'S' THEN MONTANT_REGLEMENT ELSE 0 END AS MONTANT_REGLEMENT_C,
                        CASE WHEN TYPE_REGLEMENT = 'S' AND TYPE_TIERS_REGLEMENT = 'O' AND TIERS_REGLEMENT = ANY(ARRAY[w_OPERA_FAC_complet.TIERS_FACT_AMO,w_OPERA_FAC_complet_ref.TIERS_FACT_AMO]) THEN MONTANT_REGLEMENT ELSE 0 END AS MONTANT_REGLEMENT_AMO_C,
                        CASE WHEN TYPE_REGLEMENT = 'S' AND TYPE_TIERS_REGLEMENT = 'O' AND TIERS_REGLEMENT = ANY(ARRAY[w_OPERA_FAC_complet.TIERS_FACT_AMC,w_OPERA_FAC_complet_ref.TIERS_FACT_AMC]) THEN MONTANT_REGLEMENT ELSE 0 END AS MONTANT_REGLEMENT_AMC_C,
                        CASE WHEN TYPE_REGLEMENT = 'S' AND TYPE_TIERS_REGLEMENT = 'A' THEN MONTANT_REGLEMENT ELSE 0 END AS MONTANT_REGLEMENT_IPP_C,

                        CASE WHEN TYPE_REGLEMENT = '1' THEN date(DATE_REGLEMENT) ELSE NULL END AS DATE_REGLEMENT_H,
                        CASE WHEN TYPE_REGLEMENT = '1' AND TYPE_TIERS_REGLEMENT = 'O' AND TIERS_REGLEMENT = ANY(ARRAY[w_OPERA_FAC_complet.TIERS_FACT_AMO,w_OPERA_FAC_complet_ref.TIERS_FACT_AMO]) THEN date(DATE_REGLEMENT) ELSE NULL END AS DATE_REGLEMENT_AMO_H,
                        CASE WHEN TYPE_REGLEMENT = '1' AND TYPE_TIERS_REGLEMENT = 'O' AND TIERS_REGLEMENT = ANY(ARRAY[w_OPERA_FAC_complet.TIERS_FACT_AMC,w_OPERA_FAC_complet_ref.TIERS_FACT_AMC]) THEN date(DATE_REGLEMENT) ELSE NULL END AS DATE_REGLEMENT_AMC_H,
                        CASE WHEN TYPE_REGLEMENT = '1' AND TYPE_TIERS_REGLEMENT = 'A' THEN date(DATE_REGLEMENT) ELSE NULL END AS DATE_REGLEMENT_IPP_H,

                        CASE WHEN TYPE_REGLEMENT = '1' THEN MONTANT_REGLEMENT ELSE 0 END AS MONTANT_REGLEMENT_H,
                        CASE WHEN TYPE_REGLEMENT = '1' AND TYPE_TIERS_REGLEMENT = 'O' AND TIERS_REGLEMENT = ANY(ARRAY[w_OPERA_FAC_complet.TIERS_FACT_AMO,w_OPERA_FAC_complet_ref.TIERS_FACT_AMO]) THEN MONTANT_REGLEMENT ELSE 0 END AS MONTANT_REGLEMENT_AMO_H,
                        CASE WHEN TYPE_REGLEMENT = '1' AND TYPE_TIERS_REGLEMENT = 'O' AND TIERS_REGLEMENT = ANY(ARRAY[w_OPERA_FAC_complet.TIERS_FACT_AMC,w_OPERA_FAC_complet_ref.TIERS_FACT_AMC]) THEN MONTANT_REGLEMENT ELSE 0 END AS MONTANT_REGLEMENT_AMC_H,
                        CASE WHEN TYPE_REGLEMENT = '1' AND TYPE_TIERS_REGLEMENT = 'A' THEN MONTANT_REGLEMENT ELSE 0 END AS MONTANT_REGLEMENT_IPP_H
                    FROM prod_cegiloghos.OPERA_REG 
                        JOIN w_OPERA_FAC_complet w_OPERA_FAC_complet_ref ON OPERA_REG.NO_DOSSIER = w_OPERA_FAC_complet_ref.NO_DOSSIER AND 
                                w_OPERA_FAC_complet_ref.NO_FACTURE_REFERENCE = w_OPERA_FAC_complet_ref.NO_FACTURE AND 
                                OPERA_REG.PERIODE_ANNEE = w_OPERA_FAC_complet_ref.PERIODE_ANNEE_REG
                        LEFT JOIN w_OPERA_FAC_complet ON OPERA_REG.NO_FACTURE = w_OPERA_FAC_complet.NO_FACTURE
                        LEFT JOIN activite.t_tiers_payant ON TIERS_REGLEMENT = t_tiers_payant.code_original AND TYPE_TIERS_REGLEMENT <> 'A'
                    WHERE TYPE_REGLEMENT IN ('1', 'S');

                    ALTER TABLE w_OPERA_REG_complet ADD CONSTRAINT w_OPERA_REG_complet_pkey PRIMARY KEY(oid);

					-- Les affectations au tiers payant ont été resserrés dans la création du fichier
					-- Affectation du reste selon le type de séjour
                    UPDATE w_OPERA_REG_complet SET
						MONTANT_REGLEMENT_IPP_C = MONTANT_REGLEMENT_C,
						DATE_REGLEMENT_IPP_C = DATE_REGLEMENT_C
					WHERE MONTANT_REGLEMENT_C <> 0 AND
						MONTANT_REGLEMENT_AMO_C = 0 AND
						MONTANT_REGLEMENT_AMC_C = 0 AND
						MONTANT_REGLEMENT_IPP_C = 0 AND
						TIERS_REGLEMENT = NO_DOSSIER
					;
					UPDATE w_OPERA_REG_complet SET
						MONTANT_REGLEMENT_AMO_C = MONTANT_REGLEMENT_C,
						DATE_REGLEMENT_AMC_C = DATE_REGLEMENT_C
					WHERE MONTANT_REGLEMENT_C <> 0 AND
						MONTANT_REGLEMENT_AMO_C = 0 AND
						MONTANT_REGLEMENT_AMC_C = 0 AND
						MONTANT_REGLEMENT_IPP_C = 0 AND
						type_tiers_payant = '1'
					;
					UPDATE w_OPERA_REG_complet SET
						MONTANT_REGLEMENT_AMC_C = MONTANT_REGLEMENT_C,
						DATE_REGLEMENT_AMC_C = DATE_REGLEMENT_C
					WHERE MONTANT_REGLEMENT_C <> 0 AND
						MONTANT_REGLEMENT_AMO_C = 0 AND
						MONTANT_REGLEMENT_AMC_C = 0 AND
						MONTANT_REGLEMENT_IPP_C = 0 AND
						type_tiers_payant = '2'
					;
					UPDATE w_OPERA_REG_complet SET
						MONTANT_REGLEMENT_IPP_C = MONTANT_REGLEMENT_C,
						DATE_REGLEMENT_IPP_C = DATE_REGLEMENT_C
					WHERE MONTANT_REGLEMENT_C <> 0 AND
						MONTANT_REGLEMENT_AMO_C = 0 AND
						MONTANT_REGLEMENT_AMC_C = 0 AND
						MONTANT_REGLEMENT_IPP_C = 0 AND
						type_tiers_payant = '0'
					;

					UPDATE w_OPERA_REG_complet SET
						MONTANT_REGLEMENT_IPP_H = MONTANT_REGLEMENT_H,
						DATE_REGLEMENT_IPP_H = DATE_REGLEMENT_H
					WHERE MONTANT_REGLEMENT_H <> 0 AND
						MONTANT_REGLEMENT_AMO_H = 0 AND
						MONTANT_REGLEMENT_AMC_H = 0 AND
						MONTANT_REGLEMENT_IPP_H = 0 AND
						TIERS_REGLEMENT = NO_DOSSIER
					;
					UPDATE w_OPERA_REG_complet SET
						MONTANT_REGLEMENT_AMO_H = MONTANT_REGLEMENT_H,
						DATE_REGLEMENT_AMO_H = DATE_REGLEMENT_H
					WHERE MONTANT_REGLEMENT_H <> 0 AND
						MONTANT_REGLEMENT_AMO_H = 0 AND
						MONTANT_REGLEMENT_AMC_H = 0 AND
						MONTANT_REGLEMENT_IPP_H = 0 AND
						type_tiers_payant = '1'
					;
					UPDATE w_OPERA_REG_complet SET
						MONTANT_REGLEMENT_AMC_H = MONTANT_REGLEMENT_H,
						DATE_REGLEMENT_AMC_H = DATE_REGLEMENT_H
					WHERE MONTANT_REGLEMENT_H <> 0 AND
						MONTANT_REGLEMENT_AMO_H = 0 AND
						MONTANT_REGLEMENT_AMC_H = 0 AND
						MONTANT_REGLEMENT_IPP_H = 0 AND
						type_tiers_payant = '2'
					;
					UPDATE w_OPERA_REG_complet SET
						MONTANT_REGLEMENT_IPP_H = MONTANT_REGLEMENT_H,
						DATE_REGLEMENT_IPP_H = DATE_REGLEMENT_H
					WHERE MONTANT_REGLEMENT_H <> 0 AND
						MONTANT_REGLEMENT_AMO_H = 0 AND
						MONTANT_REGLEMENT_AMC_H = 0 AND
						MONTANT_REGLEMENT_IPP_H = 0 AND
						type_tiers_payant = '0'
					;

                    

                    CREATE INDEX w_OPERA_REG_complet_i1
                    ON w_OPERA_REG_complet
                    USING btree
                    (NO_FACTURE);

                    CREATE INDEX w_OPERA_REG_complet_i2
                    ON w_OPERA_REG_complet
                    USING btree
                    (NO_DOSSIER);

                    UPDATE w_OPERA_REG_complet SET
                        MONTANT_REGLEMENT = MONTANT_REGLEMENT * COEFTF,
                        MONTANT_REGLEMENT_C = MONTANT_REGLEMENT_C * COEFTF,
                        MONTANT_REGLEMENT_AMO_C = MONTANT_REGLEMENT_AMO_C * COEFTF,
                        MONTANT_REGLEMENT_AMC_C = MONTANT_REGLEMENT_AMC_C * COEFTF,
                        MONTANT_REGLEMENT_IPP_C = MONTANT_REGLEMENT_IPP_C * COEFTF,
                        MONTANT_REGLEMENT_H = MONTANT_REGLEMENT_H * COEFTF,
                        MONTANT_REGLEMENT_AMO_H = MONTANT_REGLEMENT_AMO_H * COEFTF,
                        MONTANT_REGLEMENT_AMC_H = MONTANT_REGLEMENT_AMC_H * COEFTF,
                        MONTANT_REGLEMENT_IPP_H = MONTANT_REGLEMENT_IPP_H * COEFTF
                    WHERE MONTANT_REGLEMENT > 0 AND COEFTF < 0;


                    DROP TABLE IF EXISTS w_OPERA_REG_total;
                    CREATE TEMP TABLE w_OPERA_REG_total AS
                    SELECT
                        w_OPERA_FAC_complet.NO_DOSSIER,
                        w_OPERA_FAC_complet.NO_FACTURE,

                        COALESCE(MAX(date(DATE_REGLEMENT)),'00010101') AS DATE_REGLEMENT_MAX,

                        COALESCE(MAX(DATE_REGLEMENT_c),'00010101') AS DATE_REGLEMENT_MAX_C,
                        COALESCE(MAX(DATE_REGLEMENT_AMO_C),'00010101') AS DATE_REGLEMENT_MAX_AMO_C,
                        COALESCE(MAX(DATE_REGLEMENT_AMC_C),'00010101') AS DATE_REGLEMENT_MAX_AMC_C,
                        COALESCE(MAX(DATE_REGLEMENT_IPP_C),'00010101') AS DATE_REGLEMENT_MAX_IPP_C,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_c),0) AS MONTANT_REGLEMENT_C,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_AMO_C),0) AS MONTANT_REGLEMENT_AMO_C,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_AMC_C),0) AS MONTANT_REGLEMENT_AMC_C,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_IPP_C),0) AS MONTANT_REGLEMENT_IPP_C,

                        COALESCE(MAX(DATE_REGLEMENT_h),'00010101') AS DATE_REGLEMENT_MAX_H,
                        COALESCE(MAX(DATE_REGLEMENT_AMO_H),'00010101') AS DATE_REGLEMENT_MAX_AMO_H,
                        COALESCE(MAX(DATE_REGLEMENT_AMC_H),'00010101') AS DATE_REGLEMENT_MAX_AMC_H,
                        COALESCE(MAX(DATE_REGLEMENT_IPP_H),'00010101') AS DATE_REGLEMENT_MAX_IPP_H,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_h),0) AS MONTANT_REGLEMENT_H,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_AMO_H),0) AS MONTANT_REGLEMENT_AMO_H,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_AMC_H),0) AS MONTANT_REGLEMENT_AMC_H,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_IPP_H),0) AS MONTANT_REGLEMENT_IPP_H

                    FROM w_OPERA_FAC_complet
                        LEFT JOIN w_OPERA_REG_complet ON w_OPERA_FAC_complet.NO_FACTURE = w_OPERA_REG_complet.NO_FACTURE
                    GROUP BY 1,2;


                    ALTER TABLE w_OPERA_REG_total ADD CONSTRAINT w_OPERA_REG_total_pkey PRIMARY KEY(NO_FACTURE);

                    UPDATE w_OPERA_FAC_complet SET
                        MONTANT_REGLEMENT_C = w_OPERA_REG_total.MONTANT_REGLEMENT_C,
                        MONTANT_REGLEMENT_H = w_OPERA_REG_total.MONTANT_REGLEMENT_H,
                        MONTANT_REGLEMENT_AMO_C = w_OPERA_REG_total.MONTANT_REGLEMENT_AMO_C,
                        MONTANT_REGLEMENT_AMO_H = w_OPERA_REG_total.MONTANT_REGLEMENT_AMO_H,
                        MONTANT_REGLEMENT_AMC_C = w_OPERA_REG_total.MONTANT_REGLEMENT_AMC_C,
                        MONTANT_REGLEMENT_AMC_H = w_OPERA_REG_total.MONTANT_REGLEMENT_AMC_H,
                        MONTANT_REGLEMENT_IPP_C = w_OPERA_REG_total.MONTANT_REGLEMENT_IPP_C,
                        MONTANT_REGLEMENT_IPP_H = w_OPERA_REG_total.MONTANT_REGLEMENT_IPP_H,
                        DATE_REGLEMENT_MAX = w_OPERA_REG_total.DATE_REGLEMENT_MAX,
                        DATE_REGLEMENT_MAX_C = w_OPERA_REG_total.DATE_REGLEMENT_MAX_C,
                        DATE_REGLEMENT_MAX_AMO_C = w_OPERA_REG_total.DATE_REGLEMENT_MAX_AMO_C,
                        DATE_REGLEMENT_MAX_AMC_C = w_OPERA_REG_total.DATE_REGLEMENT_MAX_AMC_C,
                        DATE_REGLEMENT_MAX_IPP_C = w_OPERA_REG_total.DATE_REGLEMENT_MAX_IPP_C,
                        DATE_REGLEMENT_MAX_H = w_OPERA_REG_total.DATE_REGLEMENT_MAX_H,
                        DATE_REGLEMENT_MAX_AMO_H = w_OPERA_REG_total.DATE_REGLEMENT_MAX_AMO_H,
                        DATE_REGLEMENT_MAX_AMC_H = w_OPERA_REG_total.DATE_REGLEMENT_MAX_AMC_H,
                        DATE_REGLEMENT_MAX_IPP_H = w_OPERA_REG_total.DATE_REGLEMENT_MAX_IPP_H
                    FROM w_OPERA_REG_total
                    WHERE w_OPERA_FAC_complet.NO_FACTURE = w_OPERA_REG_total.NO_FACTURE;



                    
                    

                                


                    DROP TABLE IF EXISTS w_OPERA_REG_total;
                    CREATE TEMP TABLE w_OPERA_REG_total AS
                    SELECT
                        w_OPERA_FAC_complet.NO_DOSSIER,
                        w_OPERA_FAC_complet.NO_FACTURE,

                        COALESCE(MAX(date(DATE_REGLEMENT)),'00010101') AS DATE_REGLEMENT_MAX,

                        COALESCE(MAX(DATE_REGLEMENT_c),'00010101') AS DATE_REGLEMENT_MAX_C,
                        COALESCE(MAX(DATE_REGLEMENT_AMO_C),'00010101') AS DATE_REGLEMENT_MAX_AMO_C,
                        COALESCE(MAX(DATE_REGLEMENT_AMC_C),'00010101') AS DATE_REGLEMENT_MAX_AMC_C,
                        COALESCE(MAX(DATE_REGLEMENT_IPP_C),'00010101') AS DATE_REGLEMENT_MAX_IPP_C,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_c),0) AS MONTANT_REGLEMENT_C,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_AMO_C),0) AS MONTANT_REGLEMENT_AMO_C,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_AMC_C),0) AS MONTANT_REGLEMENT_AMC_C,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_IPP_C),0) AS MONTANT_REGLEMENT_IPP_C,

                        COALESCE(MAX(DATE_REGLEMENT_h),'00010101') AS DATE_REGLEMENT_MAX_H,
                        COALESCE(MAX(DATE_REGLEMENT_AMO_H),'00010101') AS DATE_REGLEMENT_MAX_AMO_H,
                        COALESCE(MAX(DATE_REGLEMENT_AMC_H),'00010101') AS DATE_REGLEMENT_MAX_AMC_H,
                        COALESCE(MAX(DATE_REGLEMENT_IPP_H),'00010101') AS DATE_REGLEMENT_MAX_IPP_H,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_h),0) AS MONTANT_REGLEMENT_H,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_AMO_H),0) AS MONTANT_REGLEMENT_AMO_H,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_AMC_H),0) AS MONTANT_REGLEMENT_AMC_H,
                        COALESCE(SUM(w_OPERA_REG_complet.MONTANT_REGLEMENT_IPP_H),0) AS MONTANT_REGLEMENT_IPP_H

                    FROM w_OPERA_FAC_complet
                        LEFT JOIN w_OPERA_REG_complet ON w_OPERA_FAC_complet.NO_FACTURE = w_OPERA_REG_complet.NO_FACTURE
                    GROUP BY 1,2;

                    UPDATE w_OPERA_FAC_complet SET
                        MONTANT_REGLEMENT_C = w_OPERA_REG_total.MONTANT_REGLEMENT_C,
                        MONTANT_REGLEMENT_H = w_OPERA_REG_total.MONTANT_REGLEMENT_H,
                        MONTANT_REGLEMENT_AMO_C = w_OPERA_REG_total.MONTANT_REGLEMENT_AMO_C,
                        MONTANT_REGLEMENT_AMO_H = w_OPERA_REG_total.MONTANT_REGLEMENT_AMO_H,
                        MONTANT_REGLEMENT_AMC_C = w_OPERA_REG_total.MONTANT_REGLEMENT_AMC_C,
                        MONTANT_REGLEMENT_AMC_H = w_OPERA_REG_total.MONTANT_REGLEMENT_AMC_H,
                        MONTANT_REGLEMENT_IPP_C = w_OPERA_REG_total.MONTANT_REGLEMENT_IPP_C,
                        MONTANT_REGLEMENT_IPP_H = w_OPERA_REG_total.MONTANT_REGLEMENT_IPP_H,
                        DATE_REGLEMENT_MAX = w_OPERA_REG_total.DATE_REGLEMENT_MAX,
                        DATE_REGLEMENT_MAX_C = w_OPERA_REG_total.DATE_REGLEMENT_MAX_C,
                        DATE_REGLEMENT_MAX_AMO_C = w_OPERA_REG_total.DATE_REGLEMENT_MAX_AMO_C,
                        DATE_REGLEMENT_MAX_AMC_C = w_OPERA_REG_total.DATE_REGLEMENT_MAX_AMC_C,
                        DATE_REGLEMENT_MAX_IPP_C = w_OPERA_REG_total.DATE_REGLEMENT_MAX_IPP_C,
                        DATE_REGLEMENT_MAX_H = w_OPERA_REG_total.DATE_REGLEMENT_MAX_H,
                        DATE_REGLEMENT_MAX_AMO_H = w_OPERA_REG_total.DATE_REGLEMENT_MAX_AMO_H,
                        DATE_REGLEMENT_MAX_AMC_H = w_OPERA_REG_total.DATE_REGLEMENT_MAX_AMC_H,
                        DATE_REGLEMENT_MAX_IPP_H = w_OPERA_REG_total.DATE_REGLEMENT_MAX_IPP_H
                    FROM w_OPERA_REG_total
                    WHERE w_OPERA_FAC_complet.NO_FACTURE = w_OPERA_REG_total.NO_FACTURE;






                    UPDATE w_OPERA_FAC_complet SET
                        PERIODE_ANNEE_ACT = w_OPERA_ACT_annee.PERIODE_ANNEE,
                        NO_FACTURE_ACT = w_OPERA_ACT_annee.NO_FACTURE
                    FROM w_OPERA_ACT_annee 
                    WHERE w_OPERA_ACT_annee.NO_DOSSIER = w_OPERA_FAC_complet.NO_DOSSIER AND
                        PERIODE_ANNEE_ACT IS NULL AND
                        w_OPERA_FAC_complet.NO_FACTURE = w_OPERA_FAC_complet.NO_FACTURE_REFERENCE AND
                        w_OPERA_FAC_complet.MONTANT_TOTAL_FACTURE <> 0;



                    DROP SEQUENCE IF EXISTS w_RSF_3_sequence;
                    CREATE TEMP SEQUENCE w_RSF_3_sequence;
        
                    DROP TABLE IF EXISTS w_RSF_3;
                    CREATE TEMP TABLE w_RSF_3 AS 
                    SELECT 
                        nextval('w_RSF_3_sequence'::regclass) AS oid,
                        NO_DOSSIER,
                        FACTURE,
                        base.cti_to_date(D_DEBUT) AS D_DEBUT,
                        base.cti_to_date(D_FIN) AS D_FIN,
                        CASE WHEN ACTE LIKE 'FJ%' THEN 'FJ' ELSE ACTE END AS ACTE,
                        to_number('0' || QTE, '0000000000') AS QTE,
                        round(COEFF::numeric,2) AS COEFF,
                        PEC_FJ,
                        MODUL,
                        PU,
                        BASE,
                        to_number('0' || TX, '0000000000') AS TX,
                        round(DEPENSE::numeric,2) AS DEPENSE,
                        round(MT_CAISSE::numeric,2) AS MT_CAISSE,
                        round(MROC::numeric,2) AS MROC,
                        NULL::bigint AS ACT_sequence
                    FROM prod_cegi.RSF_3
                        JOIN w_OPERA_FAC_complet ON w_OPERA_FAC_complet.NO_FACTURE = RSF_3.FACTURE;

                    ALTER TABLE w_RSF_3 ADD CONSTRAINT w_RSF_3_pkey PRIMARY KEY(oid);

                    

                    CREATE INDEX w_RSF_3_i1
                    ON w_RSF_3
                    USING btree
                    (FACTURE);

                    CREATE INDEX w_RSF_3_i2
                    ON w_RSF_3
                    USING btree
                    (NO_DOSSIER);

                    UPDATE w_RSF_3
                    SET DEPENSE = MROC + MT_CAISSE
                    WHERE MROC + MT_CAISSE > DEPENSE;




                    DROP TABLE IF EXISTS w_RUBRIQUES_3;
                    CREATE TEMP TABLE w_RUBRIQUES_3 AS 
                    SELECT CODE_PRESTA AS CODE_RUBRIQUE, 
                        (MAX(array[to_char(count,'FM0000000000'),ACTE]))[2] AS CODE_PRESTA
                    FROM (
                    SELECT CODE_PRESTA, ACTE, count(*) AS count
                    FROM prod_cegiloghos.OPERA_ACT
                    JOIN w_OPERA_FAC_complet ON OPERA_ACT.NO_FACTURE = w_OPERA_FAC_complet.NO_FACTURE AND OPERA_ACT.PERIODE_ANNEE = w_OPERA_FAC_complet.PERIODE_ANNEE_ACT
                    JOIN w_RSF_3 ON OPERA_ACT.NO_FACTURE = w_RSF_3.facture AND OPERA_ACT.MONTANT_ACTE = w_RSF_3.DEPENSE AND
                        TYPE_PRESTA <> 'H' AND 
						CODE_PRESTA NOT IN ('GHS', 'FJ', 'PAT') AND 
						ACTE NOT IN ('GHS', 'FJ', 'PAT') AND 
						ACTE NOT LIKE 'FJ%' AND 
						CODE_PRESTA NOT LIKE 'FJ%'
                    GROUP BY 1,2) subview
                    GROUP BY 1;

                    ALTER TABLE w_RUBRIQUES_3 ADD CONSTRAINT w_RUBRIQUES_3_pkey PRIMARY KEY(CODE_RUBRIQUE);


                    DROP SEQUENCE IF EXISTS w_RSF_4_sequence;
                    CREATE TEMP SEQUENCE w_RSF_4_sequence;

                    DROP TABLE IF EXISTS w_RSF_4;
                    CREATE TEMP TABLE w_RSF_4 AS 
                    SELECT 
                        nextval('w_RSF_4_sequence'::regclass) AS oid,
                        NO_DOSSIER,
                        RSF_4.FACTURE,
                        base.cti_to_date(D_SOINS) AS D_SOINS,
                        ACTE,
                        to_number('0' || QTE, '0000000000') AS QTE,
                        round(COEFF::numeric,2) AS COEFF,
                        round(PU::numeric,2) AS PU,
                        round(BASE::numeric,2) AS BASE,
                        to_number('0' || TX, '0000000000') AS TX,
                        round(MT_HONOR::numeric,2) AS MT_HONOR,
                        round(MT_CAISSE::numeric,2) AS MT_CAISSE,
                        round(MROC::numeric,2) AS MROC,
                        DEPASS,
                        COALESCE(RSF_4M.CODE_ACTE,'') AS CODE_CCAM,
                        COALESCE(RSF_4M.EXTDOC,'') AS EXTDOC,
                        COALESCE(RSF_4M.ACTV,'') AS ACTV,
                        COALESCE(RSF_4M.PHS,'') AS PHS,
                        COALESCE(RSF_4M.MOD1,'') AS MOD1,
                        COALESCE(RSF_4M.MOD2,'') AS MOD2,
                        COALESCE(RSF_4M.MOD3,'') AS MOD3,
                        COALESCE(RSF_4M.MOD4,'') AS MOD4,
                        COALESCE(RSF_4M.ANP,'') AS ANP,
                        COALESCE(RSF_4M.RMBEX,'') AS RMBEX
                    FROM prod_cegi.RSF_4
                        JOIN w_OPERA_FAC_complet ON w_OPERA_FAC_complet.NO_FACTURE = RSF_4.FACTURE
                        LEFT JOIN prod_cegi.RSF_4M ON RSF_4.FACTURE = RSF_4M.FACTURE AND RSF_4.I = RSF_4M.I;


                    CREATE INDEX w_RSF_4_i1
                    ON w_RSF_4
                    USING btree
                    (FACTURE);

                    CREATE INDEX w_RSF_4_i2
                    ON w_RSF_4
                    USING btree
                    (NO_DOSSIER);






                    DROP TABLE IF EXISTS w_RUBRIQUES_4;
                    CREATE TEMP TABLE w_RUBRIQUES_4 AS 
                    SELECT CODE_PRESTA AS CODE_RUBRIQUE, 
                        (MAX(array[to_char(count,'FM0000000000'),ACTE]))[2] AS CODE_PRESTA
                    FROM (
                    SELECT trim(substr(CODE_PRESTA,1,4)) AS CODE_PRESTA, trim(substr(ACTE,1,4)) AS ACTE, count(*) AS count
                    FROM prod_cegiloghos.OPERA_ACT
                    JOIN w_OPERA_FAC_complet ON OPERA_ACT.NO_FACTURE = w_OPERA_FAC_complet.NO_FACTURE AND OPERA_ACT.PERIODE_ANNEE = w_OPERA_FAC_complet.PERIODE_ANNEE_ACT
                    JOIN w_RSF_4 ON OPERA_ACT.NO_FACTURE = w_RSF_4.facture AND OPERA_ACT.MONTANT_ACTE = w_RSF_4.MT_HONOR
                        AND (TYPE_PRESTA = 'H' OR CODE_PRESTA LIKE 'FSD%' )
                    GROUP BY 1,2) subview
                    GROUP BY 1;

                    
                    INSERT INTO w_RUBRIQUES_4
                    SELECT 
                        substr(CODE_RUBRIQUE || '     ',1,4) || 'F', 
                        substr(CODE_PRESTA  || '     ',1,4) || 'F'
                    FROM w_RUBRIQUES_4
                    GROUP BY 1,2
                    UNION
                    SELECT 
                        substr(CODE_RUBRIQUE || '     ',1,4) || 'N', 
                        substr(CODE_PRESTA  || '     ',1,4) || 'N'
                    FROM w_RUBRIQUES_4
                    GROUP BY 1,2;

                    ALTER TABLE w_RUBRIQUES_4 ADD CONSTRAINT w_RUBRIQUES_4_pkey PRIMARY KEY(CODE_RUBRIQUE);



                    
                    DROP TABLE IF EXISTS w_PPRS;
                    CREATE TEMP TABLE W_PPRS AS
                    SELECT OPERA_ACT.CODE_SERVICE_DISCIPLINE, OPERA_ACT.CODE_PRESTA ,
                        MAX(COALESCE(OPERA_PPRS.COMPTE_COMPTABLE, OPERA_PPRS_D.COMPTE_COMPTABLE, '')) AS COMPTE_COMPTABLE,
                        0::bigint AS compte_produit_id
                    from prod_cegiloghos.OPERA_ACT
                    LEFT JOIN prod_cegiloghos.OPERA_PSDISC ON OPERA_ACT.CODE_SERVICE_DISCIPLINE = OPERA_PSDISC.CODE_SERVICE_DISCIPLINE
                    LEFT JOIN prod_cegiloghos.OPERA_PPRS ON
                        OPERA_PSDISC.CODE_SERVICE_TARIFAIRE = OPERA_PPRS.CODE_SERVICE_TARIFAIRE AND
                        OPERA_ACT.CODE_PRESTA = OPERA_PPRS.CODE_PRESTA
                    LEFT JOIN prod_cegiloghos.OPERA_PPRS OPERA_PPRS_D ON
                        OPERA_ACT.CODE_PRESTA = OPERA_PPRS_D.CODE_PRESTA AND
                        OPERA_PPRS_D.CODE_SERVICE_TARIFAIRE = ''
                    GROUP BY 1,2
                    ORDER BY 1,2;

                    UPDATE w_PPRS
                    SET compte_produit_id = t_compte.oid
                    FROM activite[PX].t_compte 
                    WHERE t_compte.code = COMPTE_COMPTABLE AND
						COMPTE_COMPTABLE <> ''
					;


                    DROP SEQUENCE IF EXISTS w_OPERA_ACT_sequence;
                    CREATE TEMP SEQUENCE w_OPERA_ACT_sequence;

                    DROP TABLE IF EXISTS w_OPERA_ACT_complet CASCADE;
                    CREATE TEMP TABLE w_OPERA_ACT_complet AS
                    SELECT 
                        nextval('w_OPERA_ACT_sequence'::regclass) AS oid,
                        DATE_ACTE_DEBUT,
                        DATE_ACTE_FIN,
                        HEURE_ACTE_DEBUT,
                        HEURE_ACTE_FIN,
                        w_OPERA_FAC_complet.NO_DOSSIER,
                        w_OPERA_FAC_complet.NO_FACTURE,
                        OPERA_ACT.CODE_SERVICE_DISCIPLINE,
                        TYPE_PRESTA,
                        OPERA_ACT.CODE_PRESTA AS CODE_RUBRIQUE,
                        COALESCE(w_RUBRIQUES_3.CODE_PRESTA, w_RUBRIQUES_4.CODE_PRESTA, OPERA_ACT.CODE_PRESTA) AS CODE_PRESTA,
                        w_PPRS.compte_produit_id,
                        CODE_STAT3,
                        OPERA_ACT.CODE_GHS,
                        MT_ACTE,
                        DMT_ACTE,
                        CASE WHEN OPERA_ACT.MONTANT_ACTE < 0 AND OPERA_ACT.QTE_ACTE > 0 THEN (0 - OPERA_ACT.QTE_ACTE) * CASE WHEN TYPE_PRESTA IN ('S', 's', 'P') THEN COEFF_ACTE ELSE 1 END ELSE OPERA_ACT.QTE_ACTE* CASE WHEN TYPE_PRESTA IN ('S', 's', 'P') THEN COEFF_ACTE ELSE 1 END END AS QTE_ACTE,
                        CASE WHEN TYPE_PRESTA IN ('S', 's', 'P') THEN 1 ELSE COEFF_ACTE END AS COEFF_ACTE,
                        0::numeric AS ACTE_PU,
                        OPERA_ACT.PRIX_UNITAIRE,
                        OPERA_ACT.MONTANT_ACTE,
                        CODE_LPP,
                        CODE_UCD,
                        CASE WHEN TYPE_PRESTA IN ('s','H') THEN CODE_CCAM ELSE '' END AS CODE_CCAM,
                        CODE_ACTIVITE_CCAM,
                        CODE_PHASE_CCAM,
                        CODE_MODIFICATEUR_1_CCAM,
                        CODE_MODIFICATEUR_2_CCAM,
                        CODE_MODIFICATEUR_3_CCAM,
                        CODE_MODIFICATEUR_4_CCAM,
                        CODE_ANP_CCAM,
                        ''::text AS CODE_EXTDOC_CCAM,
                        CODE_MED_PRESCRIPTEUR,
                        CASE WHEN TYPE_PRESTA IN ('s','H') THEN CODE_MED_EXECUTANT ELSE '' END AS CODE_MED_EXECUTANT,
                        OPERA_ACT.MONTANT_DP,
                        '0'::text AS DEP_OK,
                        0::int AS act_OK,
                        NULL::bigint AS RSF_sequence,
                        TAUX_AMO,
                        TAUX_AMC,
                        TAUX_IPP,
                        CASE WHEN TYPE_PRESTA NOT IN ('s','H') THEN MONTANT_AMO ELSE 0 END AS MONTANT_ACTE_AMO_C,
                        CASE WHEN TYPE_PRESTA IN ('s','H') THEN MONTANT_AMO ELSE 0 END AS MONTANT_ACTE_AMO_H,
                        CASE WHEN TYPE_PRESTA NOT IN ('s','H') THEN MONTANT_AMC ELSE 0 END AS MONTANT_ACTE_AMC_C,
                        CASE WHEN TYPE_PRESTA IN ('s','H') THEN MONTANT_AMC ELSE 0 END AS MONTANT_ACTE_AMC_H,
                        CASE WHEN TYPE_PRESTA NOT IN ('s','H') THEN MONTANT_IPP ELSE 0 END AS MONTANT_ACTE_IPP_C,
                        CASE WHEN TYPE_PRESTA IN ('s','H') THEN MONTANT_IPP ELSE 0 END AS MONTANT_ACTE_IPP_H,
                        CASE WHEN TYPE_PRESTA NOT IN ('H') THEN MONTANT_AMO ELSE 0 END AS CPT_MONTANT_ACTE_AMO_C,
                        CASE WHEN TYPE_PRESTA IN ('H') THEN MONTANT_AMO ELSE 0 END AS CPT_MONTANT_ACTE_AMO_H,
                        CASE WHEN TYPE_PRESTA NOT IN ('H') THEN MONTANT_AMC ELSE 0 END AS CPT_MONTANT_ACTE_AMC_C,
                        CASE WHEN TYPE_PRESTA IN ('H') THEN MONTANT_AMC ELSE 0 END AS CPT_MONTANT_ACTE_AMC_H,
                        CASE WHEN TYPE_PRESTA NOT IN ('H') THEN MONTANT_IPP ELSE 0 END AS CPT_MONTANT_ACTE_IPP_C,
                        CASE WHEN TYPE_PRESTA IN ('H') THEN MONTANT_IPP ELSE 0 END AS CPT_MONTANT_ACTE_IPP_H,
                        NULL::bigint AS oid_PAT,
                        0::numeric AS MONTANT_ACTE_PAT,
                        NULL::bigint AS oid_FJ,
                        0::numeric AS MONTANT_ACTE_FJ,
                        NULL::bigint AS oid_ACTP,
                        0::numeric AS MONTANT_ACTE_ACTP,
                        0::numeric AS MONTANT_DP_ACTP,
                        (
							OPERA_ACT.CODE_PRESTA::text || '|'::text || 
							OPERA_ACT.CODE_LPP::text || '|'::text || 
							OPERA_ACT.CODE_UCD::text || '|'::text || 
                            COALESCE(w_RUBRIQUES_3.CODE_PRESTA, w_RUBRIQUES_4.CODE_PRESTA, OPERA_ACT.CODE_PRESTA) || '|'::text || 
                            CASE WHEN TYPE_PRESTA IN ('s','H') THEN CODE_MED_EXECUTANT ELSE '' END || '|'::text || 
                            CASE WHEN TYPE_PRESTA IN ('s','H') THEN CODE_CCAM ELSE ''::text END
                        ) AS key
                    FROM w_OPERA_FAC_complet
                        JOIN prod_cegiloghos.OPERA_ACT ON OPERA_ACT.NO_FACTURE = w_OPERA_FAC_complet.NO_FACTURE_ACT AND OPERA_ACT.PERIODE_ANNEE = w_OPERA_FAC_complet.PERIODE_ANNEE_ACT
                        LEFT JOIN w_RUBRIQUES_3 ON OPERA_ACT.CODE_PRESTA = w_RUBRIQUES_3.CODE_RUBRIQUE
                        LEFT JOIN w_RUBRIQUES_4 ON OPERA_ACT.CODE_PRESTA = w_RUBRIQUES_4.CODE_RUBRIQUE
                        LEFT JOIN w_PPRS ON
                            OPERA_ACT.CODE_SERVICE_DISCIPLINE = w_PPRS.CODE_SERVICE_DISCIPLINE AND
                            OPERA_ACT.CODE_PRESTA = w_PPRS.CODE_PRESTA
                    WHERE OPERA_ACT.NO_FACTURE <> '000000000';
                    
                    UPDATE w_OPERA_ACT_complet
                    SET MONTANT_DP = MONTANT_DP * -1
                    WHERE (CPT_MONTANT_ACTE_AMO_H < 0 OR CPT_MONTANT_ACTE_AMC_H < 0 OR CPT_MONTANT_ACTE_IPP_H < 0) AND
                        MONTANT_DP > 0;


                    UPDATE w_OPERA_ACT_complet SET
                        DEP_OK = '1',
                        CPT_MONTANT_ACTE_AMC_H =
                            CASE 
                            WHEN MONTANT_DP = CPT_MONTANT_ACTE_IPP_H + CPT_MONTANT_ACTE_AMC_H THEN 0
                            WHEN NOT MONTANT_DP <= CPT_MONTANT_ACTE_IPP_H AND MONTANT_DP <= CPT_MONTANT_ACTE_AMC_H  THEN CPT_MONTANT_ACTE_AMC_H - MONTANT_DP
                            ELSE CPT_MONTANT_ACTE_AMC_H END,
                        CPT_MONTANT_ACTE_IPP_H =
                            CASE 
                            WHEN MONTANT_DP = CPT_MONTANT_ACTE_IPP_H + CPT_MONTANT_ACTE_AMC_H THEN 0
                            WHEN MONTANT_DP <= CPT_MONTANT_ACTE_IPP_H THEN CPT_MONTANT_ACTE_IPP_H - MONTANT_DP
                            ELSE CPT_MONTANT_ACTE_IPP_H END
                    FROM activite.t_divers 
                    WHERE t_divers.code = 'CEGICPTDEP' AND
                        t_divers.valeur = '0' AND
                        MONTANT_DP <> 0 AND (CPT_MONTANT_ACTE_AMC_H > 0 OR CPT_MONTANT_ACTE_IPP_H > 0) AND
                        MONTANT_DP <= CPT_MONTANT_ACTE_AMC_H + CPT_MONTANT_ACTE_IPP_H ;


                    UPDATE w_OPERA_ACT_complet SET
                        DEP_OK = '1',
                        CPT_MONTANT_ACTE_AMC_H =
                            CASE 
                            WHEN MONTANT_DP = CPT_MONTANT_ACTE_IPP_H + CPT_MONTANT_ACTE_AMC_H THEN 0
                            WHEN NOT MONTANT_DP >= CPT_MONTANT_ACTE_IPP_H AND MONTANT_DP >= CPT_MONTANT_ACTE_AMC_H  THEN CPT_MONTANT_ACTE_AMC_H - MONTANT_DP
                            ELSE CPT_MONTANT_ACTE_AMC_H END,
                        CPT_MONTANT_ACTE_IPP_H =
                            CASE 
                            WHEN MONTANT_DP = CPT_MONTANT_ACTE_IPP_H + CPT_MONTANT_ACTE_AMC_H THEN 0
                            WHEN MONTANT_DP >= CPT_MONTANT_ACTE_IPP_H THEN CPT_MONTANT_ACTE_IPP_H - MONTANT_DP
                            ELSE CPT_MONTANT_ACTE_IPP_H END
                    FROM activite.t_divers 
                    WHERE t_divers.code = 'CEGICPTDEP' AND
                        t_divers.valeur = '0' AND
                        MONTANT_DP <> 0 AND (CPT_MONTANT_ACTE_AMC_H < 0 OR CPT_MONTANT_ACTE_IPP_H < 0) AND
                        MONTANT_DP >= CPT_MONTANT_ACTE_AMC_H + CPT_MONTANT_ACTE_IPP_H ;

                    CREATE INDEX w_OPERA_ACT_complet_i1
                    ON w_OPERA_ACT_complet
                    USING btree
                    (NO_FACTURE);

                    CREATE INDEX w_OPERA_ACT_complet_i2
                    ON w_OPERA_ACT_complet
                    USING btree
                    (NO_DOSSIER);



                    DROP TABLE IF EXISTS w_OPERA_ACT_total;
                    CREATE TEMP TABLE w_OPERA_ACT_total AS
                    SELECT
                        NO_FACTURE,
                        MAX(COALESCE(DATE_ACTE_FIN,DATE_ACTE_DEBUT)) AS DATE_ACTE_FIN,
                        MAX(CODE_GHS) AS CODE_GHS,
                        SUM(MONTANT_ACTE_AMO_C) AS MONTANT_ACTE_AMO_C,
                        SUM(MONTANT_ACTE_AMO_H) AS MONTANT_ACTE_AMO_H,
                        SUM(MONTANT_ACTE_AMC_C) AS MONTANT_ACTE_AMC_C,
                        SUM(MONTANT_ACTE_AMC_H) AS MONTANT_ACTE_AMC_H,
                        SUM(MONTANT_ACTE_IPP_C) AS MONTANT_ACTE_IPP_C,
                        SUM(MONTANT_ACTE_IPP_H) AS MONTANT_ACTE_IPP_H,
                        SUM(CPT_MONTANT_ACTE_AMO_C) AS CPT_MONTANT_ACTE_AMO_C,
                        SUM(CPT_MONTANT_ACTE_AMO_H) AS CPT_MONTANT_ACTE_AMO_H,
                        SUM(CPT_MONTANT_ACTE_AMC_C) AS CPT_MONTANT_ACTE_AMC_C,
                        SUM(CPT_MONTANT_ACTE_AMC_H) AS CPT_MONTANT_ACTE_AMC_H,
                        SUM(CPT_MONTANT_ACTE_IPP_C) AS CPT_MONTANT_ACTE_IPP_C,
                        SUM(CPT_MONTANT_ACTE_IPP_H) AS CPT_MONTANT_ACTE_IPP_H
                    FROM w_OPERA_ACT_complet
                    GROUP BY 1;



                    INSERT INTO w_OPERA_ACT_complet
                    SELECT 
                        nextval('w_OPERA_ACT_sequence'::regclass) AS oid,
                        DATE_FACT_DEBUT AS DATE_ACTE_DEBUT,
                        w_OPERA_FAC_complet.DATE_FACT_FIN AS DATE_ACTE_FIN,
                        0 AS HEURE_ACTE_DEBUT,
                        0 AS HEURE_ACTE_FIN,
                        w_OPERA_FAC_complet.NO_DOSSIER,
                        w_OPERA_FAC_complet.NO_FACTURE,
                        ''::text AS CODE_SERVICE_DISCIPLINE,
                        'S'::text AS TYPE_PRESTA,
                        '*ECARTCTI'::text AS CODE_RUBRIQUE,
                        '*ECARTCTI'::text AS CODE_PRESTA,
                        0::bigint AS compte_produit_id,
                        ''::text AS CODE_STAT3,
                        ''::text AS CODE_GHS,
                        ''::text AS MT_ACTE,
                        ''::text AS DMT_ACTE,
                        0::numeric AS QTE_ACTE,
                        0::numeric AS COEFF_ACTE,
                        0::numeric AS ACTE_PU,
                        0::numeric AS PRIX_UNITAIRE,
                        (COALESCE(MONTANT_FACT_AMO_C,0) - COALESCE(MONTANT_ACTE_AMO_C,0)) + 
                            (COALESCE(MONTANT_FACT_AMC_C,0) - COALESCE(MONTANT_ACTE_AMC_C,0)) + 
                            (COALESCE(MONTANT_FACT_IPP_C,0) - COALESCE(MONTANT_ACTE_IPP_C,0)) AS MONTANT_ACTE,
                        ''::text AS CODE_LPP,
                        ''::text AS CODE_UCD,
                        ''::text AS CODE_CCAM,
                        ''::text AS CODE_ACTIVITE_CCAM,
                        ''::text AS CODE_PHASE_CCAM,
                        ''::text AS CODE_MODIFICATEUR_1_CCAM,
                        ''::text AS CODE_MODIFICATEUR_2_CCAM,
                        ''::text AS CODE_MODIFICATEUR_3_CCAM,
                        ''::text AS CODE_MODIFICATEUR_4_CCAM,
                        ''::text AS CODE_ANP_CCAM,
                        ''::text AS CODE_EXTDOC_CCAM,
                        ''::text AS CODE_MED_PRESCRIPTEUR,
                        ''::text AS CODE_MED_EXECUTANT,
                        0::numeric AS MONTANT_DP,
                        '0'::text AS DEP_OK,
                        1::int AS act_OK,
                        NULL::bigint AS RSF_sequence,
                        0::numeric AS TAUX_AMO,
                        0::numeric AS TAUX_AMC,
                        0::numeric AS TAUX_IPP,
                        (COALESCE(MONTANT_FACT_AMO_C,0) - COALESCE(MONTANT_ACTE_AMO_C,0)) AS MONTANT_ACTE_AMO_C,
                        0 AS MONTANT_ACTE_AMO_H,
                        (COALESCE(MONTANT_FACT_AMC_C,0) - COALESCE(MONTANT_ACTE_AMC_C,0)) AS MONTANT_ACTE_AMC_C,
                        0 AS MONTANT_ACTE_AMC_H,
                        (COALESCE(MONTANT_FACT_IPP_C,0) - COALESCE(MONTANT_ACTE_IPP_C,0)) AS MONTANT_ACTE_IPP_C,
                        0 AS MONTANT_ACTE_IPP_H,
                        (COALESCE(MONTANT_FACT_AMO_C,0) - COALESCE(MONTANT_ACTE_AMO_C,0)) AS CPT_MONTANT_ACTE_AMO_C,
                        0 AS CPT_MONTANT_ACTE_AMO_H,
                        (COALESCE(MONTANT_FACT_AMC_C,0) - COALESCE(MONTANT_ACTE_AMC_C,0)) AS CPT_MONTANT_ACTE_AMC_C,
                        0 AS CPT_MONTANT_ACTE_AMC_H,
                        (COALESCE(MONTANT_FACT_IPP_C,0) - COALESCE(MONTANT_ACTE_IPP_C,0)) AS CPT_MONTANT_ACTE_IPP_C,
                        0 AS CPT_MONTANT_ACTE_IPP_H,
                        NULL::bigint AS oid_PAT,
                        NULL::numeric AS MONTANT_ACTE_PAT,
                        NULL::bigint AS oid_FJ,
                        NULL::numeric AS MONTANT_ACTE_FJ,
                        NULL::bigint AS oid_ACTP,
                        NULL::numeric AS MONTANT_ACTE_ACTP,
                        NULL::numeric AS MONTANT_DP_ACTP,
                        (
                            '*ECARTCTI' || '|' || 
                            '*ECARTCTI' || '|' || 
                            '' || '|' || 
                            ''
                        ) AS key
                    FROM w_OPERA_FAC_complet
                        LEFT JOIN w_OPERA_ACT_total ON w_OPERA_FAC_complet.NO_FACTURE = w_OPERA_ACT_total.NO_FACTURE
                    WHERE (COALESCE(MONTANT_FACT_AMO_C,0) - COALESCE(MONTANT_ACTE_AMO_C,0)) <> 0 OR 
                        (COALESCE(MONTANT_FACT_AMC_C,0) - COALESCE(MONTANT_ACTE_AMC_C,0)) <> 0 OR 
                        (COALESCE(MONTANT_FACT_IPP_C,0) - COALESCE(MONTANT_ACTE_IPP_C,0)) <> 0;




                    -- Ajout des écarts HON
                    INSERT INTO w_OPERA_ACT_complet
                    SELECT 
                        nextval('w_OPERA_ACT_sequence'::regclass) AS oid,
                        DATE_FACT_DEBUT AS DATE_ACTE_DEBUT,
                        w_OPERA_FAC_complet.DATE_FACT_FIN AS DATE_ACTE_FIN,
                        0 AS HEURE_ACTE_DEBUT,
                        0 AS HEURE_ACTE_FIN,
                        w_OPERA_FAC_complet.NO_DOSSIER,
                        w_OPERA_FAC_complet.NO_FACTURE,
                        ''::text AS CODE_SERVICE_DISCIPLINE,
                        'H'::text AS TYPE_PRESTA,
                        '*ECARTCTI'::text AS CODE_RUBRIQUE,
                        '*ECARTCTI'::text AS CODE_PRESTA,
                        0::bigint AS compte_produit_id,
                        ''::text AS CODE_STAT3,
                        ''::text AS CODE_GHS,
                        ''::text AS MT_ACTE,
                        ''::text AS DMT_ACTE,
                        0::numeric AS QTE_ACTE,
                        0::numeric AS COEFF_ACTE,
                        0::numeric AS ACTE_PU,
                        0::numeric AS PRIX_UNITAIRE,
                        (COALESCE(MONTANT_FACT_AMO_H,0) - COALESCE(MONTANT_ACTE_AMO_H,0)) + 
                            (COALESCE(MONTANT_FACT_AMC_H,0) - COALESCE(MONTANT_ACTE_AMC_H,0)) + 
                            (COALESCE(MONTANT_FACT_IPP_H,0) - COALESCE(MONTANT_ACTE_IPP_H,0)) AS MONTANT_ACTE,
                        ''::text AS CODE_LPP,
                        ''::text AS CODE_UCD,
                        ''::text AS CODE_CCAM,
                        ''::text AS CODE_ACTIVITE_CCAM,
                        ''::text AS CODE_PHASE_CCAM,
                        ''::text AS CODE_MODIFICATEUR_1_CCAM,
                        ''::text AS CODE_MODIFICATEUR_2_CCAM,
                        ''::text AS CODE_MODIFICATEUR_3_CCAM,
                        ''::text AS CODE_MODIFICATEUR_4_CCAM,
                        ''::text AS CODE_ANP_CCAM,
                        ''::text AS CODE_EXTDOC_CCAM,
                        ''::text AS CODE_MED_PRESCRIPTEUR,
                        ''::text AS CODE_MED_EXECUTANT,
                        0::numeric AS MONTANT_DP,
                        '0'::text AS DEP_OK,
                        1::int AS act_OK,
                        NULL::bigint AS RSF_sequence,
                        0::numeric AS TAUX_AMO,
                        0::numeric AS TAUX_AMC,
                        0::numeric AS TAUX_IPP,
                        0::numeric AS MONTANT_ACTE_AMO_C,
                        (COALESCE(MONTANT_FACT_AMO_H,0) - COALESCE(MONTANT_ACTE_AMO_H,0)) AS MONTANT_ACTE_AMO_H,
                        0::numeric AS MONTANT_ACTE_AMC_C,
                        (COALESCE(MONTANT_FACT_AMC_H,0) - COALESCE(MONTANT_ACTE_AMC_H,0)) AS MONTANT_ACTE_AMC_H,
                        0::numeric AS MONTANT_ACTE_IPP_C,
                        (COALESCE(MONTANT_FACT_IPP_H,0) - COALESCE(MONTANT_ACTE_IPP_H,0)) AS MONTANT_ACTE_IPP_H,
                        0::numeric AS MONTANT_ACTE_AMO_C,
                        (COALESCE(MONTANT_FACT_AMO_H,0) - COALESCE(MONTANT_ACTE_AMO_H,0)) AS CPT_MONTANT_ACTE_AMO_H,
                        0::numeric AS MONTANT_ACTE_AMC_C,
                        (COALESCE(MONTANT_FACT_AMC_H,0) - COALESCE(MONTANT_ACTE_AMC_H,0)) AS CPT_MONTANT_ACTE_AMC_H,
                        0::numeric AS MONTANT_ACTE_IPP_C,
                        (COALESCE(MONTANT_FACT_IPP_H,0) - COALESCE(MONTANT_ACTE_IPP_H,0)) AS CPT_MONTANT_ACTE_IPP_H,
                        NULL::bigint AS oid_PAT,
                        NULL::numeric AS MONTANT_ACTE_PAT,
                        NULL::bigint AS oid_FJ,
                        NULL::numeric AS MONTANT_ACTE_FJ,
                        NULL::bigint AS oid_ACTP,
                        NULL::numeric AS MONTANT_ACTE_ACTP,
                        NULL::numeric AS MONTANT_DP_ACTP,
                        (
                            '*ECARTCTI' || '|' || 
                            '*ECARTCTI' || '|' || 
                            '' || '|' || 
                            ''
                        ) AS key
                    FROM w_OPERA_FAC_complet
                        LEFT JOIN w_OPERA_ACT_total ON w_OPERA_FAC_complet.NO_FACTURE = w_OPERA_ACT_total.NO_FACTURE
                    WHERE (COALESCE(MONTANT_FACT_AMO_H,0) - COALESCE(MONTANT_ACTE_AMO_H,0)) <> 0 OR 
                        (COALESCE(MONTANT_FACT_AMC_H,0) - COALESCE(MONTANT_ACTE_AMC_H,0)) <> 0 OR 
                        (COALESCE(MONTANT_FACT_IPP_H,0) - COALESCE(MONTANT_ACTE_IPP_H,0)) <> 0;
                    
                    
                ]]></sqlcmd>
            </NODE>
            
            <NODE label="Entêtes">
                <sqlcmd><![CDATA[
                
                    
                    UPDATE w_OPERA_FAC_complet 
                        SET DATE_FACT_FIN = w_OPERA_ACT_total.DATE_ACTE_FIN
                    FROM w_OPERA_ACT_total
                    WHERE w_OPERA_ACT_total.NO_FACTURE = w_OPERA_FAC_complet.NO_FACTURE AND
                        (w_OPERA_FAC_complet.DATE_FACT_FIN IS NULL OR w_OPERA_ACT_total.DATE_ACTE_FIN > w_OPERA_FAC_complet.DATE_FACT_FIN);

                    UPDATE w_OPERA_FAC_complet SET
                        GHS = w_OPERA_ACT_total.CODE_GHS,
                        key = TIERS_FACT_AMO || '|' || 
                            TIERS_FACT_AMC || '|' || 
                            w_OPERA_ACT_total.CODE_GHS
                    FROM w_OPERA_ACT_total
                    WHERE w_OPERA_ACT_total.NO_FACTURE = w_OPERA_FAC_complet.NO_FACTURE AND
                        w_OPERA_ACT_total.CODE_GHS IS DISTINCT FROM w_OPERA_FAC_complet.GHS;


                    

                    DROP TABLE IF EXISTS w_OPERA_FAC_complet_key;
                    CREATE TEMP TABLE w_OPERA_FAC_complet_key AS
                    SELECT
                        key,
                        TIERS_FACT_AMO,
                        TIERS_FACT_AMC,
                        GHS,
                        GHS_BEBE1,
                        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,
                        NULL::bigint AS ghs_id,
                        NULL::bigint AS ghs_bebe1_id,
                        NULL::bigint AS ghs_bebe2_id,
                        NULL::bigint AS ghs_bebe3_id
                        
                    FROM w_OPERA_FAC_complet
                    GROUP BY 1,2,3,4,5;

                    ALTER TABLE w_OPERA_FAC_complet_key ADD CONSTRAINT w_OPERA_FAC_complet_key_pkey PRIMARY KEY(KEY);

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

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

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

                    UPDATE w_OPERA_FAC_complet_key
                        set ghs_id = t_ghs.oid
                    FROM base.t_ghs
                    WHERE GHS <> '' AND t_ghs.code_text = GHS;
					
					UPDATE w_OPERA_FAC_complet_key
                        set ghs_id = t_ghs.oid
                    FROM base.t_ghs
                    WHERE ghs_id = 0 AND 
						GHS <> '' AND to_char(t_ghs.code,'FM0000') = GHS;





                    



                    DROP TABLE IF EXISTS w_OPERA_FAC_avoirs;
                    CREATE TEMP TABLE w_OPERA_FAC_avoirs AS
                    SELECT
                        w_OPERA_FAC_avoirs.NO_DOSSIER,
                        w_OPERA_FAC_avoirs.NO_FACTURE AS NO_FACTURE_AVOIR,
                        w_OPERA_FAC_avoirs.DATE_CALCUL_FACTURE AS DATE_CALCUL_FACTURE_AVOIR,
                        w_OPERA_FAC_avoirs.MONTANT_TOTAL_FACTURE AS MONTANT_TOTAL_FACTURE_AVOIR,
                        w_OPERA_FAC_avoirs.MONTANT_FACT_AMO AS MONTANT_FACT_AMO_AVOIR,
                        w_OPERA_FAC_avoirs.MONTANT_FACT_AMC AS MONTANT_FACT_AMC_AVOIR,
                        w_OPERA_FAC_avoirs.MONTANT_FACT_IPP AS MONTANT_FACT_IPP_AVOIR,
                        MAX(w_OPERA_FAC_complet.NO_FACTURE) AS NO_FACTURE_ANNULEE
                    FROM w_OPERA_FAC_complet w_OPERA_FAC_avoirs
                        LEFT JOIN w_OPERA_FAC_complet ON
                            w_OPERA_FAC_complet.NO_DOSSIER = w_OPERA_FAC_avoirs.NO_DOSSIER AND
                            w_OPERA_FAC_complet.TYPE_FACTURE IN ('D','F') AND
                            w_OPERA_FAC_complet.NO_FACTURE < w_OPERA_FAC_avoirs.NO_FACTURE AND
                            0 - w_OPERA_FAC_complet.MONTANT_FACT_AMO = w_OPERA_FAC_avoirs.MONTANT_FACT_AMO AND
                            0 - w_OPERA_FAC_complet.MONTANT_FACT_AMC = w_OPERA_FAC_avoirs.MONTANT_FACT_AMC AND
                            0 - w_OPERA_FAC_complet.MONTANT_FACT_IPP = w_OPERA_FAC_avoirs.MONTANT_FACT_IPP
                    WHERE w_OPERA_FAC_avoirs.TYPE_FACTURE = 'A'
                    GROUP BY 1,2,3,4,5,6,7;


                    CREATE INDEX w_OPERA_FAC_avoirs_i1
                    ON w_OPERA_FAC_avoirs
                    USING btree
                    (NO_FACTURE_AVOIR);

                    CREATE INDEX w_OPERA_FAC_avoirs_i2
                    ON w_OPERA_FAC_avoirs
                    USING btree
                    (NO_FACTURE_ANNULEE);


                    UPDATE w_OPERA_FAC_complet
                    SET NO_FACTURE_OD_AVOIR = NO_FACTURE_ANNULEE
                    FROM w_OPERA_FAC_avoirs
                    WHERE w_OPERA_FAC_avoirs.NO_DOSSIER = w_OPERA_FAC_complet.NO_DOSSIER AND
                        w_OPERA_FAC_avoirs.NO_FACTURE_AVOIR = w_OPERA_FAC_complet.NO_FACTURE;

                    UPDATE w_OPERA_FAC_complet SET
                        TYPE_FACTURE = 'X',
                        NO_FACTURE_OD_AVOIR = NO_FACTURE_AVOIR
                    FROM w_OPERA_FAC_avoirs
                    WHERE w_OPERA_FAC_avoirs.NO_DOSSIER = w_OPERA_FAC_complet.NO_DOSSIER AND
                        w_OPERA_FAC_avoirs.NO_FACTURE_ANNULEE = w_OPERA_FAC_complet.NO_FACTURE;


            

                    DROP TABLE IF EXISTS w_OPERA_FAC_reference;
                    CREATE TEMP TABLE w_OPERA_FAC_reference AS
                    SELECT
                        NO_FACTURE_REFERENCE,
                        MAX(DATE_REGLEMENT_MAX) AS reference_DATE_REGLEMENT_MAX,
                        MAX(DATE_REGLEMENT_MAX_C) AS reference_DATE_REGLEMENT_MAX_C,
                        MAX(DATE_REGLEMENT_MAX_H) AS reference_DATE_REGLEMENT_MAX_H,
                        MAX(DATE_REGLEMENT_MAX_IPP_C) AS reference_DATE_REGLEMENT_MAX_IPP_C,
                        MAX(DATE_REGLEMENT_MAX_IPP_H) AS reference_DATE_REGLEMENT_MAX_IPP_H,
                        MAX(DATE_REGLEMENT_MAX_AMO_C) AS reference_DATE_REGLEMENT_MAX_AMO_C,
                        MAX(DATE_REGLEMENT_MAX_AMO_H) AS reference_DATE_REGLEMENT_MAX_AMO_H,
                        MAX(DATE_REGLEMENT_MAX_AMC_C) AS reference_DATE_REGLEMENT_MAX_AMC_C,
                        MAX(DATE_REGLEMENT_MAX_AMC_H) AS reference_DATE_REGLEMENT_MAX_AMC_H
                    FROM w_OPERA_FAC_complet
                    GROUP BY NO_FACTURE_REFERENCE;

                    ALTER TABLE w_OPERA_FAC_reference ADD CONSTRAINT w_OPERA_FAC_reference_pkey PRIMARY KEY(NO_FACTURE_REFERENCE);



                    ALTER SEQUENCE activite[PX].s_factures RESTART WITH 1;


                    DROP TABLE IF EXISTS w_factures;
                    CREATE TEMP TABLE w_factures AS 
                    SELECT 
                        nextval('activite[PX].s_factures'::regclass) AS oid,
                        w_OPERA_FAC_complet.NO_DOSSIER AS no_sejour,
                        p_sejours.oid AS sejour_id,
                        w_OPERA_FAC_complet.NO_FACTURE AS no_facture,
                        date(w_OPERA_FAC_complet.DATE_FACT_DEBUT) AS date_debut,
                        date(w_OPERA_FAC_complet.DATE_FACT_FIN) AS date_fin,
                        CASE 
                            WHEN TYPE_FACTURE IN ('X') THEN 'X' 
                            WHEN TYPE_FACTURE IN ('F','X') AND w_OPERA_FAC_complet.NO_FACTURE <> w_OPERA_FAC_complet.NO_FACTURE_REFERENCE THEN '2' 
                            WHEN TYPE_FACTURE IN ('A') THEN '1' 
                            WHEN TYPE_FACTURE IN ('D') THEN '2' 
                            ELSE '0' END AS type_facture,
                        p_sejours.code_cp_demandee, 
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN '1' ELSE '0' END AS code_facture,
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN date(DATE_CALCUL_FACTURE) ELSE '20991231' END AS date_facture,
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN '1' ELSE '0' END AS code_vente,
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN date(DATE_CALCUL_FACTURE) ELSE '20991231'::date END AS date_vente,
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN extract('year' FROM DATE_CALCUL_FACTURE) * 100 + extract('month' FROM DATE_CALCUL_FACTURE) ELSE extract('year' FROM '20991231'::date) * 100 + extract('month' FROM '20991231'::date) END AS mois_vente,
                        '0'::text AS code_cloture,
                        CASE 
                            WHEN TYPE_FACTURE IN ('A') THEN 1
                            ELSE 0 END AS nb_rejets,
                        w_OPERA_FAC_complet.NO_FACTURE_REFERENCE AS no_facture_reference,
                        0::bigint AS facture_reference_id,
                        NO_FACTURE_OD_AVOIR AS no_facture_od_avoir,
                        0::bigint AS facture_od_avoir_id,
                        COALESCE(w_OPERA_FAC_complet_key.ghs_id, p_sejours.ghs_id) AS ghs_id,
                        COALESCE(w_OPERA_FAC_complet_key.ghs_bebe1_id, p_sejours.ghs_bebe1_id) AS ghs_bebe1_id, 
                        0::bigint AS ghs_bebe2_id, 
                        0::bigint AS ghs_bebe3_id,
                        ''::text AS particularite_t2a, 
                        w_OPERA_FAC_complet_key.tiers_payant_1_id,
                        w_OPERA_FAC_complet_key.tiers_payant_2_id,
                        w_OPERA_FAC_complet_key.tiers_payant_22_id,
                        w_OPERA_FAC_complet_key.tiers_payant_0_id,
                        CASE  
                            WHEN DATE_ENVOI_CETELIC_FACT_AMO between '1980-01-01' AND '2050-01-01' AND DATE_ENVOI_CETELIC_FACT_AMC between '1980-01-01' AND '2050-01-01' THEN LEAST(DATE_ENVOI_CETELIC_FACT_AMO, DATE_ENVOI_CETELIC_FACT_AMC)  
                            WHEN DATE_ENVOI_CETELIC_FACT_AMO between '1980-01-01' AND '2050-01-01' THEN DATE_ENVOI_CETELIC_FACT_AMO 
                            WHEN DATE_ENVOI_CETELIC_FACT_AMC between '1980-01-01' AND '2050-01-01' THEN DATE_ENVOI_CETELIC_FACT_AMC 
                            ELSE LEAST(DATE_ENVOI_CETELIC_FACT_AMO, DATE_ENVOI_CETELIC_FACT_AMC)
                        END AS date_expedition,
                        '00010101'::date AS date_expedition_0,
                        date(DATE_ENVOI_CETELIC_FACT_AMO) AS date_expedition_1,
                        date(DATE_ENVOI_CETELIC_FACT_AMC) AS date_expedition_2,
                        '00010101'::date AS date_expedition_22,
                        '0'::text AS code_expedie_0,
                        CASE WHEN DATE_ENVOI_CETELIC_FACT_AMO IS NOT NULL THEN '1' ELSE '0' END AS code_expedie_1,
                        CASE WHEN DATE_ENVOI_CETELIC_FACT_AMC IS NOT NULL THEN '1' ELSE '0' END AS code_expedie_2,
                        '0'::text AS code_expedie_22,
                        ''::text AS no_bordereau_0,
                        COALESCE(NO_LOT_CETELIC_FACT_AMO,'') AS no_bordereau_1,
                        COALESCE(NO_LOT_CETELIC_FACT_AMC,'') AS no_bordereau_2,
                        ''::text AS no_bordereau_22,
                        
                        DATE_REGLEMENT_MAX AS date_solde,
                        DATE_REGLEMENT_MAX_c AS date_solde_c,
                        DATE_REGLEMENT_MAX_h AS date_solde_h,
                        DATE_REGLEMENT_MAX_IPP_C AS date_solde_0_c,
                        DATE_REGLEMENT_MAX_IPP_H AS date_solde_0_h,
                        DATE_REGLEMENT_MAX_AMO_C AS date_solde_1_c,
                        DATE_REGLEMENT_MAX_AMO_H AS date_solde_1_h, 
                        DATE_REGLEMENT_MAX_AMC_C AS date_solde_2_c,
                        DATE_REGLEMENT_MAX_AMC_H AS date_solde_2_h, 
                        '00010101'::date AS date_solde_22_c,
                        '00010101'::date AS date_solde_22_h,    
                        COALESCE(MONTANT_FACT_AMO_C + MONTANT_FACT_AMC_C + MONTANT_FACT_IPP_C,0) AS montant_facture_c,
                        COALESCE(MONTANT_FACT_AMO_H + MONTANT_FACT_AMC_H + MONTANT_FACT_IPP_H,0) AS montant_facture_h,
                        COALESCE(MONTANT_FACT_IPP_C,0) AS montant_facture_0_c,
                        COALESCE(MONTANT_FACT_IPP_H,0) AS montant_facture_0_h,
                        COALESCE(MONTANT_FACT_AMO_C,0) AS montant_facture_1_c,
                        COALESCE(MONTANT_FACT_AMO_H,0) AS montant_facture_1_h,
                        COALESCE(MONTANT_FACT_AMC_C,0) AS montant_facture_2_c,
                        COALESCE(MONTANT_FACT_AMC_H,0) AS montant_facture_2_h,
                        0::numeric AS montant_facture_22_c,
                        0::numeric AS montant_facture_22_h,
                        0::numeric AS montant_facture_c_actes_inclus_dans_sejour,
                        0::numeric AS montant_facture_h_actes_inclus_dans_sejour,
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN COALESCE(MONTANT_FACT_AMO_C + MONTANT_FACT_AMC_C + MONTANT_FACT_IPP_C,0) ELSE 0 END AS montant_comptabilise_c, 
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN COALESCE(MONTANT_FACT_AMO_H + MONTANT_FACT_AMC_H + MONTANT_FACT_IPP_H,0) ELSE 0 END AS montant_comptabilise_h, 
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN COALESCE(MONTANT_FACT_IPP_C,0) ELSE 0 END AS montant_comptabilise_0_c,
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN COALESCE(MONTANT_FACT_IPP_H,0) ELSE 0 END AS montant_comptabilise_0_h, 
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN COALESCE(MONTANT_FACT_AMO_C,0) ELSE 0 END AS montant_comptabilise_1_c, 
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN COALESCE(MONTANT_FACT_AMO_H,0) ELSE 0 END AS montant_comptabilise_1_h, 
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN COALESCE(MONTANT_FACT_AMC_C,0) ELSE 0 END AS montant_comptabilise_2_c, 
                        CASE WHEN DATE_CALCUL_FACTURE IS NOT NULL THEN COALESCE(MONTANT_FACT_AMC_H,0) ELSE 0 END AS montant_comptabilise_2_h, 
                        0::numeric AS montant_comptabilise_22_c, 
                        0::numeric AS montant_comptabilise_22_h, 
                        0::numeric AS montant_comptabilise_budget_global_c,
                        w_OPERA_FAC_complet.MONTANT_REGLEMENT_C AS montant_regle_c,
                        w_OPERA_FAC_complet.MONTANT_REGLEMENT_H AS montant_regle_h,
                        w_OPERA_FAC_complet.MONTANT_REGLEMENT_IPP_C AS montant_regle_0_c,
                        w_OPERA_FAC_complet.MONTANT_REGLEMENT_IPP_H AS montant_regle_0_h,
                        w_OPERA_FAC_complet.MONTANT_REGLEMENT_AMO_C AS montant_regle_1_c,
                        w_OPERA_FAC_complet.MONTANT_REGLEMENT_AMO_H AS montant_regle_1_h,
                        w_OPERA_FAC_complet.MONTANT_REGLEMENT_AMC_C AS montant_regle_2_c,
                        w_OPERA_FAC_complet.MONTANT_REGLEMENT_AMC_H AS montant_regle_2_h,

                        CASE WHEN reference_DATE_REGLEMENT_MAX > '00010101' THEN reference_DATE_REGLEMENT_MAX ELSE '20991231' END AS date_solde_reference,
                        CASE WHEN reference_DATE_REGLEMENT_MAX_C > '00010101' THEN reference_DATE_REGLEMENT_MAX_C ELSE '20991231' END AS date_solde_reference_c,
                        CASE WHEN reference_DATE_REGLEMENT_MAX_H > '00010101' THEN reference_DATE_REGLEMENT_MAX_H ELSE '20991231' END AS date_solde_reference_h,
                        CASE WHEN reference_DATE_REGLEMENT_MAX_IPP_C > '00010101' THEN reference_DATE_REGLEMENT_MAX_IPP_C ELSE '20991231' END AS date_solde_reference_0_c,
                        CASE WHEN reference_DATE_REGLEMENT_MAX_IPP_H > '00010101' THEN reference_DATE_REGLEMENT_MAX_IPP_H ELSE '20991231' END AS date_solde_reference_0_h,
                        CASE WHEN reference_DATE_REGLEMENT_MAX_AMO_C > '00010101' THEN reference_DATE_REGLEMENT_MAX_AMO_C ELSE '20991231' END AS date_solde_reference_1_c,
                        CASE WHEN reference_DATE_REGLEMENT_MAX_AMO_H > '00010101' THEN reference_DATE_REGLEMENT_MAX_AMO_H ELSE '20991231' END AS date_solde_reference_1_h,
                        CASE WHEN reference_DATE_REGLEMENT_MAX_AMC_C > '00010101' THEN reference_DATE_REGLEMENT_MAX_AMC_C ELSE '20991231' END AS date_solde_reference_2_c,
                        CASE WHEN reference_DATE_REGLEMENT_MAX_AMC_H > '00010101' THEN reference_DATE_REGLEMENT_MAX_AMC_H ELSE '20991231' END AS date_solde_reference_2_h

                    FROM w_OPERA_FAC_complet
                        JOIN activite[PX].p_sejours ON w_OPERA_FAC_complet.NO_DOSSIER = p_sejours.code_original AND p_sejours.etat = ''
                        JOIN w_OPERA_FAC_complet_key ON w_OPERA_FAC_complet.key = w_OPERA_FAC_complet_key.key
                        JOIN w_OPERA_FAC_reference ON w_OPERA_FAC_reference.NO_FACTURE_REFERENCE = w_OPERA_FAC_complet.NO_FACTURE_REFERENCE
                        LEFT JOIN w_OPERA_ACT_total ON w_OPERA_FAC_complet.NO_FACTURE = w_OPERA_ACT_total.NO_FACTURE
                    ORDER BY 1,2;




                    -- Ajout des factures
                    
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_3');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_4');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_5');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_6');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_7');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_8');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_9');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_10');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_11');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_12');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_13');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_14');

                    INSERT INTO activite[PX].p_factures (
                        oid,
                        no_sejour,
                        provider_id,
                        sejour_id,
                        no_facture,
                        date_debut,
                        date_fin,
                        type_facture,
                        code_cp_demandee, 
                        code_facture,
                        date_facture,
                        code_vente,
                        date_vente,
                        mois_vente,
                        code_cloture,
                        nb_rejets,
                        no_facture_reference,
                        facture_reference_id,
                        no_facture_od_avoir,
                        facture_od_avoir_id,
                        ghs_id,
                        ghs_bebe1_id, 
                        ghs_bebe2_id, 
                        ghs_bebe3_id,
                        particularite_t2a, 
                        tiers_payant_1_id,
                        tiers_payant_2_id,
                        tiers_payant_22_id,
                        tiers_payant_0_id,
                        date_expedition, 
                        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,
                        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_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_facture_c_actes_inclus_dans_sejour,
                        montant_facture_h_actes_inclus_dans_sejour,
                        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_comptabilise_budget_global_c,
                        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,
                        delai_facture,
                        delai_expedition,
                        delai_expedition_0,
                        delai_expedition_1,
                        delai_expedition_2,
                        delai_expedition_22,
                        delai_solde,
                        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_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
                    )
                    SELECT
                        oid,
                        no_sejour,
                        2::bigint AS provider_id,
                        sejour_id,
                        no_facture,
                        date_debut,
                        date_fin,
                        type_facture,
                        code_cp_demandee, 
                        code_facture,
                        date_facture,
                        code_vente,
                        date_vente,
                        mois_vente,
                        code_cloture,
                        nb_rejets,
                        no_facture_reference,
                        CASE WHEN no_facture = no_facture_reference THEN oid ELSE 0 END AS facture_reference_id,
                        no_facture_od_avoir,
                        facture_od_avoir_id,
                        ghs_id,
                        ghs_bebe1_id, 
                        ghs_bebe2_id, 
                        ghs_bebe3_id,
                        particularite_t2a, 
                        tiers_payant_1_id,
                        tiers_payant_2_id,
                        tiers_payant_22_id,
                        tiers_payant_0_id,
                        date_expedition, 
                        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,
                        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_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_facture_c_actes_inclus_dans_sejour,
                        montant_facture_h_actes_inclus_dans_sejour,
                        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_comptabilise_budget_global_c,
                        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,
                        0::numeric AS montant_regle_22_c,
                        0::numeric AS montant_regle_22_h,
                        0::numeric AS delai_facture,
                        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::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,

                        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,
                        '20991231'::date AS date_solde_reference_22_c,
                        date_solde_reference_0_h,
                        date_solde_reference_1_h,
                        date_solde_reference_2_h,
                        '20991231'::date AS date_solde_reference_22_h
                    FROM w_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_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.no_facture_od_avoir <> '';
                        
                        
                        
                    UPDATE activite[PX].p_sejours
                    SET est_sans_facturation = '1' 
                    WHERE lieu_sortie_id IN 
                        (SELECT oid FROM activite[PX].t_lieux WHERE 
                            service_facturation_id IN
                            (SELECT oid FROM activite[PX].t_services_facturation WHERE est_sans_facturation = '1') OR
                            unite_fonctionnelle_id IN
                            (SELECT oid FROM activite[PX].t_unites_fonctionnelles WHERE est_sans_facturation = '1') 
                        );
                    

                    -- Séjours sans facture
                    
                    DROP TABLE IF EXISTS w_factures_trous;
                    CREATE TEMP TABLE w_factures_trous AS
                    SELECT
                        p_sejours.finess,
                        p_sejours.no_sejour,
                        p_sejours.date_entree,
                        p_sejours.tiers_payant_0_id, 
                        p_sejours.tiers_payant_1_id, 
                        p_sejours.tiers_payant_2_id, 
                        p_sejours.tiers_payant_22_id,
                        p_sejours.code_cp_demandee,
                        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 NOT NULL AND date_sortie - date_entree < 30 THEN date_sortie ELSE p_factures.date_fin END) AS date_fin_facture,
                        date(MAX(COALESCE(CASE WHEN p_factures.date_fin IS NOT NULL AND date_sortie - date_entree < 30 THEN date_sortie ELSE p_factures.date_fin END + interval '1 day', p_sejours.date_entree))) AS date_debut_encours,
                        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%' AND 
							(type_facture NOT IN ('1','X') OR p_factures.date_fin < date(now() - interval '6 month'))
                        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 
						p_sejours.type_sejour IS DISTINCT FROM '9' AND 
                        p_sejours.provider_id = 2 AND
                        p_sejours.code_prevu = '0' AND
                        date_entree <= now()
                    GROUP BY 1,2,3,4,5,6,7,8,9,10,11;



                    INSERT INTO activite[PX].p_factures(
                        finess, 
                        no_sejour, 
                        provider_id,
                        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, 
                        2::bigint AS provider_id,
                        'E' || no_sejour || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || p_calendrier.mois ELSE '' END, 
                        'E' || no_sejour || 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,13;

                    
                    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="Lignes non facturées Clinique">
                <sqlcmd><![CDATA[
				
					-- Prix unitaires non saisis, trouver le dernier
					DROP TABLE IF EXISTS w_OPERA_ACT_pu_last;
					CREATE TEMP TABLE w_OPERA_ACT_pu_last AS
					SELECT CODE_SERVICE_DISCIPLINE, 
						CODE_PRESTA,
						(MAX(Array[DATE_ACTE_DEBUT::text,PRIX_UNITAIRE::text]))[2]::numeric AS PRIX_UNITAIRE_last
					FROM prod_cegiloghos.OPERA_ACT
					WHERE NO_FACTURE IN (SELECT no_facture FROM prod_cegiloghos.OPERA_FAC) AND
						DATE_ACTE_DEBUT >= date(now() - interval '1 year') AND
						TYPE_PRESTA IN ('S', 'P') AND
						CODE_PRESTA IN (
							SELECT CODE_PRESTA 
							FROM prod_cegiloghos.OPERA_ACT 
							WHERE NO_FACTURE NOT IN (SELECT no_facture FROM prod_cegiloghos.OPERA_FAC) AND
								TYPE_PRESTA IN ('S', 'P') AND
								PRIX_UNITAIRE = 0
							) 
					GROUP BY 1,2
					HAVING COUNT(DISTINCT FLOOR(PRIX_UNITAIRE)) <= 2
					;

					-- Génération
                    INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
                        no_facture, 
                        date_debut, 
                        date_fin, 
                        nb_rubrique, 
                        coefficient, 
                        rubrique_facturation_id, 
                        prestation_id, 
                        prix_unitaire, 
                        lieu_id,
						ucd_id,
						lpp_id)
                    SELECT
                        p_factures.no_facture,
						date(DATE_ACTE_DEBUT) AS date_debut,
						date(COALESCE(DATE_ACTE_FIN, DATE_ACTE_DEBUT)) AS date_fin,
						GREATEST(0,QTE_ACTE*COEFF_ACTE) AS nb_rubrique,
						1::numeric AS coefficient,
						t_rubriques_facturation.oid AS rubrique_facturation_id,
						t_prestations.oid AS prestation_id,
						PRIX_UNITAIRE AS prix_unitaire,
						p_sejours.lieu_sortie_id AS lieu_id,
						COALESCE(t_ucd.oid,0),
						COALESCE(t_lpp.oid,0)
                    FROM prod_cegiloghos.OPERA_ACT
                        JOIN activite[PX].p_sejours ON no_dossier = p_sejours.code_original AND p_sejours.etat = ''
                        JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND 
                            type_facture = 'E' 
                        JOIN activite.t_prestations ON CODE_PRESTA = t_prestations.code
						JOIN activite[PX].t_rubriques_facturation ON CODE_PRESTA = t_rubriques_facturation.code_original
						LEFT JOIN base.t_ucd ON CODE_UCD = t_ucd.code AND CODE_UCD <> ''
						LEFT JOIN base.t_lpp ON CODE_LPP = t_lpp.code AND CODE_LPP <> ''
                    WHERE
                            date(DATE_ACTE_DEBUT) BETWEEN p_factures.date_debut AND p_factures.date_fin AND
                            TYPE_PRESTA IN ('S', 'P') AND
                            CODE_PRESTA NOT IN ('STF', 'REA', 'SRC', 'GHS', 'EXH') AND
                            PRIX_UNITAIRE <> 0 AND
                            MONTANT_ACTE <> 0
                    ;
                                            
                ]]></sqlcmd>
            </NODE>
            
            <NODE label="Lignes factures Clinique">
                <sqlcmd><![CDATA[
                
                    -- Recherche CCAM selon actes saisis

                    DROP SEQUENCE IF EXISTS w_LSCCAM_sequence;
                    CREATE TEMP SEQUENCE w_LSCCAM_sequence;
        

                    DROP TABLE IF EXISTS w_LSCCAM;
                    CREATE TEMP TABLE w_LSCCAM AS
                    SELECT 
                        nextval('w_LSCCAM_sequence'::regclass) AS oid,
                        0::bigint AS act_id,
                        CJ_SEJOUR.SEJ_ID,
                        SEJ_NUMDOS,
                        date(LSR_DDEB) AS LSR_DDEB,
                        PRA_LIBC,
                        CCAM_CODE,
                        CCAM_ACTV,
                        CCAM_PHS,
                        LSCA_MOD1,
                        LSCA_MOD2,
                        LSCA_MOD3,
                        LSCA_MOD4,
                        LSCA_EXTDOC,
                        LSCA_ASSNP,
                        LSCA_RMBEX,
                        CJ_LSRGP.LSR_ID,
                        CASE WHEN CCAM_ACTV <> '4' THEN t_ccam_regroupements.code ELSE 'ADA' END AS code_prestation_1
                    FROM prod_cegi.CJ_SEJOUR
                        JOIN w_OPERA_SEJ_select ON CJ_SEJOUR.SEJ_NUMDOS = w_OPERA_SEJ_select.NO_DOSSIER
                        JOIN prod_cegi.CJ_LSRGP ON CJ_LSRGP.SEJ_ID = CJ_SEJOUR.SEJ_ID AND LSR_ACTIF = 1
                        JOIN prod_cegi.CJ_LSCCAM ON CJ_LSCCAM.LSR_ID = CJ_LSRGP.LSR_ID AND LSCA_ACTIF = 1
                        JOIN prod_cegi.CJ_CCAM ON CJ_CCAM.CCAM_ID = CJ_LSCCAM.CCAM_ID
                        JOIN prod_cegi.CJ_PRA ON CJ_PRA.TER_ID = CJ_LSCCAM.TER_ID
                        JOIN base.t_actes ON t_actes.code = substring(CCAM_CODE, 1, 7)
                        JOIN base.t_ccam_regroupements ON ccam_regroupement_id_1 = t_ccam_regroupements.oid;

                    ALTER TABLE w_LSCCAM ADD CONSTRAINT w_LSCCAM_pkey PRIMARY KEY(oid);
                    
                    CREATE INDEX w_LSCCAM_i1
                    ON w_LSCCAM
                    USING btree
                    (SEJ_NUMDOS);




                    
                    
                    SELECT base.cti_execute('
                    UPDATE w_LSCCAM 
                    SET act_id = subview.act_id
                    FROM (
                        SELECT 
                            NO_DOSSIER,
                            date(DATE_ACTE_DEBUT) AS DATE_ACTE_DEBUT,
                            CODE_MED_EXECUTANT,
                            MIN(w_OPERA_ACT_complet.oid) AS ACT_id,
                            MIN(w_LSCCAM.oid) AS LSCCAM_id
                        FROM w_OPERA_ACT_complet
                            JOIN w_LSCCAM ON SEJ_NUMDOS = NO_DOSSIER AND
                                LSR_DDEB = date(DATE_ACTE_DEBUT) AND
                                PRA_LIBC = CODE_MED_EXECUTANT AND
                                CODE_PRESTA = code_prestation_1 AND
                                act_id = 0
                        WHERE TYPE_PRESTA = ''H'' AND
                            CODE_PRESTA IN (''ACO'', ''ADA'', ''ADC'', ''ADE'', ''ADI'', ''ATM'', ''DEN'') AND
                            CODE_CCAM = ''''
                        GROUP BY 1,2,3
                        ) subview
                    WHERE oid = subview.LSCCAM_id .,

                    UPDATE w_OPERA_ACT_complet SET
                        CODE_CCAM = CCAM_CODE,
                        CODE_ACTIVITE_CCAM = CCAM_ACTV,
                        CODE_PHASE_CCAM = CCAM_PHS,
                        CODE_MODIFICATEUR_1_CCAM = LSCA_MOD1,
                        CODE_MODIFICATEUR_2_CCAM = LSCA_MOD2,
                        CODE_MODIFICATEUR_3_CCAM = LSCA_MOD3,
                        CODE_MODIFICATEUR_4_CCAM = LSCA_MOD4,
                        CODE_ANP_CCAM = LSCA_ASSNP,
                        CODE_EXTDOC_CCAM = LSCA_EXTDOC,
                        key = CODE_RUBRIQUE || ''|''::text || 
                            CODE_PRESTA || ''|''::text || 
							CODE_LPP || ''|''::text || 
							CODE_UCD || ''|''::text || 
                            w_OPERA_ACT_complet.CODE_MED_EXECUTANT || ''|''::text || 
                            CCAM_CODE
                    FROM w_LSCCAM
                    WHERE w_OPERA_ACT_complet.oid = ACT_id AND CODE_CCAM = '''' ', 20);


                    -- Attribution OID aux codes
                    
                    CREATE INDEX w_OPERA_ACT_complet_i3
                    ON w_OPERA_ACT_complet
                    USING btree
                    (KEY);
                    
                    DROP TABLE IF EXISTS w_OPERA_ACT_complet_key;
                    CREATE TEMP TABLE w_OPERA_ACT_complet_key AS
                    SELECT
                        key,
                        CODE_PRESTA,
						CODE_LPP,
						CODE_UCD,
                        CODE_RUBRIQUE,
                        CODE_MED_EXECUTANT,
                        CODE_CCAM,
                        0::bigint AS rubrique_facturation_id,
                        0::bigint AS prestation_id,
						0::bigint AS ucd_id,
						0::bigint AS lpp_id,
                        0::bigint AS medecin_administratif_id,
                        0::bigint AS acte_id
                    FROM w_OPERA_ACT_complet
                    GROUP BY 1,2,3,4,5,6,7;




                    ALTER TABLE w_OPERA_ACT_complet_key ADD CONSTRAINT w_OPERA_ACT_complet_key_pkey PRIMARY KEY(KEY);

                    UPDATE w_OPERA_ACT_complet_key
                    SET CODE_PRESTA = trim(substr(CODE_PRESTA,1,4))
                    WHERE substr(CODE_PRESTA,5,1) IN ('F', 'N');

                    UPDATE w_OPERA_ACT_complet_key
                    SET CODE_CCAM = CODE_PRESTA
                    WHERE CODE_CCAM = '' AND CODE_MED_EXECUTANT <> '';

                    INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
                    SELECT CODE_RUBRIQUE, CODE_RUBRIQUE, CODE_RUBRIQUE, CODE_RUBRIQUE
                    FROM w_OPERA_ACT_complet_key
                    WHERE CODE_RUBRIQUE <> '' AND
                        CODE_RUBRIQUE NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL) AND CODE_RUBRIQUE != ''
                    GROUP BY 1,2,3,4;


                    INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
                    SELECT CODE_PRESTA, CODE_PRESTA, CODE_PRESTA, CODE_PRESTA
                    FROM w_OPERA_ACT_complet_key
                    WHERE CODE_PRESTA <> '' AND
                        CODE_PRESTA NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL ) AND CODE_PRESTA != ''
                    GROUP BY 1,2,3,4;



                    UPDATE w_OPERA_ACT_complet_key
                        set rubrique_facturation_id = t_rubriques_facturation.oid
                    FROM activite[PX].t_rubriques_facturation
                    WHERE code_original = CODE_RUBRIQUE;

                    UPDATE w_OPERA_ACT_complet_key
                        set prestation_id = t_prestations.oid
                    FROM activite.t_prestations
                    WHERE code = CODE_PRESTA;

                    UPDATE w_OPERA_ACT_complet_key
                        set medecin_administratif_id = t_medecins_administratifs.oid
                    FROM activite[PX].t_medecins_administratifs
                    WHERE code_original = CODE_MED_EXECUTANT;

                    INSERT INTO base.t_actes(code, texte, texte_court, nomenclature)
                    SELECT substring(CODE_CCAM, 1, 7), substring(CODE_CCAM, 1, 7), substring(CODE_CCAM, 1, 7), 'NGAP'
                    FROM w_OPERA_ACT_complet_key
                    WHERE substring(CODE_CCAM, 1, 7) <> '' AND substring(CODE_CCAM, 1, 7) = CODE_PRESTA AND substring(CODE_CCAM, 1, 7) NOT IN (SELECT code FROM base.t_actes WHERE code IS NOT NULL)
                    GROUP BY 1,2,3;

                    INSERT INTO base.t_actes(code, texte, texte_court, nomenclature)
                    SELECT substring(CODE_CCAM, 1, 7), substring(CODE_CCAM, 1, 7), substring(CODE_CCAM, 1, 7), 'CCAM'
                    FROM w_OPERA_ACT_complet_key
                    WHERE substring(CODE_CCAM, 1, 7) <> '' AND substring(CODE_CCAM, 1, 7) <> CODE_PRESTA AND substring(CODE_CCAM, 1, 7) NOT IN (SELECT code FROM base.t_actes WHERE code IS NOT NULL)
                    GROUP BY 1,2,3;

                    UPDATE w_OPERA_ACT_complet_key
                        set acte_id = t_actes.oid
                    FROM base.t_actes
                    WHERE code = substring(CODE_CCAM, 1, 7);
					
					INSERT INTO base.t_ucd (code, texte, texte_court)
					SELECT CODE_UCD, CODE_UCD, CODE_UCD
					FROM w_OPERA_ACT_complet_key
					WHERE CODE_UCD NOT IN (SELECT code FROM base.t_ucd WHERE code IS NOT NULL)
					GROUP BY 1
					ORDER BY 1
					;
					
					UPDATE w_OPERA_ACT_complet_key 
                        SET ucd_id = t_ucd.oid
                    FROM base.t_ucd
                    WHERE t_ucd.code = CODE_UCD AND
						CODE_UCD <> '';
					
					INSERT INTO base.t_lpp (code, texte, texte_court)
					SELECT CODE_LPP, CODE_LPP, CODE_LPP
					FROM w_OPERA_ACT_complet_key
					WHERE CODE_LPP NOT IN (SELECT code FROM base.t_lpp WHERE code IS NOT NULL)
					GROUP BY 1
					ORDER BY 1
					;

					UPDATE w_OPERA_ACT_complet_key 
                        SET lpp_id = t_lpp.oid
                    FROM base.t_lpp
                    WHERE t_lpp.code = CODE_LPP AND
						CODE_LPP <> '';
                    
                    
                    
                    -- Génération lignes C

                    DROP TABLE IF EXISTS w_factures_lignes_c;
                    CREATE TEMP TABLE w_factures_lignes_c AS 
                    SELECT
                        p_factures.no_sejour,
                        p_factures.oid AS facture_id,
                        w_OPERA_ACT_complet.NO_FACTURE AS no_facture,
                        p_factures.date_vente,
                        
                        COEFF_ACTE AS coefficient,
                        1::numeric AS coefficient_mco,
                        w_OPERA_ACT_complet_key.rubrique_facturation_id AS rubrique_facturation_id,
                        w_OPERA_ACT_complet_key.rubrique_facturation_id AS rubrique_comptabilisation_id,
                        w_OPERA_ACT_complet_key.prestation_id AS prestation_id,
						w_OPERA_ACT_complet_key.ucd_id AS ucd_id,
						w_OPERA_ACT_complet_key.lpp_id AS lpp_id,
                        w_OPERA_ACT_complet.compte_produit_id,
                        p_sejours.lieu_sortie_id AS lieu_id,
                        1::bigint AS origine_facturation_id,

                        CASE WHEN w_OPERA_ACT_complet.prix_unitaire <> 0 THEN w_OPERA_ACT_complet.prix_unitaire ELSE
                            ROUND(base.cti_division((MONTANT_ACTE_AMO_C + MONTANT_ACTE_AMC_C + MONTANT_ACTE_IPP_C) , (QTE_ACTE * COEFF_ACTE)),2)
                        END AS prix_unitaire,
                        coalesce(TAUX_IPP,0) AS taux_0,
                        coalesce(TAUX_AMO,0) AS taux_1,
                        coalesce(TAUX_AMC,0) AS taux_2,
                        0::numeric AS taux_22,

                        date(DATE_ACTE_DEBUT) AS date_debut,
                        date(COALESCE(DATE_ACTE_FIN,DATE_ACTE_DEBUT)) AS date_fin,
                        QTE_ACTE AS nb_rubrique,
                        QTE_ACTE AS nb_prestation,
                        MONTANT_ACTE_AMO_C + MONTANT_ACTE_AMC_C + MONTANT_ACTE_IPP_C AS montant_facture,
                        MONTANT_ACTE_IPP_C AS montant_facture_0,
                        MONTANT_ACTE_AMO_C AS montant_facture_1,
                        MONTANT_ACTE_AMC_C AS montant_facture_2,
                        0::numeric AS montant_facture_22,
                        CPT_MONTANT_ACTE_AMO_C + CPT_MONTANT_ACTE_AMC_C + CPT_MONTANT_ACTE_IPP_C AS montant_comptabilise,
                        CPT_MONTANT_ACTE_IPP_C AS montant_comptabilise_0,
                        CPT_MONTANT_ACTE_AMO_C AS montant_comptabilise_1,
                        CPT_MONTANT_ACTE_AMC_C 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,
                        0::numeric AS montant_comptabilise_budget_global_1,
                        0::numeric AS rubrique_facture_id
                            
                    FROM w_OPERA_ACT_complet
                        JOIN activite[PX].p_factures ON w_OPERA_ACT_complet.NO_FACTURE = p_factures.no_facture
                        JOIN activite[PX].p_sejours ON w_OPERA_ACT_complet.NO_DOSSIER = p_sejours.code_original AND p_sejours.etat = ''
                        JOIN w_OPERA_ACT_complet_key ON w_OPERA_ACT_complet.key = w_OPERA_ACT_complet_key.key
                    WHERE p_factures.code_facture = '1' AND TYPE_PRESTA IN ('S', 's', 'P') ;

                    CREATE INDEX w_factures_lignes_c_i1
                    ON w_factures_lignes_c
                    USING btree
                    (no_sejour);
                    
                    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;
                        
                    -- Coefficient mco paramétré dans base
                    DROP TABLE IF EXISTS w_finess;
                    CREATE TEMP TABLE w_finess AS SELECT * FROM base.t_finess LIMIT 1
                    ;
                    
                    UPDATE w_factures_lignes_c
                        SET coefficient_mco =
                        CASE 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_9 THEN w_finess.coefficient_mco_9 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_8 THEN w_finess.coefficient_mco_8 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_7 THEN w_finess.coefficient_mco_7 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_6 THEN w_finess.coefficient_mco_6 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_5 THEN w_finess.coefficient_mco_5 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_4 THEN w_finess.coefficient_mco_4 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_3 THEN w_finess.coefficient_mco_3 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_2 THEN w_finess.coefficient_mco_2 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_1 THEN w_finess.coefficient_mco_1 
                        ELSE 1::numeric 
                        END
                    FROM w_finess,
                        activite.t_prestations
                    WHERE 
                        prestation_id = t_prestations.oid AND
                        t_prestations.code IN ('GHS', 'EXH') AND
                        (CASE 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_9 THEN w_finess.coefficient_mco_9 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_8 THEN w_finess.coefficient_mco_8 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_7 THEN w_finess.coefficient_mco_7 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_6 THEN w_finess.coefficient_mco_6 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_5 THEN w_finess.coefficient_mco_5 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_4 THEN w_finess.coefficient_mco_4 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_3 THEN w_finess.coefficient_mco_3 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_2 THEN w_finess.coefficient_mco_2 
                        WHEN date(date_fin) >= w_finess.date_debut_coefficient_mco_1 THEN w_finess.coefficient_mco_1 
                        ELSE 1::numeric 
                        END) <> 1
                    ;
                
                        
                    -- Rubriques internes cti
                    SELECT activite[PX].cti_reorganize_rubrique_facture_c('w_factures_lignes_c');


                    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,
						ucd_id,
						lpp_id,
                        compte_produit_id,
                        montant_facture,
                        montant_facture_0,
                        montant_facture_1,
                        montant_facture_2,
                        montant_facture_22,
                        taux_0,
                        taux_1,
                        taux_2,
                        taux_22,
                        prix_unitaire,
                        lieu_id,
                        montant_comptabilise,
                        montant_comptabilise_0,
                        montant_comptabilise_1,
                        montant_comptabilise_2,
                        montant_comptabilise_22,
                        montant_encours,
                        montant_encours_0,
                        montant_encours_1,
                        montant_encours_2,
                        montant_encours_22,
                        montant_facture_actes_inclus_dans_sejour,
                        montant_facture_0_actes_inclus_dans_sejour,
                        montant_facture_1_actes_inclus_dans_sejour,
                        montant_facture_2_actes_inclus_dans_sejour,
                        montant_facture_22_actes_inclus_dans_sejour,
                        montant_comptabilise_budget_global_1,
                        origine_facturation_id
                    )
                    SELECT
                        facture_id,
                        no_facture,
                        date_debut,
                        date_fin,
                        nb_rubrique,
                        nb_prestation,
                        coefficient,
                        coefficient_mco,
                        rubrique_facture_id,
                        rubrique_facturation_id,
                        rubrique_comptabilisation_id,
                        prestation_id,
						ucd_id,
						lpp_id,
                        compte_produit_id,
                        montant_facture,
                        montant_facture_0,
                        montant_facture_1,
                        montant_facture_2,
                        montant_facture_22,
                        taux_0,
                        taux_1,
                        taux_2,
                        taux_22,
                        prix_unitaire,
                        lieu_id,
                        montant_comptabilise,
                        montant_comptabilise_0,
                        montant_comptabilise_1,
                        montant_comptabilise_2,
                        montant_comptabilise_22,
                        montant_encours,
                        montant_encours_0,
                        montant_encours_1,
                        montant_encours_2,
                        montant_encours_22,
                        montant_facture_actes_inclus_dans_sejour,
                        montant_facture_0_actes_inclus_dans_sejour,
                        montant_facture_1_actes_inclus_dans_sejour,
                        montant_facture_2_actes_inclus_dans_sejour,
                        montant_facture_22_actes_inclus_dans_sejour,
                        montant_comptabilise_budget_global_1,
                        origine_facturation_id
                    FROM w_factures_lignes_c;
                    
                    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');
                    
                    -- Forcage date debut = date entree pour prestations à ventiler 
                    UPDATE activite[PX].p_factures_lignes_c
                    SET date_debut = p_factures.date_debut
                    FROM activite[PX].t_rubriques_facturation, activite.t_prestations, activite[PX].p_factures
                    JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                    WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
                        prestation_id = t_prestations.oid AND
                        t_prestations.type_ventilation_jour = '1' AND 
                        ABS(nb_rubrique) > 1 AND
                        p_factures_lignes_c.date_debut = p_factures_lignes_c.date_fin AND
                        p_sejours.date_sortie <> p_sejours.date_entree ;
                    
                    
                    -- Eclatement des supplements par jour
                    DROP TABLE IF EXISTS w_factures_lignes_sup_c;

                    CREATE TEMP TABLE w_factures_lignes_sup_c AS
                    SELECT
                        p_factures_lignes_c.CTID AS from_CTID, 
                        t_prestations.code AS prestation_code,
                        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(p_factures_lignes_c.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(p_factures_lignes_c.date_debut + ((ABS(nb_prestation)-1) || ' day')::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,
                        p_factures_lignes_c.*
                    FROM activite[PX].p_factures_lignes_c
                        JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
                        JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour AND p_sejours.etat = ''
                        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 activite[PX].p_factures_lignes_c
                            JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND code = 'EXH'
                        GROUP BY 1) subview
                    WHERE w_factures_lignes_sup_c.no_facture = subview.no_facture 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
                        from_CTID,
                        no_facture,
                        date AS date_debut,
                        date AS date_fin,
                        CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_rubrique,
                        CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation,
                        coefficient,
                        coefficient_mco,
                        rubrique_facturation_id,
                        prestation_id,
						ucd_id,
						lpp_id,
                        compte_produit_id,
                        round(montant_facture / ABS(nb_det),2) AS montant_facture,
                        round(montant_facture_0 / ABS(nb_det),2) AS montant_facture_0,
                        round(montant_facture_1 / ABS(nb_det),2) AS montant_facture_1,
                        round(montant_facture_2 / ABS(nb_det),2) AS montant_facture_2,
                        round(montant_facture_22 / ABS(nb_det),2) AS montant_facture_22,
                        taux_0,
                        taux_1,
                        taux_2,
                        taux_22,
                        finess,
                        prix_unitaire,
                        lieu_id,
                        round(montant_comptabilise / ABS(nb_det),2) AS montant_comptabilise,
                        round(montant_comptabilise_0 / ABS(nb_det),2) AS montant_comptabilise_0,
                        round(montant_comptabilise_1 / ABS(nb_det),2) AS montant_comptabilise_1,
                        round(montant_comptabilise_2 / ABS(nb_det),2) AS montant_comptabilise_2,
                        round(montant_comptabilise_22 / ABS(nb_det),2) AS montant_comptabilise_22,
                        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 date_debut BETWEEN p_calendrier.date - ABS(nb_det)::integer + 1 AND p_calendrier.date AND 
                                    p_calendrier.date <> date_debut ;
                    ;


                    DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup_tot;

                    CREATE TEMP TABLE w_factures_lignes_sup_c_sup_tot AS

                    SELECT from_CTID,
                        SUM(nb_rubrique) AS nb_rubrique,
                        SUM(nb_prestation) AS nb_prestation,
                        SUM(montant_facture) AS montant_facture,
                        SUM(montant_facture_0) AS montant_facture_0,
                        SUM(montant_facture_1) AS montant_facture_1,
                        SUM(montant_facture_2) AS montant_facture_2,
                        SUM(montant_facture_22) AS montant_facture_22,
                        SUM(montant_comptabilise) AS montant_comptabilise,
                        SUM(montant_comptabilise_0) AS montant_comptabilise_0,
                        SUM(montant_comptabilise_1) AS montant_comptabilise_1,
                        SUM(montant_comptabilise_2) AS montant_comptabilise_2,
                        SUM(montant_comptabilise_22) AS montant_comptabilise_22,
                        SUM(montant_encours) AS montant_encours,
                        SUM(montant_encours_0) AS montant_encours_0,
                        SUM(montant_encours_1) AS montant_encours_1,
                        SUM(montant_encours_2) AS montant_encours_2,
                        SUM(montant_encours_22) AS montant_encours_22,
                        SUM(montant_facture_actes_inclus_dans_sejour) AS montant_facture_actes_inclus_dans_sejour,
                        SUM(montant_facture_0_actes_inclus_dans_sejour) AS montant_facture_0_actes_inclus_dans_sejour,
                        SUM(montant_facture_1_actes_inclus_dans_sejour) AS montant_facture_1_actes_inclus_dans_sejour,
                        SUM(montant_facture_2_actes_inclus_dans_sejour) AS montant_facture_2_actes_inclus_dans_sejour,
                        SUM(montant_facture_22_actes_inclus_dans_sejour) AS montant_facture_22_actes_inclus_dans_sejour,
                        SUM(montant_comptabilise_budget_global_1) AS montant_comptabilise_budget_global_1
                    FROM w_factures_lignes_sup_c_sup
                    GROUP BY 1;


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

                    INSERT INTO activite[PX].p_factures_lignes_c(
                        no_facture,
                        date_debut,
                        date_fin,
                        nb_rubrique,
                        coefficient,
                        coefficient_mco,
                        rubrique_facturation_id,
                        prestation_id,
						ucd_id,
						lpp_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,
                        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)
                    SELECT 
                        no_facture,
                        date_debut,
                        date_fin,
                        nb_rubrique,
                        coefficient,
                        coefficient_mco,
                        rubrique_facturation_id,
                        prestation_id,
						ucd_id,
						lpp_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,
                        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
                    FROM w_factures_lignes_sup_c_sup;


                    -- 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;
                            
                                            
                ]]></sqlcmd>
            </NODE>
        
            <NODE label="Compte client Clinique">
                <sqlcmd><![CDATA[
                
                    -- Mise à jour facture (montants honoraires comptabilisés en clinique)
                    DROP TABLE IF EXISTS w_correction_compta;
                    CREATE TEMP TABLE w_correction_compta AS
                    SELECT
                        no_facture,
                        SUM(montant_comptabilise - montant_facture) AS ecart,
                        SUM(montant_comptabilise_1 - montant_facture_1) AS ecart_1,
                        SUM(montant_comptabilise_2 - montant_facture_2) AS ecart_2,
                        SUM(montant_comptabilise_22 - montant_facture_22) AS ecart_22,
                        SUM(montant_comptabilise_0 - montant_facture_0) AS ecart_0
                    FROM activite[PX].p_factures_lignes_c
                    GROUP BY 1
                    HAVING SUM(montant_comptabilise - montant_facture) <> 0;


                    UPDATE activite[PX].p_factures SET
                        montant_comptabilise_c = montant_comptabilise_c + ecart,
                        montant_comptabilise_1_c = montant_comptabilise_1_c + ecart_1,
                        montant_comptabilise_2_c = montant_comptabilise_2_c + ecart_2,
                        montant_comptabilise_22_c = montant_comptabilise_22_c + ecart_22,
                        montant_comptabilise_0_c = montant_comptabilise_0_c + ecart_0
                    FROM w_correction_compta
                    WHERE w_correction_compta.no_facture = p_factures.no_facture;
                
                    -- Ventes

                    DROP TABLE IF EXISTS w_factures_soldes_c;
                    CREATE TEMP TABLE w_factures_soldes_c AS
                    SELECT
                        facture_id,
                        no_facture,
                        date_trunc('month',date_vente) + interval '1 month' - interval '1 day' AS date_comptable,
                        rubrique_comptabilisation_id,
                        prestation_id,
                        SUM(montant_comptabilise) AS montant_comptabilise,
                        SUM(montant_comptabilise_0) AS montant_comptabilise_0,
                        SUM(montant_comptabilise_1) AS montant_comptabilise_1,
                        SUM(montant_comptabilise_2) AS montant_comptabilise_2,
                        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
                    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;

                    -- Reglements complets AMO
                    INSERT INTO w_factures_soldes_c
                    SELECT
                        facture_id,
                        w_factures_lignes_c.no_facture, 
                        date_trunc('month',date_solde_1_c) + interval '1 month' - interval '1 day' AS date_comptable,
                        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(montant_comptabilise_1) AS montant_regle, 
                        0 AS montant_regle_0, 
                        SUM(montant_comptabilise_1) AS montant_regle_1, 
                        0 AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_factures_lignes_c
                        JOIN activite[PX].p_factures ON w_factures_lignes_c.no_facture = p_factures.NO_FACTURE
                    WHERE montant_comptabilise_1_c = montant_regle_1_c AND montant_comptabilise_1_c <> 0
                    GROUP BY 1,2,3,4,5
                    HAVING SUM(montant_comptabilise_1) <> 0;




                    -- Reglements partiels AMO
                    INSERT INTO w_factures_soldes_c
                    SELECT
                        p_factures.oid AS facture_id,
                        p_factures.no_facture, 
                        date_trunc('month',DATE_REGLEMENT_AMO_C) + interval '1 month' - interval '1 day' 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, 
                        SUM(MONTANT_REGLEMENT_AMO_C) AS montant_regle, 
                        0 AS montant_regle_0, 
                        SUM(MONTANT_REGLEMENT_AMO_C) AS montant_regle_1, 
                        0 AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_OPERA_REG_complet
                        JOIN activite[PX].p_factures ON w_OPERA_REG_complet.no_facture = p_factures.NO_FACTURE
                        JOIN activite.t_prestations ON t_prestations.code_original =  '*ATTNSCTI'
                        JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original =  '*ATTNSCTI'
                    WHERE MONTANT_REGLEMENT_AMO_C IS NOT NULL AND MONTANT_REGLEMENT_AMO_C <> 0 AND 
                        (montant_comptabilise_1_c <> montant_regle_1_c OR DATE_REGLEMENT_AMO_C < date_solde_1_c)
                    GROUP BY 1,2,3,4,5
                    HAVING SUM(MONTANT_REGLEMENT_AMO_C) <> 0;

                    -- contrepartie reglements partiels sur dossiers soldes AMO
                    INSERT INTO w_factures_soldes_c
                    SELECT
                        p_factures.oid AS facture_id,
                        p_factures.no_facture, 
                        date_trunc('month',date_solde_1_c) + interval '1 month' - interval '1 day' 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, 
                        SUM(0-MONTANT_REGLEMENT_AMO_C) AS montant_regle, 
                        0 AS montant_regle_0, 
                        SUM(0-MONTANT_REGLEMENT_AMO_C) AS montant_regle_1, 
                        0 AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_OPERA_REG_complet
                        JOIN activite[PX].p_factures ON w_OPERA_REG_complet.no_facture = p_factures.NO_FACTURE
                        JOIN activite.t_prestations ON t_prestations.code_original =  '*ATTNSCTI'
                        JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original =  '*ATTNSCTI'
                    WHERE MONTANT_REGLEMENT_AMO_C IS NOT NULL AND MONTANT_REGLEMENT_AMO_C <> 0 AND 
                        (montant_comptabilise_1_c = montant_regle_1_c AND DATE_REGLEMENT_AMO_C < date_solde_1_c)
                    GROUP BY 1,2,3,4,5
                    HAVING SUM(MONTANT_REGLEMENT_AMO_C) <> 0;



                    -- Reglements complets AMC
                    INSERT INTO w_factures_soldes_c
                    SELECT
                        facture_id,
                        w_factures_lignes_c.no_facture, 
                        date_trunc('month',date_solde_2_c) + interval '1 month' - interval '1 day' AS date_comptable,
                        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(montant_comptabilise_2) AS montant_regle, 
                        0 AS montant_regle_0, 
                        0 AS montant_regle_1, 
                        SUM(montant_comptabilise_2) AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_factures_lignes_c
                        JOIN activite[PX].p_factures ON w_factures_lignes_c.no_facture = p_factures.NO_FACTURE
                    WHERE montant_comptabilise_2_c = montant_regle_2_c AND montant_comptabilise_2_c <> 0
                    GROUP BY 1,2,3,4,5
                    HAVING SUM(montant_comptabilise_2) <> 0;




                    -- Reglements partiels AMC
                    INSERT INTO w_factures_soldes_c
                    SELECT
                        p_factures.oid AS facture_id,
                        p_factures.no_facture, 
                        date_trunc('month',DATE_REGLEMENT_AMC_C) + interval '1 month' - interval '1 day' 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, 
                        SUM(MONTANT_REGLEMENT_AMC_C) AS montant_regle, 
                        0 AS montant_regle_0, 
                        0 AS montant_regle_1, 
                        SUM(MONTANT_REGLEMENT_AMC_C) AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_OPERA_REG_complet
                        JOIN activite[PX].p_factures ON w_OPERA_REG_complet.no_facture = p_factures.NO_FACTURE
                        JOIN activite.t_prestations ON t_prestations.code_original =  '*ATTNSCTI'
                        JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original =  '*ATTNSCTI'
                    WHERE MONTANT_REGLEMENT_AMC_C IS NOT NULL AND MONTANT_REGLEMENT_AMC_C <> 0 AND 
                        (montant_comptabilise_2_c <> montant_regle_2_c OR DATE_REGLEMENT_AMC_C < date_solde_2_c)
                    GROUP BY 1,2,3,4,5
                    HAVING SUM(MONTANT_REGLEMENT_AMC_C) <> 0;

                    -- contrepartie reglements partiels sur dossiers soldes AMC
                    INSERT INTO w_factures_soldes_c
                    SELECT
                        p_factures.oid AS facture_id,
                        p_factures.no_facture, 
                        date_trunc('month',date_solde_2_c) + interval '1 month' - interval '1 day' 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, 
                        SUM(0-MONTANT_REGLEMENT_AMC_C) AS montant_regle, 
                        0 AS montant_regle_0, 
                        0 AS montant_regle_1, 
                        SUM(0-MONTANT_REGLEMENT_AMC_C) AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_OPERA_REG_complet
                        JOIN activite[PX].p_factures ON w_OPERA_REG_complet.no_facture = p_factures.NO_FACTURE
                        JOIN activite.t_prestations ON t_prestations.code_original =  '*ATTNSCTI'
                        JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original =  '*ATTNSCTI'
                    WHERE MONTANT_REGLEMENT_AMC_C IS NOT NULL AND MONTANT_REGLEMENT_AMC_C <> 0 AND 
                        (montant_comptabilise_2_c = montant_regle_2_c AND DATE_REGLEMENT_AMC_C < date_solde_2_c)
                    GROUP BY 1,2,3,4,5
                    HAVING SUM(MONTANT_REGLEMENT_AMC_C) <> 0;



                    -- Reglements complets IPP
                    INSERT INTO w_factures_soldes_c
                    SELECT
                        facture_id,
                        w_factures_lignes_c.no_facture, 
                        date_trunc('month',date_solde_0_c) + interval '1 month' - interval '1 day' AS date_comptable,
                        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(montant_comptabilise_0) AS montant_regle, 
                        SUM(montant_comptabilise_0) AS montant_regle_0, 
                        0 AS montant_regle_1, 
                        0 AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_factures_lignes_c
                        JOIN activite[PX].p_factures ON w_factures_lignes_c.no_facture = p_factures.NO_FACTURE
                    WHERE montant_comptabilise_0_c = montant_regle_0_c AND montant_comptabilise_0_c <> 0
                    GROUP BY 1,2,3,4,5
                    HAVING SUM(montant_comptabilise_0) <> 0;


                    -- Reglements partiels IPP
                    INSERT INTO w_factures_soldes_c
                    SELECT
                        p_factures.oid AS facture_id,
                        p_factures.no_facture, 
                        date_trunc('month',DATE_REGLEMENT_IPP_C) + interval '1 month' - interval '1 day' 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, 
                        SUM(MONTANT_REGLEMENT_IPP_C) AS montant_regle, 
                        SUM(MONTANT_REGLEMENT_IPP_C) AS montant_regle_0, 
                        0 AS montant_regle_1, 
                        0 AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_OPERA_REG_complet
                        JOIN activite[PX].p_factures ON w_OPERA_REG_complet.no_facture = p_factures.NO_FACTURE
                        JOIN activite.t_prestations ON t_prestations.code_original =  '*ATTNSCTI'
                        JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original =  '*ATTNSCTI'
                    WHERE MONTANT_REGLEMENT_IPP_C IS NOT NULL AND MONTANT_REGLEMENT_IPP_C <> 0 AND 
                        (montant_comptabilise_0_c <> montant_regle_0_c OR DATE_REGLEMENT_IPP_C < date_solde_0_c)
                    GROUP BY 1,2,3,4,5
                    HAVING SUM(MONTANT_REGLEMENT_IPP_C) <> 0;

                    -- contrepartie reglements partiels sur dossiers soldes IPP
                    INSERT INTO w_factures_soldes_c
                    SELECT
                        p_factures.oid AS facture_id,
                        p_factures.no_facture, 
                        date_trunc('month',date_solde_0_c) + interval '1 month' - interval '1 day' 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, 
                        SUM(0-MONTANT_REGLEMENT_IPP_C) AS montant_regle, 
                        SUM(0-MONTANT_REGLEMENT_IPP_C) AS montant_regle_0, 
                        0 AS montant_regle_1, 
                        0 AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_OPERA_REG_complet
                        JOIN activite[PX].p_factures ON w_OPERA_REG_complet.no_facture = p_factures.NO_FACTURE
                        JOIN activite.t_prestations ON t_prestations.code_original =  '*ATTNSCTI'
                        JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original =  '*ATTNSCTI'
                    WHERE MONTANT_REGLEMENT_IPP_C IS NOT NULL AND MONTANT_REGLEMENT_IPP_C <> 0 AND 
                        (montant_comptabilise_0_c = montant_regle_0_c AND DATE_REGLEMENT_IPP_C < date_solde_0_c)
                    GROUP BY 1,2,3,4,5
                    HAVING SUM(MONTANT_REGLEMENT_IPP_C) <> 0;


                    -- Validation

                    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_comptable,
                        rubrique_comptabilisation_id,
                        prestation_id,
                        SUM(montant_comptabilise),
                        SUM(montant_comptabilise_0),
                        SUM(montant_comptabilise_1),
                        SUM(montant_comptabilise_2),
                        SUM(montant_comptabilise_22),
                        SUM(montant_regle),
                        SUM(montant_regle_0),
                        SUM(montant_regle_1),
                        SUM(montant_regle_2),
                        SUM(montant_regle_22)
                    FROM w_factures_soldes_c
                    GROUP BY 1,2,3,4,5;

                    
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_1');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_2');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_3');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_4');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_8');
                    
                                            
                                            
                ]]></sqlcmd>
            </NODE>
        
            <NODE label="Lignes non facturées Honoraires">
                <sqlcmd><![CDATA[
                
                    TRUNCATE activite[PX].p_factures_lignes_non_facturees_h;

                    INSERT INTO activite[PX].p_factures_lignes_non_facturees_h(
                        no_facture, 
                        date_debut, 
                        date_fin, 
                        heure_debut, 
                        nb_rubrique, 
                        coefficient, 
                        medecin_facture_id, 
                        prestation_id, 
                        prix_unitaire, 
                        montant_depassement, 
                        lieu_id, 
                        acte_id, 
                        phase_ccam, 
                        activite_ccam, 
                        extension_ccam, 
                        modificateur_ccam_1, 
                        modificateur_ccam_2,
                        modificateur_ccam_3, 
                        modificateur_ccam_4)
                    SELECT 
                        p_factures.no_facture, 
                        date(LSR_DDEB) AS date_debut, 
                        date(LSR_DDEB) AS date_fin, 
                        0::numeric AS heure_debut, 
                        1::numeric AS nb_rubrique, 
                        1::numeric AS coefficient, 
                        t_medecins_administratifs.oid AS medecin_facture_id, 
                        t_prestations.oid AS prestation_id, 
                        0::numeric AS prix_unitaire, 
                        0::numeric AS montant_depassement, 
                        p_sejours.lieu_sortie_id AS lieu_id, 
                        t_actes.oid AS acte_id, 
                        CCAM_PHS AS phase_ccam, 
                        CCAM_ACTV AS activite_ccam, 
                        LSCA_EXTDOC AS extension_ccam, 
                        LSCA_MOD1 AS modificateur_ccam_1, 
                        LSCA_MOD2 AS modificateur_ccam_2,
                        LSCA_MOD3 AS modificateur_ccam_3, 
                        LSCA_MOD4 AS modificateur_ccam_4
                    FROM prod_cegi.CJ_SEJOUR
                        JOIN w_OPERA_SEJ_select ON CJ_SEJOUR.SEJ_NUMDOS = w_OPERA_SEJ_select.NO_DOSSIER
                        JOIN activite[PX].p_sejours ON w_OPERA_SEJ_select.NO_DOSSIER = p_sejours.code_original AND p_sejours.etat = ''
                        JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND 
                            p_factures.no_facture_reference = p_factures.no_facture AND 
                            code_facture <> '1' AND
                            p_factures.provider_id = 2
                        JOIN prod_cegi.CJ_LSRGP ON CJ_LSRGP.SEJ_ID = CJ_SEJOUR.SEJ_ID AND LSR_ACTIF = 1
                        JOIN prod_cegi.CJ_LSCCAM ON CJ_LSCCAM.LSR_ID = CJ_LSRGP.LSR_ID AND LSCA_ACTIF = 1
                        JOIN prod_cegi.CJ_CCAM ON CJ_CCAM.CCAM_ID = CJ_LSCCAM.CCAM_ID
                        JOIN prod_cegi.CJ_PRA ON CJ_PRA.TER_ID = CJ_LSCCAM.TER_ID
                        JOIN base.t_actes ON t_actes.code = substring(CCAM_CODE, 1, 7)
                        JOIN base.t_ccam_regroupements ON ccam_regroupement_id_1 = t_ccam_regroupements.oid
                        JOIN activite.t_prestations ON t_prestations.code = CASE WHEN CCAM_ACTV = '1' THEN t_ccam_regroupements.code ELSE 'ADA' END
                        JOIN activite[PX].t_medecins_administratifs ON PRA_LIBC = t_medecins_administratifs.code_original;
                                            
                                            
                ]]></sqlcmd>
            </NODE>
            
            <NODE label="Lignes factures Honoraires">
                <sqlcmd><![CDATA[
                    
                    DROP TABLE IF EXISTS w_factures_lignes_h;
                    CREATE TEMP TABLE w_factures_lignes_h AS 
                    SELECT
                            p_factures.no_sejour,
                            p_factures.oid AS facture_id,
                            w_OPERA_ACT_complet.NO_FACTURE AS no_facture,
                            p_factures.date_vente,
                            
                            date(DATE_ACTE_DEBUT) AS date_debut,
                            HEURE_ACTE_DEBUT * 10000 AS heure_debut,
                            date(COALESCE(DATE_ACTE_FIN,DATE_ACTE_DEBUT)) AS date_fin,
                            QTE_ACTE AS nb_rubrique,
                            QTE_ACTE AS nb_prestation,
                            COEFF_ACTE AS coefficient,
                            1::numeric AS coefficient_mco,
                            w_OPERA_ACT_complet_key.medecin_administratif_id AS medecin_facture_id,
                            w_OPERA_ACT_complet_key.medecin_administratif_id AS medecin_comptabilise_id,
                            w_OPERA_ACT_complet_key.prestation_id AS prestation_id,
                            w_OPERA_ACT_complet_key.acte_id AS acte_id, 
                            CODE_ACTIVITE_CCAM AS activite_ccam,
                            CODE_EXTDOC_CCAM AS extension_ccam,
                            CODE_PHASE_CCAM AS phase_ccam,
                            CODE_MODIFICATEUR_1_CCAM AS modificateur_ccam_1,
                            CODE_MODIFICATEUR_2_CCAM AS modificateur_ccam_2,
                            CODE_MODIFICATEUR_3_CCAM AS modificateur_ccam_3,
                            CODE_MODIFICATEUR_4_CCAM AS modificateur_ccam_4,
                            MONTANT_ACTE_AMO_H + MONTANT_ACTE_AMC_H  + MONTANT_ACTE_IPP_H  AS montant_facture,
                            MONTANT_ACTE_IPP_H AS montant_facture_0,
                            MONTANT_ACTE_AMO_H AS montant_facture_1,
                            MONTANT_ACTE_AMC_H AS montant_facture_2,
                            0::numeric AS montant_facture_22,
                            MONTANT_DP AS montant_depassement,
                            coalesce(TAUX_IPP,0) AS taux_0,
                            coalesce(TAUX_AMO,0) AS taux_1,
                            coalesce(TAUX_AMC,0) AS taux_2,
                            0::numeric AS taux_22,
                            ROUND(base.cti_division((MONTANT_ACTE_AMO_H + MONTANT_ACTE_AMC_H + MONTANT_ACTE_IPP_H) , (QTE_ACTE * COEFF_ACTE)),2) AS prix_unitaire,
                            p_sejours.lieu_sortie_id AS lieu_id,
                            CPT_MONTANT_ACTE_AMO_H + CPT_MONTANT_ACTE_AMC_H + CPT_MONTANT_ACTE_IPP_H AS montant_comptabilise,
                            CPT_MONTANT_ACTE_IPP_H AS montant_comptabilise_0,
                            CPT_MONTANT_ACTE_AMO_H AS montant_comptabilise_1,
                            CPT_MONTANT_ACTE_AMC_H 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
                    FROM w_OPERA_ACT_complet
                        JOIN activite[PX].p_factures ON w_OPERA_ACT_complet.NO_FACTURE = p_factures.no_facture
                        JOIN activite[PX].p_sejours ON w_OPERA_ACT_complet.NO_DOSSIER = p_sejours.code_original AND p_sejours.etat = ''
                        JOIN w_OPERA_ACT_complet_key ON w_OPERA_ACT_complet.key = w_OPERA_ACT_complet_key.key
                    WHERE p_factures.code_facture = '1' AND TYPE_PRESTA IN ('H','s') ;
                    ;
                    
                    -- Signe du montant dépassement selon montant facture
                    UPDATE w_factures_lignes_h
                    SET montant_depassement = montant_depassement * -1
                    WHERE
                        montant_facture < 0 and montant_depassement > 0;
                    

                    CREATE INDEX w_factures_lignes_h_i1
                    ON w_factures_lignes_h
                    USING btree
                    (no_sejour);
                    
                    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,
                        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,
                        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;
                    
                    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');
                    
                    -- Lieu exécution
                    
                    UPDATE activite[PX].p_factures_lignes_h
                    SET lieu_id = p_mouvements_sejour.lieu_id
                    FROM 
                        activite[PX].p_factures, 
                        activite[PX].p_mouvements_sejour
                    WHERE
                        p_factures_lignes_h.no_facture = p_factures.no_facture AND
                        p_factures.no_sejour = p_mouvements_sejour.no_sejour AND
                        p_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
                        p_factures_lignes_h.lieu_id <> p_mouvements_sejour.lieu_id;         
                                            
                ]]></sqlcmd>
            </NODE>
        
            <NODE label="Compte client Honoraires">
                <sqlcmd><![CDATA[
                
                    -- Mise à jour facture (montants honoraires comptabilisés en clinique)
                    
                    DROP TABLE IF EXISTS w_correction_compta;
                    CREATE TEMP TABLE w_correction_compta AS
                    SELECT
                        no_facture,
                        SUM(montant_comptabilise - montant_facture) AS ecart,
                        SUM(montant_comptabilise_1 - montant_facture_1) AS ecart_1,
                        SUM(montant_comptabilise_2 - montant_facture_2) AS ecart_2,
                        SUM(montant_comptabilise_22 - montant_facture_22) AS ecart_22,
                        SUM(montant_comptabilise_0 - montant_facture_0) AS ecart_0
                    FROM activite[PX].p_factures_lignes_h
                    GROUP BY 1
                    HAVING SUM(montant_comptabilise - montant_facture) <> 0;


                    UPDATE activite[PX].p_factures SET
                        montant_comptabilise_h = montant_comptabilise_h + ecart,
                        montant_comptabilise_1_h = montant_comptabilise_1_h + ecart_1,
                        montant_comptabilise_2_h = montant_comptabilise_2_h + ecart_2,
                        montant_comptabilise_22_h = montant_comptabilise_22_h + ecart_22,
                        montant_comptabilise_0_h = montant_comptabilise_0_h + ecart_0
                    FROM w_correction_compta
                    WHERE w_correction_compta.no_facture = p_factures.no_facture;
                    
                    -- Ventes

                    DROP TABLE IF EXISTS w_factures_soldes_h;
                    CREATE TEMP TABLE w_factures_soldes_h AS
                    SELECT
                        facture_id,
                        no_facture,
                        date_trunc('month',date_vente) + interval '1 month' - interval '1 day' AS date_comptable,
                        medecin_comptabilise_id,
                        SUM(montant_comptabilise) AS montant_comptabilise,
                        SUM(montant_comptabilise_0) AS montant_comptabilise_0,
                        SUM(montant_comptabilise_1) AS montant_comptabilise_1,
                        SUM(montant_comptabilise_2) AS montant_comptabilise_2,
                        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
                    FROM w_factures_lignes_h
                    WHERE date_vente IS NOT NULL  AND
                        (montant_comptabilise <> 0 OR 
                        montant_comptabilise_0 <> 0 OR 
                        montant_comptabilise_1 <> 0 OR 
                        montant_comptabilise_2 <> 0 OR 
                        montant_comptabilise_22 <> 0 
                        )
                    GROUP BY 1,2,3,4;

                    -- Reglements complets AMO
                    INSERT INTO w_factures_soldes_h
                    SELECT
                        facture_id,
                        w_factures_lignes_h.no_facture, 
                        date_trunc('month',date_solde_1_h) + interval '1 month' - interval '1 day' AS date_comptable,
                        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, 
                        SUM(montant_comptabilise_1) AS montant_regle, 
                        0 AS montant_regle_0, 
                        SUM(montant_comptabilise_1) AS montant_regle_1, 
                        0 AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_factures_lignes_h
                        JOIN activite[PX].p_factures ON w_factures_lignes_h.no_facture = p_factures.NO_FACTURE
                    WHERE montant_comptabilise_1_h = montant_regle_1_h AND montant_comptabilise_1_h <> 0
                    GROUP BY 1,2,3,4
                    HAVING SUM(montant_comptabilise_1) <> 0;


                    -- Reglements partiels AMO
                    INSERT INTO w_factures_soldes_h
                    SELECT
                        p_factures.oid AS facture_id,
                        p_factures.no_facture, 
                        date_trunc('month',DATE_REGLEMENT_AMO_H) + interval '1 month' - interval '1 day' AS date_comptable,
                        t_medecins_administratifs.oid AS 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, 
                        SUM(MONTANT_REGLEMENT_AMO_H) AS montant_regle, 
                        0 AS montant_regle_0, 
                        SUM(MONTANT_REGLEMENT_AMO_H) AS montant_regle_1, 
                        0 AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_OPERA_REG_complet
                        JOIN activite[PX].p_factures ON w_OPERA_REG_complet.no_facture = p_factures.NO_FACTURE
                        JOIN activite[PX].t_medecins_administratifs ON t_medecins_administratifs.code_original =  '*ATTNSCTI'
                    WHERE MONTANT_REGLEMENT_AMO_H IS NOT NULL AND MONTANT_REGLEMENT_AMO_H <> 0 AND 
                        (montant_comptabilise_1_h <> montant_regle_1_h OR DATE_REGLEMENT_AMO_H < date_solde_1_h)
                    GROUP BY 1,2,3,4
                    HAVING SUM(MONTANT_REGLEMENT_AMO_H) <> 0;

                    -- contrepartie reglements partiels sur dossiers soldes AMO
                    INSERT INTO w_factures_soldes_h
                    SELECT
                        p_factures.oid AS facture_id,
                        p_factures.no_facture, 
                        date_trunc('month',date_solde_1_h) + interval '1 month' - interval '1 day' AS date_comptable,
                        t_medecins_administratifs.oid AS 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, 
                        SUM(0-MONTANT_REGLEMENT_AMO_H) AS montant_regle, 
                        0 AS montant_regle_0, 
                        SUM(0-MONTANT_REGLEMENT_AMO_H) AS montant_regle_1, 
                        0 AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_OPERA_REG_complet
                        JOIN activite[PX].p_factures ON w_OPERA_REG_complet.no_facture = p_factures.NO_FACTURE
                        JOIN activite[PX].t_medecins_administratifs ON t_medecins_administratifs.code_original =  '*ATTNSCTI'
                    WHERE MONTANT_REGLEMENT_AMO_H IS NOT NULL AND MONTANT_REGLEMENT_AMO_H <> 0 AND 
                        (montant_comptabilise_1_h = montant_regle_1_h AND DATE_REGLEMENT_AMO_H < date_solde_1_h)
                    GROUP BY 1,2,3,4
                    HAVING SUM(MONTANT_REGLEMENT_AMO_H) <> 0;



                    -- Reglements complets AMC
                    INSERT INTO w_factures_soldes_h
                    SELECT
                        facture_id,
                        w_factures_lignes_h.no_facture, 
                        date_trunc('month',date_solde_2_h) + interval '1 month' - interval '1 day' AS date_comptable,
                        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, 
                        SUM(montant_comptabilise_2) AS montant_regle, 
                        0 AS montant_regle_0, 
                        0 AS montant_regle_1, 
                        SUM(montant_comptabilise_2) AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_factures_lignes_h
                        JOIN activite[PX].p_factures ON w_factures_lignes_h.no_facture = p_factures.NO_FACTURE
                    WHERE montant_comptabilise_2_h = montant_regle_2_h AND montant_comptabilise_2_h <> 0
                    GROUP BY 1,2,3,4
                    HAVING SUM(montant_comptabilise_2) <> 0;




                    -- Reglements partiels AMC
                    INSERT INTO w_factures_soldes_h
                    SELECT
                        p_factures.oid AS facture_id,
                        p_factures.no_facture, 
                        date_trunc('month',DATE_REGLEMENT_AMC_H) + interval '1 month' - interval '1 day' AS date_comptable,
                        t_medecins_administratifs.oid AS 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, 
                        SUM(MONTANT_REGLEMENT_AMC_H) AS montant_regle, 
                        0 AS montant_regle_0, 
                        0 AS montant_regle_1, 
                        SUM(MONTANT_REGLEMENT_AMC_H) AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_OPERA_REG_complet
                        JOIN activite[PX].p_factures ON w_OPERA_REG_complet.no_facture = p_factures.NO_FACTURE
                        JOIN activite[PX].t_medecins_administratifs ON t_medecins_administratifs.code_original =  '*ATTNSCTI'
                    WHERE MONTANT_REGLEMENT_AMC_H IS NOT NULL AND MONTANT_REGLEMENT_AMC_H <> 0 AND 
                        (montant_comptabilise_2_h <> montant_regle_2_h OR DATE_REGLEMENT_AMC_H < date_solde_2_h)
                    GROUP BY 1,2,3,4
                    HAVING SUM(MONTANT_REGLEMENT_AMC_H) <> 0;

                    -- contrepartie reglements partiels sur dossiers soldes AMC
                    INSERT INTO w_factures_soldes_h
                    SELECT
                        p_factures.oid AS facture_id,
                        p_factures.no_facture, 
                        date_trunc('month',date_solde_2_h) + interval '1 month' - interval '1 day' AS date_comptable,
                        t_medecins_administratifs.oid AS 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, 
                        SUM(0-MONTANT_REGLEMENT_AMC_H) AS montant_regle, 
                        0 AS montant_regle_0, 
                        0 AS montant_regle_1, 
                        SUM(0-MONTANT_REGLEMENT_AMC_H) AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_OPERA_REG_complet
                        JOIN activite[PX].p_factures ON w_OPERA_REG_complet.no_facture = p_factures.NO_FACTURE
                        JOIN activite[PX].t_medecins_administratifs ON t_medecins_administratifs.code_original =  '*ATTNSCTI'
                    WHERE MONTANT_REGLEMENT_AMC_H IS NOT NULL AND MONTANT_REGLEMENT_AMC_H <> 0 AND 
                        (montant_comptabilise_2_h = montant_regle_2_h AND DATE_REGLEMENT_AMC_H < date_solde_2_h)
                    GROUP BY 1,2,3,4
                    HAVING SUM(MONTANT_REGLEMENT_AMC_H) <> 0;



                    -- Reglements complets IPP
                    INSERT INTO w_factures_soldes_h
                    SELECT
                        facture_id,
                        w_factures_lignes_h.no_facture, 
                        date_trunc('month',date_solde_0_h) + interval '1 month' - interval '1 day' AS date_comptable,
                        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, 
                        SUM(montant_comptabilise_0) AS montant_regle, 
                        SUM(montant_comptabilise_0) AS montant_regle_0, 
                        0 AS montant_regle_1, 
                        0 AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_factures_lignes_h
                        JOIN activite[PX].p_factures ON w_factures_lignes_h.no_facture = p_factures.NO_FACTURE
                    WHERE montant_comptabilise_0_h = montant_regle_0_h AND montant_comptabilise_0_h <> 0
                    GROUP BY 1,2,3,4
                    HAVING SUM(montant_comptabilise_0) <> 0;


                    -- Reglements partiels IPP
                    INSERT INTO w_factures_soldes_h
                    SELECT
                        p_factures.oid AS facture_id,
                        p_factures.no_facture, 
                        date_trunc('month',DATE_REGLEMENT_IPP_H) + interval '1 month' - interval '1 day' AS date_comptable,
                        t_medecins_administratifs.oid AS 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, 
                        SUM(MONTANT_REGLEMENT_IPP_H) AS montant_regle, 
                        SUM(MONTANT_REGLEMENT_IPP_H) AS montant_regle_0, 
                        0 AS montant_regle_1, 
                        0 AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_OPERA_REG_complet
                        JOIN activite[PX].p_factures ON w_OPERA_REG_complet.no_facture = p_factures.NO_FACTURE
                        JOIN activite[PX].t_medecins_administratifs ON t_medecins_administratifs.code_original =  '*ATTNSCTI'
                    WHERE MONTANT_REGLEMENT_IPP_H IS NOT NULL AND MONTANT_REGLEMENT_IPP_H <> 0 AND 
                        (montant_comptabilise_0_h <> montant_regle_0_h OR DATE_REGLEMENT_IPP_H < date_solde_0_h)
                    GROUP BY 1,2,3,4
                    HAVING SUM(MONTANT_REGLEMENT_IPP_H) <> 0;

                    -- contrepartie reglements partiels sur dossiers soldes IPP
                    INSERT INTO w_factures_soldes_h
                    SELECT
                        p_factures.oid AS facture_id,
                        p_factures.no_facture, 
                        date_trunc('month',date_solde_0_h) + interval '1 month' - interval '1 day' AS date_comptable,
                        t_medecins_administratifs.oid AS 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, 
                        SUM(0-MONTANT_REGLEMENT_IPP_H) AS montant_regle, 
                        SUM(0-MONTANT_REGLEMENT_IPP_H) AS montant_regle_0, 
                        0 AS montant_regle_1, 
                        0 AS montant_regle_2,  
                        0 AS montant_regle_22 
                    FROM w_OPERA_REG_complet
                        JOIN activite[PX].p_factures ON w_OPERA_REG_complet.no_facture = p_factures.NO_FACTURE
                        JOIN activite[PX].t_medecins_administratifs ON t_medecins_administratifs.code_original =  '*ATTNSCTI'
                    WHERE MONTANT_REGLEMENT_IPP_H IS NOT NULL AND MONTANT_REGLEMENT_IPP_H <> 0 AND 
                        (montant_comptabilise_0_h = montant_regle_0_h AND DATE_REGLEMENT_IPP_H < date_solde_0_h)
                    GROUP BY 1,2,3,4
                    HAVING SUM(MONTANT_REGLEMENT_IPP_H) <> 0;


                        
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_1');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_3');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_4');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_8');
                    

                    INSERT INTO activite[PX].p_factures_soldes_h(
                        facture_id,
                        no_facture, 
                        date_comptable, 
                        medecin_comptabilise_id,
                        montant_comptabilise, 
                        montant_comptabilise_0, 
                        montant_comptabilise_1, 
                        montant_comptabilise_2, 
                        montant_comptabilise_22, 
                        montant_regle, 
                        montant_regle_0, 
                        montant_regle_1, 
                        montant_regle_2, 
                        montant_regle_22
                    )
                    SELECT
                        facture_id,
                        no_facture,
                        date_comptable,
                        medecin_comptabilise_id,
                        SUM(montant_comptabilise),
                        SUM(montant_comptabilise_0),
                        SUM(montant_comptabilise_1),
                        SUM(montant_comptabilise_2),
                        SUM(montant_comptabilise_22),
                        SUM(montant_regle),
                        SUM(montant_regle_0),
                        SUM(montant_regle_1),
                        SUM(montant_regle_2),
                        SUM(montant_regle_22)
                    FROM w_factures_soldes_h
                    GROUP BY 1,2,3,4;


                    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> 

        <NODE label="*FIRST*">
        
            <condition><![CDATA[
                "[CJFIRST_PRESENT]" == "OUI"
            ]]></condition>
        
            <NODE label="Préparation">
                <sqlcmd><![CDATA[

                    
                
                    
                ]]></sqlcmd>
            </NODE>
            
            <NODE label="Entêtes">
                <sqlcmd><![CDATA[
                
                    DROP TABLE IF EXISTS w_CJ_EFS_ventes;
                    CREATE TEMP TABLE w_CJ_EFS_ventes AS
                    SELECT CJ_EFT.EFS_ID, MAX(date(COALESCE(ECR_DATCPTA,EFT_DT_FAC))) AS ECR_DATCPTA
                    FROM prod_cegi.CJ_EFT 
                    LEFT JOIN prod_cegi.CJ_EFTECR ON CJ_EFTECR.EFT_ID = CJ_EFT.EFT_ID
                    LEFT JOIN prod_cegi.CMECRITURES ON CJ_EFTECR.ECR_ID = CMECRITURES.ECR_ID
                    GROUP BY 1
                    ORDER BY 1;

                    DROP TABLE IF EXISTS w_CJ_EFT_exp;
                    CREATE TEMP TABLE w_CJ_EFT_exp AS
                    SELECT CJ_HTRD.EFT_ID, MAX(date(HTR_CREATION)) AS HTR_CREATION, MAX(HTR_LOT) AS HTR_LOT
                    FROM prod_cegi.CJ_HTRD
                    JOIN prod_cegi.CJ_HTR ON CJ_HTR.HTR_ID = CJ_HTRD.HTR_ID
                    JOIN prod_cegi.CJ_EFT ON CJ_HTRD.EFT_ID = CJ_EFT.EFT_ID
                    GROUP BY 1
                    ORDER BY 1;

                    DROP TABLE IF EXISTS w_CJ_EFS_reg;
                    CREATE TEMP TABLE w_CJ_EFS_reg AS
                    SELECT 
                        CJ_EFT.EFS_ID,
                        SUM(CASE WHEN EFT_SEJHON IN (0,2) THEN XECF_MONT ELSE 0 END) AS XECF_MONT,
                        SUM(CASE WHEN EFT_SEJHON IN (1) THEN XECF_MONT ELSE 0 END) AS XECF_HON_MONT,
                        SUM(CASE WHEN EFT_TER_TYPE = 'DBT' AND EFT_SEJHON IN (0,2) THEN XECF_MONT ELSE 0 END) AS XECF_MONT_0,
                        SUM(CASE WHEN EFT_TER_TYPE = 'DBT' AND EFT_SEJHON IN (1) THEN XECF_MONT ELSE 0 END) AS XECF_HON_MONT_0,
                        SUM(CASE WHEN EFT_TER_TYPE = 'CAI' AND EFT_SEJHON IN (0,2) THEN XECF_MONT ELSE 0 END) AS XECF_MONT_1,
                        SUM(CASE WHEN EFT_TER_TYPE = 'CAI' AND EFT_SEJHON IN (1) THEN XECF_MONT ELSE 0 END) AS XECF_HON_MONT_1,
                        SUM(CASE WHEN EFT_TER_TYPE = 'MUT' AND EFT_SEJHON IN (0,2) THEN XECF_MONT ELSE 0 END) AS XECF_MONT_2,
                        SUM(CASE WHEN EFT_TER_TYPE = 'MUT' AND EFT_SEJHON IN (1) THEN XECF_MONT ELSE 0 END) AS XECF_HON_MONT_2,
                        date(MAX(CASE WHEN EFT_TER_TYPE = 'DBT' AND EFT_SEJHON IN (0,2) THEN XECE_DATE ELSE '00010101' END)) AS XECF_DATE_0,
                        date(MAX(CASE WHEN EFT_TER_TYPE = 'DBT' AND EFT_SEJHON IN (0,2) THEN XECE_DATE ELSE '00010101' END)) AS XECF_HON_DATE_0,
                        date(MAX(CASE WHEN EFT_TER_TYPE = 'CAI' AND EFT_SEJHON IN (0,2) THEN XECE_DATE ELSE '00010101' END)) AS XECF_DATE_1,
                        date(MAX(CASE WHEN EFT_TER_TYPE = 'CAI' AND EFT_SEJHON IN (0,2) THEN XECE_DATE ELSE '00010101' END)) AS XECF_HON_DATE_1,
                        date(MAX(CASE WHEN EFT_TER_TYPE = 'MUT' AND EFT_SEJHON IN (0,2) THEN XECE_DATE ELSE '00010101' END)) AS XECF_DATE_2,
                        date(MAX(CASE WHEN EFT_TER_TYPE = 'MUT' AND EFT_SEJHON IN (0,2) THEN XECE_DATE ELSE '00010101' END)) AS XECF_HON_DATE_2
                    FROM prod_cegi.CJ_XECF
                    JOIN prod_cegi.CJ_XECE ON CJ_XECF.XECE_ID = CJ_XECE.XECE_ID
                    JOIN prod_cegi.CJ_EFT ON CJ_EFT.EFT_ID = CJ_XECF.EFT_ID 
                    WHERE CJ_XECF.EFT_ID <> 0 AND
                        XECF_TYPE > 0 AND
                        CJ_XECE.JNL_CODE <> ALL(SELECT JNL_CODE FROM prod_cegi.CJ_JNLNUMFAC)
                    GROUP BY 1
                    ORDER BY 1;

                    DROP TABLE IF EXISTS w_CJ_EFS;
                    CREATE TEMP TABLE w_CJ_EFS AS
                    SELECT nextval('activite[PX].s_factures'::regclass) AS oid,
                        subview.*
                    FROM (
                        SELECT
                            CJ_EFS.EFS_ID,
                            MAX(CJ_EFS.SEJ_ID) AS SEJ_ID, 
                            MAX(SEJ_NUMDOS) AS SEJ_NUMDOS,
                            MAX(EFTB2_NUMFAC) AS EFTB2_NUMFAC,
                            MAX(date(EFS_DT_DEB)) AS EFS_DT_DEB,
                            MAX(date(EFS_DT_FIN)) AS EFS_DT_FIN,
                            MAX(date(EFS_DT_FAC)) AS EFS_DT_FAC,
                            MAX(date(EFS_DT_ANNUL)) AS EFS_DT_ANNUL,
                            MAX(EFS_INACTIF) AS EFS_INACTIF,
                            MAX(EFS_TTC) AS EFS_TTC,
                            MAX(EFS_CPTA_TTC) AS EFS_CPTA_TTC,
                            MAX(EFS_HON_TTC) AS EFS_HON_TTC,
                            MAX(EFS_CPTA_HON_TTC) AS EFS_CPTA_HON_TTC,
                            MAX(EFS_DEP) AS EFS_DEP,
                            MAX(EFS_CPTA_HON_DEP) AS EFS_CPTA_HON_DEP,
                            SUM(CASE WHEN EFT_TER_TYPE = 'DBT' AND EFT_SEJHON IN (0) THEN EFT_TTC ELSE 0 END) AS EFT_TTC_0,
                            SUM(CASE WHEN EFT_TER_TYPE = 'DBT' AND EFT_SEJHON IN (0,2) THEN EFT_CPTA_TTC ELSE 0 END) AS EFT_CPTA_TTC_0,
                            SUM(CASE WHEN EFT_TER_TYPE = 'DBT' AND EFT_SEJHON IN (1,2) THEN EFT_TTC ELSE 0 END) AS EFT_HON_TTC_0,
                            SUM(CASE WHEN EFT_TER_TYPE = 'DBT' AND EFT_SEJHON IN (1) THEN EFT_CPTA_TTC ELSE 0 END) AS EFT_CPTA_HON_TTC_0,
                            SUM(CASE WHEN EFT_TER_TYPE = 'DBT' AND EFT_SEJHON IN (1,2) THEN EFT_DEP ELSE 0 END) AS EFT_DEP_0,
                            SUM(CASE WHEN EFT_TER_TYPE = 'DBT' AND EFT_SEJHON IN (1) THEN EFT_CPTA_DEP ELSE 0 END) AS EFT_CPTA_DEP_0,
                            SUM(CASE WHEN EFT_TER_TYPE = 'CAI' AND EFT_SEJHON IN (0) THEN EFT_TTC ELSE 0 END) AS EFT_TTC_1,
                            SUM(CASE WHEN EFT_TER_TYPE = 'CAI' AND EFT_SEJHON IN (0,2) THEN EFT_CPTA_TTC ELSE 0 END) AS EFT_CPTA_TTC_1,
                            SUM(CASE WHEN EFT_TER_TYPE = 'CAI' AND EFT_SEJHON IN (1,2) THEN EFT_TTC ELSE 0 END) AS EFT_HON_TTC_1,
                            SUM(CASE WHEN EFT_TER_TYPE = 'CAI' AND EFT_SEJHON IN (1) THEN EFT_CPTA_TTC ELSE 0 END) AS EFT_CPTA_HON_TTC_1,
                            SUM(CASE WHEN EFT_TER_TYPE = 'CAI' AND EFT_SEJHON IN (1,2) THEN EFT_DEP ELSE 0 END) AS EFT_DEP_1,
                            SUM(CASE WHEN EFT_TER_TYPE = 'CAI' AND EFT_SEJHON IN (1) THEN EFT_CPTA_DEP ELSE 0 END) AS EFT_CPTA_DEP_1,
                            SUM(CASE WHEN EFT_TER_TYPE = 'MUT' AND EFT_SEJHON IN (0) THEN EFT_TTC ELSE 0 END) AS EFT_TTC_2,
                            SUM(CASE WHEN EFT_TER_TYPE = 'MUT' AND EFT_SEJHON IN (0,2) THEN EFT_CPTA_TTC ELSE 0 END) AS EFT_CPTA_TTC_2,
                            SUM(CASE WHEN EFT_TER_TYPE = 'MUT' AND EFT_SEJHON IN (1,2) THEN EFT_TTC ELSE 0 END) AS EFT_HON_TTC_2,
                            SUM(CASE WHEN EFT_TER_TYPE = 'MUT' AND EFT_SEJHON IN (1) THEN EFT_CPTA_TTC ELSE 0 END) AS EFT_CPTA_HON_TTC_2,
                            SUM(CASE WHEN EFT_TER_TYPE = 'MUT' AND EFT_SEJHON IN (1,2) THEN EFT_DEP ELSE 0 END) AS EFT_DEP_2,
                            SUM(CASE WHEN EFT_TER_TYPE = 'MUT' AND EFT_SEJHON IN (1) THEN EFT_CPTA_DEP ELSE 0 END) AS EFT_CPTA_DEP_2,
                            MAX(COALESCE(XECF_MONT,0)) AS XECF_MONT,
                            MAX(COALESCE(XECF_HON_MONT,0)) AS XECF_HON_MONT,
                            MAX(COALESCE(XECF_MONT_0,0)) AS XECF_MONT_0,
                            MAX(COALESCE(XECF_HON_MONT_0,0)) AS XECF_HON_MONT_0,
                            MAX(COALESCE(XECF_MONT_1,0)) AS XECF_MONT_1,
                            MAX(COALESCE(XECF_HON_MONT_1,0)) AS XECF_HON_MONT_1,
                            MAX(COALESCE(XECF_MONT_2,0)) AS XECF_MONT_2,
                            MAX(COALESCE(XECF_HON_MONT_2,0)) AS XECF_HON_MONT_2,
                            MAX(COALESCE(XECF_DATE_0,'00010101')) AS XECF_DATE_0,
                            MAX(COALESCE(XECF_HON_DATE_0,'00010101')) AS XECF_HON_DATE_0,
                            MAX(COALESCE(XECF_DATE_1,'00010101')) AS XECF_DATE_1,
                            MAX(COALESCE(XECF_HON_DATE_1,'00010101')) AS XECF_HON_DATE_1,
                            MAX(COALESCE(XECF_DATE_2,'00010101')) AS XECF_DATE_2,
                            MAX(COALESCE(XECF_HON_DATE_2,'00010101')) AS XECF_HON_DATE_2,
                            MAX(EFS_ETAT) AS EFS_ETAT,
                            MAX(EFS_ID_AVOIR) AS EFS_ID_AVOIR,
                            MAX(EFS_ID_RCAL) AS EFS_ID_RCAL,
                            MAX(CASE WHEN EFT_TER_TYPE = 'DBT' THEN TER_ID ELSE 0 END) AS TER_ID_0,
                            MAX(CASE WHEN EFT_TER_TYPE = 'CAI' THEN TER_ID ELSE 0 END) AS TER_ID_1,
                            MAX(CASE WHEN EFT_TER_TYPE = 'MUT' THEN TER_ID ELSE 0 END) AS TER_ID_2,
                            COALESCE(MAX(HTR_CREATION),'20991231') AS HTR_CREATION,
                            COALESCE(MAX(HTR_LOT),'') AS HTR_LOT,
                            COALESCE(MAX(ECR_DATCPTA),'20991231') AS ECR_DATCPTA,
							MAX(SEJ_CP) AS code_cp_demandee
                        FROM prod_cegi.CJ_EFS
                            JOIN w_CJ_SEJOUR_select ON CJ_EFS.SEJ_ID = w_CJ_SEJOUR_select.SEJ_ID
                            JOIN prod_cegi.CJ_EFTB2 ON CJ_EFS.EFTB2_ID = CJ_EFTB2.EFTB2_ID
                            JOIN prod_cegi.CJ_EFT ON CJ_EFS.EFS_ID = CJ_EFT.EFS_ID
                            LEFT JOIN w_CJ_EFT_exp ON CJ_EFT.EFT_ID = w_CJ_EFT_exp.EFT_ID
                            LEFT JOIN w_CJ_EFS_ventes ON CJ_EFS.EFS_ID = w_CJ_EFS_ventes.EFS_ID
                            LEFT JOIN w_CJ_EFS_reg ON CJ_EFS.EFS_ID = w_CJ_EFS_reg.EFS_ID
                        GROUP BY 1
                        ORDER BY 1
                    
                        ) subview;
            
            
                    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,
                        no_sejour,
                        provider_id,
                        sejour_id,
                        no_facture,
                        date_debut,
                        date_fin,
                        type_facture,
                        code_cp_demandee, 
                        code_facture,
                        date_facture,
                        code_vente,
                        date_vente,
                        mois_vente,
                        code_cloture,
                        nb_rejets,
                        no_facture_reference,
                        ghs_id,
                        ghs_bebe1_id, 
                        ghs_bebe2_id, 
                        ghs_bebe3_id,
                        particularite_t2a, 
                        tiers_payant_1_id,
                        tiers_payant_2_id,
                        tiers_payant_22_id,
                        tiers_payant_0_id,
                        date_expedition, 
                        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,
                        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_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
                    )
                    SELECT
                        w_CJ_EFS.oid,
                        SEJ_NUMDOS AS no_sejour,
                        0::bigint AS provider_id,
                        p_sejours.oid AS sejour_id,
                        EFTB2_NUMFAC AS no_facture,
                        EFS_DT_DEB AS date_debut,
                        EFS_DT_FIN AS date_fin,
                        CASE 
                            WHEN EFS_ID_AVOIR = 0 AND EFS_ID_RCAL = 0 THEN '0' 
                            WHEN EFS_ETAT IN ('A') THEN '1' 
                            WHEN EFS_ETAT IN ('F') AND EFS_ID_AVOIR <> 0 THEN 'X' 
                            
                            ELSE '0' END AS type_facture,
                        p_sejours.code_cp_demandee, 
                        '1' AS code_facture,
                        EFS_DT_FAC AS date_facture,
                        CASE WHEN ECR_DATCPTA <> '20991231' THEN '1' ELSE '0' END AS code_vente,
                        ECR_DATCPTA AS date_vente,
                        extract('year' FROM ECR_DATCPTA) * 100 + extract('month' FROM ECR_DATCPTA) AS mois_vente,
                        '0'::text AS code_cloture,
                        CASE WHEN EFS_ETAT IN ('A') THEN 1 ELSE 0 END AS nb_rejets,
                        EFTB2_NUMFAC AS no_facture_reference,
                        p_sejours.ghs_id,
                        p_sejours.ghs_bebe1_id, 
                        p_sejours.ghs_bebe2_id, 
                        p_sejours.ghs_bebe3_id,
                        ''::text AS particularite_t2a, 
                        COALESCE(w_CJ_ORG_1.tiers_payant_id, p_sejours.tiers_payant_1_id) AS tiers_payant_1_id,
                        COALESCE(w_CJ_ORG_2.tiers_payant_id, p_sejours.tiers_payant_2_id) AS tiers_payant_2_id,
                        0::bigint AS tiers_payant_22_id,
                        COALESCE(t_tiers_payant_0.oid, p_sejours.tiers_payant_0_id) AS tiers_payant_0_id,
                        HTR_CREATION AS date_expedition, 
                        HTR_CREATION AS date_expedition_0,
                        HTR_CREATION AS date_expedition_1,
                        HTR_CREATION AS date_expedition_2,
                        HTR_CREATION AS date_expedition_22,
                        '1'::text AS code_expedie_0,
                        CASE WHEN HTR_CREATION <> '20991231' THEN '1' ELSE '0' END::text AS code_expedie_1,
                        CASE WHEN HTR_CREATION <> '20991231' THEN '1' ELSE '0' END::text AS code_expedie_2,
                        CASE WHEN HTR_CREATION <> '20991231' THEN '1' ELSE '0' END::text AS code_expedie_22,
                        ''::text AS no_bordereau_0,
                        HTR_LOT AS no_bordereau_1,
                        ''::text AS no_bordereau_2,
                        ''::text AS no_bordereau_22,
                        GREATEST(XECF_DATE_0,XECF_DATE_1,XECF_DATE_2,XECF_HON_DATE_0,XECF_HON_DATE_1,XECF_HON_DATE_2) AS date_solde,
                        GREATEST(XECF_DATE_0,XECF_DATE_1,XECF_DATE_2) AS date_solde_c,
                        GREATEST(XECF_HON_DATE_0,XECF_HON_DATE_1,XECF_HON_DATE_2) AS date_solde_h,
                        XECF_DATE_0 AS date_solde_0_c,
                        XECF_HON_DATE_0 AS date_solde_0_h,
                        XECF_DATE_1 AS date_solde_1_c,
                        XECF_HON_DATE_1 AS date_solde_1_h,  
                        XECF_DATE_2 AS date_solde_2_c,
                        XECF_HON_DATE_2 AS date_solde_2_h,  
                        '00010101'::date AS date_solde_22_c,
                        '00010101'::date AS date_solde_22_h,    
                        EFS_TTC AS montant_facture_c,
                        EFS_HON_TTC AS montant_facture_h,
                        EFT_TTC_0 AS montant_facture_0_c,
                        EFT_HON_TTC_0 AS montant_facture_0_h,
                        EFT_TTC_1 AS montant_facture_1_c,
                        EFT_HON_TTC_1 AS montant_facture_1_h,
                        EFT_TTC_2 AS montant_facture_2_c,
                        EFT_HON_TTC_2 AS montant_facture_2_h,
                        0::numeric AS montant_facture_22_c,
                        0::numeric AS montant_facture_22_h,
                        EFS_CPTA_TTC AS montant_comptabilise_c, 
                        EFS_CPTA_HON_TTC AS montant_comptabilise_h, 
                        EFT_CPTA_TTC_0 AS montant_comptabilise_0_c,
                        EFT_CPTA_HON_TTC_0 AS montant_comptabilise_0_h, 
                        EFT_CPTA_TTC_1 AS montant_comptabilise_1_c, 
                        EFT_CPTA_HON_TTC_1 AS montant_comptabilise_1_h, 
                        EFT_CPTA_TTC_2 AS montant_comptabilise_2_c, 
                        EFT_CPTA_HON_TTC_2 AS montant_comptabilise_2_h, 
                        0::numeric AS montant_comptabilise_22_c, 
                        0::numeric AS montant_comptabilise_22_h, 
                        XECF_MONT AS montant_regle_c,
                        XECF_HON_MONT AS montant_regle_h,
                        XECF_MONT_0 AS montant_regle_0_c,
                        XECF_HON_MONT_0 AS montant_regle_0_h,
                        XECF_MONT_1 AS montant_regle_1_c,
                        XECF_HON_MONT_1 AS montant_regle_1_h,
                        XECF_MONT_2 AS montant_regle_2_c,
                        XECF_HON_MONT_2 AS montant_regle_2_h,
                        0::numeric AS montant_regle_22_c,
                        0::numeric AS montant_regle_22_h
                    FROM w_CJ_EFS
                    JOIN activite[PX].p_sejours ON p_sejours.code_original = SEJ_NUMDOS
                    LEFT JOIN w_CJ_ORG w_CJ_ORG_1 ON TER_ID_1 = w_CJ_ORG_1.TER_ID
                    LEFT JOIN w_CJ_ORG w_CJ_ORG_2 ON TER_ID_2 = w_CJ_ORG_2.TER_ID
                    LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_0 ON t_tiers_payant_0.code_original = 'PATIENT';

                    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');
                    
                    
                    -- Factures terminées sans facturation -> Ajouter facture à 0
                    INSERT INTO activite[PX].p_factures (
                        no_sejour,
                        provider_id,
                        sejour_id,
                        no_facture,
                        date_debut,
                        date_fin,
                        type_facture,
                        code_cp_demandee, 
                        code_facture,
                        date_facture,
                        code_vente,
                        date_vente,
                        mois_vente,
                        code_cloture,
                        nb_rejets,
                        no_facture_reference,
                        ghs_id,
                        ghs_bebe1_id, 
                        ghs_bebe2_id, 
                        ghs_bebe3_id,
                        particularite_t2a, 
                        tiers_payant_1_id,
                        tiers_payant_2_id,
                        tiers_payant_22_id,
                        tiers_payant_0_id,
                        date_expedition, 
                        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,
                        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_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
                    )
                    SELECT
                        SEJ_NUMDOS AS no_sejour,
                        0::bigint AS provider_id,
                        MAX(p_sejours.oid) AS sejour_id,
                        MAX(SEJ_NUMDOS||'-FT') AS no_facture,
                        MAX(p_sejours.date_entree) AS date_debut,
                        MAX(p_sejours.date_sortie) AS date_fin,
                        '0'::text AS type_facture,
                        MAX(p_sejours.code_cp_demandee), 
                        '1'::text AS code_facture,
                        MAX(p_sejours.date_sortie) AS date_facture,
                        '0' AS code_vente,
                        '20991231' AS date_vente,
                        209912 AS mois_vente,
                        '0'::text AS code_cloture,
                        0 AS nb_rejets,
                        MAX(SEJ_NUMDOS||'-FT') AS no_facture_reference,
                        MAX(p_sejours.ghs_id),
                        MAX(p_sejours.ghs_bebe1_id), 
                        MAX(p_sejours.ghs_bebe2_id), 
                        MAX(p_sejours.ghs_bebe3_id),
                        ''::text AS particularite_t2a, 
                        MAX(p_sejours.tiers_payant_1_id) AS tiers_payant_1_id,
                        MAX(p_sejours.tiers_payant_2_id) AS tiers_payant_2_id,
                        0::bigint AS tiers_payant_22_id,
                        MAX(p_sejours.tiers_payant_0_id) AS tiers_payant_0_id,
                        '20991231' AS date_expedition, 
                        '20991231' AS date_expedition_0,
                        '20991231' AS date_expedition_1,
                        '20991231' AS date_expedition_2,
                        '20991231' AS date_expedition_22,
                        '1'::text AS code_expedie_0,
                        '1' AS code_expedie_1,
                        '1' AS code_expedie_2,
                        '1' AS code_expedie_22,
                        ''::text AS no_bordereau_0,
                        ''::text AS no_bordereau_1,
                        ''::text AS no_bordereau_2,
                        ''::text AS no_bordereau_22,
                        MAX(p_sejours.date_sortie) AS date_solde,
                        MAX(p_sejours.date_sortie) AS date_solde_c,
                        MAX(p_sejours.date_sortie) AS date_solde_h,
                        MAX(p_sejours.date_sortie) AS date_solde_0_c,
                        MAX(p_sejours.date_sortie) AS date_solde_0_h,
                        MAX(p_sejours.date_sortie) AS date_solde_1_c,
                        MAX(p_sejours.date_sortie) AS date_solde_1_h,  
                        MAX(p_sejours.date_sortie) AS date_solde_2_c,
                        MAX(p_sejours.date_sortie) AS date_solde_2_h,  
                        '00010101'::date AS date_solde_22_c,
                        '00010101'::date AS date_solde_22_h,    
                        0::numeric AS montant_facture_c,
                        0::numeric AS montant_facture_h,
                        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_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,
                        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
                    FROM prod_cegi.CJ_ATF
                    JOIN prod_cegi.CJ_SEJOUR ON CJ_ATF.SEJ_ID = CJ_SEJOUR.SEJ_ID
                    JOIN activite[PX].p_sejours ON p_sejours.code_original = SEJ_NUMDOS AND provider_id = 0
                    LEFT JOIN activite[PX].p_factures ON p_factures.no_sejour = p_sejours.no_sejour 
                    WHERE ATF_TERMINE = 1 AND code_sorti = '1' AND p_factures.no_facture IS NULL
                    GROUP BY 1
                    ;


                    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.no_facture_od_avoir <> '';
                        
                        
                        
                    UPDATE activite[PX].p_sejours
                    SET est_sans_facturation = '1' 
                    WHERE lieu_sortie_id IN 
                        (SELECT oid FROM activite[PX].t_lieux WHERE 
                            service_facturation_id IN
                            (SELECT oid FROM activite[PX].t_services_facturation WHERE est_sans_facturation = '1') OR
                            unite_fonctionnelle_id IN
                            (SELECT oid FROM activite[PX].t_unites_fonctionnelles WHERE est_sans_facturation = '1') 
                        );
                    

                    -- Séjours sans facture
                    
                    DROP TABLE IF EXISTS w_factures_trous;
                    CREATE TEMP TABLE w_factures_trous AS
                    SELECT
                        p_sejours.finess,
                        p_sejours.no_sejour,
                        p_sejours.date_entree,
                        p_sejours.tiers_payant_0_id, 
                        p_sejours.tiers_payant_1_id, 
                        p_sejours.tiers_payant_2_id, 
                        p_sejours.tiers_payant_22_id,
                        p_sejours.code_cp_demandee,
                        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 NOT NULL AND date_sortie - date_entree < 30 THEN date_sortie ELSE p_factures.date_fin END) AS date_fin_facture,
                        date(MAX(COALESCE(CASE WHEN p_factures.date_fin IS NOT NULL AND date_sortie - date_entree < 30 THEN date_sortie ELSE p_factures.date_fin END + interval '1 day', p_sejours.date_entree))) AS date_debut_encours,
                        CASE WHEN code_sorti = '1' THEN date_sortie ELSE date(now()) END AS date_fin_encours
                    FROM activite[PX].p_sejours
                        JOIN w_CJ_SEJOUR_select ON p_sejours.code_original = SEJ_NUMDOS
                        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 
                        p_sejours.provider_id = 0 AND
                        p_sejours.code_prevu = '0' AND
						p_sejours.type_sejour <> '6' AND 
						p_sejours.type_sejour <> '9' AND
                        date_entree <= now()
                    GROUP BY 1,2,3,4,5,6,7,8,9,10,11;



                    INSERT INTO activite[PX].p_factures(
                        finess, 
                        no_sejour, 
                        provider_id,
                        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, 
                        0::bigint AS provider_id,
                        'E' || no_sejour || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || p_calendrier.mois ELSE '' END, 
                        'E' || no_sejour || 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,13;

                    
                    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="Lignes non facturées Clinique">
                <sqlcmd><![CDATA[
				
					-- Préparation ucd et lpp
					DROP TABLE IF EXISTS w_CJ_UCD;
                        CREATE TEMP TABLE w_CJ_UCD AS
                        SELECT CJ_UCD.UCD_ID, 
						MAX(UCD_CODE) AS UCD_CODE,
						(MAX(ARRAY[R_UCD.UCD_MAJ::text,COALESCE(UCD_DESIGNATION,UCD_CODE)]))[2] AS UCD_DESIGNATION,
						(MAX(ARRAY[R_UCD.UCD_MAJ::text,COALESCE(UCD_ATC_CODE,'')]))[2] AS UCD_ATC_CODE,
						(MAX(ARRAY[R_UCD.UCD_MAJ::text,COALESCE(UCD_ATC_LIBELLE,'')]))[2] AS UCD_ATC_LIBELLE,
						(MAX(ARRAY[R_UCD.UCD_MAJ::text,COALESCE(UCD_LABORATOIRE,'')]))[2] AS UCD_LABORATOIRE,
						(MAX(ARRAY[R_UCD.UCD_MAJ::text,COALESCE(UCD_CONDITION,'')]))[2] AS UCD_CONDITION,
						(MAX(ARRAY[R_UCD.UCD_MAJ::text,COALESCE(UCD_EPHMRA_CODE,'')]))[2] AS UCD_EPHMRA_CODE,
						(MAX(ARRAY[R_UCD.UCD_MAJ::text,COALESCE(UCD_EPHMRA_LIBELLE,'')]))[2] AS UCD_EPHMRA_LIBELLE,
						0::bigint AS cti_ucd_id
					FROM prod_cegi.CJ_UCD
					LEFT JOIN prod_cegi.R_UCD On UCD_ACTE = UCD_CODE
					GROUP BY 1
					;


					UPDATE w_CJ_UCD
					SET UCD_CODE = substr(UCD_CODE,7)
					WHERE length(UCD_CODE) = 13 AND substr(UCD_CODE,1,6) = '000000'
					;

					INSERT INTO base.t_ucd (code, texte, texte_court)
					SELECT UCD_CODE, MAX(UCD_DESIGNATION), MAX(UCD_DESIGNATION)
					FROM w_CJ_UCD
					WHERE UCD_CODE NOT IN (SELECT code FROM base.t_ucd WHERE code IS NOT NULL)
					GROUP BY 1
					ORDER BY 1
					;

					UPDATE base.t_ucd SET
						texte = CASE WHEN t_ucd.code = t_ucd.texte THEN UCD_DESIGNATION ELSE t_ucd.texte END, 
						texte_court = CASE WHEN t_ucd.code = t_ucd.texte_court THEN UCD_DESIGNATION ELSE t_ucd.texte_court END,
						laboratoire_texte = CASE WHEN t_ucd.code = '' THEN UCD_LABORATOIRE ELSE t_ucd.texte_court END,
						conditionnement_texte = CASE WHEN t_ucd.code = '' THEN UCD_CONDITION ELSE t_ucd.texte_court END,
						atc_code = CASE WHEN t_ucd.atc_code = '' THEN UCD_ATC_CODE ELSE t_ucd.atc_code END,
						atc_texte = CASE WHEN t_ucd.atc_texte = '' THEN UCD_ATC_LIBELLE ELSE t_ucd.atc_texte END,
						ephmra_code = CASE WHEN t_ucd.code = '' THEN UCD_EPHMRA_CODE ELSE t_ucd.texte_court END,
						ephmra_texte = CASE WHEN t_ucd.code = '' THEN UCD_EPHMRA_LIBELLE ELSE t_ucd.texte_court END
					FROM w_CJ_UCD
					WHERE t_ucd.code = UCD_CODE AND
						(
						t_ucd.texte IS DISTINCT FROM CASE WHEN t_ucd.code = t_ucd.texte THEN UCD_DESIGNATION ELSE t_ucd.texte END OR 
						t_ucd.texte_court IS DISTINCT FROM CASE WHEN t_ucd.code = t_ucd.texte_court THEN UCD_DESIGNATION ELSE t_ucd.texte_court END OR 
						t_ucd.laboratoire_texte IS DISTINCT FROM CASE WHEN t_ucd.code = '' THEN UCD_LABORATOIRE ELSE t_ucd.texte_court END OR 
						t_ucd.conditionnement_texte IS DISTINCT FROM CASE WHEN t_ucd.code = '' THEN UCD_CONDITION ELSE t_ucd.texte_court END OR 
						t_ucd.atc_code IS DISTINCT FROM CASE WHEN t_ucd.atc_code = '' THEN UCD_ATC_CODE ELSE t_ucd.atc_code END OR 
						t_ucd.atc_texte IS DISTINCT FROM CASE WHEN t_ucd.atc_texte = '' THEN UCD_ATC_LIBELLE ELSE t_ucd.atc_texte END OR 
						t_ucd.ephmra_code IS DISTINCT FROM CASE WHEN t_ucd.code = '' THEN UCD_EPHMRA_CODE ELSE t_ucd.texte_court END OR 
						t_ucd.ephmra_texte IS DISTINCT FROM CASE WHEN t_ucd.code = '' THEN UCD_EPHMRA_LIBELLE ELSE t_ucd.texte_court END
						)
					;
				

					UPDATE w_CJ_UCD
					SET cti_ucd_id = t_ucd.oid
					FROM base.t_ucd 
					WHERE t_ucd.code = UCD_CODE
					;
					
					DROP TABLE IF EXISTS w_CJ_LSUCD;
                    CREATE TEMP TABLE w_CJ_LSUCD AS
                    SELECT LSPST_ID, MAX(cti_ucd_id) AS ucd_id
                    FROM prod_cegi.CJ_LSUCD
                    JOIN w_CJ_UCD ON CJ_LSUCD.UCD_ID = w_CJ_UCD.UCD_ID
                    GROUP BY 1
                    ;
					
					DROP TABLE IF EXISTS w_CJ_LPP;
					CREATE TEMP TABLE w_CJ_LPP AS
					SELECT CJ_LPP.LPP_ID, 
						MAX(LPP_CODE) AS LPP_CODE,
						(MAX(ARRAY[COALESCE(R_LPP.LPP_FIN_VALIDITE::date,'20991231'::date)::text,COALESCE(LPP_COURT,LPP_CODE)]))[2] AS LPP_COURT,
						0::bigint AS cti_lpp_id
					FROM prod_cegi.CJ_LPP
					LEFT JOIN prod_cegi.R_LPP On LPP_ACTE = LPP_CODE
					GROUP BY 1
					;

					INSERT INTO base.t_lpp (code, texte, texte_court)
					SELECT LPP_CODE, MAX(LPP_COURT), MAX(LPP_COURT)
					FROM w_CJ_LPP
					WHERE LPP_CODE NOT IN (SELECT code FROM base.t_lpp WHERE code IS NOT NULL)
					GROUP BY 1
					ORDER BY 1
					;

					UPDATE base.t_lpp
					SET texte = LPP_COURT, texte_court = LPP_COURT
					FROM w_CJ_LPP
					WHERE t_lpp.code = LPP_CODE AND
						t_lpp.texte = t_lpp.code
					;
				

					UPDATE w_CJ_LPP
					SET cti_lpp_id = t_lpp.oid
					FROM base.t_lpp 
					WHERE t_lpp.code = LPP_CODE
					;

                   
                    DROP TABLE IF EXISTS w_CJ_LSLPP;
                    CREATE TEMP TABLE w_CJ_LSLPP AS
                    SELECT LSPST_ID, MAX(cti_lpp_id) AS lpp_id
                    FROM prod_cegi.CJ_LSLPP
                    JOIN w_CJ_LPP ON CJ_LSLPP.LPP_ID = w_CJ_LPP.LPP_ID
                    GROUP BY 1
                    ;
                
                    DROP TABLE IF EXISTS w_PST_rub_pre;
                    CREATE TEMP TABLE w_PST_rub_pre AS
                    SELECT CJ_LCS.PST_ID,
                        MAX(t_rubriques_facturation.oid) AS rubrique_facturation_id,
                        MAX(PST_LIBC) AS PST_LIBC,
                        MAX(LCS_LIBELLE) AS LCS_LIBELLE,
                        (MAX(ARRAY[LCS_DT_DEB::text,t_prestations.oid::text]))[2]::bigint AS prestation_id,
                        (MAX(ARRAY[LCS_DT_DEB::text,LCS_PRIX::text]))[2]::numeric AS LCS_PRIX,
                        MAX(CASE WHEN t_prestations.code = 'CPC' OR type_valorisation_non_facture = 'CP' THEN '1' ELSE '0' END) AS is_cp
                    FROM prod_cegi.CJ_LCS
                    JOIN w_RUBRIQUES ON CJ_LCS.PST_ID = w_RUBRIQUES.PST_ID
                    JOIN activite.t_prestations ON LCS_CODE = t_prestations.code
                    JOIN activite[PX].t_rubriques_facturation ON PST_LIBC = t_rubriques_facturation.code_original
                    WHERE LCS_SEJHON IN (0,2)
                    GROUP BY 1
                    ;
                     
                
                    INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
                        no_facture, 
                        facture_id,
                        date_debut, 
                        date_fin, 
                        nb_rubrique, 
                        coefficient, 
                        rubrique_facturation_id, 
                        prestation_id, 
                        prix_unitaire, 
                        lieu_id,
						lpp_id,
						ucd_id)
                    SELECT
                        p_factures.no_facture,
                        p_factures.oid AS facture_id,
                        date(LSPST_DT_DEB) AS date_debut,
                        date(COALESCE(LSPST_DT_FIN, LSPST_DT_DEB)) AS date_fin,
                        CASE WHEN LSPST_QTE*LSPST_COEFF > 99999 THEN 99999 ELSE GREATEST(0,LSPST_QTE*LSPST_COEFF) END AS nb_rubrique,
                        1::numeric AS coefficient,
                        w_PST_rub_pre.rubrique_facturation_id,
                        w_PST_rub_pre.prestation_id,
                        LSPST_PU AS prix_unitaire,
                        p_sejours.lieu_sortie_id AS lieu_id,
						COALESCE(w_CJ_LSLPP.lpp_id,0) AS lpp_id,
						COALESCE(w_CJ_LSUCD.ucd_id,0) AS ucd_id
                    FROM prod_cegi.CJ_LSPST
                        JOIN prod_cegi.CJ_LSRGP ON CJ_LSPST.LSR_ID = CJ_LSRGP.LSR_ID
                        JOIN prod_cegi.CJ_SEJOUR ON CJ_SEJOUR.SEJ_ID = CJ_LSRGP.SEJ_ID
                        JOIN activite[PX].p_sejours ON SEJ_NUMDOS = p_sejours.no_sejour 
                        JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND 
                            type_facture = 'E' AND p_factures.provider_id = 0
                        LEFT JOIN w_PST_rub_pre ON CJ_LSPST.PST_ID = w_PST_rub_pre.PST_ID
						LEFT JOIN w_CJ_LSLPP ON w_CJ_LSLPP.LSPST_ID = CJ_LSPST.LSPST_ID
						LEFT JOIN w_CJ_LSUCD ON w_CJ_LSUCD.LSPST_ID = CJ_LSPST.LSPST_ID
                    WHERE
                        date(LSPST_DT_DEB) BETWEEN p_factures.date_debut AND p_factures.date_fin AND
                        LSR_TYPE IN ('SEJ', 'HOT', 'LPP', 'UCD', 'UC2') AND 
                        LSPST_TYPE NOT IN ('GHS','PJ','CS') AND
                        code_facture <> '1' AND
                        LSPST_PU <> 0 AND
                        abs(LSPST_QTE*LSPST_COEFF*LSPST_PU) < 100000 AND
						((p_factures.code_cp_demandee = 1 OR (SELECT valeur from activite.t_divers WHERE code = 'ENCOURSVALOCP') = 1) OR is_cp !=1)
                    ;
                    
                    -- Indication des CP dans dossier (si une seule ligne de CP saisie)
                    INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
                        no_facture, 
                        facture_id,
                        date_debut, 
                        date_fin, 
                        nb_rubrique, 
                        coefficient, 
                        rubrique_facturation_id, 
                        prestation_id, 
                        prix_unitaire, 
                        lieu_id
                        )
                    SELECT
                        p_factures.no_facture,
                        p_factures.oid AS facture_id,
                        MIN(date(GREATEST(SNMA_DT_DEB, p_factures.date_debut))) AS date_debut,
                        MAX(date(LEAST(CASE WHEN SNMA_DT_FIN > SNMA_DT_DEB THEN SNMA_DT_FIN ELSE NULL END,p_factures.date_fin))) AS date_fin,
                        GREATEST(MAX(date(LEAST(CASE WHEN SNMA_DT_FIN > SNMA_DT_DEB THEN SNMA_DT_FIN ELSE NULL END,p_factures.date_fin))) - MIN(date(GREATEST(SNMA_DT_DEB, p_factures.date_debut))),1) AS nb_rubrique,
                        1::numeric AS coefficient,
                        MAX(w_PST_rub_pre.rubrique_facturation_id),
                        MAX(w_PST_rub_pre.prestation_id) AS prestation_id,
                        MAX(w_PST_rub_pre.LCS_PRIX) AS prix_unitaire,
                        MAX(p_sejours.lieu_sortie_id) AS lieu_id
                        FROM prod_cegi.CJ_SEJNMA
                    JOIN prod_cegi.CJ_CHGNVE ON CJ_SEJNMA.CHGNVE_ID = CJ_CHGNVE.CHGNVE_ID
                    JOIN prod_cegi.CJ_SEJOUR ON CJ_SEJOUR.SEJ_ID = CJ_CHGNVE.SEJ_ID
                    JOIN activite[PX].p_sejours ON code_original = SEJ_NUMDOS AND type_sejour IN ('1','2')
                    JOIN activite[PX].p_factures ON p_factures.no_sejour = p_sejours.no_sejour AND 
                                    type_facture = 'E' AND p_factures.provider_id = 0
                    JOIN w_PST_rub_pre ON CJ_SEJNMA.PST_ID = w_PST_rub_pre.PST_ID AND is_cp = '1'
                    LEFT JOIN activite[PX].p_factures_lignes_non_facturees_c ON
                            p_factures_lignes_non_facturees_c.no_facture = p_factures.no_facture AND
                            p_factures_lignes_non_facturees_c.prestation_id = w_PST_rub_pre.prestation_id
                    WHERE CHGNVE_ACTIF = '1'  AND
                        p_factures_lignes_non_facturees_c.no_facture IS NULL AND
						(p_factures.code_cp_demandee = 1 OR (SELECT valeur from activite.t_divers WHERE code = 'ENCOURSVALOCP') = 1)
                    GROUP BY 1,2
                    HAVING count(distinct w_PST_rub_pre.rubrique_facturation_id) = 1 
                    ORDER BY 1
                    ;
					
					-- Suppléments provenant du PMSI
					SELECT base.cti_execute(
					'
					DROP TABLE IF EXISTS w_SUPPLEMENT_tarif
					.,
					CREATE TEMP TABLE w_SUPPLEMENT_tarif AS
					SELECT t_prestations.code AS prestation_code, (MAX(Array[date_debut::text,prix_unitaire::text]))[2]::numeric AS prix_unitaire
					FROM activite[PX].p_factures_lignes_c
					JOIN activite[PX].t_prestations ON prestation_id = t_prestations.oid
					WHERE t_prestations.code = ''SRC'' AND montant_facture > 0 AND prix_unitaire > 0
					GROUP BY 1
					.,
					INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
                        no_facture, 
                        facture_id,
                        date_debut, 
                        date_fin, 
                        nb_rubrique, 
                        coefficient, 
                        rubrique_facturation_id, 
                        prestation_id, 
                        prix_unitaire, 
                        lieu_id,
						lpp_id,
						ucd_id)
					SELECT 
						p_factures.no_facture,
						p_factures.oid AS facture_id,
						date(D_ACTE) AS date_debut,
						date(D_ACTE) AS date_fin,
						1::numeric AS nb_rubrique,
						1::numeric AS coefficient,
						t_rubriques_facturation.oid AS rubrique_facturation_id,
						t_prestations.oid AS prestation_id,
						w_SUPPLEMENT_TARIF.prix_unitaire AS prix_unitaire,
						p_sejours.lieu_sortie_id AS lieu_id,
						0::bigint AS lpp_id,
						0::bigint AS ucd_id
					FROM prod_cegi.SUPPLEMENT
					JOIN prod_cegi.RSS ON SUPPLEMENT.N_PMSI = RSS.N_PMSI
					JOIN activite[PX].p_sejours ON N_DOSS = p_sejours.no_sejour 
								JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND 
									type_facture = ''E'' AND p_factures.provider_id = 0
								JOIN activite.t_prestations ON SUPPLEMENT.ACTE = t_prestations.code
								JOIN activite.t_rubriques_facturation ON SUPPLEMENT.ACTE = t_rubriques_facturation.code_original
								JOIN w_SUPPLEMENT_tarif ON SUPPLEMENT.ACTE = prestation_code
								LEFT JOIN activite[PX].p_factures_lignes_non_facturees_c ON
						p_factures.no_facture = p_factures_lignes_non_facturees_c.no_facture AND
						t_prestations.oid = p_factures_lignes_non_facturees_c.prestation_id
					WHERE
						date(D_ACTE) BETWEEN p_factures.date_debut AND p_factures.date_fin AND
						SUPPLEMENT.ACTE IN (''SRC'') AND
						code_facture <> ''1'' AND
						p_factures_lignes_non_facturees_c.no_facture IS NULL
					',1)
					FROM pg_tables
					WHERE tablename = 'supplement' AND
						schemaname = 'prod_cegi'
					;
                                            
                ]]></sqlcmd>
            </NODE>
            
            <NODE label="Lignes factures Clinique">
                <sqlcmd><![CDATA[
                
                    DROP TABLE IF EXISTS w_CJ_LCS;
                    CREATE TEMP TABLE w_CJ_LCS AS
                    SELECT 
                        CJ_LCS.LCS_ID,
                        MAX(CJ_LCS.EFS_ID) AS EFS_ID,
                        MAX(p_factures.sejour_id) AS sejour_id,
                        MAX(p_factures.oid) AS facture_id,
                        MAX(p_factures.date_vente) AS date_vente,
                        MAX(p_factures.no_sejour) AS no_sejour,
                        MAX(p_factures.no_facture) AS no_facture,
						MAX(CJ_LCS.LCS_IDLS) AS LCS_IDLS,
                        date(MAX(LCS_DT_DEB)) AS LCS_DT_DEB,
                        date(MAX(LCS_DT_FIN)) AS LCS_DT_FIN,
                        MAX(CJ_LCS.LCS_CODE) AS LCS_CODE,
                        MAX(PST_LIBC) AS PST_LIBC,
                        MAX(LCT_PST_CPT) AS LCT_PST_CPT,
                        MAX(LCS_GHS) AS LCS_GHS,
                        MAX(LCS_QTE*LCS_COEFF) AS LCS_QTE,
                        1::numeric AS LCS_COEFF,
                        MAX(CASE WHEN LCS_MCO <> 0 THEN LCS_MCO ELSE 1 END) AS LCS_MCO,
                        MAX(LCS_PRIX) AS LCS_PRIX,
                        MAX(CASE WHEN LCS_SEJHON = 0 THEN LCS_TTC ELSE 0 END) AS LCS_TTC,
                        MAX(LCS_CPTA_TTC) AS LCS_CPTA_TTC,
                        MAX(CASE WHEN LCT_TER_TYPE = 'DBT' AND LCS_SEJHON IN (0,2) THEN LCT_TX ELSE 0 END) AS LCT_TX_0,
                        MAX(CASE WHEN LCT_TER_TYPE = 'CAI' AND LCS_SEJHON IN (0,2) THEN LCT_TX ELSE 0 END) AS LCT_TX_1,
                        MAX(CASE WHEN LCT_TER_TYPE = 'MUT' AND LCS_SEJHON IN (0,2) THEN LCT_TX ELSE 0 END) AS LCT_TX_2,
                        SUM(CASE WHEN LCT_TER_TYPE = 'DBT' AND LCS_SEJHON IN (0) THEN LCT_TTC ELSE 0 END) AS LCT_TTC_0,
                        SUM(CASE WHEN LCT_TER_TYPE = 'DBT' AND LCS_SEJHON IN (0,2) THEN LCT_CPTA_TTC ELSE 0 END) AS LCT_CPTA_TTC_0,
                        SUM(CASE WHEN LCT_TER_TYPE = 'CAI' AND LCS_SEJHON IN (0) THEN LCT_TTC ELSE 0 END) AS LCT_TTC_1,
                        SUM(CASE WHEN LCT_TER_TYPE = 'CAI' AND LCS_SEJHON IN (0,2) THEN LCT_CPTA_TTC ELSE 0 END) AS LCT_CPTA_TTC_1,
                        SUM(CASE WHEN LCT_TER_TYPE = 'MUT' AND LCS_SEJHON IN (0) THEN LCT_TTC ELSE 0 END) AS LCT_TTC_2,
                        SUM(CASE WHEN LCT_TER_TYPE = 'MUT' AND LCS_SEJHON IN (0,2) THEN LCT_CPTA_TTC ELSE 0 END) AS LCT_CPTA_TTC_2,
						0::bigint AS ucd_id,
						0::bigint AS lpp_id
                    FROM prod_cegi.CJ_LCS
                    JOIN w_CJ_SEJOUR_select ON CJ_LCS.SEJ_ID = w_CJ_SEJOUR_select.SEJ_ID
                    JOIN w_CJ_EFS ON CJ_LCS.EFS_ID = w_CJ_EFS.EFS_ID
                    JOIN prod_cegi.CJ_LCT ON CJ_LCS.LCS_ID = CJ_LCT.LCS_ID
                    JOIN w_RUBRIQUES ON CJ_LCS.PST_ID = w_RUBRIQUES.PST_ID
                    JOIN activite[PX].p_factures ON w_CJ_EFS.oid = p_factures.oid
                    WHERE LCS_SEJHON IN (0,2)
                    GROUP BY 1;
					
					UPDATE w_CJ_LCS
                    SET ucd_id = w_CJ_LSUCD.ucd_id
                    FROM w_CJ_LSUCD
                    WHERE LCS_IDLS = LSPST_ID
                    ;
					
					UPDATE w_CJ_LCS
                    SET lpp_id = w_CJ_LSLPP.lpp_id
                    FROM w_CJ_LSLPP
                    WHERE LCS_IDLS = LSPST_ID
                    ;

                    DROP TABLE IF EXISTS w_factures_lignes_c;
                    CREATE TEMP TABLE w_factures_lignes_c AS 
                    SELECT
                        w_CJ_LCS.no_sejour,
                        w_CJ_LCS.facture_id,
                        w_CJ_LCS.no_facture,
                        w_CJ_LCS.date_vente,
                        w_CJ_LCS.LCS_COEFF AS coefficient,
                        w_CJ_LCS.LCS_MCO AS coefficient_mco,
                        COALESCE(t_rubriques_facturation.oid,0) AS rubrique_facturation_id,
                        COALESCE(t_rubriques_facturation.oid,0) AS rubrique_comptabilisation_id,
                        COALESCE(t_prestations.oid,0) AS prestation_id,
						lpp_id,
						ucd_id,
                        COALESCE(t_compte.oid,0) AS compte_produit_id,
                        p_sejours.lieu_sortie_id AS lieu_id,
                        1::bigint AS origine_facturation_id,

                        LCS_PRIX AS prix_unitaire,
                        LEAST(LCT_TX_0,100) AS taux_0,
                        LEAST(LCT_TX_1,100) AS taux_1,
                        LEAST(LCT_TX_2,100) AS taux_2,
                        0::numeric AS taux_22,

                        LCS_DT_DEB AS date_debut,
                        LCS_DT_FIN AS date_fin,
                        LCS_QTE AS nb_rubrique,
                        LCS_QTE AS nb_prestation,
                        LCS_TTC AS montant_facture,
                        LCT_TTC_0 AS montant_facture_0,
                        LCT_TTC_1 AS montant_facture_1,
                        LCT_TTC_2 AS montant_facture_2,
                        0::numeric AS montant_facture_22,
                        LCS_CPTA_TTC AS montant_comptabilise,
                        LCT_CPTA_TTC_0 AS montant_comptabilise_0,
                        LCT_CPTA_TTC_1 AS montant_comptabilise_1,
                        LCT_CPTA_TTC_2 AS montant_comptabilise_2,
                        0::numeric AS montant_comptabilise_22,
                        0::numeric AS rubrique_facture_id
                    FROM w_CJ_LCS
                        JOIN activite[PX].p_sejours ON w_CJ_LCS.sejour_id = p_sejours.oid
                        LEFT JOIN activite[PX].t_rubriques_facturation ON PST_LIBC = t_rubriques_facturation.code_original
                        LEFT JOIN activite.t_prestations ON LCS_CODE = t_prestations.code
                        LEFT JOIN activite[PX].t_compte ON LCT_PST_CPT = t_compte.code_original AND LCT_PST_CPT <> ''
                    ;


                    

                    CREATE INDEX w_factures_lignes_c_i1
                    ON w_factures_lignes_c
                    USING btree
                    (no_sejour);
                    
                    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');


                    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,
						lpp_id,
						ucd_id,
                        compte_produit_id,
                        montant_facture,
                        montant_facture_0,
                        montant_facture_1,
                        montant_facture_2,
                        montant_facture_22,
                        taux_0,
                        taux_1,
                        taux_2,
                        taux_22,
                        prix_unitaire,
                        lieu_id,
                        montant_comptabilise,
                        montant_comptabilise_0,
                        montant_comptabilise_1,
                        montant_comptabilise_2,
                        montant_comptabilise_22,
                        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,
						lpp_id,
						ucd_id,
                        compte_produit_id,
                        montant_facture,
                        montant_facture_0,
                        montant_facture_1,
                        montant_facture_2,
                        montant_facture_22,
                        taux_0,
                        taux_1,
                        taux_2,
                        taux_22,
                        prix_unitaire,
                        lieu_id,
                        montant_comptabilise,
                        montant_comptabilise_0,
                        montant_comptabilise_1,
                        montant_comptabilise_2,
                        montant_comptabilise_22,
                        origine_facturation_id
                    FROM w_factures_lignes_c;
                    
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_1');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_2');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_3');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_4');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_5');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_6');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_7');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_8');
                    
                    
                    -- Forcage date debut = date entree pour prestations à ventiler 
                    UPDATE activite[PX].p_factures_lignes_c
                    SET date_debut = p_factures.date_debut
                    FROM activite[PX].t_rubriques_facturation, activite.t_prestations, activite[PX].p_factures
                    JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                    WHERE p_factures.provider_id = 0 AND
                        p_factures_lignes_c.no_facture = p_factures.no_facture AND
                        prestation_id = t_prestations.oid AND
                        t_prestations.type_ventilation_jour = '1' AND 
                        ABS(nb_rubrique) > 1 AND
                        p_factures_lignes_c.date_debut = p_factures_lignes_c.date_fin AND
                        p_sejours.date_sortie <> p_sejours.date_entree ;
                    
                    
                    -- Eclatement des supplements par jour
                    DROP TABLE IF EXISTS w_factures_lignes_sup_c;

                    CREATE TEMP TABLE w_factures_lignes_sup_c AS
                    SELECT
                        p_factures_lignes_c.CTID AS from_CTID, 
                        t_prestations.code AS prestation_code,
                        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(p_factures_lignes_c.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(p_factures_lignes_c.date_debut + ((ABS(nb_prestation)-1) || ' day')::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,
                        p_factures_lignes_c.*
                    FROM activite[PX].p_factures_lignes_c
                        JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
                        JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour AND p_sejours.etat = ''
                        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 p_factures.provider_id = 0 AND
                        (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 activite[PX].p_factures_lignes_c
                            JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND code = 'EXH'
                        GROUP BY 1) subview
                    WHERE w_factures_lignes_sup_c.no_facture = subview.no_facture 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
                        from_CTID,
                        no_facture,
                        date AS date_debut,
                        date AS date_fin,
                        CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_rubrique,
                        CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation,
                        coefficient,
                        coefficient_mco,
                        rubrique_facturation_id,
                        prestation_id,
						lpp_id,
						ucd_id,
                        compte_produit_id,
                        round(montant_facture / ABS(nb_det),2) AS montant_facture,
                        round(montant_facture_0 / ABS(nb_det),2) AS montant_facture_0,
                        round(montant_facture_1 / ABS(nb_det),2) AS montant_facture_1,
                        round(montant_facture_2 / ABS(nb_det),2) AS montant_facture_2,
                        round(montant_facture_22 / ABS(nb_det),2) AS montant_facture_22,
                        taux_0,
                        taux_1,
                        taux_2,
                        taux_22,
                        finess,
                        prix_unitaire,
                        lieu_id,
                        round(montant_comptabilise / ABS(nb_det),2) AS montant_comptabilise,
                        round(montant_comptabilise_0 / ABS(nb_det),2) AS montant_comptabilise_0,
                        round(montant_comptabilise_1 / ABS(nb_det),2) AS montant_comptabilise_1,
                        round(montant_comptabilise_2 / ABS(nb_det),2) AS montant_comptabilise_2,
                        round(montant_comptabilise_22 / ABS(nb_det),2) AS montant_comptabilise_22,
                        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 date_debut BETWEEN p_calendrier.date - ABS(nb_det)::integer + 1 AND p_calendrier.date AND 
                                    p_calendrier.date <> date_debut ;
                    ;


                    DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup_tot;

                    CREATE TEMP TABLE w_factures_lignes_sup_c_sup_tot AS

                    SELECT from_CTID,
                        SUM(nb_rubrique) AS nb_rubrique,
                        SUM(nb_prestation) AS nb_prestation,
                        SUM(montant_facture) AS montant_facture,
                        SUM(montant_facture_0) AS montant_facture_0,
                        SUM(montant_facture_1) AS montant_facture_1,
                        SUM(montant_facture_2) AS montant_facture_2,
                        SUM(montant_facture_22) AS montant_facture_22,
                        SUM(montant_comptabilise) AS montant_comptabilise,
                        SUM(montant_comptabilise_0) AS montant_comptabilise_0,
                        SUM(montant_comptabilise_1) AS montant_comptabilise_1,
                        SUM(montant_comptabilise_2) AS montant_comptabilise_2,
                        SUM(montant_comptabilise_22) AS montant_comptabilise_22,
                        SUM(montant_encours) AS montant_encours,
                        SUM(montant_encours_0) AS montant_encours_0,
                        SUM(montant_encours_1) AS montant_encours_1,
                        SUM(montant_encours_2) AS montant_encours_2,
                        SUM(montant_encours_22) AS montant_encours_22,
                        SUM(montant_facture_actes_inclus_dans_sejour) AS montant_facture_actes_inclus_dans_sejour,
                        SUM(montant_facture_0_actes_inclus_dans_sejour) AS montant_facture_0_actes_inclus_dans_sejour,
                        SUM(montant_facture_1_actes_inclus_dans_sejour) AS montant_facture_1_actes_inclus_dans_sejour,
                        SUM(montant_facture_2_actes_inclus_dans_sejour) AS montant_facture_2_actes_inclus_dans_sejour,
                        SUM(montant_facture_22_actes_inclus_dans_sejour) AS montant_facture_22_actes_inclus_dans_sejour,
                        SUM(montant_comptabilise_budget_global_1) AS montant_comptabilise_budget_global_1
                    FROM w_factures_lignes_sup_c_sup
                    GROUP BY 1;


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

                    INSERT INTO activite[PX].p_factures_lignes_c(
                        no_facture,
                        date_debut,
                        date_fin,
                        nb_rubrique,
                        coefficient,
                        coefficient_mco,
                        rubrique_facturation_id,
                        prestation_id,
						lpp_id,
						ucd_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,
                        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)
                    SELECT 
                        no_facture,
                        date_debut,
                        date_fin,
                        nb_rubrique,
                        coefficient,
                        coefficient_mco,
                        rubrique_facturation_id,
                        prestation_id,
						lpp_id,
						ucd_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,
                        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
                    FROM w_factures_lignes_sup_c_sup;


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

                    
                                            
                ]]></sqlcmd>
            </NODE>
        
            <NODE label="Compte client Clinique">
                <sqlcmd><![CDATA[
                
                    DROP TABLE IF EXISTS w_factures_soldes_c;
                    CREATE TEMP TABLE w_factures_soldes_c AS
                    SELECT
                        facture_id,
                        no_facture,
                        date_trunc('month',date_vente) + interval '1 month' - interval '1 day' AS date_comptable,
                        rubrique_comptabilisation_id,
                        prestation_id,
                        SUM(montant_comptabilise)::numeric AS montant_comptabilise,
                        SUM(montant_comptabilise_0)::numeric AS montant_comptabilise_0,
                        SUM(montant_comptabilise_1)::numeric AS montant_comptabilise_1,
                        SUM(montant_comptabilise_2)::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
                    FROM w_factures_lignes_c
                    WHERE date_vente IS NOT NULL AND
                        date_vente <> '20991231' 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 w_factures_soldes_c
                    SELECT 
                        w_CJ_EFS.oid AS facture_id,
                        w_CJ_EFS.EFTB2_NUMFAC AS no_facture,
                        date_trunc('month',XECE_DATE) + interval '1 month' - interval '1 day' AS date_comptable,
                        COALESCE(t_rubriques_facturation.oid,t_rubriques_att.oid) AS rubrique_comptabilisation_id,
                        COALESCE(t_prestations.oid,t_prestations_att.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,
                        SUM(COALESCE(CJ_XECL.XECL_MONT,CJ_XECF.XECF_MONT))::numeric AS XECF_MONT,
                        SUM(CASE WHEN EFT_TER_TYPE = 'DBT' THEN COALESCE(CJ_XECL.XECL_MONT,CJ_XECF.XECF_MONT) ELSE 0 END)::numeric AS XECF_MONT_0,
                        SUM(CASE WHEN EFT_TER_TYPE = 'CAI' THEN COALESCE(CJ_XECL.XECL_MONT,CJ_XECF.XECF_MONT) ELSE 0 END)::numeric AS XECF_MONT_1,
                        SUM(CASE WHEN EFT_TER_TYPE = 'MUT' THEN COALESCE(CJ_XECL.XECL_MONT,CJ_XECF.XECF_MONT) ELSE 0 END)::numeric AS XECF_MONT_2,
                        0::numeric AS montant_regle_22
                    FROM prod_cegi.CJ_XECF 
                    JOIN prod_cegi.CJ_XECE ON CJ_XECF.XECE_ID = CJ_XECE.XECE_ID
                    LEFT JOIN prod_cegi.CJ_XECL ON CJ_XECL.XECF_ID = CJ_XECF.XECF_ID
                    LEFT JOIN prod_cegi.CJ_LCT ON CJ_XECL.LCT_ID = CJ_LCT.LCT_ID
                    LEFT JOIN prod_cegi.CJ_PST ON CJ_LCT.PST_ID = CJ_PST.PST_ID
                    LEFT JOIN activite.t_prestations ON LCT_CODE = t_prestations.code
                    LEFT JOIN activite[PX].t_rubriques_facturation ON PST_LIBC = t_rubriques_facturation.code_original
                    JOIN prod_cegi.CJ_EFT ON CJ_EFT.EFT_ID = CJ_XECF.EFT_ID 
                    JOIN w_CJ_EFS ON CJ_EFT.EFS_ID = w_CJ_EFS.EFS_ID
                    JOIN activite.t_prestations t_prestations_att ON t_prestations_att.code_original = '*ATTNSCTI'
                    JOIN activite[PX].t_rubriques_facturation t_rubriques_att ON t_rubriques_att.code_original = '*ATTNSCTI'

                    WHERE CJ_XECF.EFT_ID <> 0 AND
                        EFT_SEJHON IN (0,2) AND 
                        XECF_TYPE >= 0 AND
                        CJ_XECE.JNL_CODE <> ALL(SELECT JNL_CODE FROM prod_cegi.CJ_JNLNUMFAC)
                    GROUP BY 1,2,3,4,5
                    ORDER BY 1
                    ;

                    DROP TABLE IF EXISTS w_factures_soldes_soldes;
                    CREATE TEMP TABLE w_factures_soldes_soldes AS
                    SELECT facture_id,
                        MAX(CASE WHEN montant_regle <> 0 THEN date_comptable ELSE NULL END) AS date_comptable,
                        SUM(montant_comptabilise) AS montant_comptabilise,
                        SUM(montant_regle) AS montant_regle
                    FROM w_factures_soldes_c
                    GROUP BY 1
                    HAVING SUM(montant_comptabilise) = SUM(montant_regle) AND SUM(montant_regle) <> 0
                    ;

                    INSERT INTO w_factures_soldes_c
                    SELECT
                        w_factures_soldes_c.facture_id,
                        w_factures_soldes_c.no_facture,
                        w_factures_soldes_soldes.date_comptable,
                        w_factures_soldes_c.rubrique_comptabilisation_id,
                        w_factures_soldes_c.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(0-w_factures_soldes_c.montant_regle)::numeric AS montant_regle,
                        SUM(0-w_factures_soldes_c.montant_regle_0)::numeric AS montant_regle_0,
                        SUM(0-w_factures_soldes_c.montant_regle_1)::numeric AS montant_regle_1,
                        SUM(0-w_factures_soldes_c.montant_regle_2)::numeric AS montant_regle_2,
                        0::numeric AS montant_regle_22
                    FROM w_factures_soldes_c
                    JOIN w_factures_soldes_soldes ON w_factures_soldes_c.facture_id = w_factures_soldes_soldes.facture_id
                    GROUP BY 1,2,3,4,5
                    ;

                    INSERT INTO w_factures_soldes_c
                    SELECT
                        w_factures_soldes_c.facture_id,
                        w_factures_soldes_c.no_facture,
                        w_factures_soldes_soldes.date_comptable,
                        w_factures_soldes_c.rubrique_comptabilisation_id,
                        w_factures_soldes_c.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(w_factures_soldes_c.montant_comptabilise)::numeric AS montant_regle,
                        SUM(w_factures_soldes_c.montant_comptabilise_0)::numeric AS montant_regle_0,
                        SUM(w_factures_soldes_c.montant_comptabilise_1)::numeric AS montant_regle_1,
                        SUM(w_factures_soldes_c.montant_comptabilise_2)::numeric AS montant_regle_2,
                        0::numeric AS montant_regle_22
                    FROM w_factures_soldes_c
                    JOIN w_factures_soldes_soldes ON w_factures_soldes_c.facture_id = w_factures_soldes_soldes.facture_id
                    WHERE w_factures_soldes_c.montant_comptabilise <> 0
                    GROUP BY 1,2,3,4,5;
                    ;
                        
                    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_comptable,
                        rubrique_comptabilisation_id,
                        prestation_id,
                        SUM(montant_comptabilise),
                        SUM(montant_comptabilise_0),
                        SUM(montant_comptabilise_1),
                        SUM(montant_comptabilise_2),
                        SUM(montant_comptabilise_22),
                        SUM(montant_regle),
                        SUM(montant_regle_0),
                        SUM(montant_regle_1),
                        SUM(montant_regle_2),
                        SUM(montant_regle_22)
                    FROM w_factures_soldes_c
                    GROUP BY 1,2,3,4,5
                    HAVING 
                        (
                        SUM(montant_comptabilise) <> 0 OR
                        SUM(montant_comptabilise_0) <> 0 OR
                        SUM(montant_comptabilise_1) <> 0 OR
                        SUM(montant_comptabilise_2) <> 0 OR
                        SUM(montant_comptabilise_22) <> 0 OR
                        SUM(montant_regle) <> 0 OR
                        SUM(montant_regle_0) <> 0 OR
                        SUM(montant_regle_1) <> 0 OR
                        SUM(montant_regle_2) <> 0 OR
                        SUM(montant_regle_22) <> 0
                        );
                    

                    
                    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[
                    
                    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,
                        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(LCS_DT_DEB) AS date_debut,
                        date(LCS_DT_DEB) AS date_fin,
                        100000 AS heure_debut,
                        LCS_QTE AS nb_rubrique,
                        round(CASE WHEN LCS_COEFF <> 0 THEN LCS_COEFF ELSE 1.00 END::numeric,2) AS coefficient,
                        COALESCE(w_CJ_PRA_EXE.medecin_administratif_id,0) AS medecin_facture_id,
                        COALESCE(t_prestations.oid,0) AS prestation_id,
                        LCS_PRIX AS prix_unitaire,
                        LCS_DEP AS montant_depassement,
                        p_sejours.lieu_sortie_id AS lieu_id,
                        COALESCE(t_actes_ccam.oid, t_actes_ngap.oid,0) AS acte_id,
                        COALESCE(CJ_CCAM.CCAM_PHS,0)::text AS phase_ccam,
                        COALESCE(CJ_CCAM.CCAM_ACTV,'') AS activite_ccam,
                        COALESCE(CJ_LSCCAM.LSCA_EXTDOC,'') AS extension_ccam,
                        COALESCE(CJ_LSCCAM.LSCA_MOD1,'') AS modificateur_ccam_1,
                        COALESCE(CJ_LSCCAM.LSCA_MOD2,'') AS modificateur_ccam_2,
                        COALESCE(CJ_LSCCAM.LSCA_MOD3,'') AS modificateur_ccam_3,
                        COALESCE(CJ_LSCCAM.LSCA_MOD4,'') AS modificateur_ccam_4
                    FROM prod_cegi.CJ_LCS
                        LEFT JOIN prod_cegi.CJ_LSCCAM ON CJ_LSCCAM.LSCA_ID = CJ_LCS.LCS_IDLS AND
                            CJ_LCS.LCS_CODE IN ('ACO','ADA','ADC','ADE','ADI','ATM','DEN')
                        LEFT JOIN prod_cegi.CJ_CCAM ON CJ_CCAM.CCAM_ID = CJ_LSCCAM.CCAM_ID 
                        JOIN activite.t_prestations ON LCS_CODE = t_prestations.code
                        LEFT JOIN base.t_actes t_actes_ccam ON CCAM_CODE = t_actes_ccam.code
                        LEFT JOIN base.t_actes t_actes_ngap ON LCS_CODE = t_actes_ngap.code
                        LEFT JOIN w_CJ_PRA w_CJ_PRA_EXE ON w_CJ_PRA_EXE.TER_ID = LCS_TER_EXE
                        JOIN prod_cegi.CJ_SEJOUR ON CJ_SEJOUR.SEJ_ID = CJ_LCS.SEJ_ID
                        JOIN activite[PX].p_sejours ON SEJ_NUMDOS = p_sejours.no_sejour
                        JOIN activite[PX].p_factures ON SEJ_NUMDOS = p_factures.no_sejour AND
                            date(LCS_DT_DEB) BETWEEN p_factures.date_debut AND p_factures.date_fin AND
                            p_factures.provider_id = 0 AND
                            code_facture = '0' AND
							LCS_SEJHON IN (1,2)
                    ;
					
					
					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,
                        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(LSR_DDEB) AS date_debut,
                        date(LSR_DDEB) AS date_fin,
                        100000 AS heure_debut,
                        1::numeric AS nb_rubrique,
                        1 AS coefficient,
                        COALESCE(w_CJ_PRA_EXE.medecin_administratif_id,0) AS medecin_facture_id,
                        COALESCE(t_prestations.oid,0) AS prestation_id,
                        0 AS prix_unitaire,
                        0 AS montant_depassement,
                        p_sejours.lieu_sortie_id AS lieu_id,
                        t_actes.oid AS acte_id,
                        COALESCE(CJ_CCAM.CCAM_PHS,0)::text AS phase_ccam,
                        COALESCE(CJ_CCAM.CCAM_ACTV,'') AS activite_ccam,
                        COALESCE(CJ_LSCCAM.LSCA_EXTDOC,'') AS extension_ccam,
                        COALESCE(CJ_LSCCAM.LSCA_MOD1,'') AS modificateur_ccam_1,
                        COALESCE(CJ_LSCCAM.LSCA_MOD2,'') AS modificateur_ccam_2,
                        COALESCE(CJ_LSCCAM.LSCA_MOD3,'') AS modificateur_ccam_3,
                        COALESCE(CJ_LSCCAM.LSCA_MOD4,'') AS modificateur_ccam_4
                    FROM prod_cegi.CJ_LSRGP
					JOIN prod_cegi.CJ_LSCCAM ON CJ_LSRGP.lsr_id = CJ_LSCCAM.lsr_id 
					JOIN prod_cegi.CJ_SEJOUR ON (CJ_LSRGP.sej_id = CJ_SEJOUR.sej_id )
					JOIN prod_cegi.CJ_CCAM ON (CJ_LSCCAM.ccam_id = CJ_CCAM.ccam_id)
					LEFT JOIN w_CJ_PRA w_CJ_PRA_EXE ON w_CJ_PRA_EXE.TER_ID = CJ_LSCCAM.TER_ID
					JOIN base.t_actes ON (substring(CJ_CCAM.ccam_code, 1, 7) = t_actes.code)
					JOIN base.t_ccam_regroupements ON 
						(
						CCAM_ACTV <> '4' AND ccam_regroupement_id_1 = t_ccam_regroupements.oid OR
						CCAM_ACTV = '4' AND ccam_regroupement_id_4 = t_ccam_regroupements.oid
						)
					JOIN activite.t_prestations ON t_ccam_regroupements.code = t_prestations.Code
					JOIN activite[PX].p_sejours ON SEJ_NUMDOS = p_sejours.no_sejour
					JOIN activite[PX].p_factures ON SEJ_NUMDOS = p_factures.no_sejour AND
					    date(LSR_DDEB) BETWEEN p_factures.date_debut AND p_factures.date_fin AND
					    p_factures.provider_id = 0 AND
                            code_facture = '0'
                    LEFT JOIN prod_cegi.CJ_LCS ON CJ_LSCCAM.LSCA_ID = CJ_LCS.LCS_IDLS AND LCS_CODE IN ('ACO','ADA','ADC','ADE','ADI','ATM','DEN')
					WHERE LSR_ACTIF = 1 AND LSCA_ACTIF = 1 AND LCS_IDLS IS NULL
                    ;
                                
                                            
                ]]></sqlcmd>
            </NODE>
            
            <NODE label="Lignes factures Honoraires">
                <sqlcmd><![CDATA[
					INSERT INTO base.t_actes(code, texte, texte_court, nomenclature)
					SELECT LCS_CODE, LCS_CODE, LCS_CODE, 'NGAP'
					FROM prod_cegi.CJ_LCS
					LEFT JOIN base.t_actes ON LCS_CODE = t_actes.code
					WHERE LCS_CODE <> '' AND
						LCS_SEJHON IN (1,2) AND
						length(LCS_CODE) < 7 AND
						t_actes.oid IS NULL
                    GROUP BY 1,2,3
					;
					                    
                    DROP TABLE IF EXISTS w_CJ_LCS;
                    CREATE TEMP TABLE w_CJ_LCS AS
                    SELECT 
                        CJ_LCS.LCS_ID,
                        MAX(CJ_LCS.EFS_ID) AS EFS_ID,
                        MAX(p_factures.sejour_id) AS sejour_id,
                        MAX(p_factures.oid) AS facture_id,
                        MAX(p_factures.no_sejour) AS no_sejour,
                        MAX(p_factures.no_facture) AS no_facture,
                        MAX(p_factures.date_vente) AS date_vente,
                        date(MAX(LCS_DT_DEB)) AS LCS_DT_DEB,
                        date(MAX(LCS_DT_FIN)) AS LCS_DT_FIN,
                        MAX(CJ_LCS.LCS_CODE) AS LCS_CODE,
                        MAX(PST_LIBC) AS PST_LIBC,
                        MAX(LCS_TER_EXE) AS LCS_TER_EXE,
                        MAX(LCT_TER_EXE) AS LCT_TER_EXE,
                        MAX(COALESCE(CJ_CCAM.CCAM_CODE,CJ_LCS.LCS_CODE,'')) AS CCAM_CODE,
                        MAX(COALESCE(CJ_CCAM.CCAM_ACTV,'')) AS CCAM_ACTV,
                        MAX(COALESCE(CJ_CCAM.CCAM_PHS,0)) AS CCAM_PHS,
                        MAX(COALESCE(CJ_LSCCAM.LSCA_EXTDOC,'')) AS LSCA_EXTDOC,
                        MAX(COALESCE(CJ_LSCCAM.LSCA_MOD1,'')) AS LSCA_MOD1,
                        MAX(COALESCE(CJ_LSCCAM.LSCA_MOD2,'')) AS LSCA_MOD2,
                        MAX(COALESCE(CJ_LSCCAM.LSCA_MOD3,'')) AS LSCA_MOD3,
                        MAX(COALESCE(CJ_LSCCAM.LSCA_MOD4,'')) AS LSCA_MOD4,
                        MAX(LCS_GHS) AS LCS_GHS,
                        MAX(LCS_QTE) AS LCS_QTE,
                        MAX(LCS_COEFF) AS LCS_COEFF,
                        MAX(CASE WHEN LCS_MCO <> 0 THEN LCS_MCO ELSE 1 END) AS LCS_MCO,
                        MAX(LCS_PRIX) AS LCS_PRIX,
                        MAX(CASE WHEN LCS_SEJHON IN (1,2) THEN LCS_TTC ELSE 0 END) AS LCS_TTC,
                        MAX(CASE WHEN LCS_SEJHON IN (1) THEN LCS_CPTA_TTC ELSE 0 END) AS LCS_CPTA_TTC,
                        MAX(CASE WHEN LCS_SEJHON IN (1,2) THEN LCS_DEP ELSE 0 END) AS LCS_DEP,
                        MAX(CASE WHEN LCS_SEJHON IN (1) THEN LCS_CPTA_DEP ELSE 0 END) AS LCS_CPTA_DEP,
                        MAX(CASE WHEN LCT_TER_TYPE = 'DBT' AND LCS_SEJHON IN (1,2) THEN LCT_TX ELSE 0 END) AS LCT_TX_0,
                        MAX(CASE WHEN LCT_TER_TYPE = 'CAI' AND LCS_SEJHON IN (1,2) THEN LCT_TX ELSE 0 END) AS LCT_TX_1,
                        MAX(CASE WHEN LCT_TER_TYPE = 'MUT' AND LCS_SEJHON IN (1,2) THEN LCT_TX ELSE 0 END) AS LCT_TX_2,
                        SUM(CASE WHEN LCT_TER_TYPE = 'DBT' AND LCS_SEJHON IN (1,2) THEN LCT_TTC ELSE 0 END) AS LCT_TTC_0,
                        SUM(CASE WHEN LCT_TER_TYPE = 'DBT' AND LCS_SEJHON IN (1) THEN LCT_CPTA_TTC ELSE 0 END) AS LCT_CPTA_TTC_0,
                        SUM(CASE WHEN LCT_TER_TYPE = 'CAI' AND LCS_SEJHON IN (1,2) THEN LCT_TTC ELSE 0 END) AS LCT_TTC_1,
                        SUM(CASE WHEN LCT_TER_TYPE = 'CAI' AND LCS_SEJHON IN (1) THEN LCT_CPTA_TTC ELSE 0 END) AS LCT_CPTA_TTC_1,
                        SUM(CASE WHEN LCT_TER_TYPE = 'MUT' AND LCS_SEJHON IN (1,2) THEN LCT_TTC ELSE 0 END) AS LCT_TTC_2,
                        SUM(CASE WHEN LCT_TER_TYPE = 'MUT' AND LCS_SEJHON IN (1) THEN LCT_CPTA_TTC ELSE 0 END) AS LCT_CPTA_TTC_2,
                        SUM(CASE WHEN LCS_SEJHON IN (1,2) THEN LCT_DEP ELSE 0 END) AS LCT_DEP,
                        SUM(CASE WHEN LCS_SEJHON IN (1) THEN LCT_CPTA_DEP ELSE 0 END) AS LCT_CPTA_DEP
                    FROM prod_cegi.CJ_LCS
                    JOIN w_CJ_SEJOUR_select ON CJ_LCS.SEJ_ID = w_CJ_SEJOUR_select.SEJ_ID
                    JOIN w_CJ_EFS ON CJ_LCS.EFS_ID = w_CJ_EFS.EFS_ID
                    JOIN prod_cegi.CJ_LCT ON CJ_LCS.LCS_ID = CJ_LCT.LCS_ID
                    LEFT JOIN prod_cegi.CJ_LSCCAM ON CJ_LSCCAM.LSCA_ID = CJ_LCS.LCS_IDLS AND
                        CJ_LCS.LCS_CODE IN ('ACO','ADA','ADC','ADE','ADI','ATM','DEN')
                    LEFT JOIN prod_cegi.CJ_CCAM ON CJ_CCAM.CCAM_ID = CJ_LSCCAM.CCAM_ID 
                    JOIN w_RUBRIQUES ON CJ_LCS.PST_ID = w_RUBRIQUES.PST_ID
                    JOIN activite[PX].p_factures ON w_CJ_EFS.oid = p_factures.oid
                    WHERE LCS_SEJHON IN (1,2) 
                    
                    GROUP BY 1;

                    UPDATE w_CJ_LCS
                    SET LCS_CODE = PST_LIBC
                    WHERE LCS_CODE = '';
                    
                    UPDATE w_CJ_LCS
                    SET LCS_CPTA_TTC = (LCT_CPTA_TTC_0+LCT_CPTA_TTC_1+LCT_CPTA_TTC_2)
                    WHERE LCS_CPTA_TTC = 0 AND (LCT_CPTA_TTC_0+LCT_CPTA_TTC_1+LCT_CPTA_TTC_2) <> 0;


                    DROP TABLE IF EXISTS w_factures_lignes_h;
                    CREATE TEMP TABLE w_factures_lignes_h AS
                    SELECT
                        w_CJ_LCS.facture_id,
                        w_CJ_LCS.no_facture,
                        w_CJ_LCS.date_vente,
                        LCS_DT_DEB AS date_debut,
                        LCS_DT_FIN AS date_fin,
                        LCS_QTE AS nb_rubrique,
                        LCS_QTE AS nb_prestation,
                        LCS_COEFF AS coefficient,
                        LCS_MCO AS coefficient_mco,
                        COALESCE(w_CJ_PRA_EXE.medecin_administratif_id,0) AS medecin_facture_id,
                        COALESCE(w_CJ_PRA_CPT.medecin_administratif_id,0) AS medecin_comptabilise_id,
                        COALESCE(t_prestations.oid,0) AS prestation_id,
                        COALESCE(t_rubriques_facturation.oid,0) AS rubrique_facturation_id,
                        COALESCE(t_actes.oid,0) AS acte_id, 
                        CCAM_ACTV AS activite_ccam,
                        LSCA_EXTDOC AS extension_ccam,
                        CCAM_PHS AS phase_ccam,
                        LSCA_MOD1 AS modificateur_ccam_1,
                        LSCA_MOD1 AS modificateur_ccam_2,
                        LSCA_MOD1 AS modificateur_ccam_3,
                        LSCA_MOD1 AS modificateur_ccam_4,
                        LCS_TTC AS montant_facture,
                        LCT_TTC_0 AS montant_facture_0,
                        LCT_TTC_1 AS montant_facture_1,
                        LCT_TTC_2 AS montant_facture_2,
                        0::numeric AS montant_facture_22,
                        LCS_DEP AS montant_depassement,
                        LEAST(LCT_TX_0,100) AS taux_0,
                        LEAST(LCT_TX_1,100) AS taux_1,
                        LEAST(LCT_TX_2,100) AS taux_2,
                        0::numeric AS taux_22,
                        LCS_PRIX AS prix_unitaire,
                        p_sejours.lieu_sortie_id AS lieu_id,
                        LCS_CPTA_TTC AS montant_comptabilise,
                        LCT_CPTA_TTC_0 AS montant_comptabilise_0,
                        LCT_CPTA_TTC_1 AS montant_comptabilise_1,
                        LCT_CPTA_TTC_2 AS montant_comptabilise_2,
                        0::numeric AS montant_comptabilise_22
                    FROM w_CJ_LCS
                    JOIN activite[PX].p_sejours ON w_CJ_LCS.sejour_id = p_sejours.oid
                        LEFT JOIN activite[PX].t_rubriques_facturation ON PST_LIBC = t_rubriques_facturation.code_original
                        LEFT JOIN activite.t_prestations ON LCS_CODE = t_prestations.code
                        LEFT JOIN w_CJ_PRA w_CJ_PRA_EXE ON w_CJ_PRA_EXE.TER_ID = LCS_TER_EXE
                        LEFT JOIN w_CJ_PRA w_CJ_PRA_CPT ON w_CJ_PRA_CPT.TER_ID = LCT_TER_EXE
                        LEFT JOIN base.t_actes ON CCAM_CODE = t_actes.code
                    ;

                    
                    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
                        )
                    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
                    FROM w_factures_lignes_h
                    ;
                    
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_1');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_2');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_3');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_4');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_5');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_6');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_7');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_8');
                    SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_9');
    
                                            
                ]]></sqlcmd>
            </NODE>
        
            <NODE label="Compte client Honoraires">
                <sqlcmd><![CDATA[
                
                    DROP TABLE IF EXISTS w_factures_soldes_h;
                    CREATE TEMP TABLE w_factures_soldes_h AS
                    SELECT
                        facture_id,
                        no_facture,
                        date_trunc('month',date_vente) + interval '1 month' - interval '1 day' AS date_comptable,
                        rubrique_facturation_id AS rubrique_comptabilisation_id,
                        prestation_id,
                        medecin_comptabilise_id,
                        SUM(montant_comptabilise)::numeric AS montant_comptabilise,
                        SUM(montant_comptabilise_0)::numeric AS montant_comptabilise_0,
                        SUM(montant_comptabilise_1)::numeric AS montant_comptabilise_1,
                        SUM(montant_comptabilise_2)::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
                    FROM w_factures_lignes_h
                    WHERE date_vente IS NOT NULL AND
                        date_vente <> '20991231' AND
                        (montant_comptabilise <> 0 OR 
                        montant_comptabilise_0 <> 0 OR 
                        montant_comptabilise_1 <> 0 OR 
                        montant_comptabilise_2 <> 0 
                        )
                    GROUP BY 1,2,3,4,5,6;

                    INSERT INTO w_factures_soldes_h
                    SELECT 
                        w_CJ_EFS.oid AS facture_id,
                        w_CJ_EFS.EFTB2_NUMFAC AS no_facture,
                        date_trunc('month',XECE_DATE) + interval '1 month' - interval '1 day' AS date_comptable,
                        t_rubriques_facturation.oid AS rubrique_comptabilisation_id,
                        t_prestations.oid AS prestation_id,
                        t_medecins_administratifs.oid AS 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,
                        SUM(CJ_XECF.XECF_MONT)::numeric AS XECF_MONT,
                        SUM(CASE WHEN EFT_TER_TYPE = 'DBT' THEN CJ_XECF.XECF_MONT ELSE 0 END)::numeric AS XECF_MONT_0,
                        SUM(CASE WHEN EFT_TER_TYPE = 'CAI' THEN CJ_XECF.XECF_MONT ELSE 0 END)::numeric AS XECF_MONT_1,
                        SUM(CASE WHEN EFT_TER_TYPE = 'MUT' THEN CJ_XECF.XECF_MONT ELSE 0 END)::numeric AS XECF_MONT_2,
                        0::numeric AS montant_regle_22
                    FROM prod_cegi.CJ_XECF 
                    JOIN prod_cegi.CJ_XECE ON CJ_XECF.XECE_ID = CJ_XECE.XECE_ID
                    JOIN prod_cegi.CJ_EFT ON CJ_EFT.EFT_ID = CJ_XECF.EFT_ID 
                    JOIN w_CJ_EFS ON CJ_EFT.EFS_ID = w_CJ_EFS.EFS_ID
                    JOIN activite.t_prestations ON t_prestations.code_original = '*ATTNSCTI'
                    JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original = '*ATTNSCTI'
                    JOIN activite[PX].t_medecins_administratifs ON t_medecins_administratifs.code_original = '*ATTNSCTI'

                    WHERE CJ_XECF.EFT_ID <> 0 AND
                        EFT_SEJHON IN (1) AND
                        XECF_TYPE > 0 AND
                        CJ_XECE.JNL_CODE <> ALL(SELECT JNL_CODE FROM prod_cegi.CJ_JNLNUMFAC)
                    GROUP BY 1,2,3,4,5,6
                    ORDER BY 1
                    ;

                    DROP TABLE IF EXISTS w_factures_soldes_soldes;
                    CREATE TEMP TABLE w_factures_soldes_soldes AS
                    SELECT facture_id,
                        MAX(CASE WHEN montant_regle <> 0 THEN date_comptable ELSE NULL END) AS date_comptable,
                        SUM(montant_comptabilise) AS montant_comptabilise,
                        SUM(montant_regle) AS montant_regle
                    FROM w_factures_soldes_h
                    GROUP BY 1
                    HAVING SUM(montant_comptabilise) = SUM(montant_regle) AND SUM(montant_regle) <> 0
                    ;

                    INSERT INTO w_factures_soldes_h
                    SELECT
                        w_factures_soldes_h.facture_id,
                        w_factures_soldes_h.no_facture,
                        w_factures_soldes_soldes.date_comptable,
                        w_factures_soldes_h.rubrique_comptabilisation_id,
                        w_factures_soldes_h.prestation_id,
                        w_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,
                        SUM(0-w_factures_soldes_h.montant_regle)::numeric AS montant_regle,
                        SUM(0-w_factures_soldes_h.montant_regle_0)::numeric AS montant_regle_0,
                        SUM(0-w_factures_soldes_h.montant_regle_1)::numeric AS montant_regle_1,
                        SUM(0-w_factures_soldes_h.montant_regle_2)::numeric AS montant_regle_2,
                        0::numeric AS montant_regle_22
                    FROM w_factures_soldes_h
                    JOIN w_factures_soldes_soldes ON w_factures_soldes_h.facture_id = w_factures_soldes_soldes.facture_id
                    WHERE (
                        w_factures_soldes_h.montant_regle <> 0 OR
                        w_factures_soldes_h.montant_regle_0 <> 0 OR
                        w_factures_soldes_h.montant_regle_1 <> 0 OR
                        w_factures_soldes_h.montant_regle_2 <> 0
                        )
                    GROUP BY 1,2,3,4,5,6
                    ;

                    INSERT INTO w_factures_soldes_h
                    SELECT
                        w_factures_soldes_h.facture_id,
                        w_factures_soldes_h.no_facture,
                        w_factures_soldes_soldes.date_comptable,
                        w_factures_soldes_h.rubrique_comptabilisation_id,
                        w_factures_soldes_h.prestation_id,
                        w_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,
                        SUM(w_factures_soldes_h.montant_comptabilise)::numeric AS montant_regle,
                        SUM(w_factures_soldes_h.montant_comptabilise_0)::numeric AS montant_regle_0,
                        SUM(w_factures_soldes_h.montant_comptabilise_1)::numeric AS montant_regle_1,
                        SUM(w_factures_soldes_h.montant_comptabilise_2)::numeric AS montant_regle_2,
                        0::numeric AS montant_regle_22
                    FROM w_factures_soldes_h
                    JOIN w_factures_soldes_soldes ON w_factures_soldes_h.facture_id = w_factures_soldes_soldes.facture_id
                    WHERE w_factures_soldes_h.montant_comptabilise <> 0
                    GROUP BY 1,2,3,4,5,6;
                    ;
                        
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_1');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_3');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_4');
                    SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_8');
                    

                    INSERT INTO activite[PX].p_factures_soldes_h(
                        facture_id,
                        no_facture, 
                        date_comptable, 
                        rubrique_comptabilisee_id,
                        prestation_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
                    )
                    SELECT
                        facture_id,
                        no_facture,
                        date_comptable,
                        rubrique_comptabilisation_id,
                        prestation_id,
                        medecin_comptabilise_id,
                        SUM(montant_comptabilise),
                        SUM(montant_comptabilise_0),
                        SUM(montant_comptabilise_1),
                        SUM(montant_comptabilise_2),
                        SUM(montant_comptabilise_22),
                        SUM(montant_regle),
                        SUM(montant_regle_0),
                        SUM(montant_regle_1),
                        SUM(montant_regle_2),
                        SUM(montant_regle_22)
                    FROM w_factures_soldes_h
                    GROUP BY 1,2,3,4,5,6
                    HAVING 
                        (
                        SUM(montant_comptabilise) <> 0 OR
                        SUM(montant_comptabilise_0) <> 0 OR
                        SUM(montant_comptabilise_1) <> 0 OR
                        SUM(montant_comptabilise_2) <> 0 OR
                        SUM(montant_comptabilise_22) <> 0 OR
                        SUM(montant_regle) <> 0 OR
                        SUM(montant_regle_0) <> 0 OR
                        SUM(montant_regle_1) <> 0 OR
                        SUM(montant_regle_2) <> 0 OR
                        SUM(montant_regle_22) <> 0
                        );
                    

                    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> 
    </NODE>
    
    <NODE name="CHIFFRIER" label="CREATION DU CHIFFRIER">
    
        <NODE label="Récupération chiffrier CEGI">
            
            <sqlcmd><![CDATA[
                                
                TRUNCATE activite[PX].p_factures_comptables;
                TRUNCATE activite[PX].p_chiffrier_comptable;
                                                        
            ]]></sqlcmd>
        </NODE>
		
		<NODE label="Ecritures comptables (LOGHOS+FIRST">
            
            <sqlcmd><![CDATA[
			
				
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'CEGI_DOSCLI',
					'Dossiers comptable CLINIQUE',
					'1'::text,
					'Pour import écritures clients'
				WHERE 'CEGI_DOSCLI' NOT IN (SELECT code FROM activite.t_divers);

				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'CEGI_DOSHON',
					'Dossiers comptable HONORAIRES',
					''::text,
					'Pour import écritures clients'
				WHERE 'CEGI_DOSHON' NOT IN (SELECT code FROM activite.t_divers);
				
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'CEGI_CPTCLI',
					'Comptes clients',
					''::text,
					'Pour import écritures clients et chiffrier. Séparés par une virgule'
				WHERE 'CEGI_CPTCLI' NOT IN (SELECT code FROM activite.t_divers);

				INSERT INTO activite[PX].t_journal (code_original, code, texte)
				SELECT JNL_CODE,
					JNL_CODE,
					MAX(JNL_LIB)
				FROM prod_cegi.CMJOURNAUX
				WHERE JNL_CODE NOT IN (SELECT code_original FROM activite[PX].t_journal WHERE code_original IS NOT NULL)
				GROUP BY 1,2
				;
				
				-- Comptes
				INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
				SELECT PLC_COMPTE, PLC_COMPTE, MAX(PLC_LIBELLE), MAX(PLC_LIBELLE)
				FROM prod_cegi.CMPLANCPT
				WHERE PLC_COMPTE <> '' AND
					PLC_COMPTE NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code IS NOT NULL)
				GROUP BY 1
				ORDER BY 1;
				
				INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
				SELECT PLC_COMPTE, PLC_COMPTE, MAX(PLC_COMPTE), MAX(PLC_COMPTE)
				FROM prod_cegi.CMECRITURES
				WHERE PLC_COMPTE <> '' AND
					PLC_COMPTE NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code IS NOT NULL)
				GROUP BY 1
				ORDER BY 1
				;
				
				UPDATE activite[PX].t_compte
				SET texte = PLC_LIBELLE, texte_court = PLC_LIBELLE
				FROM prod_cegi.CMPLANCPT
				WHERE code = PLC_COMPTE AND
					(
					texte IS DISTINCT FROM PLC_LIBELLE OR
					texte_court IS DISTINCT FROM PLC_LIBELLE
					)
				;
								
				SELECT base.cti_execute('
				UPDATE activite[PX].t_journal
				SET type_journal = ''VE''
				WHERE type_journal = '''' AND
					code_original IN (SELECT JNL_CODE FROM prod_cegi.CJ_JNLNUMFAC)
				',1)
				WHERE 'cj_jnlnumfac' IN (SELECT tablename FROM pg_tables WHERE schemaname = 'prod_cegi')
				;


				DROP TABLE IF EXISTS w_DOS_CH;
				CREATE TEMP TABLE w_DOS_CH AS 
				SELECT base.cti_to_number(unnest(string_to_array(valeur,','))) AS DOS_ID,
					CASE WHEN code LIKE '%HON' THEN 'H' ELSE 'C' END::text AS clinique_honoraire
				FROM activite.t_divers
				WHERE code LIKE 'CEGI\_DOS%'
				;

				INSERT INTO w_DOS_CH
				SELECT DOS_ID, ''::text
				FROM prod_cegi.CMECRITURES
				WHERE (SELECT count(*) FROM w_DOS_CH) = 0 
				GROUP BY 1
				;
				
				SELECT base.cti_execute('
				UPDATE w_DOS_CH
				SET clinique_honoraire = subview.clinique_honoraire
				FROM
				(
					SELECT DOS_ID, MIN(CASE WHEN PNF_LITERAL IN (''M'',''H'') THEN ''H'' ELSE ''C'' END) AS clinique_honoraire
					FROM prod_cegi.CJ_JNLNUMFAC
					GROUP BY 1
				) subview
				WHERE w_DOS_CH.DOS_ID = subview.DOS_ID
				',1)
				WHERE 'cj_jnlnumfac' IN (SELECT tablename FROM pg_tables WHERE schemaname = 'prod_cegi')
				;

				UPDATE w_DOS_CH
				SET clinique_honoraire = 'C'
				WHERE clinique_honoraire = ''
				;

				ANALYSE w_DOS_CH
				;



				
				DROP TABLE IF EXISTS w_CMECRITURES;
				CREATE TEMP TABLE w_CMECRITURES AS
				SELECT CMECRITURES.*,
					''::text AS no_sejour,
					0::bigint AS sejour_id,
					''::text AS no_facture,
					0::bigint AS facture_id,
					0::bigint AS medecin_administratif_id,
					0::bigint AS tiers_payant_id,
					''::text AS mode_reglement_code,
					'':: text AS type_ecriture, 
					'':: text AS type_piece, 
					COALESCE(clinique_honoraire,'C') AS clinique_honoraire,
					date_part('year',ECR_DATCPTA) || '-' || ECR_NUMECR AS piece
				FROM prod_cegi.CMECRITURES
				JOIN w_DOS_CH ON CMECRITURES.DOS_ID = w_DOS_CH.DOS_ID
				WHERE ECR_DATCPTA >= '20200101'::date
				;

				
				SELECT base.cti_execute('
				UPDATE w_CMECRITURES SET
					no_facture = ECR_NUMFACT, 
					no_sejour = p_factures.no_sejour,
					facture_id = p_factures.oid,
					sejour_id = p_factures.sejour_id
				FROM prod_cegi.CJ_EFT
				JOIN prod_cegi.CJ_EFS ON CJ_EFS.EFS_ID = CJ_EFT.EFS_ID
				JOIN prod_cegi.CJ_EFTB2 ON CJ_EFS.EFTB2_ID = CJ_EFTB2.EFTB2_ID
				JOIN activite[PX].p_factures ON EFTB2_NUMFAC = no_facture
				WHERE ECR_NUMFACT = EFT_NUMFAC
				',1)
				WHERE 'cj_eft' IN (SELECT tablename FROM pg_tables WHERE schemaname = 'prod_cegi')
				;

				SELECT base.cti_execute('
				UPDATE w_CMECRITURES SET
					no_facture = ECR_NUMFACT, 
					no_sejour = p_factures.no_sejour,
					facture_id = p_factures.oid,
					sejour_id = p_factures.sejour_id
				FROM prod_cegi.CJ_EFT
				JOIN prod_cegi.CJ_EFS ON CJ_EFS.EFS_ID = CJ_EFT.EFS_ID
				JOIN prod_cegi.CJ_EFTB2 ON CJ_EFS.EFTB2_ID = CJ_EFTB2.EFTB2_ID
				JOIN activite[PX].p_factures ON EFTB2_NUMFAC = no_facture
				WHERE ECR_NUMFACT = EFTB2_NUMFAC AND
					w_CMECRITURES.facture_id = 0',1)
				WHERE 'cj_eft' IN (SELECT tablename FROM pg_tables WHERE schemaname = 'prod_cegi')
				;

				UPDATE w_CMECRITURES SET
					no_sejour = p_sejours.no_sejour,
					sejour_id = p_sejours.oid
				FROM activite[PX].p_sejours, 
					activite[PX].t_journal
				WHERE ECR_NUMPIECE = p_sejours.no_sejour AND
					JNL_CODE = t_journal.code_original AND
					t_journal.type_journal = 'VE' AND
					w_CMECRITURES.sejour_id = 0
				;
				
				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,
					taux_tva)
				SELECT 
					ECR_ID::text AS code_original, 
					ECR_DATCPTA AS date_comptable, 
					CASE 
					WHEN t_journal.type_journal = 'VE' AND PLC_COMPTE LIKE '411%' THEN 'VCLI'
					WHEN t_journal.type_journal = 'VE' AND PLC_COMPTE LIKE '412%' THEN 'VCLI'
					WHEN t_journal.type_journal = 'VE' AND PLC_COMPTE LIKE '445%' THEN 'VTVA'
					WHEN t_journal.type_journal = 'VE' AND w_CMECRITURES.clinique_honoraire = 'C' THEN 'VPRD'
					WHEN t_journal.type_journal = 'VE' AND w_CMECRITURES.clinique_honoraire = 'H' THEN 'VHON'
					WHEN PLC_COMPTE LIKE '758%' THEN 'PEPR'
					WHEN PLC_COMPTE LIKE '658%' THEN 'PEPR'
					WHEN t_journal.type_journal <> 'VE' AND PLC_COMPTE LIKE '468%' THEN 'ATT'
					WHEN t_journal.type_journal <> 'VE' AND PLC_COMPTE LIKE '471%' THEN 'ATT'
					WHEN t_journal.type_journal <> 'VE' AND PLC_COMPTE LIKE '411%' THEN 'RCLI'
					WHEN t_journal.type_journal <> 'VE' AND PLC_COMPTE LIKE '412%' THEN 'RCLI'
					WHEN t_journal.type_journal <> 'VE' AND PLC_COMPTE LIKE '419%' THEN 'ACPT'
					WHEN t_journal.type_journal <> 'VE' AND PLC_COMPTE LIKE '51%' THEN 'BANQ'
					WHEN t_journal.type_journal <> 'VE' AND PLC_COMPTE LIKE '531%' THEN 'BANQ'
					WHEN t_journal.type_journal <> 'VE' AND PLC_COMPTE LIKE '466%' THEN 'PHON'
					WHEN t_journal.type_journal <> 'VE' AND PLC_COMPTE LIKE '7%' THEN 'XPRD'
					WHEN t_journal.type_journal <> 'VE' AND PLC_COMPTE LIKE '445%' THEN 'XTVA'
					ELSE '?'||JNL_CODE END AS type_ecriture,
					CASE 
					WHEN t_journal.type_journal = 'VE' THEN 'VENTE'
					ELSE t_journal.type_journal END AS type_piece,
					w_CMECRITURES.piece, 
					w_CMECRITURES.mode_reglement_code,
					w_CMECRITURES.clinique_honoraire, 
					COALESCE(t_compte.oid,0) AS compte_id, 
					COALESCE(t_journal.oid,0) AS journal_id, 
					w_CMECRITURES.sejour_id, 
					w_CMECRITURES.no_sejour, 
					w_CMECRITURES.facture_id, 
					w_CMECRITURES.no_facture, 
					w_CMECRITURES.medecin_administratif_id, 
					w_CMECRITURES.tiers_payant_id, 
					ECR_LIBELLE AS texte, 
					round(CASE WHEN ECR_SIGNED <> 1 THEN ECR_MONTANT ELSE 0 END::numeric,2) AS montant_credit, 
					round(CASE WHEN ECR_SIGNED = 1 THEN ECR_MONTANT ELSE 0 END::numeric,2) AS montant_debit,
					'1'::text AS est_comptabilise,
					COALESCE(t_compte.taux_tva,0) AS taux_tva
				FROM w_CMECRITURES
				LEFT JOIN activite[PX].t_compte ON PLC_COMPTE = t_compte.code AND PLC_COMPTE <> ''
				LEFT JOIN activite[PX].t_journal ON w_CMECRITURES.JNL_CODE = t_journal.code_original
				WHERE t_journal.type_journal IS DISTINCT FROM 'IGNORE'
				;

                                        
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="*LOGHOS*">
        
            <condition><![CDATA[
                "[CEGILOGHOS_PRESENT]" == "OUI"
            ]]></condition>
            
            <sqlcmd><![CDATA[
                
                
                INSERT INTO activite[PX].p_chiffrier_comptable(
                    date_comptable,
                    provider_id,
                    montant_ventes_c, 
                    montant_reglements_c, 
                    montant_solde_client_c, 
                    montant_ventes_h, 
                    montant_reglements_h, 
                    montant_solde_client_h
                )
                SELECT 
                    date(date_trunc('month',date_calcul_facture) + interval '1 month' - interval '1 day') AS date_comptable,
                    2::bigint AS provider_id,
                    0::numeric AS montant_ventes_c,
                    0::numeric AS montant_reglements_c,
                    0::numeric AS montant_solde_client_c,
                    0::numeric AS montant_ventes_h,
                    0::numeric AS montant_reglements_h,
                    0::numeric AS montant_solde_client_h
                FROM prod_cegiloghos.OPERA_FAC
                WHERE date_calcul_facture >= '[ENV_ADM_ANNEEDEBUT]0101'
                GROUP BY 1
                ORDER BY 1;
                
                    
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="*FIRST*">
            
            <condition><![CDATA[
                "[CJFIRST_PRESENT]" == "OUI"
            ]]></condition>
        
        
            <sqlcmd><![CDATA[
			

                INSERT INTO activite[PX].p_chiffrier_comptable(
                    date_comptable,
                    provider_id,
                    montant_ventes_c, 
                    montant_reglements_c, 
                    montant_solde_client_c, 
                    montant_ventes_h, 
                    montant_reglements_h, 
                    montant_solde_client_h
                )
                SELECT 
                    date(date_trunc('month',ECR_DATCPTA) + interval '1 month' - interval '1 day') AS date_comptable,
                    0::bigint AS provider_id,
                    SUM(CASE WHEN CMECRITURES.JNL_CODE = CJ_JNLNUMFAC.JNL_CODE AND PNF_LITERAL = 'C' THEN CASE WHEN ECR_SIGNED = 0 THEN 0 - ECR_MONTANT ELSE  ECR_MONTANT END ELSE 0 END) AS montant_ventes_c,
                    0::numeric AS montant_reglements_c,
                    0::numeric AS montant_solde_client_c,
                    SUM(CASE WHEN CMECRITURES.JNL_CODE = CJ_JNLNUMFAC.JNL_CODE AND PNF_LITERAL = 'M' THEN CASE WHEN ECR_SIGNED = 0 THEN 0 - ECR_MONTANT ELSE  ECR_MONTANT END ELSE 0 END) AS montant_ventes_h,
                    0::numeric AS montant_reglements_h,
                    0::numeric AS montant_solde_client_h
                FROM prod_cegi.CMECRITURES
                JOIN prod_cegi.CJ_JNLNUMFAC ON CMECRITURES.DOS_ID = CJ_JNLNUMFAC.DOS_ID
				JOIN activite.t_divers ON t_divers.code = 'CEGI_CPTCLI'
                WHERE 
                    ECR_DATCPTA >= '[ENV_ADM_ANNEEDEBUT]0101' AND
                    (
						t_divers.valeur = '' AND PLC_COMPTE LIKE '41%' OR
						t_divers.valeur <> '' AND PLC_COMPTE = ANY(string_to_array(t_divers.valeur,','))
                    ) AND
                    ECR_ORIGINE = '615' AND
					(
					CJ_JNLNUMFAC.ETB_ID::text = ANY (string_to_array('[ID_ETAB]'::text,',')) OR
					'[ID_ETAB]' = '' OR
					'[ID_ETAB]' = '-1'
					)
                GROUP BY 1
                ORDER BY 1;
                
                
                
                
                                        
            ]]></sqlcmd>
        </NODE>
        
    </NODE>
    
    <NODE name="PARAM" label="RECUPERATION DES PARAMETRES">

        <NODE label="Initialisation">
			<sqlcmd><![CDATA[
				
				-- Paramètre pour identifier les entrées par les urgences.
				-- par défaut on se base sur les DMT des services
				-- on peut aussi choisir de se fier au type dossier U codé dan CEGI LOGHOS (OPERA_SEJ)
                -- ou au mode d'entrée des séjours (mode 8U)
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'URGENCES_CEGI',
					'Identification des arrivées urgences',
					'1',
					'1=Identification par DMT des services, 2=Type de dossier CEGI (type U), 3=Mode d''entrée CEGI (8U), 4=DMT OU Type de dossier, 5=DMT OU Mode d''entrée, 6=Tout'
				WHERE 'URGENCES_CEGI' NOT IN (SELECT code FROM activite.t_divers);
				
				-- Pour ignorer les types de dossiers
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'CEGIFIRST_TDI',
					'Types de dossiers CEGI à ignorer (plage)',
					'NF',
					'Séparé par une virgule. Ces séjours seront convertis en fictifs'
				WHERE 'CEGIFIRST_TDI' NOT IN (SELECT code FROM activite.t_divers);
				
				-- Pour ignorer les types de dossiers
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'CEGILOGHOS_TDI',
					'Types de dossiers CEGI LOGHOS à ignorer (plage)',
					'',
					'Séparé par une virgule. Ces séjours seront convertis en fictifs'
				WHERE 'CEGILOGHOS_TDI' NOT IN (SELECT code FROM activite.t_divers);

			]]></sqlcmd>
		</NODE>
	
		<NODE label="Tests des options installées">
            <sqlcmd><![CDATA[
                CTISELECT_PROPERTY_READ 'WITH_CORA', count(*) 
                FROM information_schema.tables
                WHERE table_schema = 'prod_cora' AND table_name = 'tb_sejour' ;
                
                CTISELECT_PROPERTY_READ 'CORA_PRESENT', CASE WHEN count(*) > 0 THEN 'OUI' ELSE 'NON' END
                FROM information_schema.tables
                WHERE table_schema = 'prod_cora' AND table_name = 'tb_sejour' ;
                
                CTISELECT_PROPERTY_READ 'CJFIRST_PRESENT', CASE WHEN count(*) > 0 THEN 'OUI' ELSE 'NON' END
                FROM information_schema.tables
                WHERE table_schema = 'prod_cegi' AND table_name = 'cj_efs' ;
                
                CTISELECT_PROPERTY_READ 'CEGILOGHOS_PRESENT', CASE WHEN count(*) > 0 THEN 'OUI' ELSE 'NON' END
                FROM information_schema.tables
                WHERE table_schema = 'prod_cegiloghos' AND table_name = 'opera_sej' ;
                
                echo CORA : [CORA_PRESENT];
                echo CJFIRST : [CJFIRST_PRESENT];
                echo LOGHOS : [CEGILOGHOS_PRESENT];
        
            ]]></sqlcmd>
        </NODE>
    
    
        <NODE name="PARAM_INIT" label="Initialisation paramètres">
            <sqlcmd><![CDATA[

                    INSERT INTO activite[PX].t_types_tiers_payant(code, texte, texte_court)
                    SELECT code, texte, texte FROM
                    (
                    SELECT '0' AS code, 'Patients' AS texte
                    UNION ALL
                    SELECT '1','Régime général'
                    UNION ALL
                    SELECT '2','Mutuelles'
                    ) subview
                    WHERE code NOT IN (SELECT code FROM activite[PX].t_types_tiers_payant);

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

                    INSERT INTO activite[PX].t_tiers_payant(code, code_original, type_tiers_payant, texte, texte_court) 
                    SELECT 'PATIENT', 'PATIENT', '0', 'PATIENTS', 'PATIENTS'
                    WHERE 'PATIENT' NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant WHERE code_original IS NOT NULL);
                    
                    
                    INSERT INTO activite[PX].t_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);
                    
                    INSERT INTO activite[PX].t_services_facturation(oid, code_original, code, texte, texte_court) 
                    SELECT 0, 0, '****', 'Non renseigné', 'Non renseigné' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_services_facturation);
                    
                    INSERT INTO activite[PX].t_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_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_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);

                    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_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_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_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.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);
                    
                    
                    
                ]]></sqlcmd>
        </NODE>
        
        <NODE name="PARAM_LOGHOS" label="*LOGHOS*">
        
            <condition><![CDATA[
                "[CEGILOGHOS_PRESENT]" == "OUI"
            ]]></condition>
        
            <NODE label="Tiers payant">
                <sqlcmd><![CDATA[


                    INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
                    SELECT
                        CODE_ORGANISME, 
                        CODE_ORGANISME, 
                        CASE WHEN TYPE_ORGANISME = 'C' THEN '1' ELSE '2' END,
                        CASE WHEN LIBELLE_ORGANISME <> '' THEN LIBELLE_ORGANISME ELSE CODE_ORGANISME END, 
                        CASE WHEN LIBELLE_ORGANISME <> '' THEN LIBELLE_ORGANISME ELSE CODE_ORGANISME END
                    FROM prod_cegiloghos.OPERA_PAMOC
                    WHERE CODE_ORGANISME NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant WHERE code_original IS NOT NULL);
                    
					UPDATE activite[PX].t_tiers_payant  SET
						code = CODE_ORGANISME,
						texte = CASE WHEN LIBELLE_ORGANISME <> '' THEN LIBELLE_ORGANISME ELSE CODE_ORGANISME END,
						texte_court = CASE WHEN LIBELLE_ORGANISME <> '' THEN LIBELLE_ORGANISME ELSE CODE_ORGANISME END
					FROM prod_cegiloghos.OPERA_PAMOC
					WHERE t_tiers_payant.code_original = OPERA_PAMOC.CODE_ORGANISME AND
						(
						code IS DISTINCT FROM CODE_ORGANISME OR
						texte IS DISTINCT FROM CASE WHEN LIBELLE_ORGANISME <> '' THEN LIBELLE_ORGANISME ELSE CODE_ORGANISME END OR
						texte_court IS DISTINCT FROM CASE WHEN LIBELLE_ORGANISME <> '' THEN LIBELLE_ORGANISME ELSE CODE_ORGANISME END
						)
					;
                    
                    UPDATE activite[PX].t_tiers_payant
                    SET grand_regime_id = t_grands_regimes.oid
                    FROM prod_cegiloghos.OPERA_PAMOC
                        JOIN base.t_grands_regimes ON OPERA_PAMOC.CODE_REGIME = t_grands_regimes.code 
                    WHERE t_tiers_payant.code_original = OPERA_PAMOC.CODE_ORGANISME AND
                        COALESCE(t_tiers_payant.grand_regime_id,0) = 0 AND
                        t_grands_regimes.oid <> 0;
                                            
                                            
                ]]></sqlcmd>
            </NODE>
            
            <NODE label="Médecins">
                <sqlcmd><![CDATA[

                    INSERT INTO base.t_specialites_medecin(code_original, code, texte, texte_court)
                    SELECT
                        CODE_SPECIALITE,
                        CODE_SPECIALITE,
                        CASE WHEN MAX(LIBELLE_SPECIALITE) <> '' THEN MAX(LIBELLE_SPECIALITE) ELSE CODE_SPECIALITE END,
                        CASE WHEN MAX(LIBELLE_SPECIALITE) <> '' THEN MAX(LIBELLE_SPECIALITE) ELSE CODE_SPECIALITE END
                    FROM prod_cegiloghos.OPERA_PMED
                        LEFT JOIN base.t_specialites_medecin ON CODE_SPECIALITE = t_specialites_medecin.code
                    WHERE to_number('0' || code_specialite,'000') > 0 AND
                        t_specialites_medecin.code IS NULL
                    GROUP BY 1,2
                    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);
                    
                    INSERT INTO activite[PX].t_medecins_administratifs(code_original, code, nom, prenom, specialite_id, medecin_id) 
                    SELECT '*ECARTCTI', chr(127) || 'ECART', 'Ecarts de répartition', '', 0, 0 WHERE '*ECARTCTI' NOT IN (SELECT code_original FROM activite[PX].t_medecins_administratifs);
                    
                    INSERT INTO activite[PX].t_medecins_administratifs(code_original, code, nom, prenom, specialite_id, medecin_id) 
                    SELECT '*ATTNSCTI', chr(127) || 'ATTNS', 'Attente (non soldé)', '', 0, 0 WHERE '*ATTNSCTI' NOT IN (SELECT code_original FROM activite[PX].t_medecins_administratifs);

                    DROP TABLE IF EXISTS w_OPERA_PMED;
                    CREATE TEMP TABLE w_OPERA_PMED AS
                    SELECT 
                        *,
                        split_part(LIBELLE_MEDECIN,' ',1) AS NOM_MEDECIN,
                        split_part(LIBELLE_MEDECIN,' ',2) || ' ' ||
                        split_part(LIBELLE_MEDECIN,' ',3) || ' ' || 
                        split_part(LIBELLE_MEDECIN,' ',4) || ' ' || 
                        split_part(LIBELLE_MEDECIN,' ',5) || ' ' || 
                        split_part(LIBELLE_MEDECIN,' ',6) || ' ' || 
                        split_part(LIBELLE_MEDECIN,' ',7) 
                        AS PRENOM_MEDECIN
                    FROM prod_cegiloghos.OPERA_PMED;

                    DROP TABLE IF EXISTS w_medecins;
                    CREATE TEMP TABLE w_medecins AS
                    SELECT 
                        CODE_MEDECIN AS CODE_MEDECIN,
                        base.cti_soundex_nom(NOM_MEDECIN) AS NOM_MEDECIN_SOUNDEX, 
                        base.cti_soundex_nom(PRENOM_MEDECIN) AS PRENOM_MEDECIN_SOUNDEX, 
                        NOM_MEDECIN, 
                        PRENOM_MEDECIN AS PRENOM_MEDECIN, 
                        SUBSTR(COALESCE(CODE_ADELI,''),1,9) AS CODE_ADELI, 
                        CODE_SPECIALITE AS CODE_SPECIALITE, 
                        COALESCE(t_medecins_administratifs.medecin_id,0) as medecin_id
                    FROM w_OPERA_PMED
                        LEFT JOIN activite[PX].t_medecins_administratifs ON CODE_MEDECIN = t_medecins_administratifs.code_original;


                    INSERT INTO base.t_medecins(nom, prenom, numero_ordre, specialite_id)
                    SELECT w_medecins.NOM_MEDECIN, w_medecins.PRENOM_MEDECIN, w_medecins.CODE_ADELI, 0 FROM
                    (SELECT SUBSTR(NOM_MEDECIN_SOUNDEX, 1, 8) AS NOM_MEDECIN_SOUNDEX, SUBSTR(PRENOM_MEDECIN_SOUNDEX, 1, 8) AS PRENOM_MEDECIN_SOUNDEX, CODE_ADELI, MIN(CODE_MEDECIN) AS CODE_MEDECIN
                    FROM w_medecins
                    GROUP BY 1,2,3) subview, w_medecins
                    WHERE w_medecins.CODE_MEDECIN = subview.CODE_MEDECIN
                        AND subview.NOM_MEDECIN_SOUNDEX || ',' || subview.PRENOM_MEDECIN_SOUNDEX || ',' ||  subview.CODE_ADELI 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_MEDECIN, w_medecins.PRENOM_MEDECIN, w_medecins.CODE_ADELI, 0 FROM
                    (SELECT NOM_MEDECIN_SOUNDEX, PRENOM_MEDECIN_SOUNDEX, MIN(CODE_MEDECIN) AS CODE_MEDECIN
                    FROM w_medecins
                    GROUP BY 1,2) subview, w_medecins
                    WHERE w_medecins.CODE_MEDECIN = subview.CODE_MEDECIN
                        AND subview.NOM_MEDECIN_SOUNDEX || ',' || subview.PRENOM_MEDECIN_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_MEDECIN_SOUNDEX, 1, 8) = subview.nom
                    AND SUBSTR(PRENOM_MEDECIN_SOUNDEX, 1, 8) = subview.prenom
                    AND CODE_ADELI = 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_MEDECIN_SOUNDEX, 1, 8) = subview.nom
                    AND SUBSTR(PRENOM_MEDECIN_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 CODE_MEDECIN, CODE_MEDECIN, NOM_MEDECIN, PRENOM_MEDECIN, COALESCE(t_specialites_medecin.oid,0), medecin_id
                    FROM w_medecins
                        LEFT JOIN base.t_specialites_medecin ON CODE_SPECIALITE = t_specialites_medecin.code
                    WHERE CODE_MEDECIN NOT IN (SELECT code_original FROM activite[PX].t_medecins_administratifs);

                    UPDATE activite[PX].t_medecins_administratifs
                    SET nom = NOM_MEDECIN,
                        prenom = PRENOM_MEDECIN,
                        specialite_id = COALESCE(t_specialites_medecin.oid,0),
                        medecin_id = w_medecins.medecin_id,
                        no_adeli = code_adeli
                    FROM w_medecins LEFT JOIN base.t_specialites_medecin ON CODE_SPECIALITE = t_specialites_medecin.code_original
                    WHERE w_medecins.CODE_MEDECIN = t_medecins_administratifs.code_original
                        AND (
                        t_medecins_administratifs.nom <> NOM_MEDECIN OR
                        t_medecins_administratifs.prenom <> PRENOM_MEDECIN OR
                        t_medecins_administratifs.specialite_id <> COALESCE(t_specialites_medecin.oid,0) OR
                        t_medecins_administratifs.medecin_id <> w_medecins.medecin_id OR
                        t_medecins_administratifs.no_adeli <> w_medecins.code_adeli
                    );

                    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;

                    -- code rpps
                    UPDATE base.t_medecins
                        SET code_rpps = subview.RPPS
                        FROM
                        (
                        SELECT medecin_id, count(DISTINCT CJ_PRC.PRC_RPPS), MAX(CJ_PRC.PRC_RPPS) AS RPPS
                        FROM activite[PX].t_medecins_administratifs
                        JOIN base.t_medecins ON t_medecins_administratifs.medecin_id = t_medecins.oid
                        JOIN prod_cegi.cj_pra ON code_original = PRA_LIBC
                        JOIN prod_cegi.cj_prc ON cj_prc.pra_id = cj_pra.pra_id
                        WHERE PRA_LIBC <> '' AND
                            CJ_PRC.PRC_RPPS <> '' AND 
                            t_medecins.code_rpps = '' AND 
                            medecin_id <> 0
                        GROUP BY 1
                        HAVING count(DISTINCT CJ_PRC.PRC_RPPS) = 1
                        ) subview
                        WHERE t_medecins.oid = subview.medecin_id
                        ;
						
					-- Adresse et coordonnées
					INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
					SELECT PRC_CPS, MAX(PRC_VILLE), MAX(PRC_VILLE), MAX(t_departements.oid)
					FROM prod_CEGI.CJ_PRC
					LEFT JOIN base.t_codes_postaux ON PRC_CPS = t_codes_postaux.code
					JOIN base.t_departements ON 
						PRC_CPS NOT LIKE '97%' AND substr(PRC_CPS,1,2) = t_departements.code OR
						PRC_CPS LIKE '97%' AND substr(PRC_CPS,1,3) = t_departements.code 
					WHERE  PRC_CPS <> '' AND
						length(PRC_CPS) = 5 AND 
						t_codes_postaux.code IS NULL
					GROUP BY 1
					;
				
					UPDATE activite[PX].t_medecins_administratifs SET
						adresse = PRC_ADRx,
						code_postal_id = subview.code_postal_id,
						ville = PRC_VILLE,
						telephone = PRC_TELx,
						fax = PRC_FAX,
						email = PRC_EMAIL
					FROM
					(
						SELECT t_medecins_administratifs.oid, 
							(MAX(ARRAY[PRC_DEPUIS::text, trim(PRC_ADR1 || ' ' || PRC_ADR2)]))[2] AS PRC_ADRx,
							(MAX(ARRAY[PRC_DEPUIS::text, trim(PRC_VILLE)]))[2] AS PRC_VILLE,
							(MAX(ARRAY[PRC_DEPUIS::text, trim(PRC_CPS)]))[2] AS PRC_CPS,
							(MAX(ARRAY[PRC_DEPUIS::text, COALESCE(t_codes_postaux.oid,0)::text]))[2]::bigint AS code_postal_id,
							(MAX(ARRAY[PRC_DEPUIS::text, trim(PRC_TEL1 || ' ' || PRC_TEL2 || ' ' || PRC_TEL3)]))[2] AS PRC_TELx,
							(MAX(ARRAY[PRC_DEPUIS::text, trim(PRC_FAX)]))[2] AS PRC_FAX,
							(MAX(ARRAY[PRC_DEPUIS::text, trim(PRC_EMAIL)]))[2] AS PRC_EMAIL
						FROM activite[PX].t_medecins_administratifs
						JOIN prod_cegi.CJ_PRA ON code_original = PRA_LIBC
						JOIN prod_cegi.CJ_PRC ON cj_prc.pra_id = cj_pra.pra_id
						LEFT JOIN base.t_codes_postaux ON PRC_CPS = t_codes_postaux.code
						WHERE PRA_LIBC <> '' 
						GROUP BY 1
						) subview
					WHERE t_medecins_administratifs.oid = subview.oid AND
						(
						t_medecins_administratifs.adresse IS DISTINCT FROM PRC_ADRx OR
						t_medecins_administratifs.code_postal_id IS DISTINCT FROM subview.code_postal_id OR
						t_medecins_administratifs.ville IS DISTINCT FROM PRC_VILLE OR
						t_medecins_administratifs.telephone IS DISTINCT FROM PRC_TELx OR
						t_medecins_administratifs.fax IS DISTINCT FROM PRC_FAX OR
						t_medecins_administratifs.email IS DISTINCT FROM PRC_EMAIL
						)
					;
                                            
                ]]></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);

                    INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits, type_t2a)
                    SELECT 
                        CODE_SERVICE_DISCIPLINE, 
                        CODE_SERVICE_DISCIPLINE, 
                        LIBELLE_SERVICE_DISCIPLINE, 
                        LIBELLE_SERVICE_DISCIPLINE, 
                        0 AS nb_lits, 
                        CASE 
                        WHEN MT = '07' THEN '0' 
                        WHEN MT = '10' THEN '0' 
                        WHEN TYPE <> '' THEN '0' 
                        ELSE '1' END
                        AS type_t2a
                    FROM prod_cegiloghos.OPERA_PSDISC
                    LEFT JOIN prod_cegiloghos.OPERA_PSTARF ON OPERA_PSDISC.CODE_SERVICE_TARIFAIRE = OPERA_PSTARF.CODE_SERVICE_TARIFAIRE
                    WHERE CODE_SERVICE_DISCIPLINE <> '' AND
						CODE_SERVICE_DISCIPLINE NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
                    ORDER BY 1;
					
					UPDATE activite[PX].t_services_facturation SET
						code = CODE_SERVICE_DISCIPLINE,
						texte = LIBELLE_SERVICE_DISCIPLINE,
						texte_court = LIBELLE_SERVICE_DISCIPLINE
                    FROM prod_cegiloghos.OPERA_PSDISC
                    WHERE t_services_facturation.code_original = CODE_SERVICE_DISCIPLINE AND 
						(
                        t_services_facturation.code IS DISTINCT FROM CODE_SERVICE_DISCIPLINE OR
						t_services_facturation.texte IS DISTINCT FROM LIBELLE_SERVICE_DISCIPLINE OR
						t_services_facturation.texte_court IS DISTINCT FROM LIBELLE_SERVICE_DISCIPLINE
						)
					;
                    
                    UPDATE activite[PX].t_services_facturation
                    SET mode_traitement_id = COALESCE(t_modes_traitement.oid,0)
                    FROM prod_cegiloghos.OPERA_PSDISC
                        JOIN prod_cegiloghos.OPERA_PSTARF ON OPERA_PSDISC.CODE_SERVICE_TARIFAIRE = OPERA_PSTARF.CODE_SERVICE_TARIFAIRE
                        LEFT JOIN base.t_modes_traitement ON MT = t_modes_traitement.code
                    WHERE t_services_facturation.code_original = CODE_SERVICE_DISCIPLINE 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 prod_cegiloghos.OPERA_PSDISC
                        JOIN prod_cegiloghos.OPERA_PSTARF ON OPERA_PSDISC.CODE_SERVICE_TARIFAIRE = OPERA_PSTARF.CODE_SERVICE_TARIFAIRE
                        LEFT JOIN base.t_dmt ON DMT = t_dmt.code
                    WHERE t_services_facturation.code_original = CODE_SERVICE_DISCIPLINE 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
                        CODE_SERVICE_DISCIPLINE,
                        CODE_SERVICE_DISCIPLINE,
                        LIBELLE_SERVICE_DISCIPLINE,
                        LIBELLE_SERVICE_DISCIPLINE
                    FROM prod_cegiloghos.OPERA_PSDISC 
                    WHERE CODE_SERVICE_DISCIPLINE NOT IN (SELECT code_original FROM activite[PX].t_unites_fonctionnelles);
					
					UPDATE activite[PX].t_unites_fonctionnelles SET
						code = CODE_SERVICE_DISCIPLINE,
						texte = LIBELLE_SERVICE_DISCIPLINE,
						texte_court = LIBELLE_SERVICE_DISCIPLINE
                    FROM prod_cegiloghos.OPERA_PSDISC
                    WHERE t_unites_fonctionnelles.code_original = CODE_SERVICE_DISCIPLINE AND 
						(
                        t_unites_fonctionnelles.code IS DISTINCT FROM CODE_SERVICE_DISCIPLINE OR
						t_unites_fonctionnelles.texte IS DISTINCT FROM LIBELLE_SERVICE_DISCIPLINE OR
						t_unites_fonctionnelles.texte_court IS DISTINCT FROM LIBELLE_SERVICE_DISCIPLINE
						)
					;
                        
                    -- 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);

                    SELECT base.cti_execute('
                    INSERT INTO activite[PX].t_unites_medicales(code_original, code, texte, texte_court)
                    SELECT CODE, CODE, LIB, LIB
                    FROM prod_cegi.UM
                    WHERE CODE NOT IN (SELECT code_original FROM activite[PX].t_unites_medicales)
						ORDER BY CODE',1)
					WHERE (SELECT count(*) FROM information_schema.tables WHERE table_name = 'um' AND table_schema='prod_cegi') > 0
					;
					
					SELECT base.cti_execute('
                    UPDATE activite[PX].t_unites_medicales SET
						code = UM.CODE,
						texte = UM.LIB,
						texte_court = UM.LIB
                    FROM prod_cegi.UM
                    WHERE UM.CODE = t_unites_medicales.code_original AND
						(
						t_unites_medicales.code IS DISTINCT FROM UM.CODE OR
						t_unites_medicales.texte IS DISTINCT FROM UM.LIB OR
						t_unites_medicales.texte_court IS DISTINCT FROM UM.LIB
						)',1)
					WHERE (SELECT count(*) FROM information_schema.tables WHERE table_name = 'um' AND table_schema='prod_cegi') > 0
					;


                    -- 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_OPERA_PLIT;
                    CREATE TEMP TABLE w_OPERA_PLIT AS
                    SELECT
                        CODE_LIT,
                        LIBELLE_LIT,
                    CASE WHEN CODE_ETAGE <> '' THEN CODE_ETAGE ELSE SUBSTR(CODE_LIT,1,1) END AS CODE_ETAGE,
                    CASE WHEN CODE_ETAGE <> '' THEN LIBELLE_ETAGE ELSE 'Etage ' || SUBSTR(CODE_LIT,1,1) END AS LIBELLE_ETAGE
                    FROM prod_cegiloghos.OPERA_PLIT;
                    
                    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 
                        CODE_ETAGE, 
                        CODE_ETAGE,  
                        MAX(LIBELLE_ETAGE),  
                        MAX(LIBELLE_ETAGE),  
                        0 AS nb_lits
                    FROM w_OPERA_PLIT
                    WHERE CODE_ETAGE <> '' AND 
                        CODE_ETAGE NOT IN (SELECT code_original FROM activite[PX].t_etages WHERE code_original IS NOT NULL)
                    GROUP BY 1,2
                    ORDER BY 1;
					
					UPDATE activite[PX].t_etages SET
						code = CODE_ETAGE,
						texte = LIBELLE_ETAGE,
						texte_court = LIBELLE_ETAGE
                    FROM 
						(
						SELECT 
							CODE_ETAGE, 
							MAX(LIBELLE_ETAGE) AS LIBELLE_ETAGE
						FROM w_OPERA_PLIT
						WHERE CODE_ETAGE <> ''
						GROUP BY 1
						) subview
                    WHERE t_etages.code_original = CODE_ETAGE AND 
						(
                        t_etages.code IS DISTINCT FROM CODE_ETAGE OR
						t_etages.texte IS DISTINCT FROM LIBELLE_ETAGE OR
						t_etages.texte_court IS DISTINCT FROM LIBELLE_ETAGE
						)
					;
                    
                    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 CODE_ETAGE || '|' || CODE_LIT, CODE_LIT, MAX(LIBELLE_LIT), MAX(LIBELLE_LIT), t_etages.oid, 'N'
                    FROM w_OPERA_PLIT
                        JOIN activite[PX].t_etages ON CODE_ETAGE = t_etages.code_original
                    WHERE CODE_LIT <> '' AND CODE_ETAGE || '|' || CODE_LIT NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL)
					GROUP BY 1,2,5
                    ORDER BY 1;
					
					
					UPDATE activite[PX].t_lits SET
						code = CODE_LIT,
						texte = LIBELLE_LIT,
						texte_court = LIBELLE_LIT
                    FROM 
						(
						SELECT 
							CODE_ETAGE, 
							CODE_LIT,
							MAX(LIBELLE_LIT) AS LIBELLE_LIT
						FROM w_OPERA_PLIT
						WHERE CODE_ETAGE <> '' AND CODE_LIT <> ''
						GROUP BY 1,2
						) subview
                    WHERE t_lits.code_original = (CODE_ETAGE || '|' || CODE_LIT) AND 
						(
                        t_lits.code IS DISTINCT FROM CODE_LIT OR
						t_lits.texte IS DISTINCT FROM LIBELLE_LIT OR
						t_lits.texte_court IS DISTINCT FROM LIBELLE_LIT
						)
					;

                                        
                ]]></sqlcmd>
            </NODE>
                    
            <NODE label="Facturation">
                <sqlcmd><![CDATA[
                
                    -- Comptes
                    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 COMPTE_COMPTABLE, COMPTE_COMPTABLE, MAX(LIBELLE_COMPTE_COMPTABLE), MAX(LIBELLE_COMPTE_COMPTABLE)
                    FROM prod_cegiloghos.OPERA_PPRS
                    WHERE COMPTE_COMPTABLE <> '' AND
						COMPTE_COMPTABLE NOT IN (SELECT code FROM activite[PX].t_compte WHERE code IS NOt NULL)
                    GROUP BY 1
                    ORDER BY 1;

                    -- 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  '*ECARTCTI', chr(127) || 'ECART', 'Ecarts de répartition', 'Ecarts de répartition'
                    WHERE '*ECARTCTI' NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation);
                    
                    INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court) 
                    SELECT  '*ATTNSCTI', chr(127) || 'ATTNS', 'Attente (non soldé)', 'Attente (non soldé)'
                    WHERE '*ATTNSCTI' NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation);

                    INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
                    SELECT 
                        CODE_PRESTA,
                        CODE_PRESTA,
                        LIBELLE_PRESTA,
                        LIBELLE_PRESTA
                    FROM 
						(
						SELECT 
							CODE_PRESTA,
							(MAX(ARRAY[CASE WHEN CODE_SERVICE_TARIFAIRE = '' THEN '1' ELSE '0' END::text, LIBELLE_PRESTA]))[2] AS LIBELLE_PRESTA
						FROM prod_cegiloghos.OPERA_PPRS
						GROUP BY 1
						) subview
                    WHERE CODE_PRESTA NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
                    ;
					
					UPDATE activite[PX].t_rubriques_facturation SET
						code = CODE_PRESTA,
						texte = LIBELLE_PRESTA,
						texte_court = LIBELLE_PRESTA
					FROM (
						SELECT 
							CODE_PRESTA,
							(MAX(ARRAY[CASE WHEN CODE_SERVICE_TARIFAIRE = '' THEN '1' ELSE '0' END::text, LIBELLE_PRESTA]))[2] AS LIBELLE_PRESTA
						FROM prod_cegiloghos.OPERA_PPRS
						GROUP BY 1
						) subview
						WHERE CODE_PRESTA = code_original AND
						(
						code IS DISTINCT FROM CODE_PRESTA OR
						texte IS DISTINCT FROM LIBELLE_PRESTA OR
						texte_court IS DISTINCT FROM LIBELLE_PRESTA
						)
					;




                    -- Prestations
                    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);
                    
                    INSERT INTO activite.t_prestations(code_original, code, texte, texte_court, clinique_honoraire) 
                    SELECT  '*ECARTCTI', chr(127) || 'ECART', 'Ecarts de répartition', 'Ecarts de répartition', '' 
                    WHERE '*ECARTCTI' NOT IN (SELECT code_original FROM activite.t_prestations WHERE code_original IS NOT NULL);
                    
                    INSERT INTO activite.t_prestations(code_original, code, texte, texte_court, clinique_honoraire) 
                    SELECT  '*ATTNSCTI', chr(127) || 'ATTNS', 'Attente (non soldé)', 'Attente (non soldé)', '' 
                    WHERE '*ATTNSCTI' NOT IN (SELECT code_original FROM activite.t_prestations WHERE code_original IS NOT NULL);

                    INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
                    SELECT 
                        CODE_PRESTA,
                        CODE_PRESTA,
                        LIBELLE_PRESTA,
                        LIBELLE_PRESTA
                    FROM 
						(
						SELECT 
							CODE_PRESTA,
							(MAX(ARRAY[CASE WHEN CODE_SERVICE_TARIFAIRE = '' THEN '1' ELSE '0' END::text, LIBELLE_PRESTA]))[2] AS LIBELLE_PRESTA
						FROM prod_cegiloghos.OPERA_PPRS
						GROUP BY 1
						) subview
                    WHERE CODE_PRESTA NOT IN (SELECT code_original FROM activite.t_prestations)
                    ;
                                            
                ]]></sqlcmd>
            </NODE>
        
        </NODE>
        
        <NODE name="PARAM_FIRST" label="*FIRST*">
        
            <condition><![CDATA[
                "[CJFIRST_PRESENT]" == "OUI"
            ]]></condition>
            
            <NODE label="Tiers payant">
                <sqlcmd><![CDATA[

                    INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
					SELECT TIES_CODEP, UPPER(MAX(TIES_VILLE)), UPPER(MAX(TIES_VILLE)), MAX(t_departements.oid)
					FROM prod_cegi.CJ_ORG
					JOIN prod_cegi.CJ_AFF on CJ_AFF.TER_ID = CJ_ORG.TER_ID AND AFF_TYPE = ANY (Array['M', 'C'])
					JOIN prod_cegi.CMTIESERV ON CJ_ORG.TER_ID = CMTIESERV.TIE_ID AND CMTIESERV.TIES_SERV = 0
					LEFT JOIN base.t_codes_postaux ON TIES_CODEP = t_codes_postaux.code
					JOIN base.t_departements ON 
						TIES_CODEP NOT LIKE '97%' AND substr(TIES_CODEP,1,2) = t_departements.code OR
						TIES_CODEP LIKE '97%' AND substr(TIES_CODEP,1,3) = t_departements.code 
					WHERE t_codes_postaux.oid IS NULL AND 
						length(TIES_CODEP) = 5
					GROUP BY 1
					;

                    DROP TABLE IF EXISTS w_CJ_ORG;
                    CREATE TEMP TABLE w_CJ_ORG AS
                    SELECT
                        CJ_AFF.TER_ID, 
                        ORG_LIBC, 
                        CASE WHEN ORG_TYPES = 'C' THEN '1' ELSE '2' END AS type_tiers_payant,
                        CASE WHEN ORG_LIBELLE <> '' THEN ORG_LIBELLE ELSE ORG_LIBC END AS ORG_LIBELLE, 
                        0::bigint AS tiers_payant_id,
                        MAX(COALESCE(trim(TIES_ADR1 || ' ' || TIES_ADR2),'')) AS TIES_ADRx,
						MAX(COALESCE(t_codes_postaux.oid,0)) AS code_postal_id,
						MAX(COALESCE(TIES_CODEP,'')) AS TIES_CODEP,
						MAX(COALESCE(TIES_VILLE,'')) AS TIES_VILLE,
						MAX(COALESCE(TIES_TEL,'')) AS TIES_TEL,
						MAX(COALESCE(TIES_FAX,'')) AS TIES_FAX,
						MAX(COALESCE(TIES_EMAIL,'')) AS TIES_EMAIL
                    FROM prod_cegi.CJ_ORG
                        JOIN prod_cegi.CJ_AFF on CJ_AFF.TER_ID = CJ_ORG.TER_ID AND AFF_TYPE = ANY (Array['M', 'C'])
                        LEFT JOIN prod_cegi.CMTIERS ON CJ_ORG.ORG_LIBC = CMTIERS.TIE_nomc
						LEFT JOIN prod_cegi.CMTIESERV ON CMTIERS.TIE_ID = CMTIESERV.TIE_ID AND CMTIESERV.TIES_SERV = 0 
						LEFT JOIN base.t_codes_postaux ON TIES_CODEP = t_codes_postaux.code AND TIES_CODEP <> ''
                    WHERE CJ_ORG.TER_ID <> 0
                    GROUP BY 1,2,3,4,5
					;

                    ANALYSE w_CJ_ORG
					;
              
                
                    INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
                    SELECT
                        ORG_LIBC, 
                        ORG_LIBC, 
                        MAX(type_tiers_payant),
                        MAX(ORG_LIBELLE), 
                        MAX(ORG_LIBELLE)
                    FROM w_CJ_ORG
                    WHERE ORG_LIBC NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant WHERE code_original IS NOT NULL)
                    GROUP BY 1,2
                    ORDER BY 1
                    ;

                    UPDATE activite[PX].t_tiers_payant SET
						texte = ORG_LIBELLE,
						texte_court = ORG_LIBELLE,
						adresse = TIES_ADRx,
						code_postal_id = w_CJ_ORG.code_postal_id,
						ville = TIES_VILLE,
						telephone = TIES_TEL,
						fax = TIES_FAX,
						email = TIES_EMAIL
					FROM w_CJ_ORG
					WHERE t_tiers_payant.code_original = ORG_LIBC AND
						(
						t_tiers_payant.texte IS DISTINCT FROM ORG_LIBELLE OR
						t_tiers_payant.texte_court IS DISTINCT FROM ORG_LIBELLE OR
						t_tiers_payant.adresse IS DISTINCT FROM TIES_ADRx OR
						t_tiers_payant.code_postal_id IS DISTINCT FROM w_CJ_ORG.code_postal_id OR
						t_tiers_payant.ville IS DISTINCT FROM TIES_VILLE OR
						t_tiers_payant.telephone IS DISTINCT FROM TIES_TEL OR
						t_tiers_payant.fax IS DISTINCT FROM TIES_FAX OR
						t_tiers_payant.email IS DISTINCT FROM TIES_EMAIL
						)
					;
					
                    UPDATE activite[PX].t_tiers_payant
                    SET grand_regime_id = t_grands_regimes.oid
                    FROM prod_cegi.CJ_ORG
                        JOIN prod_cegi.CJ_RGM ON CJ_RGM.RGM_ID = CJ_ORG.RGM_ID
                        JOIN base.t_grands_regimes ON CJ_RGM.RGM_LIBC = t_grands_regimes.code 
                    WHERE t_tiers_payant.code_original = CJ_ORG.TER_ID AND
                        CJ_ORG.TER_ID <> 0 AND
                        COALESCE(t_tiers_payant.grand_regime_id,0) = 0 AND
                        t_grands_regimes.oid <> 0;

                    UPDATE w_CJ_ORG
                    SET tiers_payant_id = t_tiers_payant.oid
                    FROM activite[PX].t_tiers_payant
                    WHERE ORG_LIBC = code_original;
                        
                ]]></sqlcmd>
            </NODE>
            
            <NODE label="Médecins">
                <sqlcmd><![CDATA[

                    -- Spécialités (
                    INSERT INTO base.t_specialites_medecin(code_original, code, texte, texte_court)
                    SELECT
                        SPE_LIBC,
                        SPE_LIBC,
                        CASE WHEN MAX(SPE_LIBELLE) <> '' THEN MAX(SPE_LIBELLE) ELSE SPE_LIBC END,
                        CASE WHEN MAX(SPE_LIBELLE) <> '' THEN MAX(SPE_LIBELLE) ELSE SPE_LIBC END
                    FROM prod_cegi.CJ_SPE
                    WHERE SPE_LIBC NOT IN (SELECT code FROM base.t_specialites_medecin WHERE code is NOT null) AND
                        SPE_LIBC <> '?' AND
                        SPE_LIBELLE <> '?' AND
                        SPE_ID IN (SELECT SPE_ID FROM prod_cegi.CJ_PRA)
                    GROUP BY 1,2
                    ORDER BY 1;

                    SELECT base.cti_execute(
                    'INSERT INTO base.t_specialites_medecin(code_original, code, texte, texte_court)
                    SELECT code || ''..'', code || ''..'', texte, texte
                    FROM pmsi.t_specialites_medecin
                    WHERE length(code) = 2 AND
                        (code || ''..'') NOT IN (SELECT code FROM base.t_specialites_medecin WHERE code is NOT null) 
                    ',1)
                    WHERE 't_specialites_medecin' IN (SELECT tablename FROM pg_tables WHERE schemaname = 'pmsi' AND tablename = 't_specialites_medecin')
                    ;

                    DROP TABLE IF EXISTS w_CJ_PRA;
                    CREATE TEMP TABLE w_CJ_PRA AS
                    SELECT 
                        CJ_PRA.*,
                        COALESCE(SPE_LIBC,'') AS SPE_LIBC,
                        COALESCE(PRC_IDENTIFICATION,'') AS PRC_IDENTIFICATION,
                        0::bigint AS medecin_administratif_id
                    FROM prod_cegi.CJ_PRA
                    LEFT JOIN prod_cegi.CJ_SPE ON CJ_PRA.SPE_ID = CJ_SPE.SPE_ID
                    LEFT JOIN 
                        (
                        SELECT PRA_ID, 
                            (MAX(ARRAY[PRC_DEPUIS::text,SUBSTR(COALESCE(PRC_IDENTIFICATION,''),1,9)]))[2] AS PRC_IDENTIFICATION
                        FROM prod_cegi.CJ_PRC
                        GROUP BY 1
                        ) subview ON CJ_PRA.PRA_ID = subview.PRA_ID
                    WHERE PER_NOM <> '?';

                    


                    DROP TABLE IF EXISTS w_medecins;
                    CREATE TEMP TABLE w_medecins AS
                    SELECT 
                        PRA_LIBC,
                        w_CJ_PRA.PRA_ID,
                        base.cti_soundex_nom(PER_NOM) AS PER_NOM_SOUNDEX, 
                        base.cti_soundex_nom(PER_PRENOM) AS PER_PRENOM_SOUNDEX, 
                        PER_NOM, 
                        PER_PRENOM AS PER_PRENOM, 
                        PRC_IDENTIFICATION AS CODE_ADELI, 
                        SPE_LIBC AS SPE_LIBC, 
                        COALESCE(t_medecins_administratifs.medecin_id,0) as medecin_id
                    FROM w_CJ_PRA
                        LEFT JOIN activite[PX].t_medecins_administratifs ON w_CJ_PRA.PRA_LIBC = t_medecins_administratifs.code_original;


                    INSERT INTO base.t_medecins(nom, prenom, numero_ordre, specialite_id)
                    SELECT w_medecins.PER_NOM, w_medecins.PER_PRENOM, w_medecins.CODE_ADELI, 0 FROM
                    (SELECT SUBSTR(PER_NOM_SOUNDEX, 1, 8) AS PER_NOM_SOUNDEX, SUBSTR(PER_PRENOM_SOUNDEX, 1, 8) AS PER_PRENOM_SOUNDEX, CODE_ADELI, MIN(PRA_LIBC) AS PRA_LIBC
                    FROM w_medecins
                    GROUP BY 1,2,3) subview, w_medecins
                    WHERE w_medecins.PRA_LIBC = subview.PRA_LIBC
                        AND subview.PER_NOM_SOUNDEX || ',' || subview.PER_PRENOM_SOUNDEX || ',' ||  subview.CODE_ADELI 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.PER_NOM, w_medecins.PER_PRENOM, w_medecins.CODE_ADELI, 0 FROM
                    (SELECT PER_NOM_SOUNDEX, PER_PRENOM_SOUNDEX, MIN(PRA_LIBC) AS PRA_LIBC
                    FROM w_medecins
                    GROUP BY 1,2) subview, w_medecins
                    WHERE w_medecins.PRA_LIBC = subview.PRA_LIBC
                        AND subview.PER_NOM_SOUNDEX || ',' || subview.PER_PRENOM_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(PER_NOM_SOUNDEX, 1, 8) = substr(subview.nom,1,8)
                    AND SUBSTR(PER_PRENOM_SOUNDEX, 1, 8) = substr(subview.prenom,1,8)
                    AND CODE_ADELI = 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 PER_NOM_SOUNDEX = subview.nom
                    AND PER_PRENOM_SOUNDEX = 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 PRA_LIBC, PRA_LIBC, PER_NOM, PER_PRENOM, COALESCE(t_specialites_medecin.oid,0), medecin_id
                    FROM w_medecins
                        LEFT JOIN base.t_specialites_medecin ON SPE_LIBC = t_specialites_medecin.code
                    WHERE PRA_LIBC NOT IN (SELECT code_original FROM activite[PX].t_medecins_administratifs WHERE code_original IS NOT NULL);

                    UPDATE activite[PX].t_medecins_administratifs
                    SET nom = PER_NOM,
                        prenom = PER_PRENOM,
                        specialite_id = COALESCE(t_specialites_medecin.oid,0),
                        medecin_id = w_medecins.medecin_id,
                        no_adeli = code_adeli
                    FROM w_medecins LEFT JOIN base.t_specialites_medecin ON SPE_LIBC = t_specialites_medecin.code_original
                    WHERE w_medecins.PRA_LIBC = t_medecins_administratifs.code_original
                        AND (
                        t_medecins_administratifs.nom <> PER_NOM OR
                        t_medecins_administratifs.prenom <> PER_PRENOM OR
                        t_medecins_administratifs.specialite_id <> COALESCE(t_specialites_medecin.oid,0) OR
                        t_medecins_administratifs.medecin_id <> w_medecins.medecin_id OR
                        t_medecins_administratifs.no_adeli <> w_medecins.code_adeli
                    );

                    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;


                    UPDATE w_CJ_PRA
                    SET medecin_administratif_id = t_medecins_administratifs.oid
                    FROM activite[PX].t_medecins_administratifs
                    WHERE activite[PX].t_medecins_administratifs.code_original = PRA_LIBC;
                                            
                ]]></sqlcmd>
            </NODE>
            
            <NODE label="Hébergement">
                <sqlcmd><![CDATA[
                    
                    DROP TABLE IF EXISTS w_CJ_NVE_service;
                    CREATE TEMP TABLE w_CJ_NVE_service AS
                    SELECT 
                        NVE_ID, 
                        NVE_LIBC, 
                        NVE_LIBELLE, 
                        COALESCE(t_services_facturation.oid,0) AS service_facturation_id,
                        COALESCE(t_services_facturation.mode_traitement_id,0) AS mode_traitement_id,
                        COALESCE(t_unites_fonctionnelles.oid,0) AS unite_fonctionnelle_id
                    FROM prod_cegi.CJ_NVE
                    LEFT JOIN activite[PX].t_services_facturation ON activite[PX].t_services_facturation.code_original = NVE_LIBC
                    LEFT JOIN activite[PX].t_unites_fonctionnelles ON activite[PX].t_unites_fonctionnelles.code_original = NVE_LIBC
                    WHERE NVE_TYPE = 'SAD' AND
                        (
                        CJ_NVE.ETB_ID::text = ANY (string_to_array('[ID_ETAB]'::text,',')) OR
                        '[ID_ETAB]' = '' OR
                        '[ID_ETAB]' = '-1'
                        )
                    ORDER BY 1;
                    
                    INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits, type_t2a)
                    SELECT 
                        NVE_LIBC, 
                        NVE_LIBC, 
                        NVE_LIBELLE, 
                        NVE_LIBELLE, 
                        0 AS nb_lits, 
                        '0' AS type_t2a
                    FROM w_CJ_NVE_service
                    WHERE NVE_LIBC <> '' AND
						NVE_LIBC NOT IN (SELECT code_original FROM activite[PX].t_services_facturation WHERE code_original IS NOT NULL)
                    ORDER BY 1;
					
					
                    UPDATE activite[PX].t_services_facturation SET
						code = NVE_LIBC,
						texte = NVE_LIBELLE,
						texte_court = NVE_LIBELLE
					FROM w_CJ_NVE_service
					WHERE NVE_LIBC = code_original AND
						(
							code IS DISTINCT FROM NVE_LIBC OR
							texte IS DISTINCT FROM NVE_LIBELLE OR
							texte_court IS DISTINCT FROM NVE_LIBELLE
						)
					;

                    INSERT INTO base.t_modes_traitement(code, texte, texte_court)
                    SELECT MTR_LIBC, MTR_LIBELLE, MTR_LIBELLE
                    FROM prod_cegi.CJ_MTR
                    WHERE MTR_LIBC NOT IN (SELECT code FROM base.t_modes_traitement)
                    ORDER BY MTR_LIBC;
                    
                    INSERT INTO base.t_dmt(code, texte, texte_court)
                    SELECT DMT_LIBC, DMT_LIBELLE, DMT_LIBELLE
                    FROM prod_cegi.CJ_DMT
                    WHERE DMT_LIBC NOT IN (SELECT code FROM base.t_dmt)
                    ORDER BY DMT_LIBC;
                    
                    UPDATE activite[PX].t_services_facturation
                    SET mode_traitement_id = COALESCE(t_modes_traitement.oid,0)
                    FROM prod_cegi.CJ_NVE
                        JOIN prod_cegi.CJ_MTR ON CJ_NVE.MTR_ID = CJ_MTR.MTR_ID
                        LEFT JOIN base.t_modes_traitement ON MTR_LIBC = t_modes_traitement.code
                    WHERE t_services_facturation.code = NVE_LIBC AND 
                        COALESCE(t_services_facturation.mode_traitement_id,0) = 0 AND
                        COALESCE(t_services_facturation.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 prod_cegi.CJ_NVE
                        JOIN prod_cegi.CJ_DMT ON CJ_NVE.DMT_ID = CJ_DMT.DMT_ID
                        LEFT JOIN base.t_dmt ON DMT_LIBC = t_dmt.code
                    WHERE t_services_facturation.code_original = NVE_LIBC AND 
                        COALESCE(t_services_facturation.dmt_id,0) = 0 AND
                        COALESCE(t_services_facturation.dmt_id,0) <> COALESCE(t_dmt.oid,0);
                        
                    UPDATE w_CJ_NVE_service
                    SET service_facturation_id = t_services_facturation.oid
                    FROM activite[PX].t_services_facturation
                    WHERE NVE_LIBC = t_services_facturation.code_original AND
                        service_facturation_id = 0;
                        
                    UPDATE w_CJ_NVE_service
                    SET mode_traitement_id = t_services_facturation.mode_traitement_id
                    FROM activite[PX].t_services_facturation
                    WHERE NVE_LIBC = t_services_facturation.code_original AND
                        w_CJ_NVE_service.mode_traitement_id = 0 AND
                        t_services_facturation.mode_traitement_id <> 0;


                    -- Unités fonctionnelles
                    INSERT INTO activite[PX].t_unites_fonctionnelles(code_original, code, texte, texte_court)
                    SELECT 
                        NVE_LIBC, 
                        NVE_LIBC, 
                        NVE_LIBELLE, 
                        NVE_LIBELLE
                    FROM w_CJ_NVE_service
                    WHERE NVE_LIBC NOT IN (SELECT code_original FROM activite[PX].t_unites_fonctionnelles WHERE code_original IS NOT NULL)
                    ORDER BY 1;
					
					UPDATE activite[PX].t_unites_fonctionnelles SET
						code = NVE_LIBC,
						texte = NVE_LIBELLE,
						texte_court = NVE_LIBELLE
					FROM w_CJ_NVE_service
					WHERE NVE_LIBC = code_original AND
						(
							code IS DISTINCT FROM NVE_LIBC OR
							texte IS DISTINCT FROM NVE_LIBELLE OR
							texte_court IS DISTINCT FROM NVE_LIBELLE
						)
					;

                    UPDATE w_CJ_NVE_service
                    SET unite_fonctionnelle_id = t_unites_fonctionnelles.oid
                    FROM activite[PX].t_unites_fonctionnelles
                    WHERE NVE_LIBC = t_unites_fonctionnelles.code_original AND
                        unite_fonctionnelle_id = 0;
                        
                    -- Unités médicales
					SELECT base.cti_execute('
                    INSERT INTO activite[PX].t_unites_medicales(code_original, code, texte, texte_court)
                    SELECT CODE, CODE, LIB, LIB
                    FROM prod_cegi.UM
                    WHERE CODE NOT IN (SELECT code_original FROM activite[PX].t_unites_medicales)
						ORDER BY CODE',1)
					WHERE (SELECT count(*) FROM information_schema.tables WHERE table_name = 'um' AND table_schema='prod_cegi') > 0;  
					
					SELECT base.cti_execute('
                    UPDATE activite[PX].t_unites_medicales SET
						code = UM.CODE,
						texte = UM.LIB,
						texte_court = UM.LIB
                    FROM prod_cegi.UM
                    WHERE UM.CODE = t_unites_medicales.code_original AND
						(
						t_unites_medicales.code IS DISTINCT FROM UM.CODE OR
						t_unites_medicales.texte IS DISTINCT FROM UM.LIB OR
						t_unites_medicales.texte_court IS DISTINCT FROM UM.LIB
						)',1)
					WHERE (SELECT count(*) FROM information_schema.tables WHERE table_name = 'um' AND table_schema='prod_cegi') > 0
					;

                    -- Activités

                    
                    

                    -- Etages et lits
                    DROP TABLE IF EXISTS w_LITS;
                    CREATE TEMP TABLE w_LITS AS
                    SELECT
                        0::bigint AS cti_lit_id,
                        CJ_NVE.NVE_ID,
                        CJ_NVE.NVE_LIBC AS CODE_LIT,
                        CJ_NVE.NVE_LIBELLE AS LIBELLE_LIT,
                        0::bigint AS cti_etage_id,
                        COALESCE(CJ_NVE_ETAGE.NVE_LIBC,'')::text AS CODE_ETAGE,
                        COALESCE(CJ_NVE_ETAGE.NVE_LIBELLE,'')::text AS LIBELLE_ETAGE,
                        CJ_NVE.ETB_ID
                    FROM prod_cegi.CJ_NVE
                    LEFT JOIN prod_cegi.LITS ON CJ_NVE.NVE_ID = LITS.NVE_ID
                    LEFT JOIN prod_cegi.CHAMBRE ON LITS.NVE_ID_ANC = CHAMBRE.NVE_ID
                    LEFT JOIN prod_cegi.CJ_NVE CJ_NVE_ETAGE ON CHAMBRE.NVE_ID_ANC = CJ_NVE_ETAGE.NVE_ID
                    WHERE CJ_NVE.NVE_TYPE = 'LIT' AND
                        CJ_NVE.NVE_LIBC <> '' AND
                        (
                        CJ_NVE.ETB_ID::text = ANY (string_to_array('[ID_ETAB]'::text,',')) OR
                        '[ID_ETAB]' = '' OR
                        '[ID_ETAB]' = '-1'
                        );

                    -- Etage selon import LOGHOS
                    UPDATE w_LITS SET
                        cti_lit_id = t_lits.oid,
                        cti_etage_id = t_lits.etage_id,
                        CODE_ETAGE = t_etages.code,
                        LIBELLE_ETAGE = t_etages.texte
                    FROM activite[PX].t_lits
                    JOIN activite[PX].t_etages ON etage_id = t_etages.oid
                    WHERE CODE_LIT = t_lits.code AND
                        w_LITS.CODE_ETAGE = '' AND
                        t_etages.code_original NOT LIKE '*N%';

                    -- Etage selon codification
                    UPDATE w_LITS SET
                        cti_etage_id = subview.cti_etage_id,
                        CODE_ETAGE = subview.CODE_ETAGE,
                        LIBELLE_ETAGE = subview.LIBELLE_ETAGE
                    FROM
                        (
                        SELECT substr(CODE_LIT,1,2) AS prefix,
                            length(CODE_LIT) AS l, 
                            MAX(cti_etage_id) AS cti_etage_id,
                            MAX(CODE_ETAGE) AS CODE_ETAGE,
                            MAX(LIBELLE_ETAGE) AS LIBELLE_ETAGE,
                            count(DISTINCT cti_etage_id) AS nb
                        FROM w_LITS
                        WHERE cti_etage_id <> 0
                        GROUP BY 1,2
                        HAVING count(DISTINCT cti_etage_id) = 1
                        ORDER BY 1,2
                        ) subview
                    WHERE w_LITS.cti_etage_id = 0 AND
                        substr(w_LITS.CODE_LIT,1,2) = subview.prefix AND
                        length(w_LITS.CODE_LIT) = subview.l AND
                        w_LITS.CODE_ETAGE = '';

                    UPDATE w_LITS SET
                        cti_etage_id = subview.cti_etage_id,
                        CODE_ETAGE = subview.CODE_ETAGE,
                        LIBELLE_ETAGE = subview.LIBELLE_ETAGE
                    FROM
                        (
                        SELECT substr(CODE_LIT,1,1) AS prefix,
                            MAX(cti_etage_id) AS cti_etage_id,
                            MAX(CODE_ETAGE) AS CODE_ETAGE,
                            MAX(LIBELLE_ETAGE) AS LIBELLE_ETAGE,
                            count(DISTINCT cti_etage_id) AS nb
                        FROM w_LITS
                        WHERE cti_etage_id <> 0
                        GROUP BY 1
                        HAVING count(DISTINCT cti_etage_id) = 1
                        ORDER BY 1
                        ) subview
                    WHERE w_LITS.cti_etage_id = 0 AND
                        substr(w_LITS.CODE_LIT,1,1) = subview.prefix AND
                        w_LITS.CODE_ETAGE = '' ;
                        
                    UPDATE w_LITS
                    SET CODE_ETAGE = '*N', LIBELLE_ETAGE = 'Non trouvé'
                    WHERE CODE_ETAGE = '' AND CODE_LIT <> '' AND
                        (SELECT COUNT(DISTINCT ETB_ID) FROM w_LITS) <= 1
                    ;
                    

                    UPDATE w_LITS
                    SET CODE_ETAGE = '*N-'||ETB_ID, LIBELLE_ETAGE = 'Non trouvé'
                    WHERE CODE_ETAGE = '' AND CODE_LIT <> '' AND
                        (SELECT COUNT(DISTINCT ETB_ID) FROM w_LITS) > 1
                    ;

                    
                    
                    INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court, nb_lits)
                    SELECT 
                        CODE_ETAGE, 
                        CODE_ETAGE,  
                        MAX(LIBELLE_ETAGE),  
                        MAX(LIBELLE_ETAGE),  
                        0 AS nb_lits
                    FROM w_LITS
                    WHERE cti_etage_id = 0 AND
                        CODE_ETAGE <> '' AND 
                        CODE_ETAGE NOT IN (SELECT code_original FROM activite[PX].t_etages WHERE code_original IS NOT NULL)
                    GROUP BY 1,2
                    ORDER BY 1;

                    INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere) 
                    SELECT CODE_ETAGE || '|' || CODE_LIT, CODE_LIT, MAX(LIBELLE_LIT), MAX(LIBELLE_LIT), MAX(t_etages.oid), 'N'
                    FROM w_LITS
                        JOIN activite[PX].t_etages ON CODE_ETAGE = t_etages.code_original
                    WHERE cti_lit_id = 0 AND
                        CODE_LIT <> '' AND CODE_ETAGE || '|' || CODE_LIT NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL)
                    GROUP BY 1,2
                    ORDER BY 1;
					
					UPDATE activite[PX].t_etages SET
						code = CODE_ETAGE,
						texte = LIBELLE_ETAGE,
						texte_court = LIBELLE_ETAGE
                    FROM 
						(
						SELECT 
							CODE_ETAGE, 
							MAX(LIBELLE_ETAGE) AS LIBELLE_ETAGE
						FROM w_LITS
						WHERE CODE_ETAGE <> ''
						GROUP BY 1
						) subview
                    WHERE t_etages.code_original = CODE_ETAGE AND 
						(
                        t_etages.code IS DISTINCT FROM CODE_ETAGE OR
						t_etages.texte IS DISTINCT FROM LIBELLE_ETAGE OR
						t_etages.texte_court IS DISTINCT FROM LIBELLE_ETAGE
						)
					;

                    UPDATE w_LITS SET
                        cti_lit_id = t_lits.oid,
                        cti_etage_id = t_lits.etage_id,
                        CODE_ETAGE = t_etages.code_original,
                        LIBELLE_ETAGE = t_etages.texte
                    FROM activite[PX].t_lits
                    JOIN activite[PX].t_etages ON etage_id = t_etages.oid
                    WHERE CODE_LIT = t_lits.code AND
                        cti_lit_id = 0;
						
					UPDATE activite[PX].t_lits
					SET texte = NVE_LIBELLE, texte_court = NVE_LIBELLE
					FROM (
						SELECT NVE_LIBC, MAX(NVE_LIBELLE) AS NVE_LIBELLE
						FROM prod_cegi.CJ_NVE
						WHERE NVE_TYPE = 'LIT' AND
							(
							CJ_NVE.ETB_ID::text = ANY (string_to_array('[ID_ETAB]'::text,',')) OR
							'[ID_ETAB]' = '' OR
							'[ID_ETAB]' = '-1'
							)
						GROUP BY 1
						) subview
					WHERE t_lits.code = NVE_LIBC AND
						(
						texte IS DISTINCT FROM NVE_LIBELLE OR
						texte_court IS DISTINCT FROM NVE_LIBELLE
						)
					;

                                        
                ]]></sqlcmd>
            </NODE>
                    
            <NODE label="Facturation">
                <sqlcmd><![CDATA[
                
                    -- Comptes
					UPDATE activite[PX].t_compte SET
						code = PLC_COMPTE,
						texte = PLC_LIBELLE, 
						texte_court = PLC_LIBELLE
                    FROM prod_cegi.CMPLANCPT
                    WHERE (code = PLC_COMPTE OR code_original = PLC_COMPTE) AND
                        (
                        code IS DISTINCT FROM PLC_COMPTE OR
                        texte IS DISTINCT FROM PLC_LIBELLE OR
                        texte_court IS DISTINCT FROM PLC_LIBELLE
                        )
					;
						
                    INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
                    SELECT PLC_COMPTE, PLC_COMPTE, MAX(PLC_LIBELLE), MAX(PLC_LIBELLE)
                    FROM prod_cegi.CMPLANCPT
                    WHERE PLC_COMPTE <> '' AND
						PLC_COMPTE NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code IS NOT NULL)
                    GROUP BY 1
                    ORDER BY 1;
					
					INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
                    SELECT PLC_COMPTE, PLC_COMPTE, MAX(PLC_COMPTE), MAX(PLC_COMPTE)
                    FROM prod_cegi.CMECRITURES
                    WHERE PLC_COMPTE <> '' AND
						PLC_COMPTE NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code IS NOT NULL)
                    GROUP BY 1
                    ORDER BY 1
					;
                    

                    -- Rubriques 
                    DROP TABLE IF EXISTS w_RUBRIQUES_PRESTATIONS;
                    CREATE TEMP TABLE w_RUBRIQUES_PRESTATIONS AS
                    SELECT CJ_LCS.PST_ID, 
                        PST_LIBC, 
                        PST_LIBELLE,
                        LCS_CODE, 
                        PST_NOMTAB,
                        PST_LIBELLE AS LCS_LIBELLE
                    FROM prod_cegi.CJ_LCS
                    JOIN prod_cegi.CJ_PST ON CJ_LCS.PST_ID = CJ_PST.PST_ID
                    GROUP BY 1,2,3,4,5
                    ;
					
					INSERT INTO w_RUBRIQUES_PRESTATIONS
                    SELECT CJ_LSPST.PST_ID, 
                        PST_LIBC, 
                        PST_LIBELLE,
                        PST_LIBC, 
                        PST_NOMTAB,
                        PST_LIBELLE AS LCS_LIBELLE
                    FROM prod_cegi.CJ_LSPST
                    JOIN prod_cegi.CJ_PST ON CJ_LSPST.PST_ID = CJ_PST.PST_ID
                    WHERE CJ_LSPST.PST_ID NOT IN (SELECT PST_ID FROM w_RUBRIQUES_PRESTATIONS)
                    GROUP BY 1,2,3,4,5
                    ;

                    UPDATE w_RUBRIQUES_PRESTATIONS
                    SET LCS_CODE = PST_LIBC 
                    WHERE LCS_CODE = '';


                    UPDATE w_RUBRIQUES_PRESTATIONS SET
                        PST_LIBC = LCS_CODE,
                        PST_LIBELLE = t_prestations.texte,
                        LCS_LIBELLE = t_prestations.texte
                    FROM activite.t_prestations
                    WHERE LCS_CODE = t_prestations.code AND
                        PST_NOMTAB <> 0 AND
                        PST_LIBC <> LCS_CODE;
                        
                    DROP TABLE IF EXISTS w_RUBRIQUES;
                    CREATE TEMP TABLE w_RUBRIQUES AS
                    SELECT PST_ID,
                        MAX(PST_LIBC) AS PST_LIBC,
                        MAX(LCS_LIBELLE) AS LCS_LIBELLE
                    FROM w_RUBRIQUES_PRESTATIONS
                    GROUP BY 1
                    ORDER BY 1
                    ; 
                        
                    INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
                    SELECT 
                        PST_LIBC,
                        PST_LIBC,
                        MAX(PST_LIBELLE),
                        MAX(PST_LIBELLE)
                    FROM w_RUBRIQUES_PRESTATIONS
                    WHERE PST_LIBC NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL )
                    GROUP BY 1,2;

					UPDATE activite[PX].t_rubriques_facturation SET
						code = PST_LIBC,
						texte = PST_LIBELLE,
						texte_court = PST_LIBELLE
                    FROM 
						(
						SELECT 
							PST_LIBC, 
							MAX(PST_LIBELLE) AS PST_LIBELLE
						FROM w_RUBRIQUES_PRESTATIONS
						WHERE PST_LIBC <> ''
						GROUP BY 1
						) subview
                    WHERE t_rubriques_facturation.code_original = PST_LIBC AND 
						(
                        t_rubriques_facturation.code IS DISTINCT FROM PST_LIBC OR
						t_rubriques_facturation.texte IS DISTINCT FROM PST_LIBELLE OR
						t_rubriques_facturation.texte_court IS DISTINCT FROM PST_LIBELLE
						)
					;

                    -- Prestations
                    INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
                    SELECT 
                        LCS_CODE,
                        LCS_CODE,
                        MAX(LCS_LIBELLE),
                        MAX(LCS_LIBELLE)
                    FROM w_RUBRIQUES_PRESTATIONS
                    WHERE LCS_CODE NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL) AND
                        LCS_CODE <> ''
                    GROUP BY 1,2;
					
					UPDATE activite.t_prestations SET
						code = LCS_CODE,
						texte = LCS_LIBELLE,
						texte_court = LCS_LIBELLE
                    FROM 
						(
						SELECT 
							LCS_CODE, 
							MAX(LCS_LIBELLE) AS LCS_LIBELLE
						FROM w_RUBRIQUES_PRESTATIONS
						WHERE LCS_CODE <> ''
						GROUP BY 1
						) subview
                    WHERE t_prestations.code_original = LCS_CODE AND 
						(
                        t_prestations.code IS DISTINCT FROM LCS_CODE OR
						t_prestations.texte IS DISTINCT FROM LCS_LIBELLE OR
						t_prestations.texte_court IS DISTINCT FROM LCS_LIBELLE
						)
					;

                    INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court) 
                    SELECT  '*ATTNSCTI', chr(127) || 'ATTNS', 'Attente (non soldé)', 'Attente (non soldé)'
                    WHERE '*ATTNSCTI' NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation);

                    INSERT INTO activite[PX].t_prestations(code_original, code, texte, texte_court, clinique_honoraire) 
                    SELECT  '*ECARTCTI', chr(127) || 'ECART', 'Ecarts de répartition', 'Ecarts de répartition', '' 
                    WHERE '*ECARTCTI' NOT IN (SELECT code_original FROM activite[PX].t_prestations WHERE code_original IS NOT NULL);
                    
                    INSERT INTO activite[PX].t_prestations(code_original, code, texte, texte_court, clinique_honoraire) 
                    SELECT  '*ATTNSCTI', chr(127) || 'ATTNS', 'Attente (non soldé)', 'Attente (non soldé)', '' 
                    WHERE '*ATTNSCTI' NOT IN (SELECT code_original FROM activite[PX].t_prestations WHERE code_original IS NOT NULL);
                                            
                ]]></sqlcmd>
            </NODE>
        
        </NODE>
        
    </NODE>
        
    <NODE name="POST" label="TRAITEMENTS COMPLEMENTAIRES">
		<NODE label="Correction des lits mal trouv?s">
            <sqlcmd><![CDATA[
                UPDATE activite[PX].t_lieux
                SET code_original_4 = subview.code_original,
                    lit_id = subview.lit_id
                FROM 
                (
                SELECT code, max(code_original) AS code_original, MAX(oid) AS lit_id
                FROM activite[PX].t_lits
                GROUP BY 1
                HAVING count(*) = 1
                ) subview
                WHERE t_lieux.lit_id = 0 AND
                     split_part(code_original_4,'|',2) = code
                ;
            ]]></sqlcmd>                
        </NODE>
		<NODE label="Compléments patients">
			<sqlcmd><![CDATA[
						
				DROP TABLE IF EXISTS w_CJ_PATIENT_CP;
				CREATE TEMP TABLE w_CJ_PATIENT_CP AS
				SELECT 
					PAT_ID,
					MAX(PAT_IPP) AS no_patient,
					MAX(PER_CP) AS CODE_POSTAL 
				FROM prod_cegi.CJ_PATIENT 
				WHERE PAT_IPP IN (SELECT no_patient FROM activite[PX].p_sejours)
				GROUP BY 1;
				
				CREATE INDEX w_PATIENT_i1
				  ON w_CJ_PATIENT_CP 
				  USING btree
				  (PAT_ID);
						
				  
				-- Ajout codes postaux inexistants
				INSERT INTO base.t_codes_postaux(code, texte, texte_court)
				SELECT CODE_POSTAL, CODE_POSTAL, CODE_POSTAL
				FROM w_CJ_PATIENT_CP
				WHERE CODE_POSTAL NOT IN (SELECT code FROM base.t_codes_postaux) AND CODE_POSTAL IS NOT NULL AND CODE_POSTAL <> ''
				GROUP BY 1,2,3
				ORDER BY 1;
				
				-- Maj code postal sur séjours
				UPDATE activite[PX].p_sejours
				SET code_postal_id = t_codes_postaux.oid
				FROM base.t_codes_postaux, w_CJ_PATIENT_CP
				WHERE w_CJ_PATIENT_CP.CODE_POSTAL = t_codes_postaux.code AND
					p_sejours.no_patient = w_CJ_PATIENT_CP.no_patient AND
					p_sejours.no_patient IS NOT NULL and p_sejours.no_patient <> 0 AND
					w_CJ_PATIENT_CP.CODE_POSTAL IS NOT NULL AND  w_CJ_PATIENT_CP.CODE_POSTAL <> '' AND
					p_sejours.code_postal_id = 0;
							  
				--  Maj table OID
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'c_postaux', code_postal_id 
				FROM activite[PX].p_sejours 
				WHERE code_postal_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'c_postaux')
				GROUP BY 2;
                
                -- 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,
					PER_NOMVOIE,
                    COALESCE(t_codes_postaux.oid,0),
                    PER_VILLE,
					PAT_TEL_FIXE,
					PAT_TEL_PORT,
					PAT_EMAIL
				FROM w_CJ_PATIENT
					JOIN activite[PX].p_sejours ON no_sejour = SEJ_NUMDOS
                    LEFT JOIN base.t_codes_postaux on PER_CP = t_codes_postaux.code
				;
                 ]]></sqlcmd>                
        </NODE>

		<NODE label="Medecin traitant LOGHOS">
            <condition><![CDATA[
                "[CEGILOGHOS_PRESENT]" == "OUI"
            ]]></condition>

			<sqlcmd><![CDATA[

			DROP TABLE IF EXISTS w_OPERA_PMED;
			
			CREATE TEMP TABLE w_OPERA_PMED AS
			SELECT 
				code_medecin,
				split_part(LIBELLE_MEDECIN,' ',1) AS NOM_MEDECIN,
				split_part(LIBELLE_MEDECIN,' ',2) || ' ' ||
				split_part(LIBELLE_MEDECIN,' ',3) || ' ' || 
				split_part(LIBELLE_MEDECIN,' ',4) || ' ' || 
				split_part(LIBELLE_MEDECIN,' ',5) || ' ' || 
				split_part(LIBELLE_MEDECIN,' ',6) || ' ' || 
				split_part(LIBELLE_MEDECIN,' ',7) 
				AS PRENOM_MEDECIN
			FROM prod_cegiloghos.OPERA_PMED;
			
			DROP TABLE IF EXISTS w_OPERA_SEJ;

			CREATE TEMP TABLE w_OPERA_SEJ AS
			SELECT 
				no_dossier,
				max(code_med_traitant) as code_med_traitant,
				max(w_OPERA_PMED.NOM_MEDECIN) as nom_med_traitant,
				max(w_OPERA_PMED.PRENOM_MEDECIN) as prenom_med_traitant				
			FROM prod_cegiloghos.OPERA_SEJ
				LEFT JOIN w_OPERA_PMED ON CODE_MED_TRAITANT = w_OPERA_PMED.CODE_MEDECIN
			WHERE 
				DATE_SORTIE_SEJOUR >= '20120101' OR 
				DATE_SORTIE_SEJOUR IS NULL OR
				DATE_SORTIE_SEJOUR <= '00010101'
			GROUP BY 1;
			
			CREATE INDEX w_OPERA_SEJ_i1
			  ON w_OPERA_SEJ 
			  USING btree
			  (no_dossier);	
					  
			UPDATE w_OPERA_SEJ 
			SET code_med_traitant = '-' || code_med_traitant 
			WHERE code_med_traitant = '0'
			;				  
					  
			-- 	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 DISTINCT code_med_traitant, code_med_traitant, nom_med_traitant, prenom_med_traitant, 0, ''
			FROM w_OPERA_SEJ
			WHERE code_med_traitant NOT IN (SELECT code FROM activite[PX].t_medecins_traitants_administratifs)
			AND code_med_traitant <> '' AND code_med_traitant IS NOT NULL;
										
			--  maj code rpps
			UPDATE activite[PX].t_medecins_traitants_administratifs
			SET no_rpps = cj_prc.prc_rpps
			FROM prod_cegi.cj_prc, prod_cegi.cj_pra 
			WHERE cj_prc.pra_id = cj_pra.pra_id
				  AND cj_pra.pra_libc = t_medecins_traitants_administratifs.code
				  AND (t_medecins_traitants_administratifs.no_rpps IS NULL OR t_medecins_traitants_administratifs.no_rpps = '')
				  AND cj_prc.prc_rpps IS not NULL AND cj_prc.prc_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_OPERA_SEJ, activite[PX].t_medecins_traitants_administratifs
			WHERE w_OPERA_SEJ.no_dossier = p_sejours.no_sejour AND
				w_OPERA_SEJ.code_med_traitant = t_medecins_traitants_administratifs.code AND
				w_OPERA_SEJ.code_med_traitant IS NOT NULL AND w_OPERA_SEJ.code_med_traitant <> '' AND
				medecin_traitant_id IS DISTINCT FROM t_medecins_traitants_administratifs.oid;
				
			  ]]></sqlcmd>
		</NODE>   
			
		<NODE label="Medecin traitant FIRST">
			<condition><![CDATA[
				SELECT count(*) > 0 FROM information_schema.tables WHERE table_name = 'pamlf_sej' AND table_schema='prod_cegi';
			]]></condition>
			
			<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_FIRST_SEJ;
				CREATE TEMP TABLE w_FIRST_SEJ AS
				SELECT 
					SEJ_NUMDOS as no_dossier,
					PRA_ID::text as code_med_traitant,
					max(PER_NOM) as nom_med_traitant,
					max(PER_PRENOM) as prenom_med_traitant				
				FROM prod_cegi.PAMLF_SEJ
					LEFT JOIN prod_cegi.CJ_PRA ON MED_TRAIT = PRA_ID
				WHERE 
					SEJ_DT_SORTIE >= '20120101' OR 
					SEJ_DT_SORTIE IS NULL OR
					SEJ_DT_SORTIE <= '00010101'
				GROUP BY 1,2
				;
				
				CREATE INDEX w_FIRST_SEJ_i1
				  ON w_FIRST_SEJ 
				  USING btree
				  (no_dossier);
						  
				-- 	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 DISTINCT code_med_traitant, code_med_traitant, nom_med_traitant, prenom_med_traitant, 0, ''
				FROM w_FIRST_SEJ
				WHERE code_med_traitant NOT IN (SELECT code FROM activite[PX].t_medecins_traitants_administratifs)
				AND code_med_traitant <> '' AND code_med_traitant IS NOT NULL
				;
				
					
				-- maj id médecin_traitant dans séjours
				UPDATE activite[PX].p_sejours
				SET medecin_traitant_id = t_medecins_traitants_administratifs.oid
				FROM w_FIRST_SEJ, activite[PX].t_medecins_traitants_administratifs
				WHERE w_FIRST_SEJ.no_dossier = p_sejours.no_sejour AND
					w_FIRST_SEJ.code_med_traitant = t_medecins_traitants_administratifs.code AND
					w_FIRST_SEJ.code_med_traitant IS NOT NULL AND w_FIRST_SEJ.code_med_traitant <> '' AND
					medecin_traitant_id IS DISTINCT FROM t_medecins_traitants_administratifs.oid
				;
				
				--  maj code rpps
				UPDATE activite[PX].t_medecins_traitants_administratifs
				SET no_rpps = cj_prc.prc_rpps
				FROM prod_cegi.cj_prc, prod_cegi.cj_pra 
				WHERE cj_prc.pra_id = cj_pra.pra_id
					  AND cj_pra.pra_libc = t_medecins_traitants_administratifs.code
					  AND (t_medecins_traitants_administratifs.no_rpps IS NULL OR t_medecins_traitants_administratifs.no_rpps = '')
					  AND cj_prc.prc_rpps IS not NULL AND cj_prc.prc_rpps <>'' ;

				
				
				-- D après table CJ_PATPRA
				DROP TABLE IF EXISTS w_CJ_PATPRA;
				CREATE TEMP TABLE w_CJ_PATPRA AS
				SELECT PAT_ID, 
					CJ_PATPRA.PRA_ID, 
					date(PATPRA_DT_DEB) AS PATPRA_DT_DEB,
					'20991231'::date AS PATPRA_DT_FIN,
					CJ_PRA.PRA_LIBC,
					CJ_PRA.PER_NOM,
					CJ_PRA.PER_PRENOM,
					row_number() OVER (PARTITION BY PAT_ID ORDER BY PATPRA_DT_DEB, PATPRA_ID) AS seq
				FROM prod_cegi.CJ_PATPRA
				JOIN prod_cegi.CJ_PRA ON CJ_PATPRA.PRA_ID = CJ_PRA.PRA_ID
				WHERE PATPRA_TRAIT = 1 AND
					CJ_PATPRA.PRA_ID <> 0 AND
					CJ_PATPRA.PAT_ID <> 0
				;

				UPDATE w_CJ_PATPRA
				SET PATPRA_DT_DEB = '00010101' 
				WHERE seq = 1
				;
				
				ANALYSE w_CJ_PATPRA
				;

				UPDATE w_CJ_PATPRA
				SET PATPRA_DT_FIN = date(w_CJ_PATPRA2.PATPRA_DT_DEB - interval '1 day')
				FROM w_CJ_PATPRA w_CJ_PATPRA2
				WHERE w_CJ_PATPRA.PAT_ID = w_CJ_PATPRA2.PAT_ID AND
					w_CJ_PATPRA.seq = w_CJ_PATPRA2.seq-1
				;


				DROP TABLE IF EXISTS w_CJ_PATPRA_sej;
				CREATE TEMP TABLE w_CJ_PATPRA_sej AS
				SELECT
					SEJ_NUMDOS as no_dossier,
					PRA_LIBC as code_med_traitant,
					PER_NOM as nom_med_traitant,
					PER_PRENOM as prenom_med_traitant ,
					PRA_ID
				FROM w_CJ_PATPRA
				JOIN prod_cegi.CJ_SEJOUR ON CJ_SEJOUR.PAT_ID = w_CJ_PATPRA.PAT_ID AND
					date(SEJ_DT_ENTREE) BETWEEN PATPRA_DT_DEB AND PATPRA_DT_FIN
				WHERE PRA_LIBC <> '' AND
					PRA_LIBC IS NOT NULL
				;

				CREATE INDEX w_CJ_PATPRA_sej_i1
				  ON w_CJ_PATPRA_sej 
				  USING btree
				  (no_dossier);	
						  
				ANALYSE w_CJ_PATPRA_sej
				;
						  
				-- 	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 code_med_traitant, code_med_traitant, MAX(nom_med_traitant), MAX(prenom_med_traitant), 0, ''
				FROM w_CJ_PATPRA_sej
				WHERE code_med_traitant NOT IN (SELECT code FROM activite[PX].t_medecins_traitants_administratifs)
				GROUP BY 1
				ORDER BY 1;

                UPDATE activite[PX].t_medecins_traitants_administratifs SET 
                    nom = w_CJ_PATPRA_sej.nom_med_traitant,
                    prenom = w_CJ_PATPRA_sej.prenom_med_traitant
                FROM w_CJ_PATPRA_sej
                WHERE code_med_traitant = t_medecins_traitants_administratifs.code
                AND (nom IS DISTINCT FROM w_CJ_PATPRA_sej.nom_med_traitant OR prenom IS DISTINCT FROM w_CJ_PATPRA_sej.prenom_med_traitant);

				ANALYSE activite[PX].t_medecins_traitants_administratifs
				;
				
				--  maj code rpps
				UPDATE activite[PX].t_medecins_traitants_administratifs
				SET no_rpps = CJ_PRC.PRC_RPPS
				FROM prod_cegi.CJ_PRC
				JOIN prod_cegi.CJ_PRA ON CJ_PRC.PRA_ID = CJ_PRA.PRA_ID
				WHERE CJ_PRA.PRA_LIBC = t_medecins_traitants_administratifs.code AND
					  (t_medecins_traitants_administratifs.no_rpps IS NULL OR t_medecins_traitants_administratifs.no_rpps = '') AND
					  CJ_PRC.PRC_RPPS IS NOT NULL AND
					  CJ_PRC.PRC_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_cj_patpra_sej, activite[PX].t_medecins_traitants_administratifs
				WHERE w_cj_patpra_sej.no_dossier = p_sejours.no_sejour AND
					medecin_traitant_id = 0 AND
					w_cj_patpra_sej.code_med_traitant = t_medecins_traitants_administratifs.code AND
					w_cj_patpra_sej.code_med_traitant IS NOT NULL AND w_cj_patpra_sej.code_med_traitant <> ''
				;
				
				
			]]></sqlcmd>				
		</NODE>
    
        <NODE label="Compléments facture">
            <sqlcmd><![CDATA[
			
				-- ELA Pour correction tier payant 1 null (Par KEA le 25/09/2017)
				UPDATE activite[PX].p_sejours
				SET tiers_payant_1_id = 0
				WHERE tiers_payant_1_id is null;

				UPDATE activite[PX].p_factures
				SET tiers_payant_1_id = 0
				WHERE tiers_payant_1_id is null;

				UPDATE activite[PX].p_factures_reference
				SET tiers_payant_1_id = 0
				WHERE tiers_payant_1_id is null;
                
                -- Recalcul des 10% SSR
				-- recherche tarif 100% et génération -10%
				
				-- Lignes factures à traiter
				DROP TABLE IF EXISTS w_moins10;
				CREATE TEMP TABLE w_moins10 AS  
				SELECT p_factures_lignes_c.*, 
					p_factures_lignes_c.CTID AS CTID_orig,
					CASE 
						WHEN (t_prestations.code = 'PJ' OR type_valorisation_non_facture = 'PJ') AND
							montant_comptabilise_0=0 AND 
							montant_comptabilise_2=0 AND 
							montant_comptabilise_22=0 AND						
							ABS(round(base.cti_division(((prix_unitaire*nb_prestation*0.9)-montant_comptabilise_1),nb_prestation),0)) BETWEEN 17 AND 37
						THEN round(base.cti_division(((prix_unitaire*nb_prestation*0.9)-montant_comptabilise_1),ABS(nb_prestation)),2)
						ELSE 0::numeric END AS montant_fj,
						t_prestations.code AS prestation_code,
						type_valorisation_non_facture,
						'M'::text || CASE WHEN t_prestations.code <> 'PJ' THEN t_prestations.code ELSE 'PJS' END AS prestation_mcode
				FROM activite[PX].p_factures_lignes_c
				JOIN activite[PX].t_lieux ON lieu_id = t_lieux.oid
				JOIN activite[PX].t_services_facturation ON t_services_facturation.oid = service_facturation_id
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				WHERE date_fin >= '20170701' AND
					date_debut >= '20170701' AND
					type_t2a = '2' AND
					prestation_id = ANY (SELECT to_id FROM activite.t_listes_contenu JOIN activite.t_listes ON liste_id = t_listes.oid AND t_listes.code = 'DMAP_MFS') AND
					montant_comptabilise <> 0 AND
					montant_comptabilise_1 <> 0 AND
					round(prix_unitaire * nb_prestation,2) <> montant_comptabilise AND
					abs(round(prix_unitaire * nb_prestation,2)) <> abs(montant_comptabilise)+(nb_prestation*18)
				ORDER BY no_facture, prestation_id
				;

				-- Calcul tarif plein
				UPDATE w_moins10 SET
					montant_facture_1 = 
						CASE WHEN prestation_code = 'PJ' OR type_valorisation_non_facture = 'PJ' THEN round(prix_unitaire * nb_prestation * taux_1 / 100,2) - montant_fj
						ELSE round(prix_unitaire * nb_prestation * taux_1 / 100,2) END,
					montant_facture = 
						CASE WHEN prestation_code = 'PJ' OR type_valorisation_non_facture = 'PJ' THEN round(prix_unitaire * nb_prestation * taux_1 / 100,2) - montant_fj
						ELSE round(prix_unitaire * nb_prestation * taux_1 / 100,2) END +
							(montant_facture_2+montant_facture_22+montant_facture_0)
				;


				-- Génération prestations spécifiques 
				INSERT INTO activite.t_prestations (code, texte, texte_court)
				SELECT prestation_mcode, t_prestations.texte || ' (-10%)', t_prestations.texte || ' (-10%)'
				FROM w_moins10
				JOIN activite.t_prestations on prestation_id = t_prestations.oid
				WHERE prestation_mcode NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL)
				GROUP BY 1,2,3
				;
			
				-- Maj tarif plein
				UPDATE activite[PX].p_factures_lignes_c
				SET montant_facture = w_moins10.montant_facture, montant_facture_1 = w_moins10.montant_facture_1
				FROM w_moins10
				WHERE p_factures_lignes_c.CTID = w_moins10.CTID_orig;
				;
				
				-- Génération -10%
				UPDATE w_moins10 SET
					montant_facture = montant_comptabilise - montant_facture,
					montant_facture_1 = montant_comptabilise_1 - montant_facture_1,
					montant_facture_2 = montant_comptabilise_2 - montant_facture_2,
					montant_facture_22 = montant_comptabilise_22 - montant_facture_22,
					montant_facture_0 = montant_comptabilise_0 - montant_facture_0,
					montant_comptabilise = 0,
					montant_comptabilise_1 = 0,
					montant_comptabilise_2 = 0,
					montant_comptabilise_22 = 0,
					montant_comptabilise_0 = 0,
					prestation_id = t_prestations.oid
				FROM activite.t_prestations
				WHERE t_prestations.code = prestation_mcode
				;
			
				ALTER TABLE w_moins10 DROP COLUMN CTID_orig;
				ALTER TABLE w_moins10 DROP COLUMN montant_fj;
				ALTER TABLE w_moins10 DROP COLUMN prestation_code;
				ALTER TABLE w_moins10 DROP COLUMN prestation_mcode;
                ALTER TABLE w_moins10 DROP COLUMN type_valorisation_non_facture;
			
				INSERT INTO activite[PX].p_factures_lignes_c
				SELECT *
				FROM w_moins10
				WHERE montant_facture <> 0
				;
			
			
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('activite[PX].p_factures_lignes_c')
                ;
                
                       
                -- Prestation des lignes non facturées selon usage en facturation
            
                UPDATE activite[PX].p_factures_lignes_non_facturees_c
                SET prestation_id = subview.prestation_id
                FROM (
                SELECT rubrique_facturation_id,
                    (MAX(Array[nb, prestation_id]))[2] AS prestation_id
                FROM (
                    SELECT 
                        rubrique_facturation_id, 
                        prestation_id,
                        count(*) AS nb
                    FROM activite[PX].p_factures_lignes_c
                    WHERE montant_facture <> 0
                    GROUP BY 1,2
                    ORDER BY 1
                    ) subview
                GROUP BY 1
                ) subview
                WHERE p_factures_lignes_non_facturees_c.rubrique_facturation_id = subview.rubrique_facturation_id AND
                        p_factures_lignes_non_facturees_c.prestation_id IS DISTINCT FROM subview.prestation_id;
                        
                -- Comptes LOGHOS abrégés
                DROP TABLE IF EXISTS w_compte_translation;
                CREATE TEMP TABLE w_compte_translation AS
                SELECT t_compte_loghos.oid AS from_id, t_compte.oid AS to_id
                FROM activite[PX].t_compte
                JOIN activite[PX].t_compte t_compte_loghos ON rpad(t_compte_loghos.code,8,'0') = t_compte.code and
                    t_compte_loghos.code <> t_compte.code AND
                    t_compte_loghos.oid <> t_compte.oid AND
                    (
                    t_compte_loghos.code = t_compte_loghos.texte OR
                    t_compte_loghos.texte = t_compte.texte
                    );

                UPDATE activite[PX].p_factures_lignes_c
                SET compte_produit_id = to_id
                FROM w_compte_translation
                WHERE compte_produit_id = from_id;

                UPDATE activite[PX].p_factures_encours_lignes_c
                SET compte_produit_id = to_id
                FROM w_compte_translation
                WHERE compte_produit_id = from_id;
                
                
                -- factures de reference
                            
                DROP TABLE IF EXISTS w_sejours_facture_reference;

                CREATE TEMP TABLE w_sejours_facture_reference AS
                SELECT 
                    no_sejour,
                    MAX(p_factures.no_facture) AS no_facture_last,
                    MAX(CASE WHEN type_facture <> '1' AND type_facture <> 'X' THEN p_factures.no_facture ELSE null END) AS no_facture_reference_last,
                    MAX(CASE WHEN type_facture <> '1' AND type_facture <> 'X' AND t_prestations.code = 'GHS' THEN p_factures.no_facture ELSE null END) AS no_facture_reference_ghs_last
                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);


                UPDATE activite[PX].p_factures
                SET no_facture_reference = COALESCE(no_facture_reference_ghs_last, no_facture_reference_last, no_facture_last)
                FROM w_sejours_facture_reference
                WHERE p_factures.no_sejour = w_sejours_facture_reference.no_sejour AND
                    p_factures.no_facture_reference <> COALESCE(no_facture_reference_ghs_last, no_facture_reference_last, no_facture_last);
                        
                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 <> p_factures_references.oid;
            
                UPDATE activite[PX].p_factures SET date_expedition_0 = date_facture WHERE date_expedition_0 < date_facture AND date_facture <> '2099-12-31';
				
				-- Incohérence total réglé facture et soldes clients (déphasage XECE, XECF)
				UPDATE activite[PX].p_factures SET
					montant_regle_1_c = subview.montant_regle_1,
					montant_regle_2_c = subview.montant_regle_2,
					montant_regle_0_c = subview.montant_regle_0
				FROM
				(
					SELECT p_factures.no_facture,
						SUM(p_factures_soldes_c.montant_regle_1) AS montant_regle_1, 
						SUM(p_factures_soldes_c.montant_regle_2) AS montant_regle_2, 
						SUM(p_factures_soldes_c.montant_regle_0) AS montant_regle_0, 
						MAX(montant_regle_1_c) AS montant_regle_1_c, 
						MAX(montant_regle_2_c) AS montant_regle_2_c, 
						MAX(montant_regle_0_c) AS montant_regle_0_c
					FROM activite[PX].p_factures
					JOIN activite[PX].p_factures_soldes_c ON p_factures.no_facture = p_factures_soldes_c.no_facture
					GROUP BY 1
					HAVING 
						SUM(p_factures_soldes_c.montant_regle_1) <> MAX(montant_regle_1_c) OR
						SUM(p_factures_soldes_c.montant_regle_2) <> MAX(montant_regle_2_c) OR
						SUM(p_factures_soldes_c.montant_regle_0) <> MAX(montant_regle_0_c)
				 ) subview
				 WHERE p_factures.no_facture = subview.no_facture
				 ;
                
                
            ]]></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,  
                    
                    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
                
                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 p_sejours.no_sejour;

                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 = CASE WHEN w_sejours_total.date_expedition_0 <> '0001-01-01' THEN w_sejours_total.date_expedition_0 ELSE '2099-12-31' END,  
                    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 = CASE WHEN w_sejours_total.date_expedition_1 <> '0001-01-01' THEN w_sejours_total.date_expedition_1 ELSE '2099-12-31' END,   
                    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 = CASE WHEN w_sejours_total.date_expedition_2 <> '0001-01-01' THEN w_sejours_total.date_expedition_2 ELSE '2099-12-31' END, 
                    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 = CASE WHEN w_sejours_total.date_expedition_22 <> '0001-01-01' THEN w_sejours_total.date_expedition_22 ELSE '2099-12-31' END, 
                    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
                    
                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 CASE WHEN w_sejours_total.date_expedition_0 <> '0001-01-01' THEN w_sejours_total.date_expedition_0 ELSE '2099-12-31' END 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 CASE WHEN w_sejours_total.date_expedition_1 <> '0001-01-01' THEN w_sejours_total.date_expedition_1 ELSE '2099-12-31' END 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 CASE WHEN w_sejours_total.date_expedition_2 <> '0001-01-01' THEN w_sejours_total.date_expedition_2 ELSE '2099-12-31' END 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 CASE WHEN w_sejours_total.date_expedition_22 <> '0001-01-01' THEN w_sejours_total.date_expedition_22 ELSE '2099-12-31' END 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

                );
                
                UPDATE activite[PX].p_sejours set 
                    ghm_id = t_ghs.ghm_id::bigint
                FROM base.t_ghs
                WHERE 
                    p_sejours.ghs_id = t_ghs.oid
                    AND p_sejours.ghm_id = 0
                    AND p_sejours.ghs_id > 0;
                
                UPDATE activite[PX].p_sejours 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
                
                WHERE
                    
                    delai_groupage IS DISTINCT FROM 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 
                        OR
                    delai_facture IS DISTINCT FROM 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
                        OR
                    delai_expedition IS DISTINCT FROM 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
                        OR
                    delai_solde IS DISTINCT FROM 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
                        OR

                    delai_expedition_0 IS DISTINCT FROM 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
                        OR
                    delai_solde_0 IS DISTINCT FROM 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
                        OR

                    delai_expedition_1 IS DISTINCT FROM 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
                        OR
                    delai_solde_1 IS DISTINCT FROM 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
                        OR

                    delai_expedition_2 IS DISTINCT FROM 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
                        OR
                    delai_solde_2 IS DISTINCT FROM 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
                        OR

                    delai_expedition_22 IS DISTINCT FROM 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
                        OR
                    delai_solde_22 IS DISTINCT FROM 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;
                                                        
                                        
            ]]></sqlcmd>
        </NODE>
        
    
        <NODE label="Tables répliquées">
        
            <condition><![CDATA[
                "[PX]" == ""
            ]]></condition>
            
            <sqlcmd><![CDATA[

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

    <NODE name="ENCOURS" label="ENCOURS ET VALORISATION DES NON FACTURES">
		
		<condition><![CDATA[
            "[CJFIRST_PRESENT]" == "OUI"
        ]]></condition>
		
        <NODE label="Encours et valorisation non facturés">
            <sqlcmd><![CDATA[

                   -- entetes factures encours
				DROP TABLE IF EXISTS w_factures_references;
				CREATE TEMP TABLE w_factures_references AS
				SELECT
					no_sejour,
					date_fin,
					MIN(date_debut) AS date_debut,
					MAX(no_facture) AS no_facture
				FROM activite[PX].p_factures
				WHERE no_facture_reference = no_facture AND code_facture >= '1'
				GROUP BY 1,2;
			
				CREATE INDEX w_factures_references_i1 ON w_factures_references USING btree (no_sejour);
	
	
				DROP TABLE IF EXISTS w_EFS_DT_FAC;
				CREATE TEMP TABLE w_EFS_DT_FAC AS
				SELECT date(date_trunc('month', EFS_DT_FAC) + interval '1 month' - interval '1 day') AS date_encours, MAX(date(EFS_DT_FAC)) AS EFS_DT_FAC
				FROM prod_cegi.CJ_ENC_EFS
				WHERE date(EFS_DT_FAC) >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1
				ORDER BY 1;
	
				CREATE INDEX w_EFS_DT_FAC_i1 ON w_EFS_DT_FAC USING btree (date_encours);
	
				DROP TABLE IF EXISTS w_factures_encours;
				CREATE TEMP TABLE w_factures_encours AS
				SELECT
						0 AS oid,
						CJ_ENC_EFS.EFS_ID,
						p_sejours.finess,
						p_sejours.no_sejour,
						p_sejours.date_entree,
						p_sejours.date_sortie,
						p_sejours.oid AS sejour_id,
						p_sejours.lieu_sortie_id,
						COALESCE(w_factures_references.no_facture,'ID' || CJ_ENC_EFS.EFS_ID)  || '.EP' || substr(to_char(date_part('year', CJ_ENC_EFS.EFS_DT_FAC),'FM0000'),3,2) || to_char(date_part('month', CJ_ENC_EFS.EFS_DT_FAC),'FM00') AS no_facture,
						w_factures_references.no_facture AS no_facture_reference,
						date(EFS_DT_DEB) AS date_debut,
						date(EFS_DT_FIN) AS date_fin,
						date_encours,
						'P'::text AS code_origine,
						CASE WHEN date(EFS_DT_FIN) > date_encours OR p_sejours.date_sortie > date_encours THEN '0' ELSE '1' END AS code_sorti,
						p_sejours.tiers_payant_1_id,
						p_sejours.tiers_payant_2_id,
						p_sejours.tiers_payant_22_id,
						p_sejours.tiers_payant_0_id,
						p_sejours.ghs_id,
						p_sejours.ghs_bebe1_id,
						p_sejours.ghs_bebe2_id,
						p_sejours.ghs_bebe3_id,
						p_sejours.code_cp_demandee,
						SUM(CASE WHEN EFT_TER_TYPE = 'DBT' AND EFT_SEJHON IN (0) THEN EFT_TTC ELSE 0 END) + 
						SUM(CASE WHEN EFT_TER_TYPE = 'CAI' AND EFT_SEJHON IN (0) THEN EFT_TTC ELSE 0 END) +
						SUM(CASE WHEN EFT_TER_TYPE = 'MUT' AND EFT_SEJHON IN (0) THEN EFT_TTC ELSE 0 END) AS montant_encours_c,
						SUM(CASE WHEN EFT_TER_TYPE = 'DBT' AND EFT_SEJHON IN (0) THEN EFT_TTC ELSE 0 END)  AS montant_encours_0_c,
						SUM(CASE WHEN EFT_TER_TYPE = 'CAI' AND EFT_SEJHON IN (0) THEN EFT_TTC ELSE 0 END)  AS montant_encours_1_c,
						SUM(CASE WHEN EFT_TER_TYPE = 'MUT' AND EFT_SEJHON IN (0) THEN EFT_TTC ELSE 0 END)  AS montant_encours_2_c,
						0::numeric AS montant_encours_22_c,
						0::numeric AS montant_encours_h,
						0::numeric AS montant_encours_0_h,
						0::numeric AS montant_encours_1_h,
						0::numeric AS montant_encours_2_h,
						0::numeric AS montant_encours_22_h
				FROM  prod_cegi.CJ_ENC_EFS
					JOIN prod_cegi.CJ_SEJOUR w_CJ_SEJOUR_select ON CJ_ENC_EFS.SEJ_ID = w_CJ_SEJOUR_select.SEJ_ID
					JOIN prod_cegi.CJ_ENC_EFT ON CJ_ENC_EFS.EFS_ID = CJ_ENC_EFT.EFS_ID
					JOIN w_EFS_DT_FAC ON date(CJ_ENC_EFS.EFS_DT_FAC) = w_EFS_DT_FAC.EFS_DT_FAC AND
						date(date_trunc('month',CJ_ENC_EFS.EFS_DT_FAC) + interval '1 month' - interval '1 day') = date_encours
					JOIN activite[PX].p_sejours ON code_original  = w_CJ_SEJOUR_select.SEJ_NUMDOS
					LEFT JOIN w_factures_references ON p_sejours.no_sejour = w_factures_references.no_sejour AND
						date(EFS_DT_FIN) BETWEEN w_factures_references.date_debut AND w_factures_references.date_fin
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24
				;
			
				CREATE INDEX w_factures_encours_i1 ON w_factures_encours USING btree (EFS_ID);
	

	            SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_2');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_4');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_5');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_6');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_7');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_8');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_9');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_10');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_11');
				
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_lignes_c_2');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_lignes_c_3');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_lignes_c_4');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_lignes_c_5');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_lignes_c_6');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_lignes_c_7');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_lignes_c_8');
	
				DELETE FROM activite[PX].p_factures_encours WHERE code_origine = 'P';
				DELETE FROM activite[PX].p_factures_encours_lignes_c
					WHERE no_facture NOT IN (SELECT no_facture FROM activite[PX].p_factures_encours);
					
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_1');
				SELECT base.cti_disable_index('activite[PX].', 'i_factures_encours_lignes_c_1');
	
				INSERT INTO activite[PX].p_factures_encours(
					sejour_id,
					no_sejour,
					no_facture,
					no_facture_reference,
					date_debut,
					date_fin,
					date_encours,
					code_origine,
					code_sorti,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					tiers_payant_0_id,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					code_cp_demandee,
					montant_encours_c,
					montant_encours_0_c,
					montant_encours_1_c,
					montant_encours_2_c,
					montant_encours_22_c,
					montant_encours_h,
					montant_encours_0_h,
					montant_encours_1_h,
					montant_encours_2_h,
					montant_encours_22_h
					)
				SELECT
					sejour_id,
					no_sejour,
					no_facture,
					no_facture_reference,
					date_debut,
					date_fin,
					date_encours,
					code_origine,
					code_sorti,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					tiers_payant_0_id,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					code_cp_demandee,
					montant_encours_c,
					montant_encours_0_c,
					montant_encours_1_c,
					montant_encours_2_c,
					montant_encours_22_c,
					montant_encours_h,
					montant_encours_0_h,
					montant_encours_1_h,
					montant_encours_2_h,
					montant_encours_22_h
				FROM w_factures_encours;
		
				UPDATE w_factures_encours SET oid = p_factures_encours.oid
				FROM activite[PX].p_factures_encours 
				WHERE w_factures_encours.no_facture = p_factures_encours.no_facture;
				
				SELECT base.cti_enable_index('activite[PX].', 'i_factures_encours_1');
		
				DROP SEQUENCE IF EXISTS w_factures_encours_lignes_c_sequence;
				CREATE TEMP SEQUENCE w_factures_encours_lignes_c_sequence;
		
                DROP TABLE IF EXISTS w_factures_encours_lignes_c;
				CREATE TEMP TABLE w_factures_encours_lignes_c AS
				SELECT
					nextval('w_factures_encours_lignes_c_sequence'::regclass) AS oid,
					w_factures_encours.no_sejour,
					CJ_ENC_LCS.LCS_ID,
					w_factures_encours.oid AS facture_id,
					w_factures_encours.no_facture,
					w_factures_encours.date_entree,
					w_factures_encours.date_sortie,
					date(MAX(LCS_DT_DEB)) AS date_debut,
					date(MAX(LCS_DT_FIN)) AS date_fin,
					MAX(LCS_QTE*LCS_COEFF) AS nb_rubrique,
					1::numeric AS coefficient,
					MAX(CASE WHEN LCS_MCO <> 0 THEN LCS_MCO ELSE 1 END) AS coefficient_mco,
					COALESCE(t_rubriques_facturation.oid, 0) AS rubrique_facturation_id, 
					COALESCE(t_rubriques_facturation.oid, 0) AS rubrique_comptabilisation_id,
					MAX(COALESCE(t_compte.oid::bigint, 0)) AS compte_produit_id, 
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id, 
					
					0::numeric AS taux_22,
					MAX(LCS_PRIX) AS prix_unitaire,
					w_factures_encours.lieu_sortie_id AS lieu_id,
					MAX(LCS_QTE*LCS_COEFF) AS nb_prestation,
		
					LEAST(MAX(CASE WHEN LCT_TER_TYPE = 'DBT' AND LCS_SEJHON IN (0,2) THEN LCT_TX ELSE 0 END),100) AS taux_0,
					LEAST(MAX(CASE WHEN LCT_TER_TYPE = 'CAI' AND LCS_SEJHON IN (0,2) THEN LCT_TX ELSE 0 END),100) AS taux_1,
					LEAST(MAX(CASE WHEN LCT_TER_TYPE = 'MUT' AND LCS_SEJHON IN (0,2) THEN LCT_TX ELSE 0 END),100) AS taux_2,
					MAX(CASE WHEN LCS_SEJHON = 0 THEN LCS_TTC ELSE 0 END) AS montant_encours,
					SUM(CASE WHEN LCT_TER_TYPE = 'DBT' AND LCS_SEJHON IN (0) THEN LCT_TTC ELSE 0 END) AS montant_encours_0,
					SUM(CASE WHEN LCT_TER_TYPE = 'CAI' AND LCS_SEJHON IN (0) THEN LCT_TTC ELSE 0 END) AS montant_encours_1,
					SUM(CASE WHEN LCT_TER_TYPE = 'MUT' AND LCS_SEJHON IN (0) THEN LCT_TTC ELSE 0 END) AS montant_encours_2,
					0::numeric AS montant_encours_22
				FROM prod_cegi.CJ_ENC_LCS
					JOIN w_factures_encours ON CJ_ENC_LCS.EFS_ID = w_factures_encours.EFS_ID
					JOIN prod_cegi.CJ_ENC_LCT ON CJ_ENC_LCS.LCS_ID = CJ_ENC_LCT.LCS_ID
					JOIN w_RUBRIQUES ON CJ_ENC_LCS.PST_ID = w_RUBRIQUES.PST_ID
					LEFT JOIN activite[PX].t_rubriques_facturation ON PST_LIBC = t_rubriques_facturation.code_original
					LEFT JOIN activite.t_prestations ON LCS_CODE = t_prestations.code
					LEFT JOIN activite[PX].t_compte ON LCT_PST_CPT = t_compte.code_original AND LCT_PST_CPT <> ''
					JOIN activite[PX].p_factures_encours ON w_factures_encours.oid = p_factures_encours.oid
				WHERE LCS_SEJHON IN (0,2)
				GROUP BY 1,2,3,4,5,6,7,13,14,16,19;
		
	
				DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c;
				CREATE TEMP TABLE w_factures_encours_lignes_sup_c AS
				SELECT
					w_factures_encours_lignes_c.oid AS from_oid,
					t_prestations.code AS prestation_code,
					date(date_debut) AS date_debut_ghs,
					date(date_fin - interval '1 day') AS date_fin_ghs,
					(date(date_fin) - date(date_debut)) * CASE WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation_ghs,
					CASE WHEN t_prestations.code = 'GHS' THEN date(w_factures_encours_lignes_c.date_entree + interval '1 day') ELSE date(w_factures_encours_lignes_c.date_debut + interval '1 day') END AS date_debut_det,
					CASE WHEN t_prestations.code = 'GHS' THEN date(w_factures_encours_lignes_c.date_sortie - interval '1 day') ELSE date(w_factures_encours_lignes_c.date_debut + ((ABS(nb_prestation)-1) || ' day')::interval)  END AS date_fin_det,
					ABS(CASE WHEN t_prestations.code = 'GHS' THEN date(w_factures_encours_lignes_c.date_sortie) - date(w_factures_encours_lignes_c.date_entree) ELSE nb_prestation END) AS nb_det,
					w_factures_encours_lignes_c.*
				FROM w_factures_encours_lignes_c
					JOIN activite[PX].p_sejours ON w_factures_encours_lignes_c.no_sejour = p_sejours.no_sejour
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND 
						(
						code IN ('PJ', 'PJ1', 'PJ2', 'FJ', 'SSM', 'GHS', 'EXH', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO') OR
						t_prestations.type_ventilation_jour = '1'
						)
				WHERE (nb_prestation > 1 or nb_prestation < -1 OR (t_prestations.code = 'GHS' AND date(date_fin) - date(date_debut) > 1)) ;

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

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


				UPDATE w_factures_encours_lignes_c
				SET
					date_fin = w_factures_encours_lignes_c.date_debut,
					nb_rubrique = w_factures_encours_lignes_c.nb_rubrique - w_factures_encours_lignes_sup_c_gen_tot.nb_rubrique,
					nb_prestation = w_factures_encours_lignes_c.nb_prestation - w_factures_encours_lignes_sup_c_gen_tot.nb_prestation,
					montant_encours = w_factures_encours_lignes_c.montant_encours - w_factures_encours_lignes_sup_c_gen_tot.montant_encours,
					montant_encours_0 = w_factures_encours_lignes_c.montant_encours_0 - w_factures_encours_lignes_sup_c_gen_tot.montant_encours_0,
					montant_encours_1 = w_factures_encours_lignes_c.montant_encours_1 - w_factures_encours_lignes_sup_c_gen_tot.montant_encours_1,
					montant_encours_2 = w_factures_encours_lignes_c.montant_encours_2 - w_factures_encours_lignes_sup_c_gen_tot.montant_encours_2,
					montant_encours_22 = w_factures_encours_lignes_c.montant_encours_22 - w_factures_encours_lignes_sup_c_gen_tot.montant_encours_22
				FROM w_factures_encours_lignes_sup_c_gen_tot
				WHERE w_factures_encours_lignes_c.oid = from_oid;
	
	
				INSERT INTO w_factures_encours_lignes_c(
					oid,
					no_sejour,
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id, 
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id, 
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22)
				SELECT
					nextval('w_factures_encours_lignes_c_sequence'::regclass) AS oid,
					no_sejour,
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id, 
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id, 
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22
				FROM w_factures_encours_lignes_sup_c_gen;
	
	
	
				UPDATE w_factures_encours_lignes_c 
				SET lieu_id = p_mouvements_sejour.lieu_id
				FROM activite[PX].p_mouvements_sejour
				WHERE w_factures_encours_lignes_c.no_sejour = p_mouvements_sejour.no_sejour AND
					w_factures_encours_lignes_c.date_debut = p_mouvements_sejour.date AND 
					(p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.nb_sorties_directes = 1) AND
					w_factures_encours_lignes_c.lieu_id IS DISTINCT FROM p_mouvements_sejour.lieu_id;
	
				
	
				INSERT INTO activite[PX].p_factures_encours_lignes_c(
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22
				)
				SELECT
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22
				FROM w_factures_encours_lignes_c;
				
				SELECT base.cti_vacuum_table('activite[PX]','p_factures_encours');
				SELECT base.cti_vacuum_table('activite[PX]','p_factures_encours_lignes_c');
				
			    SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_8');
				
				
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_9');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_10');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_11');
				
				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_factures_references CASCADE;
				DROP TABLE IF EXISTS w_factures_encours CASCADE;
				DROP TABLE IF EXISTS w_factures_encours_lignes_c CASCADE;
				DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c CASCADE;
				DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c_gen CASCADE;
				DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c_gen_tot CASCADE;
              
            ]]></sqlcmd>
        </NODE>
    </NODE>
    
    <NODE name="VACUUM" label="REORGANISATION BASE DE DONNEES">
            
        <NODE label="Réorganisation tables">
            <sqlcmd><![CDATA[
            
                VACUUM ANALYSE activite[PX].p_chiffrier;
                VACUUM ANALYSE activite[PX].p_chiffrier_comptable;
                VACUUM ANALYSE activite[PX].p_chiffrier_shs;
                VACUUM ANALYSE activite[PX].p_factures;
                VACUUM ANALYSE activite[PX].p_factures_comptables;
                VACUUM ANALYSE activite[PX].p_factures_lignes_c;
                VACUUM ANALYSE activite[PX].p_factures_lignes_h;
                VACUUM ANALYSE activite[PX].p_factures_lignes_non_facturees_c;
                VACUUM ANALYSE activite[PX].p_factures_lignes_non_facturees_h;
                VACUUM ANALYSE activite[PX].p_factures_rejets;
                VACUUM ANALYSE activite[PX].p_factures_soldes_c;
                VACUUM ANALYSE activite[PX].p_factures_soldes_h;
                VACUUM ANALYSE activite[PX].p_mouvements_sejour;
                VACUUM ANALYSE activite[PX].p_patients;
                VACUUM ANALYSE activite[PX].p_sejours;
                VACUUM ANALYSE activite[PX].t_activites;
                VACUUM ANALYSE activite[PX].t_classes;
                VACUUM ANALYSE activite[PX].t_classes_sections;
                VACUUM ANALYSE activite[PX].t_classes_sections_elements;
                VACUUM ANALYSE activite[PX].t_etages;
                VACUUM ANALYSE activite[PX].t_ghs_c;
                VACUUM ANALYSE activite[PX].t_indicateurs;
                VACUUM ANALYSE activite[PX].t_lieux;
                VACUUM ANALYSE activite[PX].t_lieux_c;
                VACUUM ANALYSE activite[PX].t_listes;
                VACUUM ANALYSE activite[PX].t_listes_contenu;
                VACUUM ANALYSE activite[PX].t_listes_tables;
                VACUUM ANALYSE activite[PX].t_lits;
                VACUUM ANALYSE activite[PX].t_medecins_administratifs;
                VACUUM ANALYSE activite[PX].t_medecins_administratifs_c;
                VACUUM ANALYSE activite.t_prestations;
                VACUUM ANALYSE activite[PX].t_rapports;
                VACUUM ANALYSE activite[PX].t_rapports_rubriques;
                VACUUM ANALYSE activite[PX].t_rejets_noemie;
                VACUUM ANALYSE activite[PX].t_rubriques_facturation;
                VACUUM ANALYSE activite[PX].t_services_facturation;
                VACUUM ANALYSE activite[PX].t_specialites_medecin;
                VACUUM ANALYSE activite[PX].t_tiers_payant;
                VACUUM ANALYSE activite[PX].t_types_tiers_payant;
                VACUUM ANALYSE activite[PX].t_unites_fonctionnelles;
                VACUUM ANALYSE activite[PX].t_unites_medicales;
                
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Vide cache">
            <sqlcmd><![CDATA[
            
                SELECT cti_cache_reload as log from cache.cti_cache_reload('iCTI_activite', true);
                
            ]]></sqlcmd>
        </NODE>
            

    </NODE>

    <NODE name="RAZ" label="RAZ BASE">
    
        <NODE label="Nettoyage des tables">
            <sqlcmd><![CDATA[

                TRUNCATE activite[PX].p_patients;
                
                TRUNCATE activite[PX].p_sejours;
                
                TRUNCATE activite[PX].p_mouvements_sejour;
                
                TRUNCATE activite[PX].t_lieux;
                
                TRUNCATE activite[PX].p_factures;
                
                TRUNCATE activite[PX].p_factures_lignes_non_facturees_c;
                
                TRUNCATE activite[PX].p_factures_lignes_non_facturees_h;
                
                TRUNCATE activite[PX].p_factures_lignes_c;
                
                TRUNCATE activite[PX].p_factures_lignes_h;
                
                TRUNCATE activite[PX].p_factures_rejets;
                
                TRUNCATE activite[PX].p_factures_soldes_c;
                
                TRUNCATE activite[PX].p_factures_soldes_h;
                
                TRUNCATE activite[PX].p_factures_comptables;
                                        
            ]]></sqlcmd>
        </NODE>
        
    </NODE>

</ROOT>
