<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
    <NODE name="PMSICOMPLEMENTS" label="RECUPERATION DES DONNEES COMPLEMENTAIRES PMSI EVOLUCARE OPALE">
        <NODE label="Tests des options installées">
            <sqlcmd><![CDATA[ 
				
                CTISELECT_PROPERTY_READ 'WITH_MEDSPHERE', count(*) 
                FROM information_schema.tables
                WHERE table_schema = 'prod_csis' AND table_name = 'sid_dossieradministratif_dadm' ;
                
                echo MEDSPHERE : [WITH_MEDSPHERE];
        
            ]]></sqlcmd>
        </NODE>
		<NODE label="Paramètres">
            <sqlcmd><![CDATA[
                
                /*******************************************************************************
                 *                           SPECIALITES MEDECIN                               *
                 *******************************************************************************/
                
                -- Récupération des spécialites officielles
                DROP TABLE IF EXISTS w_specialite
                ;
                CREATE TEMP TABLE w_specialite AS
                    SELECT
                        to_char(special.code, 'FM09') AS code,
                        to_char(special.code, 'FM09') || '..'::text AS code_interne,
                        special.libelle AS texte
                    FROM
                        prod_evolucare_opale.special
                ;
                
                -- Insertion des nouvelles spécialités officielles
                INSERT INTO pmsi.t_specialites_medecin(code, texte)
                SELECT 
                    w_specialite.code, 
                    w_specialite.texte
                FROM 
                    w_specialite
                    LEFT JOIN pmsi.t_specialites_medecin ON t_specialites_medecin.code = w_specialite.code
                WHERE t_specialites_medecin.code IS NULL
                ;
                
                -- Màj des spécialités officielles créées via import PMSI
                UPDATE pmsi.t_specialites_medecin
                SET texte = w_specialite.texte
                FROM w_specialite
                WHERE t_specialites_medecin.code = w_specialite.code
                    AND t_specialites_medecin.code = t_specialites_medecin.texte
                ;
                
                -- Récupération des spécialites internes
                INSERT INTO pmsi.t_specialites_internes_medecin(code, texte)
                SELECT 
                    w_specialite.code_interne,
                    w_specialite.texte
                FROM 
                    w_specialite
                    LEFT JOIN pmsi.t_specialites_internes_medecin ON
                         w_specialite.code_interne = t_specialites_internes_medecin.code
                WHERE
                    t_specialites_internes_medecin.code IS NULL
                ;
                
                -- FIN boulot actuel
                
                /**********************************************************************************
                 *                                MAJ MEDECINS                                    *
                 **********************************************************************************/
                -- Récupération des médecins
                DROP TABLE IF EXISTS w_medecin
                ;
                
                CREATE TEMP TABLE w_medecin AS
                    SELECT
                        interv.code,
                        interv.nom,
                        interv.prenom,
                        replace(interv.numadeli, ' ', '') as no_adeli,
                        COALESCE(t_specialites_medecin.oid, 0) as specialite_id,
                        COALESCE(t_specialites_internes_medecin.oid, 0) as specialite_interne_id
                    FROM
                        prod_evolucare_opale.interv
                        LEFT JOIN pmsi.t_specialites_medecin ON t_specialites_medecin.code = to_char(interv.c_special, 'FM09')
                        LEFT JOIN pmsi.t_specialites_internes_medecin ON t_specialites_internes_medecin.code = to_char(interv.c_special, 'FM09') || '..'::text
                    GROUP BY 1,2,3,4,5,6;
                
                CREATE INDEX w_medecin_i1
                  ON w_medecin
                  USING btree
                  (code)
                ;
                
                -- Insertion des nouveaux médecins
                INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, no_adeli, specialite_interne_id)
                SELECT
                    w_medecin.code::text,
                    w_medecin.nom,
                    w_medecin.prenom,
                    w_medecin.specialite_id,
                    w_medecin.no_adeli,
                    w_medecin.specialite_interne_id
                FROM w_medecin
                    LEFT JOIN pmsi.t_medecins ON t_medecins.code = w_medecin.code
                WHERE
                    t_medecins.code IS NULL;
                
                SELECT pmsi.cti_reorganize_medecins_c()
                ;
                
                /******************************************************************************
                 *                             UNITES MEDICALES                               *
                 ******************************************************************************/
                
                DROP TABLE IF EXISTS w_um
                ;
                
                CREATE TEMP TABLE w_um AS
                    SELECT
                        unite.code as oid,
                        unite.libelle as texte,
                        unite.libexport as code,
                        base.cti_to_number(unite.nblit) as nblit,
                        unite.dateeff::date,
                        COALESCE(t_types_autorisations.code, ''::text) as type_autorisation
                    FROM prod_evolucare_opale.unite
                        LEFT JOIN pmsi.t_types_autorisations ON t_types_autorisations.code = to_char(unite.c_typautum, 'FM09')
                    GROUP BY 1,2,3,4,5,6
                ;
                
                CREATE INDEX w_um_i1
                  ON w_um
                  USING btree
                  (oid)
                ;
                
                CREATE INDEX w_um_i2
                  ON w_um
                  USING btree
                  (code)
                ;
                
                -- Insertion des nouvelles UM
                INSERT INTO pmsi.t_unites_medicales(code, texte, type_autorisation, date_effet_autorisation, nb_lits)
                    SELECT
                        w_um.code,
                        w_um.texte,
                        w_um.type_autorisation,
                        w_um.dateeff,
                        w_um.nblit
                    FROM 
                        w_um
                        LEFT JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = w_um.code
                    WHERE 
                        t_unites_medicales.code IS NULL
                ;
                
                -- Màj libellés UM quand UM créée via import PMSI
                UPDATE pmsi.t_unites_medicales SET 
                    texte = w_um.texte
                FROM w_um
                WHERE
                    t_unites_medicales.code = w_um.code
                    AND t_unites_medicales.texte = t_unites_medicales.code
                ;
                
            ]]></sqlcmd>
        </NODE>
        <NODE label="Identités">
            <sqlcmd><![CDATA[
                
                /******************************************************************************
                 *                        N° SEJOUR ADMINISTRATIF                             *
                 ******************************************************************************/
                 
                UPDATE [SCHEMA].p_rss SET
                    no_sejour_administratif = rssgrp.numnda
                FROM
                    prod_evolucare_opale.rssgrp
                WHERE 1=1
                    AND ghm_id <> 0
                    AND p_rss.import_id = [IMPORT_ID]
                    AND rssgrp.numrss::numeric = p_rss.no_rss
                    AND rssgrp.datesor::date = p_rss.date_sortie
                    AND p_rss.no_sejour_administratif IS DISTINCT FROM rssgrp.numnda
                ;
                     
                /**********************************************************************************
                 *                             MAJ DES PATIENTS                                   *
                 **********************************************************************************/
                 
                UPDATE [SCHEMA].p_rss SET 
                    no_patient = base.cti_to_number(patient.numipp)
                FROM 
                    prod_evolucare_opale.rssgrp
                    JOIN prod_evolucare_opale.patient ON patient.code = rssgrp.c_patient
                WHERE 1=1
                    AND rssgrp.numrss::numeric = p_rss.no_rss
                    AND rssgrp.datesor::date = p_rss.date_sortie
                    AND p_rss.import_id = [IMPORT_ID]
                    AND p_rss.ghm_id <> 0
                    AND p_rss.no_patient IS DISTINCT FROM base.cti_to_number(patient.numipp)
                ;
                
                
                -- Màj des noms, prénoms et nom de naissance des patients RSS AVEC GHM
                UPDATE [SCHEMA].p_identites SET
                    nom = patient.nomus,
                    prenom = patient.prenoms,
                    nom_naissance = patient.nomnaiss
                FROM [SCHEMA].p_rss,
                    prod_evolucare_opale.rssgrp,
                    prod_evolucare_opale.patient
                WHERE 1=1
                    AND p_identites.rss_id = p_rss.oid
                    AND rssgrp.numrss::numeric = p_rss.no_rss
                    AND rssgrp.datesor::date = p_rss.date_sortie
                    AND patient.code = rssgrp.c_patient
                    AND p_rss.import_id = [IMPORT_ID]
                    AND p_rss.ghm_id <> 0
                    AND (
                        nom IS DISTINCT FROM patient.nomus OR
                        prenom IS DISTINCT FROM patient.prenoms OR
                        nom_naissance IS DISTINCT FROM patient.nomnaiss
                    )
                ;
                
            ]]></sqlcmd>
        </NODE>
        <NODE label="Identites MEDSPHERE">
			<condition><![CDATA[
                "[WITH_MEDSPHERE]" != "0"
            ]]></condition>
            <sqlcmd><![CDATA[
			
				
            ]]></sqlcmd>
        </NODE>
        <NODE label="Médecins RSS MEDSPHERE">
			<condition><![CDATA[
                "[WITH_MEDSPHERE]" != "0"
            ]]></condition>
            <sqlcmd><![CDATA[ 
            
				DROP TABLE IF EXISTS w_SMV_MOUVEMENT_SEJOUR;
				CREATE TEMP TABLE w_SMV_MOUVEMENT_SEJOUR AS
				SELECT
					DADM_NDA,
					MIN(MVMT_DATEHEURE)::date AS w_MVMT_DATEHEURE,
					COALESCE((MIN(CASE WHEN TMVT_CODE = 'R' AND SMVT_CODE NOT IN ('A') AND MVMT_CHPNUM1 <> 0 THEN array[MVMT_DATEHEURE::text,MEDN_CODE::text] ELSE NULL END))[2],'0') AS MVMT_CHPNUM1_medecin,
					COALESCE((MAX(CASE WHEN TMVT_CODE = 'M' AND SMVT_CODE NOT IN ('A') AND MVMT_CHPNUM1 <> 0 THEN array[MVMT_DATEHEURE::text,NTMD_CODE::text] ELSE NULL END))[2],'0') AS MVMT_CHPNUM1_unite_medicale
				FROM prod_csis.SID_DOSSIERADMINISTRATIF_DADM
					JOIN prod_csis.SST_ETABLISSEMENT_ETAB ON ETAB_ID = DADM_ID_ETAB AND ETAB_FINESS = '[FINESS]'
					JOIN [SCHEMA].p_rss ON p_rss.no_sejour_administratif = DADM_NDA
					LEFT JOIN prod_csis.SMV_MOUVEMENT_MVMT ON MVMT_ID_DADM = DADM_ID  
					LEFT JOIN prod_csis.SMV_TYPEMOUVEMENT_TMVT ON MVMT_ID_TMVT = TMVT_ID
					LEFT JOIN prod_csis.SMV_STATUTMOUVEMENT_SMVT ON MVMT_ID_SMVT = SMVT_ID
					LEFT JOIN prod_csis.SCA_RESUMESS_RESS ON DADM_ID = RESS_ID_DADM
					LEFT JOIN prod_csis.SST_MEDECIN_MEDN ON MVMT_CHPNUM1 = MEDN_ID
					LEFT JOIN prod_csis.SST_UNITEMED_NTMD ON MVMT_CHPNUM1 = NTMD_ID
				WHERE 1=1
					AND p_rss.ghm_id = 0
				GROUP BY 1
				HAVING MIN(MVMT_DATEHEURE)::date = MIN(p_rss.date_sortie);
				
				
				INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, no_adeli, specialite_interne_id)
				WITH w_sst_medecin AS (
					SELECT MVMT_CHPNUM1_medecin AS w_recc_code_medn FROM w_SMV_MOUVEMENT_SEJOUR GROUP BY 1
				)
				SELECT   
					MEDN_CODE, 
					MAX(replace(MEDN_NOM, '''', ' ')) AS NOM, 
					MAX(replace(MEDN_PRENOM, '''', ' ')) AS PRENOM, 
					MAX(COALESCE(t_specialites_medecin.oid,0)),
					MAX(MEDN_CODEADELI),
					MAX(COALESCE(t_specialites_internes_medecin.oid,0))
				FROM prod_csis.sst_medecin_medn 
					JOIN w_sst_medecin ON w_recc_code_medn = MEDN_CODE
					LEFT JOIN prod_csis.SST_MEDETAB_METB ON METB_ID_MEDN = MEDN_ID
					LEFT JOIN prod_csis.SST_ETABLISSEMENT_ETAB ON METB_ID_ETAB = ETAB_ID 
					LEFT JOIN prod_csis.SNO_SPECIALITESS_SPSS ON  MEDN_ID_SPSS = SPSS_ID
					LEFT JOIN pmsi.t_specialites_medecin ON (t_specialites_medecin.code = SPSS_CODE)
					LEFT JOIN pmsi.t_specialites_internes_medecin ON (t_specialites_internes_medecin.code = SPSS_CODE || '..')
					LEFT JOIN pmsi.t_medecins ON t_medecins.code = MEDN_CODE
				WHERE 1=1
					AND MEDN_CODE <> ''
					AND t_medecins.code IS NULL 
				GROUP BY 1
				ORDER BY 1
				;
				
				UPDATE [SCHEMA].p_rss SET
					medecin_rss_id = t_medecins.oid
				FROM
					w_SMV_MOUVEMENT_SEJOUR
					JOIN pmsi.t_medecins ON t_medecins.code = w_SMV_MOUVEMENT_SEJOUR.MVMT_CHPNUM1_medecin
				WHERE 1=1
					AND p_rss.no_sejour_administratif = w_SMV_MOUVEMENT_SEJOUR.DADM_NDA
					AND medecin_rss_id = 0;
            
            ]]></sqlcmd>
        </NODE>
        <NODE label="Médecins actes">
            <sqlcmd><![CDATA[ 
            
            /**********************************************************************************
             *                        MAJ DES MEDECINS ACTES                                  *
             **********************************************************************************/
             
            UPDATE [SCHEMA].p_rss_actes
            SET medecin_id = t_medecins.oid
            FROM
                prod_evolucare_opale.rssgrp
                JOIN prod_evolucare_opale.releve ON releve.numrss = rssgrp.numrss::numeric 
                    AND releve.numnda = rssgrp.numnda
                JOIN prod_evolucare_opale.actes ON actes.c_releve = releve.code
                JOIN pmsi.t_actes ON substring(actes.ccamacte, 1, 7) = t_actes.code
                JOIN pmsi.t_medecins on t_medecins.code = actes.c_interv::text,
                [SCHEMA].p_rss
            WHERE 1=1
                AND p_rss_actes.rss_id = p_rss.oid
                AND p_rss_actes.acte_id = t_actes.oid
                AND p_rss.ghm_id <> 0
                AND p_rss.import_id = [IMPORT_ID]
                AND p_rss_actes.no_rum = releve.indice
                AND p_rss_actes.activite_ccam = actes.activite
                AND p_rss_actes.date_acte = actes.dateacte::date
                AND p_rss_actes.medecin_id IS DISTINCT FROM t_medecins.oid
            ;
            
            
            -- Màj des médecins RSS d'après les médecins actes si pas encore de médecin RSS dans p_rss 
            -- et qu'il y a des exécutants renseignés dans p_rss_actes
            -- On prend l'exécutant de l'acte avec le plus fort ICR
            DROP TABLE IF EXISTS w_executants;
            CREATE TEMP TABLE w_executants AS
            SELECT
                p_rss_actes.rss_id,
                (MAX(ARRAY[t_actes.icr_1, p_rss_actes.medecin_id]))[2] AS medecin_id
            FROM
                [SCHEMA].p_rss_actes
                JOIN pmsi.t_actes ON t_actes.oid = p_rss_actes.acte_id
                JOIN [SCHEMA].p_rss ON p_rss.oid = p_rss_actes.rss_id
            WHERE 1=1
                AND p_rss.medecin_rss_id = 0
                AND p_rss_actes.medecin_id != 0
                AND p_rss_actes.activite_ccam = '1'
            GROUP BY p_rss_actes.rss_id;
            
            UPDATE [SCHEMA].p_rss SET
                medecin_rss_id = w_executants.medecin_id
            FROM w_executants
            WHERE 1=1
                AND w_executants.rss_id = p_rss.oid
                AND p_rss.medecin_rss_id = 0;
            
            ]]></sqlcmd>
        </NODE>
        <NODE label="Medecins actes MEDSPHERE">
			<condition><![CDATA[
                "[WITH_MEDSPHERE]" != "0"
            ]]></condition>
            <sqlcmd><![CDATA[ 
            
            /**********************************************************************************
             *                        MAJ DES MEDECINS ACTES                                  *
             **********************************************************************************/
             
            DROP TABLE IF EXISTS w_dadm_actes;
			CREATE TEMP TABLE w_dadm_actes AS
			SELECT 
				DADM_NDA,
				date(DADM_DATEDEBUT) AS DADM_DATEDEBUT,
				date(DADM_DATEFIN) AS DADM_DATEFIN,
				date(RECC_DATEACTE) AS RECC_DATEACTE,
				COALESCE(RECC_CODECCAM,'') AS RECC_CODECCAM,
				RECC_CODEACTIVITE,
				RECC_ID_MEDN,
				MEDN_CODE,
				t_medecins.oid AS medecin_id
			FROM prod_csis.SID_DOSSIERADMINISTRATIF_DADM
				JOIN prod_csis.SST_ETABLISSEMENT_ETAB ON DADM_ID_ETAB = ETAB_ID AND ETAB_FINESS = '[FINESS]'
				JOIN prod_csis.MPM_RECUEILCCAM_RECC ON RECC_ID_DADM = DADM_ID
				JOIN prod_csis.SST_MEDECIN_MEDN ON RECC_ID_MEDN = MEDN_ID
				JOIN pmsi.t_medecins ON MEDN_CODE = t_medecins.code
			GROUP BY 1,2,3,4,5,6,7,8,9;
			
			INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, no_adeli, specialite_interne_id)
			WITH w_sst_medecin AS (
				SELECT RECC_ID_MEDN as w_recc_id_medn FROM w_dadm_actes GROUP BY 1
			)
			SELECT   
				MEDN_CODE, 
				MAX(replace(MEDN_NOM, '''', ' ')) AS NOM, 
				MAX(replace(MEDN_PRENOM, '''', ' ')) AS PRENOM, 
				MAX(COALESCE(t_specialites_medecin.oid,0)),
				MAX(MEDN_CODEADELI),
				MAX(COALESCE(t_specialites_internes_medecin.oid,0))
			FROM prod_csis.sst_medecin_medn 
				JOIN w_sst_medecin ON w_recc_id_medn = MEDN_ID
				LEFT JOIN prod_csis.SST_MEDETAB_METB ON METB_ID_MEDN = MEDN_ID
				LEFT JOIN prod_csis.SST_ETABLISSEMENT_ETAB ON METB_ID_ETAB = ETAB_ID 
				LEFT JOIN prod_csis.SNO_SPECIALITESS_SPSS ON  MEDN_ID_SPSS = SPSS_ID
				LEFT JOIN pmsi.t_specialites_medecin ON (t_specialites_medecin.code = SPSS_CODE)
				LEFT JOIN pmsi.t_specialites_internes_medecin ON (t_specialites_internes_medecin.code = SPSS_CODE || '..')
				LEFT JOIN pmsi.t_medecins ON t_medecins.code = MEDN_CODE
			WHERE 1=1
				AND MEDN_CODE <> ''
				AND t_medecins.code IS NULL 
			GROUP BY 1
			ORDER BY 1
			;
			
			
			UPDATE [SCHEMA].p_rss_actes
			SET medecin_id = w_dadm_actes.medecin_id
			FROM 
				w_dadm_actes
				JOIN pmsi.t_medecins ON t_medecins.code = w_dadm_actes.MEDN_CODE
				JOIN [SCHEMA].p_rss ON no_sejour_administratif = DADM_NDA,
				pmsi.t_actes
			WHERE acte_id = t_actes.oid AND 
				p_rss_actes.rss_id = p_rss.oid AND
				p_rss.en_cours LIKE '0' AND
				(p_rss.date_sortie = dadm_datefin OR p_rss.date_entree = dadm_datedebut) AND
				t_actes.code = substring(RECC_CODECCAM, 1, 7) AND 
				activite_ccam = RECC_CODEACTIVITE AND 
				date_acte = RECC_DATEACTE AND
				p_rss_actes.medecin_id = 0; 
            
            ]]></sqlcmd>
        </NODE>
        <NODE label="UM externes MEDSPHERE">
			<condition><![CDATA[
                "[WITH_MEDSPHERE]" != "0"
            ]]></condition>
            <sqlcmd><![CDATA[ 
            
            INSERT INTO pmsi.t_unites_medicales(code, texte)
			WITH w_sst_um AS (
				SELECT MVMT_CHPNUM1_unite_medicale AS w_code_um FROM w_SMV_MOUVEMENT_SEJOUR GROUP BY 1
			)
			SELECT
				NTMD_CODE,
				NTMD_LIBELLE
			FROM 
				prod_csis.SST_UNITEMED_NTMD
				JOIN prod_csis.SST_ETABLISSEMENT_ETAB ON ETAB_ID = NTMD_ID_ETAB AND ETAB_FINESS = '[FINESS]'
				JOIN w_sst_um ON w_code_um = NTMD_CODE
				LEFT JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = NTMD_CODE
			WHERE 
				t_unites_medicales.code IS NULL
            ;
			
			UPDATE [SCHEMA].p_rss_rum SET
				unite_medicale = t_unites_medicales.code
				,unite_medicale_id = t_unites_medicales.oid
			FROM
				pmsi.p_rss
				JOIN w_SMV_MOUVEMENT_SEJOUR ON p_rss.no_sejour_administratif = w_SMV_MOUVEMENT_SEJOUR.DADM_NDA
				JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = MVMT_CHPNUM1_unite_medicale
			WHERE 1=1
				AND p_rss.oid = p_rss_rum.rss_id
				AND p_rss.ghm_id = 0
				AND p_rss_rum.unite_medicale_id = 0;
            
            ]]></sqlcmd>
        </NODE>
            
    </NODE>
    <NODE name="PMSIENCOURS" label="RECUPERATION DES DOSSIERS PMSI EN-COURS EVOLUCARE OPALE">
        <NODE label="Tests des options installees">
            <sqlcmd><![CDATA[ 
				
                CTISELECT_PROPERTY_READ 'WITH_MEDSPHERE', count(*) 
                FROM information_schema.tables
                WHERE table_schema = 'prod_csis' AND table_name = 'sid_dossieradministratif_dadm' ;
                
                echo MEDSPHERE : [WITH_MEDSPHERE];
        
            ]]></sqlcmd>
        </NODE>
        <NODE label="Paramètres">
            <sqlcmd><![CDATA[
                
                /*******************************************************************************
                 *                           SPECIALITES MEDECIN                               *
                 *******************************************************************************/
                
                -- Récupération des spécialites officielles
                DROP TABLE IF EXISTS w_specialite
                ;
                CREATE TEMP TABLE w_specialite AS
                    SELECT
                        to_char(special.code, 'FM09') AS code,
                        to_char(special.code, 'FM09') || '..'::text AS code_interne,
                        special.libelle AS texte
                    FROM
                        prod_evolucare_opale.special
                ;
                
                -- Insertion des nouvelles spécialités officielles
                INSERT INTO pmsi.t_specialites_medecin(code, texte)
                SELECT 
                    w_specialite.code, 
                    w_specialite.texte
                FROM 
                    w_specialite
                    LEFT JOIN pmsi.t_specialites_medecin ON t_specialites_medecin.code = w_specialite.code
                WHERE t_specialites_medecin.code IS NULL
                ;
                
                -- Màj des spécialités officielles créées via import PMSI
                UPDATE pmsi.t_specialites_medecin
                SET texte = w_specialite.texte
                FROM w_specialite
                WHERE t_specialites_medecin.code = w_specialite.code
                    AND t_specialites_medecin.code = t_specialites_medecin.texte
                ;
                
                -- Récupération des spécialites internes
                INSERT INTO pmsi.t_specialites_internes_medecin(code, texte)
                SELECT 
                    w_specialite.code_interne,
                    w_specialite.texte
                FROM 
                    w_specialite
                    LEFT JOIN pmsi.t_specialites_internes_medecin ON
                         w_specialite.code_interne = t_specialites_internes_medecin.code
                WHERE
                    t_specialites_internes_medecin.code IS NULL
                ;
                
                -- FIN boulot actuel
                
                /**********************************************************************************
                 *                                MAJ MEDECINS                                    *
                 **********************************************************************************/
                -- Récupération des médecins
                DROP TABLE IF EXISTS w_medecin
                ;
                
                CREATE TEMP TABLE w_medecin AS
                    SELECT
                        interv.code,
                        interv.nom,
                        interv.prenom,
                        replace(interv.numadeli, ' ', '') as no_adeli,
                        COALESCE(t_specialites_medecin.oid, 0) as specialite_id,
                        COALESCE(t_specialites_internes_medecin.oid, 0) as specialite_interne_id
                    FROM
                        prod_evolucare_opale.interv
                        LEFT JOIN pmsi.t_specialites_medecin ON t_specialites_medecin.code = to_char(interv.c_special, 'FM09')
                        LEFT JOIN pmsi.t_specialites_internes_medecin ON t_specialites_internes_medecin.code = to_char(interv.c_special, 'FM09') || '..'::text
                    GROUP BY 1,2,3,4,5,6;
                
                CREATE INDEX w_medecin_i1
                  ON w_medecin
                  USING btree
                  (code)
                ;
                
                -- Insertion des nouveaux médecins
                INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, no_adeli, specialite_interne_id)
                SELECT
                    w_medecin.code::text,
                    w_medecin.nom,
                    w_medecin.prenom,
                    w_medecin.specialite_id,
                    w_medecin.no_adeli,
                    w_medecin.specialite_interne_id
                FROM w_medecin
                    LEFT JOIN pmsi.t_medecins ON t_medecins.code = w_medecin.code
                WHERE
                    t_medecins.code IS NULL;
                
                SELECT pmsi.cti_reorganize_medecins_c()
                ;
                
                /******************************************************************************
                 *                             UNITES MEDICALES                               *
                 ******************************************************************************/
                
                DROP TABLE IF EXISTS w_um
                ;
                
                CREATE TEMP TABLE w_um AS
                    SELECT
                        unite.code as oid,
                        unite.libelle as texte,
                        unite.libexport as code,
                        base.cti_to_number(unite.nblit) as nblit,
                        unite.dateeff::date,
                        COALESCE(t_types_autorisations.code, ''::text) as type_autorisation
                    FROM prod_evolucare_opale.unite
                        LEFT JOIN pmsi.t_types_autorisations ON t_types_autorisations.code = to_char(unite.c_typautum, 'FM09')
                    GROUP BY 1,2,3,4,5,6
                ;
                
                CREATE INDEX w_um_i1
                  ON w_um
                  USING btree
                  (oid)
                ;
                
                CREATE INDEX w_um_i2
                  ON w_um
                  USING btree
                  (code)
                ;
                
                -- Insertion des nouvelles UM
                INSERT INTO pmsi.t_unites_medicales(code, texte, type_autorisation, date_effet_autorisation, nb_lits)
                    SELECT
                        w_um.code,
                        w_um.texte,
                        w_um.type_autorisation,
                        w_um.dateeff,
                        w_um.nblit
                    FROM 
                        w_um
                        LEFT JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = w_um.code
                    WHERE 
                        t_unites_medicales.code IS NULL
                ;
                
                -- Màj libellés UM quand UM créée via import PMSI
                UPDATE pmsi.t_unites_medicales SET 
                    texte = w_um.texte
                FROM w_um
                WHERE
                    t_unites_medicales.code = w_um.code
                    AND t_unites_medicales.texte = t_unites_medicales.code
                    AND t_unites_medicales.texte != w_um.texte
                ;
                
                /******************************************************************************
                 *                                 PATIENTS                                   *
                 ******************************************************************************/
                
                DROP TABLE IF EXISTS w_patient;
                CREATE TEMP TABLE w_patient AS
                SELECT
                    patient.code,
                    patient.numid,
                    patient.numipp,
                    patient.numsecu,
                    patient.ddn,
                    patient.sexe,
                    patient.nomnaiss,
                    patient.nomus,
                    patient.prenoms,
                    patient.codepostal
                FROM
                    prod_evolucare_opale.patient
                GROUP BY 1,2,3,4,5,6,7,8,9,10;
                
                CREATE INDEX w_patient_i1 ON w_patient USING btree (code);
                
            ]]></sqlcmd>
        </NODE>
        <NODE label="RSS">
            <sqlcmd><![CDATA[
                
                /*********************************************************************************
                 *                            SELECTION DES RSS A CREER                          *
                 *********************************************************************************/
                
                DROP TABLE IF EXISTS w_select;
                CREATE TEMP TABLE w_select AS
                    SELECT
                        rssgrp.code,
                        rssgrp.numrss,
                        rssgrp.numnda
                    FROM prod_evolucare_opale.rssgrp
                        LEFT JOIN pmsi.p_rss
                            ON  rssgrp.numrss::numeric = p_rss.no_rss
                            AND rssgrp.datesor::date = p_rss.date_sortie
                    WHERE 1=1
                        AND p_rss.no_rss IS NULL
                        AND rssgrp.datesor >= '[ANNEE]0101'::date
                        AND rssgrp.nbrum > 0
                    GROUP BY 1,2,3
                ;
                
                CREATE INDEX w_select_i1 ON w_select USING btree (code);
                
                -- Il y a des lignes dédoublées dans RSSGRP, certainement quand les séjours sont groupés non validés.
                -- les groupés validés n'ont qu'une ligne
                -- les groupés non validés ont une ligne avec un GHM/GHS défini et une autre avec un GHS 9999
                -- les non groupés n'ont qu'une ligne avec un GHS 9999
                -- Peut-être faudrait-il plutôt exploiter le champ GPRET de la table RELEVE
                DROP TABLE IF EXISTS w_rssgrp;
                CREATE TEMP TABLE w_rssgrp AS
                SELECT
                    rssgrp.numrss,
                    rssgrp.numnda,
                    rssgrp.dateent,
                    rssgrp.datesor,
                    rssgrp.numfiness,
                    rssgrp.c_patient,
                    MIN(rssgrp.gpghs) as gpghs,
                    (MIN(array[rssgrp.gpghs, rssgrp.gpcmd]))[2] as gpcmd,
                    (MIN(array[rssgrp.gpghs, rssgrp.gpghm]))[2] as gpghm,
                    count(DISTINCT gpghs) as nbgrp
                FROM
                    prod_evolucare_opale.rssgrp
                    JOIN w_select ON w_select.code = rssgrp.code
                GROUP BY 1,2,3,4,5,6
                ORDER BY 1;
                
                CREATE INDEX w_rssgrp_i1 ON w_rssgrp USING btree (c_patient);
                
                
                DROP TABLE IF EXISTS w_rss;
                CREATE TEMP TABLE w_rss AS
                SELECT
                    nextval('pmsi.s_rss'::regclass) as rss_id,
                    w_rssgrp.numrss,
                    base.cti_to_number(w_rssgrp.numrss) as no_rss,
                    w_rssgrp.numnda,
                    w_rssgrp.dateent::date,
                    w_rssgrp.datesor::date,
                    w_rssgrp.gpcmd,
                    w_rssgrp.gpcmd || w_rssgrp.gpghm as ghm,
                    w_rssgrp.gpghs as ghs,
                    w_rssgrp.numfiness,
                    w_rssgrp.nbgrp,
                    base.cti_to_number(w_patient.numipp) as numipp,
                    w_patient.ddn,
                    w_patient.codepostal,
                    w_patient.sexe,
                    w_patient.nomnaiss,
                    w_patient.nomus,
                    w_patient.prenoms
                FROM
                    w_rssgrp
                    JOIN w_patient ON w_patient.code = w_rssgrp.c_patient;
                    
                CREATE INDEX w_rss_i1 ON w_rss USING btree (ghm);
                CREATE INDEX w_rss_i2 ON w_rss USING btree (ghs);
                CREATE INDEX w_rss_i3 ON w_rss USING btree (codepostal);
                
                
                INSERT INTO pmsi.p_rss (
                    age,
                    base_remboursement,
                    ca_exb,
                    ca_exh,
                    ca_ghs,
                    ca_ghs_theorique,
                    ca_neonat,
                    ca_rea,
                    ca_si,
                    ca_sur,
                    cma,
                    code_postal,
                    code_postal_id,
                    coefficient_prudentiel_theorique,
                    confirmation_codage,
                    date_entree,
                    date_import,
                    date_naissance,
                    date_sortie,
                    dmi_facture,
                    duree_sejour,
                    en_cours,
                    en_cours_etat,
                    finess,
                    forfait_facture,
                    ghm_fg9,
                    ghm_id,
                    ghm_production_id,
                    ghs_id,
                    groupe_ghm,
                    honoraires_factures,
                    import_id,
                    mois_sortie,
                    nb_exb,
                    nb_exh,
                    nb_ghs,
                    nb_ghsmin,
                    nb_neonat,
                    nb_rea,
                    nb_rsa,
                    nb_rum,
                    nb_seances,
                    nb_si,
                    nb_sur,
                    no_patient,
                    no_rss,
                    no_sejour_administratif,
                    nombre_ivg_anterieures,
                    numero_innovation,
                    oid,
                    patient_id,
                    phc_facture,
                    poids_bebe,
                    secteur,
                    sejour_facture,
                    sexe,
                    supprime,
                    t2a_facture,
                    type_dosimetrie,
                    type_machine_rdth,
                    version_groupage
                )
                SELECT
                    date_part('year', age(w_rss.dateent, w_rss.ddn)) as age,
                    0::numeric as base_remboursement,
                    0::numeric as ca_exb,
                    0::numeric as ca_exh,
                    0::numeric as ca_ghs,
                    0::numeric as ca_ghs_theorique,
                    0::numeric as ca_neonat,
                    0::numeric as ca_rea,
                    0::numeric as ca_si,
                    0::numeric as ca_sur,
                    ''::text as cma,
                    COALESCE(t_codes_postaux_c.code, chr(127) || '****'::text) as code_postal,
                    COALESCE(t_codes_postaux_c.oid, 0::bigint) as code_postal_id,
                    CASE 
                        WHEN w_rss.datesor::date >= '20160301'::date THEN 0.9950
                        WHEN w_rss.datesor::date >= '20130301'::date THEN 0.9965
                        ELSE 1 END as coefficient_prudentiel_theorique,
                    ''::text as confirmation_codage,
                    w_rss.dateent as date_entree,
                    NOW()::date as date_import,
                    w_rss.ddn::date as date_naissance,
                    w_rss.datesor::date as date_sortie,
                    0::numeric as dmi_facture,
                    w_rss.datesor::date - w_rss.dateent::date as duree_sejour,
                    '1'::text as en_cours,
                    CASE
                        WHEN w_rss.nbgrp = 1 AND w_rss.ghs = '9999' THEN 'S'::text
                        WHEN w_rss.nbgrp > 1 THEN 'G'::text
                        ELSE 'V'::text END as en_cours_etat,
                    w_rss.numfiness as finess,
                    0::numeric as forfait_facture,
                    ''::text as ghm_fg9,
                    COALESCE(t_ghm.oid, 0) as ghm_id,
                    COALESCE(t_ghm.oid, 0) as ghm_production_id,
                    COALESCE(t_ghs.oid, 0) as ghs_id,
                    ''::text as groupe_ghm,
                    0::numeric as honoraires_factures,
                    -1::bigint as import_id,
                    to_number(to_char(w_rss.datesor::date, 'YYYYMM'), '999999') as mois_sortie,
                    0::bigint as nb_exb,
                    0::bigint as nb_exh,
                    0::bigint as nb_ghs,
                    0::bigint as nb_ghsmin,
                    0::bigint as nb_neonat,
                    0::bigint as nb_rea,
                    1::bigint as nb_rsa,
                    0::bigint as nb_rum,
                    0::bigint as nb_seances,
                    0::bigint as nb_si,
                    0::bigint as nb_sur,
                    w_rss.numipp as no_patient,
                    w_rss.no_rss as no_rss,
                    w_rss.numnda as no_sejour_administratif,
                    0::bigint as nombre_ivg_anterieures,
                    ''::text as numero_innovation,
                    w_rss.rss_id as oid,
                    0::bigint as patient_id,
                    0::numeric as phc_facture,
                    0::numeric as poids_bebe,
                    ''::text as secteur,
                    0::numeric as sejour_facture,
                    w_rss.sexe as sexe,
                    ''::text as supprime,
                    0::numeric as t2a_facture,
                    ''::text as type_dosimetrie,
                    ''::text as type_machine_rdth,
                    ''::text as version_groupage
                FROM 
                    w_rss
                    LEFT JOIN pmsi.t_codes_postaux_c ON t_codes_postaux_c.code = w_rss.codepostal
                    LEFT JOIN pmsi.t_ghm ON t_ghm.code = w_rss.ghm
                    LEFT JOIN pmsi.t_ghs ON t_ghs.code = w_rss.ghs
                ;
                
            ]]></sqlcmd>
        </NODE>
        <NODE label="Medecins RSS MEDSPHERE">
			<condition><![CDATA[
                "[WITH_MEDSPHERE]" != "0"
            ]]></condition>
            <sqlcmd><![CDATA[ 
            
				DROP TABLE IF EXISTS w_SMV_MOUVEMENT_SEJOUR;
				CREATE TEMP TABLE w_SMV_MOUVEMENT_SEJOUR AS
				SELECT
					DADM_NDA,
					MIN(MVMT_DATEHEURE)::date AS w_MVMT_DATEHEURE,
					COALESCE((MIN(CASE WHEN TMVT_CODE = 'R' AND SMVT_CODE NOT IN ('A') AND MVMT_CHPNUM1 <> 0 THEN array[MVMT_DATEHEURE::text,MEDN_CODE::text] ELSE NULL END))[2],'0') AS MVMT_CHPNUM1_medecin,
					COALESCE((MAX(CASE WHEN TMVT_CODE = 'M' AND SMVT_CODE NOT IN ('A') AND MVMT_CHPNUM1 <> 0 THEN array[MVMT_DATEHEURE::text,NTMD_CODE::text] ELSE NULL END))[2],'0') AS MVMT_CHPNUM1_unite_medicale
				FROM prod_csis.SID_DOSSIERADMINISTRATIF_DADM
					JOIN prod_csis.SST_ETABLISSEMENT_ETAB ON ETAB_ID = DADM_ID_ETAB AND ETAB_FINESS = '[FINESS]'
					JOIN pmsi.p_rss ON p_rss.no_sejour_administratif = DADM_NDA
					LEFT JOIN prod_csis.SMV_MOUVEMENT_MVMT ON MVMT_ID_DADM = DADM_ID  
					LEFT JOIN prod_csis.SMV_TYPEMOUVEMENT_TMVT ON MVMT_ID_TMVT = TMVT_ID
					LEFT JOIN prod_csis.SMV_STATUTMOUVEMENT_SMVT ON MVMT_ID_SMVT = SMVT_ID
					LEFT JOIN prod_csis.SCA_RESUMESS_RESS ON DADM_ID = RESS_ID_DADM
					LEFT JOIN prod_csis.SST_MEDECIN_MEDN ON MVMT_CHPNUM1 = MEDN_ID
					LEFT JOIN prod_csis.SST_UNITEMED_NTMD ON MVMT_CHPNUM1 = NTMD_ID
				WHERE 1=1
					AND p_rss.en_cours = '1'
				GROUP BY 1
				HAVING MIN(MVMT_DATEHEURE)::date = MIN(p_rss.date_sortie);
				
				
				INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, no_adeli, specialite_interne_id)
				WITH w_sst_medecin AS (
					SELECT MVMT_CHPNUM1_medecin AS w_recc_code_medn FROM w_SMV_MOUVEMENT_SEJOUR GROUP BY 1
				)
				SELECT   
					MEDN_CODE, 
					MAX(replace(MEDN_NOM, '''', ' ')) AS NOM, 
					MAX(replace(MEDN_PRENOM, '''', ' ')) AS PRENOM, 
					MAX(COALESCE(t_specialites_medecin.oid,0)),
					MAX(MEDN_CODEADELI),
					MAX(COALESCE(t_specialites_internes_medecin.oid,0))
				FROM prod_csis.sst_medecin_medn 
					JOIN w_sst_medecin ON w_recc_code_medn = MEDN_CODE
					LEFT JOIN prod_csis.SST_MEDETAB_METB ON METB_ID_MEDN = MEDN_ID
					LEFT JOIN prod_csis.SST_ETABLISSEMENT_ETAB ON METB_ID_ETAB = ETAB_ID 
					LEFT JOIN prod_csis.SNO_SPECIALITESS_SPSS ON  MEDN_ID_SPSS = SPSS_ID
					LEFT JOIN pmsi.t_specialites_medecin ON (t_specialites_medecin.code = SPSS_CODE)
					LEFT JOIN pmsi.t_specialites_internes_medecin ON (t_specialites_internes_medecin.code = SPSS_CODE || '..')
					LEFT JOIN pmsi.t_medecins ON t_medecins.code = MEDN_CODE
				WHERE 1=1
					AND MEDN_CODE <> ''
					AND t_medecins.code IS NULL 
				GROUP BY 1
				ORDER BY 1
				;
				
				UPDATE pmsi.p_rss SET
					medecin_rss_id = t_medecins.oid
				FROM
					w_SMV_MOUVEMENT_SEJOUR
					JOIN pmsi.t_medecins ON t_medecins.code = w_SMV_MOUVEMENT_SEJOUR.MVMT_CHPNUM1_medecin
				WHERE 1=1
					AND p_rss.no_sejour_administratif = w_SMV_MOUVEMENT_SEJOUR.DADM_NDA
					AND medecin_rss_id = 0;
            
            ]]></sqlcmd>
        </NODE>
        <NODE label="Identités">
            <sqlcmd><![CDATA[
                
                INSERT INTO pmsi.p_identites(
                        finess,
                        rss_id,
                        no_rss,
                        nom,
                        prenom,
                        nom_naissance)
                SELECT
                        w_rss.numfiness AS finess,
                        w_rss.rss_id AS rss_id,
                        w_rss.no_rss AS no_rss,
                        w_rss.nomus AS nom,
                        w_rss.prenoms AS prenom,
                        w_rss.nomnaiss AS nom_naissance
                FROM w_rss
                ;
                
            ]]></sqlcmd>
        </NODE>
        <NODE label="Rum">
            <sqlcmd><![CDATA[ 
                
                DROP TABLE IF EXISTS w_releve
                ;
                CREATE TEMP TABLE w_releve AS 
                SELECT
                    releve.code,
                    releve.numfiness,
                    releve.numrss,
                    w_rss.no_rss,
                    releve.numnda,
                    releve.indice,
                    releve.numid,
                    COALESCE(unite.libexport, ''::text) as unite,
                    COALESCE(f_typeautum.codeexp, ''::text) as typeaut,
                    releve.dateent::date,
                    releve.datesor::date,
                    COALESCE(f_modeent.codexp, '8'::text) as modeent,
                    COALESCE(f_modesor.codexp, '8'::text) as modesor,
                    COALESCE(f_destinat.codexp, ''::text) as destinat,
                    COALESCE(f_provenan.codexp, ''::text) as provenan,
                    w_rss.rss_id,
                    MAX(releve.nbdas) as nbdas,
                    MAX(releve.nbseance) as nbseance,
                    (MIN(ARRAY[releve.gpghs, w_rss.gpcmd]))[2] as cmd,
                    (MIN(ARRAY[releve.gpghs, releve.dp]))[2] as dp,
                    (MIN(ARRAY[releve.gpghs, releve.dr]))[2] as dr,
                    base.cti_to_number(MAX(releve.igs2)) as igs2
                FROM
                    prod_evolucare_opale.releve
                    JOIN w_rss
                        ON releve.numrss = w_rss.numrss
                        AND releve.numnda = w_rss.numnda
                    LEFT JOIN prod_evolucare_opale.unite ON unite.code = releve.c_unite
                    LEFT JOIN prod_evolucare_opale.f_typeautum ON f_typeautum.code = unite.c_typautum
                    LEFT JOIN prod_evolucare_opale.f_modeent ON f_modeent.code = releve.c_modeent
                    LEFT JOIN prod_evolucare_opale.f_modesor ON f_modesor.code = releve.c_modesor
                    LEFT JOIN prod_evolucare_opale.f_destinat ON f_destinat.code = releve.c_destinat
                    LEFT JOIN prod_evolucare_opale.f_provenan ON f_provenan.code = releve.c_provenan
                GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16;
                
                CREATE INDEX w_releve_i1 ON w_releve USING btree (code);
                
                INSERT INTO pmsi.p_rss_rum(
                    date_entree,
                    date_sortie,
                    destination,
                    diagnostic_principal_id,
                    diagnostic_relie_id,
                    duree_sejour,
                    finess,
                    igs2,
                    mode_entree,
                    mode_sortie,
                    nb_seances,
                    no_rss,
                    no_rum,
                    provenance,
                    rss_id,
                    type_autorisation,
                    unite_medicale,
                    unite_medicale_id
                    )
                SELECT
                    w_releve.dateent as date_entree,
                    w_releve.datesor as date_sortie,
                    w_releve.destinat as destination,
                    COALESCE(diag_p.oid, 0) as diagnostic_principal_id,
                    COALESCE(diag_r.oid, 0) as diagnostic_relie_id,
                    w_releve.datesor - w_releve.dateent as duree_sejour,
                    w_releve.numfiness as finess,
                    w_releve.igs2 as igs2,
                    w_releve.modeent as mode_entree,
                    w_releve.modesor as mode_sortie,
                    w_releve.nbseance as nb_seances,
                    w_releve.no_rss as no_rss,
                    w_releve.indice as no_rum,
                    w_releve.provenan as provenance,
                    w_releve.rss_id,
                    COALESCE(t_unites_medicales.type_autorisation, ''::text) as type_autorisation,
                    COALESCE(t_unites_medicales.code, chr(127) || '***'::text) as unite_medicale,
                    COALESCE(t_unites_medicales.oid, 0) as unite_medicale_id
                FROM
                    w_releve
                    LEFT JOIN pmsi.t_diagnostics diag_p ON diag_p.code = w_releve.dp
                    LEFT JOIN pmsi.t_diagnostics diag_r ON diag_r.code = w_releve.dr
                    LEFT JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = w_releve.unite
                ;
                
                -- Mise à jour des infos dans p_rss
                
                DROP TABLE IF EXISTS w_rss_rum;
                CREATE TEMP TABLE w_rss_rum AS
                SELECT 
                    w_releve.rss_id, 
                    count(*) AS nb_rum, 
                    MIN(indice) AS no_premier_rum,  
                    MAX(indice) AS no_dernier_rum,
                    (MIN(ARRAY[indice::text, modeent::text]))[2] as modeent,
                    (MIN(ARRAY[indice::text, provenan::text]))[2] as provenan,
                    (MAX(ARRAY[indice::text, modesor::text]))[2] as modesor,
                    (MAX(ARRAY[indice::text, destinat::text]))[2] as destinat,
                    SUM(w_releve.nbseance) as nbseance,
                    SUM(w_releve.igs2) as igs2,
                    MAX(w_releve.cmd) as cmd,
                    MAX(w_releve.dp) as dp,
                    MAX(w_releve.dr) as dr,
                    MAX(w_releve.unite) as unite
                FROM 
                    w_releve
                GROUP BY 1;
                
                UPDATE pmsi.p_rss SET
                    nb_rum = w_rss_rum.nb_rum,
                    mode_entree = w_rss_rum.modeent,
                    mode_sortie = w_rss_rum.modesor,
                    provenance = w_rss_rum.provenan,
                    destination = w_rss_rum.destinat,
                    nb_seances = w_rss_rum.nbseance,
                    igs2 = w_rss_rum.igs2,
                    nb_rsa = GREATEST(p_rss.nb_rsa, CASE WHEN w_rss_rum.cmd = '28' THEN w_rss_rum.nbseance ELSE p_rss.nb_rsa END)
                FROM
                    w_rss_rum
                WHERE
                    w_rss_rum.rss_id = p_rss.oid;
                    
                -- Pour les mono-RUM, on met à jour DP/DR et UMP
                
                WITH w_update AS (
                    SELECT
                        w_rss_rum.rss_id,
                        COALESCE(diag_p.oid, 0::bigint) as dp_id,
                        COALESCE(diag_r.oid, 0::bigint) as dr_id,
                        COALESCE(um.oid, 0::bigint) as um_id,
                        w_rss_rum.no_premier_rum as rum_principal
                    FROM
                        w_rss_rum
                        LEFT JOIN pmsi.t_diagnostics diag_p ON diag_p.code = w_rss_rum.dp
                        LEFT JOIN pmsi.t_diagnostics diag_r ON diag_r.code = w_rss_rum.dr
                        LEFT JOIN pmsi.t_unites_medicales um ON um.code = w_rss_rum.unite
                    WHERE
                        w_rss_rum.nb_rum = 1
                )
                UPDATE pmsi.p_rss SET
                    diagnostic_principal_id = w_update.dp_id,
                    diagnostic_relie_id = w_update.dr_id,
                    unite_medicale_principale_id = w_update.um_id,
                    no_rum_principal = w_update.rum_principal
                FROM
                    w_update
                WHERE 1=1
                    AND w_update.rss_id = p_rss.oid;
                
                
            ]]></sqlcmd>
        </NODE>
        <NODE label="Diagnostics">
            <sqlcmd><![CDATA[
                
                -- LeS DAS sont dans la table DIAG
                DROP TABLE IF EXISTS w_diag;
                CREATE TEMP TABLE w_diag AS
                SELECT
                    diag.codediag as diag,
                    w_releve.numfiness,
                    w_releve.no_rss,
                    w_releve.indice,
                    w_releve.rss_id,
                    'DA'::text as diagtype,
                    'DA'::text as diagtyperss,
                    w_releve.unite
                FROM
                    prod_evolucare_opale.diag
                    JOIN w_releve ON w_releve.code = diag.c_releve
                GROUP BY 1,2,3,4,5,6,7,8
                ;
                
                -- Les DP/DR sont dans RELEVE
                -- Pour élire le DP RSS, on prend le DP du premier RUM (à l'arrache, sans s'embeter quoi)
                INSERT INTO w_diag
                    SELECT
                        w_releve.dp as diag,
                        w_releve.numfiness,
                        w_releve.no_rss,
                        w_releve.indice,
                        w_releve.rss_id,
                        'DP'::text as diagtype,
                        CASE WHEN w_releve.indice = 1 THEN 'DP'::text ELSE 'DA'::text END as diagtyperss,
                        w_releve.unite
                    FROM
                        w_releve
                    WHERE
                        w_releve.dp != ''::text
                UNION ALL
                    SELECT
                        w_releve.dr as diag,
                        w_releve.numfiness,
                        w_releve.no_rss,
                        w_releve.indice,
                        w_releve.rss_id,
                        'DR'::text as diagtype,
                        'DR'::text as diagtyperss,
                        w_releve.unite
                    FROM
                        w_releve
                    WHERE
                        w_releve.dr != ''::text;
                    
                INSERT INTO pmsi.p_rss_diagnostics(
                    diagnostic_id,
                    finess,
                    imprecis,
                    no_rss,
                    no_rum,
                    rss_id,
                    type_diagnostic,
                    type_diagnostic_rss,
                    unite_medicale,
                    unite_medicale_id
                )
                SELECT
                    COALESCE(t_diagnostics.oid, 0::bigint) as diagnostic_id,
                    w_diag.numfiness as finess,
                    ''::text as imprecis,
                    w_diag.no_rss as no_rss,
                    w_diag.indice as no_rum,
                    w_diag.rss_id as rss_id,
                    w_diag.diagtype as type_diagnostic,
                    w_diag.diagtyperss as type_diagnostic_rss,
                    COALESCE(t_unites_medicales.code, chr(127) || '***'::text) as unite_medicale,
                    COALESCE(t_unites_medicales.oid, 0::bigint) as unite_medicale_id
                FROM
                    w_diag
                    LEFT JOIN pmsi.t_diagnostics ON t_diagnostics.code = w_diag.diag
                    LEFT JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = w_diag.unite
                ;
                
            ]]></sqlcmd>
        </NODE>
        <NODE label="Actes">
            <sqlcmd><![CDATA[
                
                WITH w_actes AS (
                    SELECT
                        w_releve.numfiness,
                        w_releve.rss_id,
                        w_releve.no_rss,
                        w_releve.indice,
                        w_releve.unite,
                        actes.dateacte::date,
                        actes.c_interv,
                        actes.ccamacte,
                        actes.abbr_desc,
                        actes.nb,
                        actes.ccamphase,
                        actes.activite,
                        actes.extdoc,
                        actes.rmbstex,
                        actes.assocnp
                    FROM
                        prod_evolucare_opale.actes
                        JOIN w_releve ON w_releve.code = actes.c_releve
                )
                INSERT INTO pmsi.p_rss_actes(
                    finess,
                    rss_id,
                    no_rss,
                    no_rum,
                    unite_medicale,
                    unite_medicale_id,
                    date_acte,
                    medecin_id,
                    acte_id,
                    nombre,
                    phase_ccam,
                    activite_ccam,
                    extension_ccam,
                    modificateur_ccam_1,
                    modificateur_ccam_2,
                    modificateur_ccam_3,
                    modificateur_ccam_4,
                    remboursement_excp_ccam,
                    association_nonprevue_ccam
                )
                SELECT
                    w_actes.numfiness as finess,
                    w_actes.rss_id as rss_id,
                    w_actes.no_rss as no_rss,
                    w_actes.indice as no_rum,
                    COALESCE(t_unites_medicales.code, chr(127) || '***'::text) as unite_medicale,
                    COALESCE(t_unites_medicales.oid, 0::bigint) as unite_medicale_id,
                    w_actes.dateacte as date_acte,
                    COALESCE(t_medecins.oid, 0::bigint) as medecin_id,
                    t_actes.oid as acte_id,
                    w_actes.nb as nombre,
                    w_actes.ccamphase as phase_ccam,
                    w_actes.activite as activite_ccam,
                    w_actes.extdoc as extension_ccam,
                    ''::text as modificateur_ccam_1,
                    ''::text as modificateur_ccam_2,
                    ''::text as modificateur_ccam_3,
                    ''::text as modificateur_ccam_4,
                    w_actes.rmbstex as remboursement_excp_ccam,
                    w_actes.assocnp as association_nonprevue_ccam
                FROM
                    w_actes
                    JOIN pmsi.t_actes ON t_actes.code = w_actes.ccamacte
                    LEFT JOIN pmsi.t_medecins ON t_medecins.code = w_actes.c_interv
                    LEFT JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = w_actes.unite
                ;

            ]]></sqlcmd>
        </NODE>
        <NODE label="Factures">
            <sqlcmd><![CDATA[
            
                INSERT INTO pmsi.p_rsf_total (
                    base_remboursement,
                    ca_exb,
                    ca_exh,
                    ca_ghs,
                    ca_neonat,
                    ca_rea,
                    ca_sur,
                    code_gestion,
                    code_pec,
                    code_regularisation,
                    dmi_facture,
                    facturation_18euros,
                    finess,
                    forfait_facture,
                    honoraires_factures,
                    honoraires_remboursable,
                    honoraires_remboursable_2,
                    justificatif_exo,
                    montant_dmi_ghs2006,
                    nature_pec,
                    nb_exb,
                    nb_exh,
                    nb_ghs,
                    nb_ghsmin,
                    nb_neonat,
                    nb_rea,
                    nb_si,
                    nb_sur,
                    no_at_date_adc,
                    no_facture,
                    no_facture_sejour_mere,
                    no_organisme_complementaire,
                    no_rss,
                    participation_assure_avant_oc,
                    pat_benef_cmu,
                    phc_facture,
                    rang_beneficiaire,
                    regime,
                    rss_id,
                    sejour_facture,
                    sejour_remboursable,
                    sejour_remboursable_2,
                    t2a_facture,
                    valorise_fides
                )
                SELECT
                    0::numeric as base_remboursement,
                    0::numeric as ca_exb,
                    0::numeric as ca_exh,
                    0::numeric as ca_ghs,
                    0::numeric as ca_neonat,
                    0::numeric as ca_rea,
                    0::numeric as ca_sur,
                    ''::text ascode_gestion,
                    ''::text ascode_pec,
                    ''::text ascode_regularisation,
                    0::bigint as dmi_facture,
                    ''::text as facturation_18euros,
                    p_rss.finess,
                    0::numeric as forfait_facture,
                    0::numeric as honoraires_factures,
                    0::numeric as honoraires_remboursable,
                    0::numeric as honoraires_remboursable_2,
                    ''::text as justificatif_exo,
                    0::numeric as montant_dmi_ghs2006,
                    ''::text as nature_pec,
                    0::bigint nb_exb,
                    0::bigint nb_exh,
                    0::bigint nb_ghs,
                    0::bigint nb_ghsmin,
                    0::bigint nb_neonat,
                    0::bigint nb_rea,
                    0::bigint nb_si,
                    0::bigint nb_sur,
                    ''::text as no_at_date_adc,
                    ''::text as no_facture,
                    ''::text as no_facture_sejour_mere,
                    ''::text as no_organisme_complementaire,
                    p_rss.no_rss,
                    0::numeric as participation_assure_avant_oc,
                    0::bigint as pat_benef_cmu,
                    0::numeric as phc_facture,
                    ''::text as rang_beneficiaire,
                    ''::text as regime,
                    p_rss.oid as rss_id,
                    0::numeric as sejour_facture,
                    0::numeric as sejour_remboursable,
                    0::numeric as sejour_remboursable_2,
                    0::numeric as t2a_facture,
                    NULL as valorise_fides
                FROM
                    pmsi.p_rss
                    LEFT JOIN pmsi.p_rsf_total ON p_rsf_total.rss_id = p_rss.oid
                WHERE 1=1
                    AND p_rss.en_cours = '1'
                    AND p_rsf_total.rss_id IS NULL
            ]]></sqlcmd>
        </NODE>
    </NODE>
    
    <NODE name="PMSIETAT" label="RECUPERATION ETAT DES DOSSIERS">
            
        <NODE label="Initialisation">
            <sqlcmd><![CDATA[
            
                -- Séjours non groupés
                INSERT INTO pmsi.t_ghm(
                    code,
                    texte,
                    mco,
                    aso,
                    severite,
                    cmd_id,
                    ghm5_id,
                    ligne_oap_id,
                    cas_id)
                SELECT
                    '99Z99Z' AS code,
                    'Séjours sortis non groupés' AS texte,
                    '?' AS mco,
                    '?' AS aso,
                    'Z' AS severite,
                    COALESCE((SELECT oid FROM pmsi.t_cmd WHERE code = '99'),0) AS cmd_id,
                    COALESCE((SELECT oid FROM pmsi.t_ghm5 WHERE code = '99Z99'),0) AS ghm5_id,
                    0 AS ligne_oap_id,
                    COALESCE((SELECT oid FROM base.t_cas WHERE code = '?'),0) AS cas_id
                WHERE '99Z99Z' NOT IN (SELECT code FROM pmsi.t_ghm)
                UNION
                SELECT
                    '99Z98Z' AS code,
                    'GHM indisponible' AS texte,
                    '?' AS mco,
                    '?' AS aso,
                    'Z' AS severite,
                    COALESCE((SELECT oid FROM pmsi.t_cmd WHERE code = '99'),0) AS cmd_id,
                    COALESCE((SELECT oid FROM pmsi.t_ghm5 WHERE code = '99Z98'),0) AS ghm5_id,
                    0 AS ligne_oap_id,
                    COALESCE((SELECT oid FROM base.t_cas WHERE code = '?'),0) AS cas_id
                WHERE '99Z98Z' NOT IN (SELECT code FROM pmsi.t_ghm);
                    
            
                
                SELECT pmsi.cti_initialize_rss_etat();
                
            ]]></sqlcmd>
        </NODE>

        <NODE label="Etat des dossiers">
            <sqlcmd><![CDATA[
                                        
            ]]></sqlcmd>
        </NODE>
        
        
    </NODE>

</ROOT>
